private InputStream wrapResponseStream(HttpURLConnection connection, Status status) { try { return new HttpURLConnectionStream(connection, status); } catch (IOException e) { connection.disconnect(); throw new HTTPException(e); } }
public default <A> Optional<A> transform(final Function<InputStream, A> f) { try(InputStream is = getInputStream()) { return Optional.ofNullable(f.apply(is)); } catch (IOException e) { throw new HTTPException(e); } } }
public InputStream getInputStream() { if (isAvailable()) { try { return Files.newInputStream(file.toPath()); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } throw new HTTPException(String.format("File %s cannot be read.", file.getAbsolutePath())); }
protected void writeBody(PrintStream writer, Optional<Payload> payload) { payload.ifPresent(p -> { writer.print("\r\n"); if (p.isAvailable()) { try (InputStream stream = p.getInputStream()) { IOUtils.copy(stream, writer); writer.print("\r\n"); } catch (IOException e) { throw new HTTPException("Unable to write the body of the response", e); } } }); } }
private <A> Optional<A> lift(Payload p, ThrowableFunction<Payload, A, IOException> f) { try(InputStream is = p.getInputStream()) { InputStreamPayload isp = new InputStreamPayload(is, p.getMimeType(), p.length()); return Optional.ofNullable(f.apply(isp)); } catch (IOException e) { throw new HTTPException(e); } }
@Override protected HTTPResponse resolveImpl(HTTPRequest request) throws IOException { URL url = request.getRequestURI().toURL(); URLConnection openConnection = url.openConnection(); if (openConnection instanceof HttpsURLConnection) { HttpsURLConnection connection = (HttpsURLConnection) openConnection; doRequest(request, connection); return convertResponse(connection); } else if (openConnection instanceof HttpURLConnection) { HttpURLConnection connection = (HttpURLConnection) openConnection; doRequest(request, connection); return convertResponse(connection); } throw new HTTPException("This resolver only supports HTTP calls"); }
@Override public synchronized HTTPResponse insert(HTTPRequest request, HTTPResponse response) { Key key = Key.create(request, response); try { HTTPResponse storedResponse = createCacheableResponse(key, response); SerializableCacheItem item = createCacheItem(storedResponse); writeItem(key, item); return item.getResponse(); } catch (IOException e) { throw new HTTPException(e); } }
@Override public synchronized HTTPResponse update(HTTPRequest request, HTTPResponse response) { Key key = Key.create(request, response); try { SerializableCacheItem item = createCacheItem(response); writeItem(key, item); } catch (IOException e) { throw new HTTPException(e); } return get(key).getResponse(); }