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:io.selendroid.server.util.HttpClientUtil.java

License:Apache License

public static HttpResponse executeRequest(String url, HttpMethod method) throws Exception {
    HttpRequestBase request = null;/*from  w  ww .  ja v  a  2s  . c  o  m*/
    if (HttpMethod.GET.equals(method)) {
        request = new HttpGet(url);
    } else if (HttpMethod.POST.equals(method)) {
        request = new HttpPost(url);
    } else if (HttpMethod.DELETE.equals(method)) {
        request = new HttpDelete(url);
    } else {
        throw new RuntimeException("Provided HttpMethod not supported");
    }
    return getHttpClient().execute(request);
}

From source file:io.selendroid.server.util.HttpClientUtil.java

License:Apache License

public static boolean isServerStarted(int port) {
    HttpResponse response = null;//from  ww w  . ja v a 2s. co  m
    try {
        response = executeRequest("http://localhost:" + port + "/wd/hub/sessions", HttpMethod.GET);
    } catch (Exception e) {
        return false;
    }
    try {
        JSONObject result = parseJsonResponse(response);
        return result.getInt("status") == 0;
    } catch (Exception e) {
        return false;
    }
}

From source file:io.selendroid.standalone.server.handler.InspectorTreeHandler.java

License:Apache License

@Override
public Response handleRequest(HttpRequest request, JSONObject payload) throws JSONException {
    String sessionId = getSessionId(request);
    log.info("inspector tree handler, sessionId: " + sessionId);

    ActiveSession session;/*from   w w  w . j  ava  2  s .c  o  m*/
    if (sessionId == null || sessionId.isEmpty()) {
        if (getSelendroidDriver(request).getActiveSessions() != null
                && getSelendroidDriver(request).getActiveSessions().size() >= 1) {
            session = getSelendroidDriver(request).getActiveSessions().get(0);
            log.info("Selected sessionId: " + session.getSessionId());
        } else {
            return new UiResponse("",
                    "Selendroid inspector can only be used if there is an active test session running. "
                            + "To start a test session, add a break point into your test code and run the test in debug mode.");
        }
    } else {
        session = getActiveSession(request);
    }

    try {
        HttpResponse r = HttpClientUtil.executeRequest(
                "http://localhost:" + session.getSelendroidServerPort() + "/inspector/tree", HttpMethod.GET);
        return new JsResult(EntityUtils.toString(r.getEntity(), Charset.forName("UTF-8")));
    } catch (Exception e) {
        log.log(Level.SEVERE, "Cannot get element tree for inspector", e);
        throw new SelendroidException(e);
    }
}

From source file:io.selendroid.standalone.server.handler.ProxyToDeviceHandler.java

License:Apache License

private JSONObject proxyRequestToDevice(HttpRequest request, ActiveSession session, String url, String method)
        throws Exception {
    HttpResponse r;//from  w  w w.j  a v  a 2  s.co  m
    if ("get".equalsIgnoreCase(method)) {
        log.fine("Proxy GET to the device: " + url);
        r = HttpClientUtil.executeRequest(url, HttpMethod.GET);
    } else if ("post".equalsIgnoreCase(method)) {
        JSONObject payload = getPayload(request);
        log.fine("Proxy POST to the device: " + url + ", payload:\n" + payload);
        r = HttpClientUtil.executeRequestWithPayload(url, session.getSelendroidServerPort(), HttpMethod.POST,
                payload.toString());
    } else if ("delete".equalsIgnoreCase(method)) {
        log.fine("Proxy DELETE to the device: " + url);
        r = HttpClientUtil.executeRequest(url, HttpMethod.DELETE);
    } else {
        throw new SelendroidException("HTTP method not supported: " + method);
    }
    return HttpClientUtil.parseJsonResponse(r);
}

From source file:io.selendroid.standalone.server.util.HttpClientUtil.java

License:Apache License

