Example usage for io.netty.handler.codec.http HttpHeaders names

List of usage examples for io.netty.handler.codec.http HttpHeaders names

Introduction

In this page you can find the example usage for io.netty.handler.codec.http HttpHeaders names.

Prototype

public abstract Set<String> names();

Source Link

Document

Returns a new Set that contains the names of all headers in this object.

Usage

From source file:HttpUploadClientHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
    if (msg instanceof HttpResponse) {
        HttpResponse response = (HttpResponse) msg;

        System.err.println("STATUS: " + response.getStatus());
        System.err.println("VERSION: " + response.getProtocolVersion());

        if (!response.headers().isEmpty()) {
            for (String name : response.headers().names()) {
                for (String value : response.headers().getAll(name)) {
                    System.err.println("HEADER: " + name + " = " + value);
                }//w w w .  ja  v a  2s .  com
            }
        }

        if (response.getStatus().code() == 200 && response.headers()
                .contains(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED, true)) {
            readingChunks = true;
            System.err.println("CHUNKED CONTENT {");
        } else {
            System.err.println("CONTENT {");
        }
    }
    if (msg instanceof HttpContent) {
        HttpContent chunk = (HttpContent) msg;
        System.err.println(chunk.content().toString(CharsetUtil.UTF_8));

        if (chunk instanceof LastHttpContent) {
            if (readingChunks) {
                System.err.println("} END OF CHUNKED CONTENT");
            } else {
                System.err.println("} END OF CONTENT");
            }
            readingChunks = false;
        } else {
            System.err.println(chunk.content().toString(CharsetUtil.UTF_8));
        }
    }
}

From source file:HttpUploadClient.java

License:Apache License

/**
 * Standard usage of HTTP API in Netty without file Upload (get is not able to achieve File upload due to limitation
 * on request size)./*  w ww  .  ja  v a2  s  .  co  m*/
 *
 * @return the list of headers that will be used in every example after
 **/
private static List<Entry<String, String>> formGet(Bootstrap bootstrap, String host, int port, String get,
        URI uriSimple) throws Exception {
    // Start the connection attempt.
    // No use of HttpPostRequestEncoder since not a POST
    Channel channel = bootstrap.connect(host, port).sync().channel();

    // Prepare the HTTP request.
    QueryStringEncoder encoder = new QueryStringEncoder(get);
    // add Form attribute
    encoder.addParam("getform", "GET");
    encoder.addParam("info", "first value");
    encoder.addParam("secondinfo", "secondvalue &");
    // not the big one since it is not compatible with GET size
    // encoder.addParam("thirdinfo", textArea);
    encoder.addParam("thirdinfo", "third value\r\ntest second line\r\n\r\nnew line\r\n");
    encoder.addParam("Send", "Send");

    URI uriGet;
    try {
        uriGet = new URI(encoder.toString());
    } catch (URISyntaxException e) {
        logger.log(Level.WARNING, "Error: ", e);
        return null;
    }

    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
            uriGet.toASCIIString());
    HttpHeaders headers = request.headers();
    headers.set(HttpHeaders.Names.HOST, host);
    headers.set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
    headers.set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP + ',' + HttpHeaders.Values.DEFLATE);

    headers.set(HttpHeaders.Names.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
    headers.set(HttpHeaders.Names.ACCEPT_LANGUAGE, "fr");
    headers.set(HttpHeaders.Names.REFERER, uriSimple.toString());
    headers.set(HttpHeaders.Names.USER_AGENT, "Netty Simple Http Client side");
    headers.set(HttpHeaders.Names.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

    headers.set(HttpHeaders.Names.COOKIE, ClientCookieEncoder.encode(new DefaultCookie("my-cookie", "foo"),
            new DefaultCookie("another-cookie", "bar")));

    // send request
    List<Entry<String, String>> entries = headers.entries();
    channel.write(request).sync();

    // Wait for the server to close the connection.
    channel.closeFuture().sync();

    return entries;
}

From source file:adalightserver.http.HttpServer.java

License:Apache License

private void handleStaticFileRequest(ChannelHandlerContext ctx, FullHttpRequest req, String path)
        throws Exception {

    if (req.getMethod() != HttpMethod.GET) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
        return;//from ww  w  . j  ava  2  s . co  m
    }

    if (path.equals("/"))
        path = "/index.html";

    final String spath = sanitizeUri(path);
    if (spath == null) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
        return;
    }
    File file = new File(spath);
    if (file.isHidden() || !file.exists()) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
        return;
    }
    if (file.isDirectory() || !file.isFile() || !file.canRead()) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
        return;
    }

    RandomAccessFile raf = null;
    byte[] content;
    long fileLength;
    try {
        raf = new RandomAccessFile(file, "r");
        fileLength = raf.length();
        if (fileLength > 4 * 1024 * 1024) {
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND));
            return;
        }
        content = new byte[(int) fileLength];
        raf.read(content);
    } catch (Exception e) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND));
        return;
    } finally {
        if (raf != null)
            raf.close();
    }

    FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK);
    res.content().writeBytes(content);

    MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
    res.headers().set(HttpHeaders.Names.CONTENT_TYPE, mimeTypesMap.getContentType(file.getPath()));
    res.headers().set(HttpHeaders.Names.CONTENT_LENGTH, fileLength);

    sendHttpResponse(ctx, req, res);
}

