Search in sources :

Example 21 with DefaultHttpResponse

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse in project LogHub by fbacchella.

the class HttpRequestProcessing method writeResponse.

protected boolean writeResponse(ChannelHandlerContext ctx, FullHttpRequest request, ChunkedInput<ByteBuf> content, int length) {
    // Build the response object.
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    return internalWriteResponse(ctx, request, response, length, () -> {
        HttpChunkedInput chunked = new HttpChunkedInput(content, LastHttpContent.EMPTY_LAST_CONTENT);
        ctx.write(response);
        return ctx.writeAndFlush(chunked);
    });
}
Also used : HttpChunkedInput(io.netty.handler.codec.http.HttpChunkedInput) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse)

Example 22 with DefaultHttpResponse

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse in project ballerina by ballerina-lang.

the class HttpUtil method createHttpCarbonMessage.

public static HTTPCarbonMessage createHttpCarbonMessage(boolean isRequest) {
    HTTPCarbonMessage httpCarbonMessage;
    if (isRequest) {
        httpCarbonMessage = new HTTPCarbonMessage(new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, ""));
    } else {
        httpCarbonMessage = new HTTPCarbonMessage(new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK));
    }
    httpCarbonMessage.completeMessage();
    return httpCarbonMessage;
}
Also used : HTTPCarbonMessage(org.wso2.transport.http.netty.message.HTTPCarbonMessage) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse)

Example 23 with DefaultHttpResponse

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse in project apollo by apollo-rsps.

the class HttpRequestWorker method service.

@Override
protected void service(ResourceProvider provider, Channel channel, HttpRequest request) throws IOException {
    String path = request.getUri();
    Optional<ByteBuffer> buf = provider.get(path);
    HttpResponseStatus status = HttpResponseStatus.OK;
    String mime = getMimeType(request.getUri());
    if (!buf.isPresent()) {
        status = HttpResponseStatus.NOT_FOUND;
        mime = "text/html";
    }
    ByteBuf wrapped = buf.isPresent() ? Unpooled.wrappedBuffer(buf.get()) : createErrorPage(status, "The page you requested could not be found.");
    HttpResponse response = new DefaultHttpResponse(request.getProtocolVersion(), status);
    response.headers().set("Date", new Date());
    response.headers().set("Server", SERVER_IDENTIFIER);
    response.headers().set("Content-type", mime + ", charset=" + CHARACTER_SET.name());
    response.headers().set("Cache-control", "no-cache");
    response.headers().set("Pragma", "no-cache");
    response.headers().set("Expires", new Date(0));
    response.headers().set("Connection", "close");
    response.headers().set("Content-length", wrapped.readableBytes());
    channel.write(response);
    channel.writeAndFlush(wrapped).addListener(ChannelFutureListener.CLOSE);
}
Also used : HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) ByteBuf(io.netty.buffer.ByteBuf) ByteBuffer(java.nio.ByteBuffer) Date(java.util.Date)

Example 24 with DefaultHttpResponse

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse in project flink by apache.

the class HistoryServerStaticFileServerHandler method respondWithFile.

/**
 * Response when running with leading JobManager.
 */
