Example usage for io.netty.handler.codec.http HttpMethod GET

List of usage examples for io.netty.handler.codec.http HttpMethod GET

Introduction

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

Prototype

HttpMethod GET

To view the source code for io.netty.handler.codec.http HttpMethod GET.

Click Source Link

Document

The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI.

Usage

From source file:com.dlc.server.DLCHttpServerHandler.java

private void getAllFiles(ChannelHandlerContext ctx, HttpRequest req, Map<String, List<String>> params) {
    if (req.method() == HttpMethod.GET) {
        writeResponse(ctx, gson.toJson(c.getIndexedFiles()));
    }/*w  w  w  .j  av  a2 s . co m*/
}

From source file:com.dwarf.netty.guide.http.snoop.HttpSnoopClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    URI uri = new URI(URL);
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    int port = uri.getPort();
    if (port == -1) {
        if ("http".equalsIgnoreCase(scheme)) {
            port = 80;/*w  w w . ja va  2 s .  c o  m*/
        } else if ("https".equalsIgnoreCase(scheme)) {
            port = 443;
        }
    }

    if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
        System.err.println("Only HTTP(S) is supported.");
        return;
    }

    // Configure SSL context if necessary.
    final boolean ssl = "https".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new HttpSnoopClientInitializer(sslCtx));

        // Make the connection attempt.
        Channel ch = b.connect(host, port).sync().channel();

        // Prepare the HTTP request.
        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
                uri.getRawPath());
        request.headers().set(HttpHeaderNames.HOST, host);
        request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
        request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);

        // Set some example cookies.
        request.headers().set(HttpHeaderNames.COOKIE, ClientCookieEncoder
                .encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar")));

        // Send the HTTP request.
        ch.writeAndFlush(request);

        // Wait for the server to close the connection.
        ch.closeFuture().sync();
    } finally {
        // Shut down executor threads to exit.
        group.shutdownGracefully();
    }
}

From source file:com.example.grpc.server.PrometheusServer.java

License:Apache License

public void start() {
    final ServerBootstrap bootstrap = new ServerBootstrap();

    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override/*from w  ww .j  ava 2  s  . com*/
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    ChannelPipeline pipeline = socketChannel.pipeline();
                    pipeline.addLast("decoder", new HttpRequestDecoder());
                    pipeline.addLast("encoder", new HttpResponseEncoder());
                    pipeline.addLast("prometheus", new SimpleChannelInboundHandler<Object>() {
                        @Override
                        protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o)
                                throws Exception {
                            if (!(o instanceof HttpRequest)) {
                                return;
                            }

                            HttpRequest request = (HttpRequest) o;

                            if (!"/metrics".equals(request.uri())) {
                                final FullHttpResponse response = new DefaultFullHttpResponse(
                                        HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
                                channelHandlerContext.writeAndFlush(response)
                                        .addListener(ChannelFutureListener.CLOSE);
                                return;
                            }

                            if (!HttpMethod.GET.equals(request.method())) {
                                final FullHttpResponse response = new DefaultFullHttpResponse(
                                        HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_ACCEPTABLE);
                                channelHandlerContext.writeAndFlush(response)
                                        .addListener(ChannelFutureListener.CLOSE);
                                return;
                            }

                            ByteBuf buf = Unpooled.buffer();
                            ByteBufOutputStream os = new ByteBufOutputStream(buf);
                            OutputStreamWriter writer = new OutputStreamWriter(os);
                            TextFormat.write004(writer, registry.metricFamilySamples());
                            writer.close();
                            os.close();

                            final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                                    HttpResponseStatus.OK, buf);
                            response.headers().set(HttpHeaderNames.CONTENT_TYPE, TextFormat.CONTENT_TYPE_004);
                            channelHandlerContext.writeAndFlush(response)
                                    .addListener(ChannelFutureListener.CLOSE);
                        }
                    });

                }
            });

    try {
        this.channel = bootstrap.bind(this.port).sync().channel();
    } catch (InterruptedException e) {
        // do nothing
    }
}