From source file:c5db.control.ClientHttpProtostuffEncoder.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, Message msg, List<Object> out) throws Exception {
    Class<?> messageType = msg.getClass();

    LowCopyProtobufOutput outputSerializer = new LowCopyProtobufOutput();
    msg.cachedSchema().writeTo(outputSerializer, msg);
    List<ByteBuffer> serializedBuffers = outputSerializer.buffer.finish();
    ByteBuf requestContent = Unpooled.wrappedBuffer(serializedBuffers.toArray(new ByteBuffer[] {}));

    DefaultFullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.POST,
            "foo", requestContent);

    httpRequest.headers().set(HttpProtostuffConstants.PROTOSTUFF_HEADER_NAME, messageType.getName());
    httpRequest.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/octet-stream");
    httpRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, requestContent.readableBytes());

    out.add(httpRequest);/*from  ww w . jav a2  s . co  m*/
}

From source file:c5db.control.ServerHttpProtostuffEncoder.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, Message msg, List<Object> out) throws Exception {
    Class<?> messageType = msg.getClass();

    LowCopyProtobufOutput outputSerializer = new LowCopyProtobufOutput();
    msg.cachedSchema().writeTo(outputSerializer, msg);
    List<ByteBuffer> serializedBuffers = outputSerializer.buffer.finish();
    ByteBuf replyContent = Unpooled.wrappedBuffer(serializedBuffers.toArray(new ByteBuffer[] {}));

    DefaultFullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_0,
            HttpResponseStatus.OK, replyContent);
    httpResponse.headers().set(HttpProtostuffConstants.PROTOSTUFF_HEADER_NAME, messageType.getName());
    httpResponse.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/octet-stream");

    out.add(httpResponse);/*from   www . j ava2  s  .c  o m*/

}

From source file:cf.component.http.JsonTextResponseRequestHandler.java

License:Open Source License

@Override
public HttpResponse handleRequest(HttpRequest request, Matcher uriMatcher, ByteBuf body)
        throws RequestException {
    final String responseBody = handle(request, uriMatcher, body);
    final ByteBuf buffer = Unpooled.copiedBuffer(responseBody, CharsetUtil.UTF_8);
    final HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
            buffer);//from   w  w  w . ja  v  a  2  s .  co m
    final HttpHeaders headers = response.headers();
    headers.add(HttpHeaders.Names.CONTENT_TYPE, "application/json; charset=UTF-8");
    headers.add(HttpHeaders.Names.CONTENT_LENGTH, buffer.readableBytes());
    return response;
}

