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:org.graylog2.inputs.transports.netty.HttpHandlerTest.java

License:Open Source License

@Test
public void messageReceivedReturns405ForInvalidMethod() {
    final HttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
    httpRequest.headers().add(HttpHeaderNames.HOST, "localhost");
    httpRequest.headers().add(HttpHeaderNames.ORIGIN, "http://example.com");
    httpRequest.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);

    channel.writeInbound(httpRequest);//from  w w  w.j ava 2s .  co m
    channel.finish();

    final HttpResponse httpResponse = channel.readOutbound();
    assertThat(httpResponse.status()).isEqualTo(HttpResponseStatus.METHOD_NOT_ALLOWED);
    final HttpHeaders headers = httpResponse.headers();
    assertThat(headers.get(HttpHeaderNames.CONTENT_LENGTH)).isEqualTo("0");
    assertThat(headers.get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("http://example.com");
    assertThat(headers.get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS)).isEqualTo("true");
    assertThat(headers.get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS))
            .isEqualTo("Authorization, Content-Type");
}

From source file:org.hornetq.core.remoting.impl.netty.NettyConnector.java

License:Apache License

public Connection createConnection() {
    if (channelClazz == null) {
        return null;
    }//w  w w.  j a  va  2 s  . c o  m

    // HORNETQ-907 - strip off IPv6 scope-id (if necessary)
    SocketAddress remoteDestination = new InetSocketAddress(host, port);
    InetAddress inetAddress = ((InetSocketAddress) remoteDestination).getAddress();
    if (inetAddress instanceof Inet6Address) {
        Inet6Address inet6Address = (Inet6Address) inetAddress;
        if (inet6Address.getScopeId() != 0) {
            try {
                remoteDestination = new InetSocketAddress(InetAddress.getByAddress(inet6Address.getAddress()),
                        ((InetSocketAddress) remoteDestination).getPort());
            } catch (UnknownHostException e) {
                throw new IllegalArgumentException(e.getMessage());
            }
        }
    }

    HornetQClientLogger.LOGGER.debug("Remote destination: " + remoteDestination);

    ChannelFuture future;
    //port 0 does not work so only use local address if set
    if (localPort != 0) {
        SocketAddress localDestination;
        if (localAddress != null) {
            localDestination = new InetSocketAddress(localAddress, localPort);
        } else {
            localDestination = new InetSocketAddress(localPort);
        }
        future = bootstrap.connect(remoteDestination, localDestination);
    } else {
        future = bootstrap.connect(remoteDestination);
    }

    future.awaitUninterruptibly();

    if (future.isSuccess()) {
        final Channel ch = future.channel();
        SslHandler sslHandler = ch.pipeline().get(SslHandler.class);
        if (sslHandler != null) {
            Future<Channel> handshakeFuture = sslHandler.handshakeFuture();
            if (handshakeFuture.awaitUninterruptibly(30000)) {
                if (handshakeFuture.isSuccess()) {
                    ChannelPipeline channelPipeline = ch.pipeline();
                    HornetQChannelHandler channelHandler = channelPipeline.get(HornetQChannelHandler.class);
                    channelHandler.active = true;
                } else {
                    ch.close().awaitUninterruptibly();
                    HornetQClientLogger.LOGGER.errorCreatingNettyConnection(handshakeFuture.cause());
                    return null;
                }
            } else {
                //handshakeFuture.setFailure(new SSLException("Handshake was not completed in 30 seconds"));
                ch.close().awaitUninterruptibly();
                return null;
            }

        }
        if (httpUpgradeEnabled) {
            // Send a HTTP GET + Upgrade request that will be handled by the http-upgrade handler.
            try {
                //get this first incase it removes itself
                HttpUpgradeHandler httpUpgradeHandler = (HttpUpgradeHandler) ch.pipeline().get("http-upgrade");
                URI uri = new URI("http", null, host, port, null, null, null);
                HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
                        uri.getRawPath());
                request.headers().set(HttpHeaders.Names.HOST, host);
                request.headers().set(HttpHeaders.Names.UPGRADE, HORNETQ_REMOTING);
                request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE);

                final String endpoint = ConfigurationHelper.getStringProperty(
                        TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, null, configuration);
                if (endpoint != null) {
                    request.headers().set(TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, endpoint);
                }

                // Get 16 bit nonce and base 64 encode it
                byte[] nonce = randomBytes(16);
                String key = base64(nonce);
                request.headers().set(SEC_HORNETQ_REMOTING_KEY, key);
                ch.attr(REMOTING_KEY).set(key);

                HornetQClientLogger.LOGGER.debugf("Sending HTTP request %s", request);

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

                if (!httpUpgradeHandler.awaitHandshake()) {
                    return null;
                }
            } catch (URISyntaxException e) {
                HornetQClientLogger.LOGGER.errorCreatingNettyConnection(e);
                return null;
            }
        } else {
            ChannelPipeline channelPipeline = ch.pipeline();
            HornetQChannelHandler channelHandler = channelPipeline.get(HornetQChannelHandler.class);
            channelHandler.active = true;
        }

        // No acceptor on a client connection
        Listener connectionListener = new Listener();
        NettyConnection conn = new NettyConnection(configuration, ch, connectionListener,
                !httpEnabled && batchDelay > 0, false);
        connectionListener.connectionCreated(null, conn, HornetQClient.DEFAULT_CORE_PROTOCOL);
        return conn;
    } else {
        Throwable t = future.cause();

        if (t != null && !(t instanceof ConnectException)) {
            HornetQClientLogger.LOGGER.errorCreatingNettyConnection(future.cause());
        }

        return null;
    }
}