From source file:com.fire.login.http.HttpInboundHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;
        URI uri = URI.create(req.getUri());
        ctx.channel().attr(KEY_PATH).set(uri.getPath());

        if (req.getMethod().equals(HttpMethod.GET)) {
            QueryStringDecoder decoder = new QueryStringDecoder(URI.create(req.getUri()));
            Map<String, List<String>> parameter = decoder.parameters();
            dispatch(ctx.channel(), parameter);
            return;
        }/*  ww  w . j  ava2  s . c  om*/

        decoder = new HttpPostRequestDecoder(factory, req);
    }

    if (decoder != null) {
        if (msg instanceof HttpContent) {
            HttpContent chunk = (HttpContent) msg;
            decoder.offer(chunk);

            List<InterfaceHttpData> list = decoder.getBodyHttpDatas();
            Map<String, List<String>> parameter = new HashMap<>();
            for (InterfaceHttpData data : list) {
                if (data.getHttpDataType() == HttpDataType.Attribute) {
                    Attribute attribute = (Attribute) data;
                    addParameter(attribute.getName(), attribute.getValue(), parameter);
                }
            }

            if (chunk instanceof LastHttpContent) {
                reset();
                dispatch(ctx.channel(), parameter);
            }
        }
    }
}

From source file:com.flysoloing.learning.network.netty.spdy.client.SpdyClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)
            .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.NPN,
                    // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                    SelectorFailureBehavior.NO_ADVERTISE,
                    // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                    SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.SPDY_3_1,
                    ApplicationProtocolNames.HTTP_1_1))
            .build();//from   w  ww . j a  v  a 2s.c o  m

    HttpResponseClientHandler httpResponseHandler = new HttpResponseClientHandler();
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.remoteAddress(HOST, PORT);
        b.handler(new SpdyClientInitializer(sslCtx, httpResponseHandler));

        // Start the client.
        Channel channel = b.connect().syncUninterruptibly().channel();
        System.out.println("Connected to " + HOST + ':' + PORT);

        // Create a GET request.
        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "");
        request.headers().set(HttpHeaderNames.HOST, HOST);
        request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);

        // Send the GET request.
        channel.writeAndFlush(request).sync();

        // Waits for the complete HTTP response
        httpResponseHandler.queue().take().sync();
        System.out.println("Finished SPDY HTTP GET");

        // Wait until the connection is closed.
        channel.close().syncUninterruptibly();
    } finally {
        workerGroup.shutdownGracefully();
    }
}

From source file:com.github.ambry.admin.AdminIntegrationTest.java

License:Open Source License

/**
 * Tests the {@link AdminBlobStorageService#ECHO} operation. Checks to see that the echo matches input text.
 * @throws ExecutionException//from ww  w .j  a v a  2s  .  com
 * @throws InterruptedException
 * @throws JSONException
 */
@Test
public void echoTest() throws ExecutionException, InterruptedException, JSONException {
    String inputText = "loremIpsum";
    String uri = AdminBlobStorageService.ECHO + "?" + EchoHandler.TEXT_KEY + "=" + inputText;
    FullHttpRequest httpRequest = buildRequest(HttpMethod.GET, uri, null, null);
    Queue<HttpObject> responseParts = nettyClient.sendRequest(httpRequest, null, null).get();
    HttpResponse response = (HttpResponse) responseParts.poll();
    assertEquals("Unexpected status", HttpResponseStatus.OK, response.getStatus());
    assertEquals("Unexpected Content-Type", "application/json",
            HttpHeaders.getHeader(response, HttpHeaders.Names.CONTENT_TYPE));
    ByteBuffer buffer = getContent(response, responseParts);
    String echoedText = new JSONObject(new String(buffer.array())).getString(EchoHandler.TEXT_KEY);
    assertEquals("Did not get expected response", inputText, echoedText);
}

From source file:com.github.ambry.admin.AdminIntegrationTest.java

License:Open Source License

/**
 * Tests the {@link AdminBlobStorageService#GET_REPLICAS_FOR_BLOB_ID} operation.
 * <p/>// w w w  . j a  va 2 s .c  o m
 * For a random {@link PartitionId} in the {@link ClusterMap}, a {@link BlobId} is created. The string representation
 * is sent to the server as a part of request. The returned replica list is checked for equality against a locally
 * obtained replica list.
 * @throws ExecutionException
 * @throws InterruptedException
 * @throws JSONException
 */