public static HttpResponse executeRequest(String url, HttpMethod method) throws Exception {
    HttpRequestBase request;/*  w w w.j  av  a 2 s .  c o  m*/
    if (HttpMethod.GET.equals(method)) {
        request = new HttpGet(url);
    } else if (HttpMethod.POST.equals(method)) {
        request = new HttpPost(url);
    } else if (HttpMethod.DELETE.equals(method)) {
        request = new HttpDelete(url);
    } else {
        throw new RuntimeException("Provided HttpMethod not supported: " + method);
    }
    return getHttpClient().execute(request);
}

From source file:io.selendroid.standalone.server.util.HttpClientUtil.java

License:Apache License

public static boolean isServerStarted(int port) {
    HttpResponse response;//w  w  w .  j  av  a2  s.c  o  m
    try {
        response = executeRequest("http://localhost:" + port + "/wd/hub/sessions", HttpMethod.GET);
    } catch (Exception e) {
        return false;
    }
    try {
        JSONObject result = parseJsonResponse(response);
        return result.getInt("status") == 0;
    } catch (Exception e) {
        return false;
    }
}

From source file:io.syncframework.netty.RequestHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpRequest) {
        this.request = (HttpRequest) msg;

        ///*from  w w  w .ja v  a2 s.com*/
        // Verify application's domain. This is a common code to both static and dynamic request handlers... 
        // This may save CPU cycles if there is no domain responsible for the request.
        //
        domain = getDomain(request);
        application = ApplicationManager.getApplication(domain);
        if (application == null) {
            if (log.isTraceEnabled())
                log.trace("no application found responsible for domain: {}", domain);
            sendFileNotFound(ctx);
            return;
        }

        // check if GET or POST ... 
        // if GET it is possible that we may handle a static file request. 
        // In this case we don't need to create Request/Response wrappers objects...
        boolean isGET = this.request.method().equals(HttpMethod.GET);
        if (isGET) {
            boolean xsc = false;
            if (server.config().getTrustedProxyMode()) {
                xsc = this.request.headers().getAsString("X-SAS-Client") != null ? true : false;
            }
            if (log.isTraceEnabled())
                log.trace("Proxied request? {}", xsc);
            if (xsc) {
                // this point forward we translate the request into sas.Request...
                requestWrapper.setRequest(this.request);
                requestWrapper.getRequestContext().put(RequestContext.DOMAIN, domain);
                requestWrapper.getRequestContext().put(RequestContext.METHOD,
                        this.request.method().asciiName());
                requestWrapper.getRequestContext().put(RequestContext.URL, this.request.uri());
                requestWrapper.getRequestContext().put(RequestContext.REMOTE_ADDRESS,
                        this.request.headers().getAsString("X-SAS-Client"));

                if (handleRequestDynamically(ctx)) {
                    // no need to continue as the action has been taken by the application
                    return;
                }
            } else {
                if (handleRequestStatically(ctx)) {
                    // no need to continue as the static file has been served
                    return;
                }

                requestWrapper.setRequest(this.request);
                requestWrapper.getRequestContext().put(RequestContext.DOMAIN, domain);
                requestWrapper.getRequestContext().put(RequestContext.METHOD,
                        this.request.method().asciiName());
                requestWrapper.getRequestContext().put(RequestContext.URL, this.request.uri());
                // We already verified the X-SAS-Client header and it is not available...
                InetSocketAddress isa = (InetSocketAddress) ctx.channel().remoteAddress();
                requestWrapper.getRequestContext().put(RequestContext.REMOTE_ADDRESS, isa.getHostString());

                if (handleRequestDynamically(ctx)) {
                    // no need to continue as the page has been delivered
                    return;
                }
            }

            sendFileNotFound(ctx);
            return;
        }

        // treating POST requests...
        // posts may come with multiples reads... chunks or multipart...
        // utilize auxiliary requestWrapper.
        try {
            decoder = new HttpPostRequestDecoder(factory, request, HttpConstants.DEFAULT_CHARSET);
        } catch (ErrorDataDecoderException e1) {
            // e1.printStackTrace();
            log.error("failed to decode HTTP post request", e1);
            sendError(ctx, HttpResponseStatus.BAD_REQUEST);
            ctx.channel().close();
            return;
        }
    }

    if (decoder != null) {
        if (msg instanceof HttpContent) {
            HttpContent chunk = (HttpContent) msg;
            try {
                decoder.offer(chunk);
            } catch (Exception e) {
                log.error("failed to decode HTTP post request", e);
                sendError(ctx, HttpResponseStatus.BAD_REQUEST);
                ctx.channel().close();
                return;
            }

            try {
                readHttpDataChunkByChunk();
            } catch (Exception e) {
                sendException(ctx, e);
                return;
            }

            // example of reading only if at the end
            if (chunk instanceof LastHttpContent) {
                if (log.isTraceEnabled())
                    log.trace("last http request chunk identified; handling request...");

                // this point forward we translate the request into sas.Request...
                requestWrapper.setRequest(this.request);
                requestWrapper.getRequestContext().put(RequestContext.DOMAIN, domain);
                requestWrapper.getRequestContext().put(RequestContext.METHOD,
                        this.request.method().asciiName());
                requestWrapper.getRequestContext().put(RequestContext.URL, this.request.uri());

                boolean xsc = false;
                if (server.config().getTrustedProxyMode()) {
                    xsc = this.request.headers().getAsString("X-SAS-Client") != null ? true : false;
                }
                if (log.isTraceEnabled())
                    log.trace("Proxied request? {}", xsc);
                if (xsc) {
                    requestWrapper.getRequestContext().put(RequestContext.REMOTE_ADDRESS,
                            this.request.headers().getAsString("X-SAS-Client"));
                } else {
                    InetSocketAddress isa = (InetSocketAddress) ctx.channel().remoteAddress();
                    requestWrapper.getRequestContext().put(RequestContext.REMOTE_ADDRESS, isa.getHostString());
                }
                if (handleRequestDynamically(ctx)) {
                    // no need to continue as the action has been taken by the application
                    return;
                }
                sendFileNotFound(ctx);
                return;
            }
        }
    } else {
        sendFileNotFound(ctx);
        return;
    }
}