From source file:org.icgc.dcc.storage.test.s3.S3Request.java

License:Open Source License

public boolean isGet() {
    return ctx.getRequest().getMethod() == HttpMethod.GET;
}

From source file:org.iotivity.cloud.base.HttpClient.java

License:Open Source License

public void connect(String strUrl) throws URISyntaxException, InterruptedException, SSLException {
    URI uri = new URI(strUrl);

    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;//from  www  . ja va  2  s.  com
        } else if ("https".equalsIgnoreCase(scheme)) {
            port = 443;
        }
    }

    if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
        return;
    }

    final boolean ssl = "https".equalsIgnoreCase(scheme);
    final SslContext sslCtx;

    if (ssl) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup group = new NioEventLoopGroup();

    try {
        Bootstrap b = new Bootstrap();
        b.group(group);
        b.channel(NioSocketChannel.class);
        b.handler(new HttpClientInitializer(sslCtx));

        Channel ch = b.connect(host, port).sync().channel();

        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
                uri.getRawPath());
        request.headers().set(HttpHeaders.Names.HOST, host);
        request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
        request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);

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

        ch.writeAndFlush(request);

        ch.closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}

From source file:org.iotivity.cloud.base.protocols.http.HCProxyProcessor.java

License:Open Source License

/**
 * This function returns a message created by the request,
 * which implements IRequest(used in the cloud)
 * translated from the HTTP request./*  w w w.  java  2s .  com*/
 * 
 * @return requestMessage
 */
public Message getRequestMessage() {

    Message requestMessage = null;

    String coapUriPath = mTargetCoapPath;
    String coapUriQuery = mTargetCoapQuery;
    ContentFormat coapContentFormat = null;
    if (mContentFormat != null) {
        if (mContentFormat.equalsIgnoreCase(APPLICATION_CBOR)) {
            coapContentFormat = ContentFormat.APPLICATION_CBOR;
        }
    }
    byte[] coapPayload = mCborContent;

    if (mHttpMethod == HttpMethod.POST) {

        CoapRequest coapRequest = new CoapRequest(RequestMethod.POST);
        coapRequest.setToken(createToken());
        coapRequest.setUriPath(coapUriPath);
        if (coapUriQuery != null) {
            coapRequest.setUriQuery(coapUriQuery);
        }
        if (coapPayload != null) {
            coapRequest.setContentFormat(coapContentFormat);
            coapRequest.setPayload(coapPayload);
        }
        requestMessage = coapRequest;

    } else if (mHttpMethod == HttpMethod.PUT) {

        CoapRequest coapRequest = new CoapRequest(RequestMethod.PUT);
        coapRequest.setToken(createToken());
        coapRequest.setUriPath(coapUriPath);
        if (coapUriQuery != null) {
            coapRequest.setUriQuery(coapUriQuery);
        }
        if (coapPayload != null) {
            coapRequest.setContentFormat(coapContentFormat);
            coapRequest.setPayload(coapPayload);
        }
        requestMessage = coapRequest;

    } else if (mHttpMethod == HttpMethod.GET) {

        CoapRequest coapRequest = new CoapRequest(RequestMethod.GET);
        coapRequest.setToken(createToken());
        coapRequest.setUriPath(coapUriPath);
        if (coapUriQuery != null) {
            coapRequest.setUriQuery(coapUriQuery);
        }
        requestMessage = coapRequest;

    } else if (mHttpMethod == HttpMethod.DELETE) {

        CoapRequest coapRequest = new CoapRequest(RequestMethod.DELETE);
        coapRequest.setToken(createToken());
        coapRequest.setUriPath(coapUriPath);
        if (coapUriQuery != null) {
            coapRequest.setUriQuery(coapUriQuery);
        }
        requestMessage = coapRequest;
    }

    return requestMessage;
}

From source file:org.iotivity.cloud.base.protocols.proxy.CoapHttpProxyHandler.java

License:Open Source License

CoapRequest httpRequestToCoAPRequest(String uri, HttpRequest httpRequest) {
    CoapRequest coapRequest;//w w  w  .ja v  a  2  s.  c o  m

    // TODO: coapRequest converter required
    // coapRequest.getOptions().setUriQuery();
    if (httpRequest.getMethod() == HttpMethod.GET) {
        coapRequest = new CoapRequest(CoapMethod.GET);
    } else if (httpRequest.getMethod() == HttpMethod.PUT) {
        coapRequest = new CoapRequest(CoapMethod.PUT);
    } else if (httpRequest.getMethod() == HttpMethod.POST) {
        coapRequest = new CoapRequest(CoapMethod.POST);
    } else if (httpRequest.getMethod() == HttpMethod.DELETE) {
        coapRequest = new CoapRequest(CoapMethod.DELETE);
    } else {
        throw new IllegalArgumentException();
    }

    coapRequest.setUriPath(uri);

    return coapRequest;
}