From source file:cf.dropsonde.firehose.NettyFirehoseOnSubscribe.java

License:Open Source License

public NettyFirehoseOnSubscribe(URI uri, String token, String subscriptionId, boolean skipTlsValidation,
        EventLoopGroup eventLoopGroup, Class<? extends SocketChannel> channelClass) {
    try {/*from   w w  w .j av a2  s. c  om*/
        final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
        final String scheme = uri.getScheme() == null ? "ws" : uri.getScheme();
        final int port = getPort(scheme, uri.getPort());
        final URI fullUri = uri.resolve("/firehose/" + subscriptionId);

        final SslContext sslContext;
        if ("wss".equalsIgnoreCase(scheme)) {
            final SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();
            if (skipTlsValidation) {
                sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
            } else {
                TrustManagerFactory trustManagerFactory = TrustManagerFactory
                        .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                trustManagerFactory.init((KeyStore) null);
                sslContextBuilder.trustManager(trustManagerFactory);
            }
            sslContext = sslContextBuilder.build();
        } else {
            sslContext = null;
        }

        bootstrap = new Bootstrap();
        if (eventLoopGroup == null) {
            this.eventLoopGroup = new NioEventLoopGroup();
            bootstrap.group(this.eventLoopGroup);
        } else {
            this.eventLoopGroup = null;
            bootstrap.group(eventLoopGroup);
        }
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000)
                .channel(channelClass == null ? NioSocketChannel.class : channelClass).remoteAddress(host, port)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel c) throws Exception {
                        final HttpHeaders headers = new DefaultHttpHeaders();
                        headers.add(HttpHeaders.Names.AUTHORIZATION, token);
                        final WebSocketClientHandler handler = new WebSocketClientHandler(
                                WebSocketClientHandshakerFactory.newHandshaker(fullUri, WebSocketVersion.V13,
                                        null, false, headers));
                        final ChannelPipeline pipeline = c.pipeline();
                        if (sslContext != null) {
                            pipeline.addLast(sslContext.newHandler(c.alloc(), host, port));
                        }
                        pipeline.addLast(new ReadTimeoutHandler(30));
                        pipeline.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192));
                        pipeline.addLast(HANDLER_NAME, handler);

                        channel = c;
                    }
                });
    } catch (NoSuchAlgorithmException | SSLException | KeyStoreException e) {
        throw new RuntimeException(e);
    }
}

From source file:cf.service.NettyBrokerServer.java

License:Open Source License

private HttpResponse encodeResponse(JsonObject jsonBody) throws RequestException {
    final String json = toString(jsonBody);
    LOGGER.debug("JSON response to server {}", json);
    final byte[] bytes = json.getBytes();
    final ByteBuf buffer = Unpooled.wrappedBuffer(bytes);
    final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
            buffer);// w  w w  . j av  a2  s  .  com
    response.headers().add(HttpHeaders.Names.CONTENT_TYPE, "application/json");
    response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, bytes.length);
    return response;
}

From source file:cn.wantedonline.puppy.httpserver.component.HttpObjectAggregator.java

License:Apache License