From source file:io.undertow.server.protocol.http2.HTTP2ViaUpgradeTestCase.java

License:Open Source License

@Test
public void testHttp2WithNettyClient() throws Exception {

    message = "Hello World";

    EventLoopGroup workerGroup = new NioEventLoopGroup();
    Http2ClientInitializer initializer = new Http2ClientInitializer(Integer.MAX_VALUE);

    try {/*  w w  w  .  j a va 2  s  .c  o  m*/
        // Configure the client.
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        final int port = DefaultServer.getHostPort("default") + 1;
        final String host = DefaultServer.getHostAddress("default");
        b.remoteAddress(host, port);
        b.handler(initializer);

        // Start the client.

        Channel channel = b.connect().syncUninterruptibly().channel();

        Http2SettingsHandler http2SettingsHandler = initializer.settingsHandler();
        http2SettingsHandler.awaitSettings(5, TimeUnit.SECONDS);
        HttpResponseHandler responseHandler = initializer.responseHandler();
        int streamId = 3;
        URI hostName = URI.create("http://" + host + ':' + port);
        System.err.println("Sending request(s)...");
        // Create a simple GET request.
        final ChannelPromise promise = channel.newPromise();
        responseHandler.put(streamId, promise);
        FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
                hostName.toString());
        request.headers().add(HttpHeaderNames.HOST, hostName);
        request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
        request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
        channel.writeAndFlush(request);
        streamId += 2;
        promise.await(10, TimeUnit.SECONDS);
        Assert.assertEquals(message, messages.poll());
        System.out.println("Finished HTTP/2 request(s)");

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

From source file:io.urmia.api.handler.RestApiHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

    if (msg instanceof HttpRequest) {

        if (requestState != RequestState.EXPECT_REQUEST) {
            sendError(ctx, ERROR_BAD_REQUEST);
            return;
        }//from   w w  w  .j a  v a 2s  .co m

        request = (HttpRequest) msg;

        log.info("received HttpRequest: {} {}", request.getMethod(), request.getUri());

        final ObjectRequest r;

        try {
            r = new ObjectRequest(request);
        } catch (ExceptionInInitializerError e) {
            log.warn("unable to parse the request into a command: {}", request.getUri());
            return;
        }

        objectRequest = r;
        httpRequest = request;

        if (HttpMethod.PUT.equals(request.getMethod())) {
            if (objectRequest.isNotDirectory()) // make dir request
                setupProxyToPUT(ctx, objectRequest);

            requestState = RequestState.EXPECT_CONTENT_OR_LAST;
        } else {
            requestState = RequestState.EXPECT_LAST;
            ctx.read();
        }

        return;
    }

    if (objectRequest == null) {
        String uri = request == null ? "" : request.getUri();
        log.warn("not expecting an empty objectRequest. parse error maybe: {}", uri);
        ByteBuf body = request == null || request.getMethod().equals(HttpMethod.HEAD) ? null
                : errorBody("ResourceNotFoundError", uri + " does not exist");
        sendError(ctx, HttpResponseStatus.NOT_FOUND, body);
        return;
    }

    if (msg instanceof HttpContent) {

        if (requestState != RequestState.EXPECT_LAST && requestState != RequestState.EXPECT_CONTENT_OR_LAST) {
            log.warn("not expecting LAST or CONTENT, requestState: {}", requestState);
            sendError(ctx, HttpResponseStatus.NOT_EXTENDED);
            return;
        }

        final boolean last = msg instanceof LastHttpContent;
        final boolean emptyLast = last && msg == LastHttpContent.EMPTY_LAST_CONTENT;

        if (proxyMode && !emptyLast) // todo: the emptyLast was added for mln
            ctx.fireChannelRead(msg);

        // example of reading only if at the end
        if (last) {

            log.debug("received LastHttpContent: {}", msg);
            requestState = RequestState.EXPECT_REQUEST;

            final HttpRequest request = httpRequest;

            if (HttpMethod.HEAD.equals(request.getMethod())) {
                handleHEAD(ctx, objectRequest);
                return;
            }

            if (HttpMethod.GET.equals(request.getMethod())) {
                handleGET(ctx, objectRequest);
                return;
            }

            if (HttpMethod.DELETE.equals(request.getMethod())) {
                handleDELETE(ctx, objectRequest);
                return;
            }

            if (HttpMethod.PUT.equals(request.getMethod())) {
                if (proxyMode)
                    log.info("finished file upload: {}", objectRequest);
                else
                    handlePUTmkdir(ctx, objectRequest);
                return;
            }

            log.warn("unknown request: {}", request);
            sendError(ctx, HttpResponseStatus.BAD_REQUEST);
        }

        return;
    }

    log.warn("unexpected msg type: {}", msg);
    sendError(ctx, HttpResponseStatus.BAD_REQUEST);
}

From source file:io.urmia.job.codec.JobDecoder.java

License:Open Source License

JobRequest decode(FullHttpRequest fullHttpRequest) {

    final String uri = fullHttpRequest.getUri();
    final HttpMethod method = fullHttpRequest.getMethod();

    if (HttpMethod.GET.equals(method)) {
        if (isGet(uri))
            return new JobGetRequest(fullHttpRequest);

        return new JobQueryRequest(fullHttpRequest);
    }/*from   w w  w .ja v a 2  s  .  com*/

    if (HttpMethod.POST.equals(method)) {
        if (isInput(uri))
            return new JobInputRequest(fullHttpRequest);

        if (isCancel(uri))
            return new JobCancelRequest(fullHttpRequest);

        return new JobCreateRequest(fullHttpRequest);
    }

    throw new IllegalArgumentException("unknown job request: " + method + " " + uri);
}