/** * @return the URI in the method-line. */ public URI getUri() { return requestLine.getUri(); }
/** * @return this request's method name. */ public String getMethod() { return requestLine.getMethod(); }
@Override public void writeTo(OutputStream outputStream) throws IOException { byte[] bytes = toString().getBytes(StandardCharsets.US_ASCII); outputStream.write(bytes); outputStream.write('\r'); outputStream.write('\n'); }
@Override public Optional<RawHttpResponse<?>> route(RawHttpRequest request) { final Optional<RawHttpResponse<?>> response; if (request.getMethod().equals("GET")) { String path = request.getStartLine().getUri() .normalize().getPath() .replaceAll(DIR_BACK_PATTERN, ""); // provide the index.html file at the root path if (path.isEmpty() || path.equals("/")) { path = "index.html"; } Optional<FileResult> resource = fileLocator.find(path, request.getHeaders().get("Accept")); response = resource.map(fileResult -> HttpResponses.getOkResponse(request.getStartLine().getHttpVersion()) .withHeaders(fileResult.contentTypeHeader) .withBody(new FileBody(fileResult.file))); } else { response = Optional.of(HttpResponses.getMethodNotAllowedResponse(request.getStartLine().getHttpVersion())); } return response; }
@SuppressWarnings("unchecked") private RawHttpResponse<?> route(RawHttpRequest request) throws IOException { RawHttpResponse<Void> response; try { response = router.route(request).map(res -> (RawHttpResponse<Void>) res) .orElseGet(() -> options.notFoundResponse(request).orElseGet(() -> HttpResponses.getNotFoundResponse(request.getStartLine().getHttpVersion()))); } catch (Exception e) { e.printStackTrace(); response = options.serverErrorResponse(request).orElseGet(() -> HttpResponses.getServerErrorResponse(request.getStartLine().getHttpVersion())); } return options.onResponse(request, response); }
private RequestLine verifyHost(RequestLine requestLine, RawHttpHeaders.Builder headers) { List<String> hostHeaderValues = headers.get("Host"); URI requestLineUri = requestLine.getUri(); @Nullable String requestLineHost = requestLineUri.getHost(); if (hostHeaderValues.isEmpty()) { } else if (hostHeaderValues.size() == 1) { if (requestLineHost == null) try { RequestLine newRequestLine = requestLine.withHost(hostHeaderValues.iterator().next()); headers.overwrite("Host", newRequestLine.getUri().getHost()); return newRequestLine; } catch (IllegalArgumentException e) {
/** * @param host the host to be used in the method line's URI. * @return a copy of this method line, but with the given host */ public RequestLine withHost(String host) { try { if (!host.matches("[a-z]{1,6}://.*")) { host = "http://" + host; } URI hostURI = URI.create(host); URI newURI = new URI(hostURI.getScheme(), hostURI.getUserInfo(), hostURI.getHost(), hostURI.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment()); return new RequestLine(method, newURI, httpVersion); } catch (Exception e) { throw new IllegalArgumentException("Invalid host format" + Optional.ofNullable( e.getMessage()).map(s -> ": " + s).orElse("")); } }
@SuppressWarnings("unchecked") private RawHttpResponse<?> route(RawHttpRequest request) throws IOException { RawHttpResponse<Void> response; try { response = router.route(request).map(res -> (RawHttpResponse<Void>) res) .orElseGet(() -> options.notFoundResponse(request).orElseGet(() -> HttpResponses.getNotFoundResponse(request.getStartLine().getHttpVersion()))); } catch (Exception e) { e.printStackTrace(); response = options.serverErrorResponse(request).orElseGet(() -> HttpResponses.getServerErrorResponse(request.getStartLine().getHttpVersion())); } return options.onResponse(request, response); }
private RequestLine verifyHost(RequestLine requestLine, RawHttpHeaders.Builder headers) { List<String> hostHeaderValues = headers.get("Host"); URI requestLineUri = requestLine.getUri(); @Nullable String requestLineHost = requestLineUri.getHost(); if (hostHeaderValues.isEmpty()) { } else if (hostHeaderValues.size() == 1) { if (requestLineHost == null) try { RequestLine newRequestLine = requestLine.withHost(hostHeaderValues.iterator().next()); headers.overwrite("Host", newRequestLine.getUri().getHost()); return newRequestLine; } catch (IllegalArgumentException e) {
/** * @param host the host to be used in the method line's URI. * @return a copy of this method line, but with the given host */ public RequestLine withHost(String host) { try { if (!host.matches("[a-z]{1,6}://.*")) { host = "http://" + host; } URI hostURI = URI.create(host); URI newURI = new URI(hostURI.getScheme(), hostURI.getUserInfo(), hostURI.getHost(), hostURI.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment()); return new RequestLine(method, newURI, httpVersion); } catch (Exception e) { throw new IllegalArgumentException("Invalid host format" + Optional.ofNullable( e.getMessage()).map(s -> ": " + s).orElse("")); } }
client.getInputStream(), ((InetSocketAddress) client.getRemoteSocketAddress()).getAddress()); HttpVersion httpVersion = request.getStartLine().getHttpVersion(); Optional<String> connectionOption = request.getHeaders().getFirst("Connection");
/** * @return the URI in the method-line. */ public URI getUri() { return requestLine.getUri(); }
/** * @return this request's method name. */ public String getMethod() { return requestLine.getMethod(); }
private RequestLine buildRequestLine(String requestLine) { if (requestLine.isEmpty()) { throw new InvalidHttpRequest("No content", 0); } String[] parts = requestLine.split("\\s"); if (parts.length == 2 || parts.length == 3) { String method = parts[0]; OptionalInt illegalIndex = FieldValues.indexOfNotAllowedInTokens(method); if (illegalIndex.isPresent()) { throw new InvalidHttpRequest("Invalid method name: illegal character at index " + illegalIndex.getAsInt(), 1); } URI uri = parseUri(parts[1]); HttpVersion httpVersion = options.insertHttpVersionIfMissing() ? HttpVersion.HTTP_1_1 : null; if (parts.length == 3) try { httpVersion = HttpVersion.parse(parts[2]); } catch (IllegalArgumentException e) { throw new InvalidHttpRequest("Invalid HTTP version", 1); } if (httpVersion == null) { throw new InvalidHttpRequest("Missing HTTP version", 1); } return new RequestLine(method, uri, httpVersion); } else { throw new InvalidHttpRequest("Invalid request line", 1); } }
@Override public void writeTo(OutputStream outputStream) throws IOException { byte[] bytes = toString().getBytes(StandardCharsets.US_ASCII); outputStream.write(bytes); outputStream.write('\r'); outputStream.write('\n'); }
client.getInputStream(), ((InetSocketAddress) client.getRemoteSocketAddress()).getAddress()); HttpVersion httpVersion = request.getStartLine().getHttpVersion(); Optional<String> connectionOption = request.getHeaders().getFirst("Connection");
/** * Determines whether a response with the given status-line should have a body. * <p> * If provided, the request-line of the request which produced such response is taken into * consideration. See <a href="https://tools.ietf.org/html/rfc7230#section-3.3">Section 3.3</a> * of RFC-7230 for details. * * @param statusLine status-line of response * @param requestLine request-line of request, if any * @return true if such response has a body, false otherwise */ public static boolean responseHasBody(StatusLine statusLine, @Nullable RequestLine requestLine) { if (requestLine != null) { if (requestLine.getMethod().equalsIgnoreCase("HEAD")) { return false; // HEAD response must never have a body } if (requestLine.getMethod().equalsIgnoreCase("CONNECT") && startsWith(2, statusLine.getStatusCode())) { return false; // CONNECT successful means start tunelling } } int statusCode = statusLine.getStatusCode(); // All 1xx (Informational), 204 (No Content), and 304 (Not Modified) // responses do not include a message body. boolean hasNoBody = startsWith(1, statusCode) || statusCode == 204 || statusCode == 304; return !hasNoBody; }
private RequestLine buildRequestLine(String requestLine) { if (requestLine.isEmpty()) { throw new InvalidHttpRequest("No content", 0); } String[] parts = requestLine.split("\\s"); if (parts.length == 2 || parts.length == 3) { String method = parts[0]; OptionalInt illegalIndex = FieldValues.indexOfNotAllowedInTokens(method); if (illegalIndex.isPresent()) { throw new InvalidHttpRequest("Invalid method name: illegal character at index " + illegalIndex.getAsInt(), 1); } URI uri = parseUri(parts[1]); HttpVersion httpVersion = options.insertHttpVersionIfMissing() ? HttpVersion.HTTP_1_1 : null; if (parts.length == 3) try { httpVersion = HttpVersion.parse(parts[2]); } catch (IllegalArgumentException e) { throw new InvalidHttpRequest("Invalid HTTP version", 1); } if (httpVersion == null) { throw new InvalidHttpRequest("Missing HTTP version", 1); } return new RequestLine(method, uri, httpVersion); } else { throw new InvalidHttpRequest("Invalid request line", 1); } }
public RawHttpResponse<CloseableHttpResponse> send(RawHttpRequest request) throws IOException { RequestBuilder builder = RequestBuilder.create(request.getMethod()); builder.setUri(request.getUri()); builder.setVersion(toProtocolVersion(request.getStartLine().getHttpVersion())); request.getHeaders().getHeaderNames().forEach((name) -> request.getHeaders().get(name).forEach(value -> builder.addHeader(new BasicHeader(name, value)))); request.getBody().ifPresent(b -> builder.setEntity(new InputStreamEntity(b.asRawStream()))); CloseableHttpResponse response = httpClient.execute(builder.build()); RawHttpHeaders headers = readHeaders(response); StatusLine statusLine = adaptStatus(response.getStatusLine()); @Nullable LazyBodyReader body; if (response.getEntity() != null) { FramedBody framedBody = http.getFramedBody(statusLine, headers); body = new LazyBodyReader(framedBody, response.getEntity().getContent()); } else { body = null; } return new RawHttpResponse<>(response, request, statusLine, headers, body); }
/** * Determines whether a response with the given status-line should have a body. * <p> * If provided, the request-line of the request which produced such response is taken into * consideration. See <a href="https://tools.ietf.org/html/rfc7230#section-3.3">Section 3.3</a> * of RFC-7230 for details. * * @param statusLine status-line of response * @param requestLine request-line of request, if any * @return true if such response has a body, false otherwise */ public static boolean responseHasBody(StatusLine statusLine, @Nullable RequestLine requestLine) { if (requestLine != null) { if (requestLine.getMethod().equalsIgnoreCase("HEAD")) { return false; // HEAD response must never have a body } if (requestLine.getMethod().equalsIgnoreCase("CONNECT") && startsWith(2, statusLine.getStatusCode())) { return false; // CONNECT successful means start tunelling } } int statusCode = statusLine.getStatusCode(); // All 1xx (Informational), 204 (No Content), and 304 (Not Modified) // responses do not include a message body. boolean hasNoBody = startsWith(1, statusCode) || statusCode == 204 || statusCode == 304; return !hasNoBody; }