@Test
public void getReplicasForBlobIdTest() throws ExecutionException, InterruptedException, JSONException {
    List<PartitionId> partitionIds = CLUSTER_MAP.getWritablePartitionIds();
    PartitionId partitionId = partitionIds.get(new Random().nextInt(partitionIds.size()));
    String originalReplicaStr = partitionId.getReplicaIds().toString().replace(", ", ",");
    BlobId blobId = new BlobId(partitionId);
    String uri = AdminBlobStorageService.GET_REPLICAS_FOR_BLOB_ID + "?"
            + GetReplicasForBlobIdHandler.BLOB_ID_KEY + "=" + blobId;
    FullHttpRequest httpRequest = buildRequest(HttpMethod.GET, uri, null, null);
    Queue<HttpObject> responseParts = nettyClient.sendRequest(httpRequest, null, null).get();
    HttpResponse response = (HttpResponse) responseParts.poll();
    assertEquals("Unexpected status", HttpResponseStatus.OK, response.getStatus());
    assertEquals("Unexpected Content-Type", "application/json",
            HttpHeaders.getHeader(response, HttpHeaders.Names.CONTENT_TYPE));
    ByteBuffer buffer = getContent(response, responseParts);
    JSONObject responseObj = new JSONObject(new String(buffer.array()));
    String returnedReplicasStr = responseObj.getString(GetReplicasForBlobIdHandler.REPLICAS_KEY).replace("\"",
            "");
    assertEquals("Returned response for the BlobId do no match with the replicas IDs of partition",
            originalReplicaStr, returnedReplicasStr);
}

From source file:com.github.ambry.admin.AdminIntegrationTest.java

License:Open Source License

/**
 * Gets the blob with blob ID {@code blobId} and verifies that the headers and content match with what is expected.
 * @param blobId the blob ID of the blob to GET.
 * @param expectedHeaders the expected headers in the response.
 * @param expectedContent the expected content of the blob.
 * @throws ExecutionException//from www .  j a v a  2s  .  com
 * @throws InterruptedException
 */
private void getBlobAndVerify(String blobId, HttpHeaders expectedHeaders, ByteBuffer expectedContent)
        throws ExecutionException, InterruptedException {
    FullHttpRequest httpRequest = buildRequest(HttpMethod.GET, blobId, null, null);
    Queue<HttpObject> responseParts = nettyClient.sendRequest(httpRequest, null, null).get();
    HttpResponse response = (HttpResponse) responseParts.poll();
    assertEquals("Unexpected response status", HttpResponseStatus.OK, response.getStatus());
    checkCommonGetHeadHeaders(response.headers(), expectedHeaders);
    ByteBuffer responseContent = getContent(response, responseParts);
    assertArrayEquals("GET content does not match original content", expectedContent.array(),
            responseContent.array());
}

From source file:com.github.ambry.admin.AdminIntegrationTest.java

License:Open Source License

/**
 * Verifies that the right response code is returned for GET, HEAD and DELETE once a blob is deleted.
 * @param blobId the ID of the blob that was deleted.
 * @throws ExecutionException/*from w ww.  j  av a 2 s  .c  om*/
 * @throws InterruptedException
 */
private void verifyOperationsAfterDelete(String blobId) throws ExecutionException, InterruptedException {
    FullHttpRequest httpRequest = buildRequest(HttpMethod.GET, blobId, null, null);
    verifyDeleted(httpRequest, HttpResponseStatus.GONE);

    httpRequest = buildRequest(HttpMethod.HEAD, blobId, null, null);
    verifyDeleted(httpRequest, HttpResponseStatus.GONE);

    httpRequest = buildRequest(HttpMethod.DELETE, blobId, null, null);
    verifyDeleted(httpRequest, HttpResponseStatus.ACCEPTED);
}

From source file:com.github.ambry.frontend.FrontendIntegrationTest.java

License:Open Source License

@Test
public void healtCheckRequestTest() throws ExecutionException, InterruptedException, IOException {
    FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
            "/healthCheck", Unpooled.buffer(0));
    Queue<HttpObject> responseParts = nettyClient.sendRequest(httpRequest, null, null).get();
    HttpResponse response = (HttpResponse) responseParts.poll();
    assertEquals("Unexpected response status", HttpResponseStatus.OK, response.getStatus());
    ByteBuffer content = getContent(response, responseParts);
    assertEquals("GET content does not match original content", "GOOD", new String(content.array()));
}