private void respondWithFile(ChannelHandlerContext ctx, HttpRequest request, String requestPath) throws IOException, ParseException, RestHandlerException {
    // make sure we request the "index.html" in case there is a directory request
    if (requestPath.endsWith("/")) {
        requestPath = requestPath + "index.html";
    }
    if (!requestPath.contains(".")) {
        // we assume that the path ends in either .html or .js
        requestPath = requestPath + ".json";
    }
    // convert to absolute path
    final File file = new File(rootPath, requestPath);
    if (!file.exists()) {
        // file does not exist. Try to load it with the classloader
        ClassLoader cl = HistoryServerStaticFileServerHandler.class.getClassLoader();
        try (InputStream resourceStream = cl.getResourceAsStream("web" + requestPath)) {
            boolean success = false;
            try {
                if (resourceStream != null) {
                    URL root = cl.getResource("web");
                    URL requested = cl.getResource("web" + requestPath);
                    if (root != null && requested != null) {
                        URI rootURI = new URI(root.getPath()).normalize();
                        URI requestedURI = new URI(requested.getPath()).normalize();
                        // expected scope.
                        if (!rootURI.relativize(requestedURI).equals(requestedURI)) {
                            LOG.debug("Loading missing file from classloader: {}", requestPath);
                            // ensure that directory to file exists.
                            file.getParentFile().mkdirs();
                            Files.copy(resourceStream, file.toPath());
                            success = true;
                        }
                    }
                }
            } catch (Throwable t) {
                LOG.error("error while responding", t);
            } finally {
                if (!success) {
                    LOG.debug("Unable to load requested file {} from classloader", requestPath);
                    throw new NotFoundException("File not found.");
                }
            }
        }
    }
    StaticFileServerHandler.checkFileValidity(file, rootPath, LOG);
    // cache validation
    final String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE);
    if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat(StaticFileServerHandler.HTTP_DATE_FORMAT, Locale.US);
        Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);
        // Only compare up to the second because the datetime format we send to the client
        // does not have milliseconds
        long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
        long fileLastModifiedSeconds = file.lastModified() / 1000;
        if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Responding 'NOT MODIFIED' for file '" + file.getAbsolutePath() + '\'');
            }
            StaticFileServerHandler.sendNotModified(ctx);
            return;
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Responding with file '" + file.getAbsolutePath() + '\'');
    }
    // Don't need to close this manually. Netty's DefaultFileRegion will take care of it.
    final RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Could not find file {}.", file.getAbsolutePath());
        }
        HandlerUtils.sendErrorResponse(ctx, request, new ErrorResponseBody("File not found."), NOT_FOUND, Collections.emptyMap());
        return;
    }
    try {
        long fileLength = raf.length();
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
        StaticFileServerHandler.setContentTypeHeader(response, file);
        // the job overview should be updated as soon as possible
        if (!requestPath.equals("/joboverview.json")) {
            StaticFileServerHandler.setDateAndCacheHeaders(response, file);
        }
        if (HttpHeaders.isKeepAlive(request)) {
            response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
        }
        HttpHeaders.setContentLength(response, fileLength);
        // write the initial line and the header.
        ctx.write(response);
        // write the content.
        ChannelFuture lastContentFuture;
        if (ctx.pipeline().get(SslHandler.class) == null) {
            ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise());
            lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
        } else {
            lastContentFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), ctx.newProgressivePromise());
        // HttpChunkedInput will write the end marker (LastHttpContent) for us.
        }
        // close the connection, if no keep-alive is needed
        if (!HttpHeaders.isKeepAlive(request)) {
            lastContentFuture.addListener(ChannelFutureListener.CLOSE);
        }
    } catch (Exception e) {
        raf.close();
        LOG.error("Failed to serve file.", e);
        throw new RestHandlerException("Internal server error.", INTERNAL_SERVER_ERROR);
    }
}
Also used : ChannelFuture(org.apache.flink.shaded.netty4.io.netty.channel.ChannelFuture) InputStream(java.io.InputStream) ChunkedFile(org.apache.flink.shaded.netty4.io.netty.handler.stream.ChunkedFile) FileNotFoundException(java.io.FileNotFoundException) NotFoundException(org.apache.flink.runtime.rest.NotFoundException) FileNotFoundException(java.io.FileNotFoundException) ErrorResponseBody(org.apache.flink.runtime.rest.messages.ErrorResponseBody) DefaultHttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponse) DefaultFileRegion(org.apache.flink.shaded.netty4.io.netty.channel.DefaultFileRegion) URI(java.net.URI) URL(java.net.URL) Date(java.util.Date) SslHandler(org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslHandler) NotFoundException(org.apache.flink.runtime.rest.NotFoundException) ParseException(java.text.ParseException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) RestHandlerException(org.apache.flink.runtime.rest.handler.RestHandlerException) RestHandlerException(org.apache.flink.runtime.rest.handler.RestHandlerException) HttpChunkedInput(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpChunkedInput) RandomAccessFile(java.io.RandomAccessFile) DefaultHttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) ChunkedFile(org.apache.flink.shaded.netty4.io.netty.handler.stream.ChunkedFile) SimpleDateFormat(java.text.SimpleDateFormat)

Example 25 with DefaultHttpResponse

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse in project netty-socketio by mrniko.

the class EncoderHandler method write.

private void write(XHROptionsMessage msg, ChannelHandlerContext ctx, ChannelPromise promise) {
    HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK);
    res.headers().add(HttpHeaderNames.SET_COOKIE, "io=" + msg.getSessionId()).add(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE).add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS, HttpHeaderNames.CONTENT_TYPE);
    String origin = ctx.channel().attr(ORIGIN).get();
    addOriginHeaders(origin, res);
    ByteBuf out = encoder.allocateBuffer(ctx.alloc());
    sendMessage(msg, ctx.channel(), out, res, promise);
}
Also used : DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) ByteBuf(io.netty.buffer.ByteBuf)

Aggregations

DefaultHttpResponse (io.netty.handler.codec.http.DefaultHttpResponse)64 HttpResponse (io.netty.handler.codec.http.HttpResponse)34 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)23 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)18 HttpContent (io.netty.handler.codec.http.HttpContent)14 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)11 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)11 ChannelFuture (io.netty.channel.ChannelFuture)10 HttpRequest (io.netty.handler.codec.http.HttpRequest)10 ByteBuf (io.netty.buffer.ByteBuf)9 DefaultLastHttpContent (io.netty.handler.codec.http.DefaultLastHttpContent)9 HttpObject (io.netty.handler.codec.http.HttpObject)9 RandomAccessFile (java.io.RandomAccessFile)9 Test (org.junit.Test)9 FileNotFoundException (java.io.FileNotFoundException)7 IOException (java.io.IOException)7 Channel (io.netty.channel.Channel)6 File (java.io.File)6 HttpChunkedInput (io.netty.handler.codec.http.HttpChunkedInput)5 URL (java.net.URL)5