private static Predicate<Throwable> isServiceUnavailable() { return httpExceptionCodePredicate(code -> code == HttpResponseStatus.SERVICE_UNAVAILABLE.code()); }
private void sendError(ChannelHandlerContext ctx, String error) { if (ctx.channel().isActive()) { DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR, Unpooled.wrappedBuffer(error.getBytes(ConfigConstants.DEFAULT_CHARSET))); response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain"); response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes()); ctx.writeAndFlush(response); } } }
/** * Sends a simple DELETE request to the given path. You only specify the $path part of * http://$host:$host/$path. * * @param path The $path to DELETE (http://$host:$host/$path) */ public void sendDeleteRequest(String path, FiniteDuration timeout) throws TimeoutException, InterruptedException { if (!path.startsWith("/")) { path = "/" + path; } HttpRequest getRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.DELETE, path); getRequest.headers().set(HttpHeaders.Names.HOST, host); getRequest.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); sendRequest(getRequest, timeout); }
currentDecoder.destroy(); currentDecoder = null; if (currentRequest.getMethod() == HttpMethod.GET || currentRequest.getMethod() == HttpMethod.DELETE) { else if (currentRequest.getMethod() == HttpMethod.POST) { currentRequestPath = new QueryStringDecoder(currentRequest.getUri(), ENCODING).path(); currentDecoder = new HttpPostRequestDecoder(DATA_FACTORY, currentRequest, ENCODING); throw new IOException("Unsupported HTTP method: " + currentRequest.getMethod().name()); currentDecoder.offer(chunk); while (currentDecoder.hasNext()) { InterfaceHttpData data = currentDecoder.next(); if (data.getHttpDataType() == HttpDataType.FileUpload && tmpDir != null) { DiskFileUpload file = (DiskFileUpload) data; if (file.isCompleted()) { String name = file.getFilename(); file.renameTo(target); QueryStringEncoder encoder = new QueryStringEncoder(currentRequestPath); encoder.addParam("filepath", target.getAbsolutePath()); encoder.addParam("filename", name); currentRequest.setUri(encoder.toString());
final String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE); if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { SimpleDateFormat dateFormatter = new SimpleDateFormat(StaticFileServerHandler.HTTP_DATE_FORMAT, Locale.US); long fileLength = raf.length(); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); StaticFileServerHandler.setContentTypeHeader(response, file); StaticFileServerHandler.setDateAndCacheHeaders(response, file); if (HttpHeaders.isKeepAlive(request)) { response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); HttpHeaders.setContentLength(response, fileLength); lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } else { lastContentFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), ctx.newProgressivePromise()); if (!HttpHeaders.isKeepAlive(request)) { lastContentFuture.addListener(ChannelFutureListener.CLOSE);
LOG.debug("{} request for file '{}'", request.getMethod(), path); if (!(request.getMethod() == GET || request.getMethod() == HEAD)) { sendMethodNotAllowed(ctx); return; HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); HttpHeaders.setHeader(response, CONNECTION, HttpHeaders.Values.CLOSE); HttpHeaders.setHeader(response, CACHE_CONTROL, "private"); HttpHeaders.setHeader(response, CONTENT_TYPE, "application/octet-stream"); HttpHeaders.setContentLength(response, status.getLen()); if (request.getMethod() == GET) {
@Override protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { LOG.debug("Received {}", msg); if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; currentStatus = response.getStatus(); currentType = response.headers().get(HttpHeaders.Names.CONTENT_TYPE); currentLocation = response.headers().get(HttpHeaders.Names.LOCATION); if (HttpHeaders.isTransferEncodingChunked(response)) { LOG.debug("Content is chunked"); } } if (msg instanceof HttpContent) { HttpContent content = (HttpContent) msg; // Add the content currentContent += content.content().toString(CharsetUtil.UTF_8); // Finished with this if (content instanceof LastHttpContent) { responses.add(new SimpleHttpResponse(currentStatus, currentType, currentContent, currentLocation)); currentStatus = null; currentType = null; currentLocation = null; currentContent = ""; ctx.close(); } } } }
public static HttpResponse getRedirectResponse(String redirectAddress, String path, HttpResponseStatus code) { checkNotNull(redirectAddress, "Redirect address"); checkNotNull(path, "Path"); String newLocation = String.format("%s%s", redirectAddress, path); HttpResponse redirectResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, code); redirectResponse.headers().set(HttpHeaders.Names.LOCATION, newLocation); redirectResponse.headers().set(HttpHeaders.Names.CONTENT_LENGTH, 0); return redirectResponse; }
/** * Writes a simple error response message. * * @param ctx The channel context to write the response to. * @param status The response status. */ private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { FullHttpResponse response = new DefaultFullHttpResponse( HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8)); HttpHeaders.setHeader(response, CONTENT_TYPE, "text/plain; charset=UTF-8"); // close the connection as soon as the error message is sent. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } }
/** * Send the "405 Method Not Allowed" response. * * @param ctx The channel context to write the response to. */ private static void sendMethodNotAllowed(ChannelHandlerContext ctx) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED); // close the connection as soon as the error message is sent. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
@Override protected void initChannel(SocketChannel ch) { RouterHandler handler = new RouterHandler(router, new HashMap<>()); // SSL should be the first handler in the pipeline if (sslFactory != null) { ch.pipeline().addLast("ssl", sslFactory.createNettySSLHandler()); } ch.pipeline() .addLast(new HttpServerCodec()) .addLast(new ChunkedWriteHandler()) .addLast(handler.getName(), handler) .addLast(new UnknownFileHandler()); } };
public static String getFromHTTP(String url, Time timeout) throws Exception { final URL u = new URL(url); LOG.info("Accessing URL " + url + " as URL: " + u); final long deadline = timeout.toMilliseconds() + System.currentTimeMillis(); while (System.currentTimeMillis() <= deadline) { HttpURLConnection connection = (HttpURLConnection) u.openConnection(); connection.setConnectTimeout(100000); connection.connect(); if (Objects.equals(HttpResponseStatus.SERVICE_UNAVAILABLE, HttpResponseStatus.valueOf(connection.getResponseCode()))) { // service not available --> Sleep and retry LOG.debug("Web service currently not available. Retrying the request in a bit."); Thread.sleep(100L); } else { InputStream is; if (connection.getResponseCode() >= 400) { // error! LOG.warn("HTTP Response code when connecting to {} was {}", url, connection.getResponseCode()); is = connection.getErrorStream(); } else { is = connection.getInputStream(); } return IOUtils.toString(is, ConfigConstants.DEFAULT_CHARSET); } } throw new TimeoutException("Could not get HTTP response in time since the service is still unavailable."); }
@Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new HttpClientCodec()); p.addLast(new HttpContentDecompressor()); p.addLast(new ClientHandler(responses)); } });
/** * Sends a simple GET request to the given path. You only specify the $path part of * http://$host:$host/$path. * * @param path The $path to GET (http://$host:$host/$path) */ public void sendGetRequest(String path, FiniteDuration timeout) throws TimeoutException, InterruptedException { if (!path.startsWith("/")) { path = "/" + path; } HttpRequest getRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path); getRequest.headers().set(HttpHeaders.Names.HOST, host); getRequest.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); sendRequest(getRequest, timeout); }
private static Predicate<Throwable> httpExceptionCodePredicate(Predicate<Integer> statusCodePredicate) { return (throwable) -> ExceptionUtils.findThrowable(throwable, RestClientException.class) .map(restClientException -> { final int code = restClientException.getHttpResponseStatus().code(); return statusCodePredicate.test(code); }) .orElse(false); }
private static void sendNotFound(ChannelHandlerContext ctx) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND); // close the connection as soon as the error message is sent. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } }
@Override protected void initChannel(SocketChannel ch) { RouterHandler handler = new RouterHandler(WebFrontendBootstrap.this.router, new HashMap<>()); // SSL should be the first handler in the pipeline if (serverSSLFactory != null) { ch.pipeline().addLast("ssl", serverSSLFactory.createNettySSLHandler()); } ch.pipeline() .addLast(new HttpServerCodec()) .addLast(new ChunkedWriteHandler()) .addLast(new HttpRequestHandler(uploadDir)) .addLast(handler.getName(), handler) .addLast(new PipelineErrorHandler(WebFrontendBootstrap.this.log)); } };
public HttpResponseStatus getHttpResponseStatus() { return HttpResponseStatus.valueOf(responseCode); } }
/** * Sends a simple PATCH request to the given path. You only specify the $path part of * http://$host:$host/$path. * * @param path The $path to PATCH (http://$host:$host/$path) */ public void sendPatchRequest(String path, FiniteDuration timeout) throws TimeoutException, InterruptedException { if (!path.startsWith("/")) { path = "/" + path; } HttpRequest getRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PATCH, path); getRequest.headers().set(HttpHeaders.Names.HOST, host); getRequest.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); sendRequest(getRequest, timeout); }
public RestHandlerException(String errorMessage, HttpResponseStatus httpResponseStatus, Throwable cause) { super(errorMessage, cause); this.responseCode = httpResponseStatus.code(); }