From source file:org.janusgraph.graphdb.tinkerpop.gremlin.server.handler.HttpHMACAuthenticationHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
    if (msg instanceof FullHttpRequest) {
        final FullHttpRequest req = (FullHttpRequest) msg;
        final HttpMethod method = req.getMethod();
        final Map<String, String> credentialsMap = getCredentialsMap(ctx, req);
        if (credentialsMap == null) {
            sendError(ctx, msg);//from   www .  j  a v a2s. c  o  m
            return;
        }
        if ("/session".equals(req.getUri()) && method.equals(HttpMethod.GET)) {
            try {
                credentialsMap.put(PROPERTY_GENERATE_TOKEN, "true");
                authenticator.authenticate(credentialsMap);
            } catch (Exception e) {
                sendError(ctx, msg);
                return;
            }
            replyWithToken(ctx, msg, credentialsMap.get(PROPERTY_TOKEN));
        } else {
            try {
                authenticator.authenticate(credentialsMap);
                ctx.fireChannelRead(req);
            } catch (Exception e) {
                sendError(ctx, msg);
                return;
            }
        }
    }
}

From source file:org.janusgraph.graphdb.tinkerpop.gremlin.server.handler.HttpHMACAuthenticationHandlerTest.java

License:Apache License

@Test
public void testChannelReadGetAuthToken() throws Exception {
    final ChannelHandlerContext ctx = createMock(ChannelHandlerContext.class);
    final FullHttpRequest msg = createMock(FullHttpRequest.class);
    final HttpHeaders headers = createMock(HttpHeaders.class);
    final Authenticator authenticator = createMock(Authenticator.class);
    final ChannelFuture cf = createMock(ChannelFuture.class);
    final String encodedUserNameAndPass = Base64.getEncoder().encodeToString("user:pass".getBytes());
    final Capture<Map<String, String>> credMap = EasyMock.newCapture(CaptureType.ALL);
    expect(msg.getMethod()).andReturn(HttpMethod.GET);
    expect(msg.headers()).andReturn(headers).anyTimes();
    expect(msg.getUri()).andReturn("/session");
    expect(headers.get(eq("Authorization"))).andReturn("Basic " + encodedUserNameAndPass);
    expect(authenticator.authenticate(and(isA(Map.class), capture(credMap))))
            .andReturn(new AuthenticatedUser("foo"));
    expect(ctx.writeAndFlush(eqHttpStatus(OK))).andReturn(cf);
    expect(cf.addListener(ChannelFutureListener.CLOSE)).andReturn(null);
    expect(msg.release()).andReturn(false);
    final HttpHMACAuthenticationHandler handler = new HttpHMACAuthenticationHandler(authenticator);
    replayAll();/*w w w  .  jav a  2s  . co  m*/
    handler.channelRead(ctx, (Object) msg);
    verifyAll();
    assertNotNull(credMap.getValue().get(HttpHMACAuthenticationHandler.PROPERTY_GENERATE_TOKEN));
}

From source file:org.janusgraph.graphdb.tinkerpop.gremlin.server.handler.HttpHMACAuthenticationHandlerTest.java

License:Apache License

@Test
public void testChannelReadTokenAuth() throws Exception {
    final ChannelHandlerContext ctx = createMock(ChannelHandlerContext.class);
    final FullHttpRequest msg = createMock(FullHttpRequest.class);
    final HttpHeaders headers = createMock(HttpHeaders.class);
    final Authenticator authenticator = createMock(Authenticator.class);
    final String encodedToken = Base64.getEncoder().encodeToString("askdjhf823asdlkfsasd".getBytes());
    expect(msg.getMethod()).andReturn(HttpMethod.GET);
    expect(msg.headers()).andReturn(headers).anyTimes();
    expect(msg.getUri()).andReturn("/");
    expect(headers.get(eq("Authorization"))).andReturn("Token " + encodedToken);
    expect(ctx.fireChannelRead(isA(FullHttpRequest.class))).andReturn(ctx);
    expect(authenticator.authenticate(isA(Map.class))).andReturn(new AuthenticatedUser("foo"));
    final HttpHMACAuthenticationHandler handler = new HttpHMACAuthenticationHandler(authenticator);
    replayAll();/*from  ww  w.  j a v  a2  s  .c  o m*/
    handler.channelRead(ctx, (Object) msg);
    verifyAll();
}

From source file:org.jboss.aerogear.simplepush.server.netty.SimplePushSockJSServiceTest.java

License:Apache License

private FullHttpRequest httpGetRequest(final String path) {
    return new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path);
}