@Override
protected void decode(final ChannelHandlerContext ctx, HttpObject msg, List<Object> out) throws Exception {
    AggregatedFullHttpMessage currentMessage = this.currentMessage;

    if (msg instanceof HttpMessage) {
        tooLongFrameFound = false;// w  w  w.  j  av  a2 s  . com
        assert currentMessage == null;

        HttpMessage m = (HttpMessage) msg;

        // Handle the 'Expect: 100-continue' header if necessary.
        if (is100ContinueExpected(m)) {
            if (HttpHeaders.getContentLength(m, 0) > maxContentLength) {
                tooLongFrameFound = true;
                final ChannelFuture future = ctx.writeAndFlush(EXPECTATION_FAILED.duplicate().retain());
                future.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (!future.isSuccess()) {
                            ctx.fireExceptionCaught(future.cause());
                        }
                    }
                });
                if (closeOnExpectationFailed) {
                    future.addListener(ChannelFutureListener.CLOSE);
                }
                ctx.pipeline().fireUserEventTriggered(HttpExpectationFailedEvent.INSTANCE);
                return;
            }
            ctx.writeAndFlush(CONTINUE.duplicate().retain()).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        ctx.fireExceptionCaught(future.cause());
                    }
                }
            });
        }

        if (!m.getDecoderResult().isSuccess()) {
            removeTransferEncodingChunked(m);
            out.add(toFullMessage(m));
            this.currentMessage = null;
            return;
        }
        if (msg instanceof HttpRequest) {
            HttpRequest header = (HttpRequest) msg;
            this.currentMessage = currentMessage = new AggregatedFullHttpRequest(header,
                    ctx.alloc().compositeBuffer(maxCumulationBufferComponents), null);
        } else if (msg instanceof HttpResponse) {
            HttpResponse header = (HttpResponse) msg;
            this.currentMessage = currentMessage = new AggregatedFullHttpResponse(header,
                    Unpooled.compositeBuffer(maxCumulationBufferComponents), null);
        } else {
            throw new Error();
        }

        // A streamed message - initialize the cumulative buffer, and wait for incoming chunks.
        removeTransferEncodingChunked(currentMessage);
    } else if (msg instanceof HttpContent) {
        if (tooLongFrameFound) {
            if (msg instanceof LastHttpContent) {
                this.currentMessage = null;
            }
            // already detect the too long frame so just discard the content
            return;
        }
        assert currentMessage != null;

        // Merge the received chunk into the content of the current message.
        HttpContent chunk = (HttpContent) msg;
        CompositeByteBuf content = (CompositeByteBuf) currentMessage.content();

        if (content.readableBytes() > maxContentLength - chunk.content().readableBytes()) {
            tooLongFrameFound = true;

            // release current message to prevent leaks
            currentMessage.release();
            this.currentMessage = null;

            throw new TooLongFrameException("HTTP content length exceeded " + maxContentLength + " bytes.");
        }

        // Append the content of the chunk
        if (chunk.content().isReadable()) {
            chunk.retain();
            content.addComponent(chunk.content());
            content.writerIndex(content.writerIndex() + chunk.content().readableBytes());
        }

        final boolean last;
        if (!chunk.getDecoderResult().isSuccess()) {
            currentMessage.setDecoderResult(DecoderResult.failure(chunk.getDecoderResult().cause()));
            last = true;
        } else {
            last = chunk instanceof LastHttpContent;
        }

        if (last) {
            this.currentMessage = null;

            // Merge trailing headers into the message.
            if (chunk instanceof LastHttpContent) {
                LastHttpContent trailer = (LastHttpContent) chunk;
                currentMessage.setTrailingHeaders(trailer.trailingHeaders());
            } else {
                currentMessage.setTrailingHeaders(new DefaultHttpHeaders());
            }

            // Set the 'Content-Length' header. If one isn't already set.
            // This is important as HEAD responses will use a 'Content-Length' header which
            // does not match the actual body, but the number of bytes that would be
            // transmitted if a GET would have been used.
            //
            // See rfc2616 14.13 Content-Length
            if (!isContentLengthSet(currentMessage)) {
                currentMessage.headers().set(HttpHeaders.Names.CONTENT_LENGTH,
                        String.valueOf(content.readableBytes()));
            }
            // All done
            out.add(currentMessage);
        }
    } else {
        throw new Error();
    }
}

From source file:cn.wantedonline.puppy.httpserver.component.HttpRequest.java

License:Apache License

/**
 * Returns the host name of the server to which the request was sent.
 * It is the value of the part before ":" in the Host header value,
 * if any, or the resolved server name, or the server IP address.
 * @return/*from   w  w w. ja  v a  2s .  c o m*/
 */
public String getServerName() {
    return headers().get(HttpHeaders.Names.HOST);
}