Example usage for io.netty.handler.codec.http HttpRequest setUri

List of usage examples for io.netty.handler.codec.http HttpRequest setUri

Introduction

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

Prototype

HttpRequest setUri(String uri);

Source Link

Document

Set the requested URI (or alternatively, path)

Usage

From source file:com.digisky.innerproxy.testclient.HttpSnoopClient.java

License:Apache License

public static void test(Channel ch, String uri, String sjson) {
    HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
    request.headers().set(HttpHeaders.Names.HOST, "127.0.0.1");
    request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
    request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);

    request.setMethod(HttpMethod.POST);//from w  w w . j ava  2  s . c  o m
    request.setUri("/" + uri);
    HttpPostRequestEncoder bodyRequestEncoder = null;
    try {
        bodyRequestEncoder = new HttpPostRequestEncoder(request, false);
    } catch (ErrorDataEncoderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } // false => not multipart
      //***********************************************************************
    try {
        bodyRequestEncoder.addBodyAttribute("val", sjson);
    } catch (ErrorDataEncoderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //***********************************************************************
    try {
        request = bodyRequestEncoder.finalizeRequest();
    } catch (ErrorDataEncoderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    ch.writeAndFlush(request);
    try {
        ch.closeFuture().sync();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.digisky.outerproxy.testclient.HttpSnoopClient.java

License:Apache License

public static void testWithEncode(Channel ch, String uri, String sjson) {
    HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
    request.headers().set(HttpHeaders.Names.HOST, "127.0.0.1");
    request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
    request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);

    request.setMethod(HttpMethod.POST);//from   w ww  . ja  v  a 2 s  .c  o m
    request.setUri("/" + uri);
    HttpPostRequestEncoder bodyRequestEncoder = null;
    try {
        bodyRequestEncoder = new HttpPostRequestEncoder(request, false);
    } catch (ErrorDataEncoderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } // false => not multipart
      //***********************************************************************
    ByteBuf b = Unpooled.buffer();
    b.writeBytes("{}".getBytes());
    try {
        bodyRequestEncoder.addBodyAttribute("val", sjson);
    } catch (ErrorDataEncoderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //***********************************************************************
    try {
        request = bodyRequestEncoder.finalizeRequest();
    } catch (ErrorDataEncoderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    ch.writeAndFlush(request);
    try {
        ch.closeFuture().sync();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.litgh.RouterTest.java

License:Open Source License

public void testRouterAPI() {
    Router router = new Router();
    final Map<String, Boolean> test = new HashMap<String, Boolean>();

    router.GET("/GET", new Handler() {
        public void handle(HttpRequest req, FullHttpResponse resp, List<Param> params) {
            test.put("GET", true);
        }//from  ww  w. j ava  2  s . co  m
    });

    router.POST("/POST", new Handler() {
        public void handle(HttpRequest req, FullHttpResponse resp, List<Param> params) {
            test.put("POST", true);
        }
    });

    router.PUT("/PUT", new Handler() {
        public void handle(HttpRequest req, FullHttpResponse resp, List<Param> params) {
            test.put("PUT", true);
        }
    });

    router.DELETE("/DELETE", new Handler() {
        public void handle(HttpRequest req, FullHttpResponse resp, List<Param> params) {
            test.put("DELETE", true);
        }
    });

    router.HEAD("/HEAD", new Handler() {
        public void handle(HttpRequest req, FullHttpResponse resp, List<Param> params) {
            test.put("HEAD", true);
        }
    });

    router.PATCH("/PATCH", new Handler() {
        public void handle(HttpRequest req, FullHttpResponse resp, List<Param> params) {
            test.put("PATCH", true);
        }
    });

    HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/GET");
    FullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    router.serverHttp(req, resp);

    req.setMethod(HttpMethod.POST);
    req.setUri("/POST");
    router.serverHttp(req, resp);

    req.setMethod(HttpMethod.PUT);
    req.setUri("/PUT");
    router.serverHttp(req, resp);

    req.setMethod(HttpMethod.DELETE);
    req.setUri("/DELETE");
    router.serverHttp(req, resp);

    req.setMethod(HttpMethod.HEAD);
    req.setUri("/HEAD");
    router.serverHttp(req, resp);

    req.setMethod(HttpMethod.PATCH);
    req.setUri("/PATCH");
    router.serverHttp(req, resp);

    assertEquals("routing GET failed", Boolean.TRUE, test.get("GET"));
    assertEquals("routing POST failed", Boolean.TRUE, test.get("POST"));
    assertEquals("routing PUT failed", Boolean.TRUE, test.get("PUT"));
    assertEquals("routing DELETE failed", Boolean.TRUE, test.get("DELETE"));
    assertEquals("routing HEAD failed", Boolean.TRUE, test.get("HEAD"));
    assertEquals("routing PATCH failed", Boolean.TRUE, test.get("PATCH"));
}

From source file:com.mastfrog.netty.http.client.HttpClient.java

License:Open Source License

private void submit(final URL url, HttpRequest rq, final AtomicBoolean cancelled, final ResponseFuture handle,
        final ResponseHandler<?> r, RequestInfo info, Duration timeout, boolean noAggregate) {
    if (info != null && info.isExpired()) {
        cancelled.set(true);//from  w  w  w. ja va2  s. c om
    }
    if (cancelled.get()) {
        handle.event(new State.Cancelled());
        return;
    }
    try {
        for (RequestInterceptor i : interceptors) {
            rq = i.intercept(rq);
        }
        final HttpRequest req = rq;
        Bootstrap bootstrap;
        if (url.getProtocol().isSecure()) {
            bootstrap = startSsl(url.getHostAndPort());
        } else {
            bootstrap = start(url.getHostAndPort());
        }
        if (!url.isValid()) {
            throw new IllegalArgumentException(url.getProblems() + "");
        }
        TimeoutTimerTask tt = null;
        if (info == null) {
            info = new RequestInfo(url, req, cancelled, handle, r, timeout, tt, noAggregate);
            if (timeout != null) {
                tt = new TimeoutTimerTask(cancelled, handle, r, info);
                timer.schedule(tt, timeout.getMillis());
            }
            info.timer = tt;
        }
        if (info.isExpired()) {
            handle.event(new State.Timeout(info.age()));
            return;
        }
        handle.event(new State.Connecting());
        //XXX who is escaping this?
        req.setUri(req.getUri().replaceAll("%5f", "_"));
        ChannelFuture fut = bootstrap.connect(url.getHost().toString(), url.getPort().intValue());
        if (tt != null) {
            fut.channel().closeFuture().addListener(tt);
        }
        fut.channel().attr(KEY).set(info);
        handle.setFuture(fut);
        if (!monitors.isEmpty()) {
            for (ActivityMonitor m : monitors) {
                m.onStartRequest(url);
            }
            fut.channel().closeFuture().addListener(new AdapterCloseNotifier(url));
        }

        fut.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    Throwable cause = future.cause();
                    if (cause == null) {
                        cause = new ConnectException(url.getHost().toString());
                    }
                    handle.event(new State.Error(cause));
                    if (r != null) {
                        r.onError(cause);
                    }
                    cancelled.set(true);
                }
                if (cancelled.get()) {
                    future.cancel(true);
                    if (future.channel().isOpen()) {
                        future.channel().close();
                    }
                    for (ActivityMonitor m : monitors) {
                        m.onEndRequest(url);
                    }
                    return;
                }
                handle.event(new State.Connected(future.channel()));
                handle.event(new State.SendRequest(req));
                future = future.channel().writeAndFlush(req);
                future.addListener(new ChannelFutureListener() {

                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (cancelled.get()) {
                            future.cancel(true);
                            future.channel().close();
                        }
                        handle.event(new State.AwaitingResponse());
                    }

                });
            }

        });
    } catch (Exception ex) {
        Exceptions.chuck(ex);
    }
}

From source file:io.reactivex.netty.protocol.http.client.DefaultRedirectHandler.java

License:Apache License

protected HttpClientRequest<I> createRedirectRequest(HttpClientRequest<I> original, URI redirectLocation,
        int redirectStatus) {
    HttpRequest nettyRequest = original.getNettyRequest();
    nettyRequest.setUri(getNettyRequestUri(redirectLocation));

    HttpClientRequest<I> newRequest = new HttpClientRequest<I>(nettyRequest, original);

    if (redirectStatus == 303) {
        // according to HTTP spec, 303 mandates the change of request type to GET
        nettyRequest.setMethod(HttpMethod.GET);
        // If it is a get, then the content is not to be sent.
        newRequest.removeContent();/* w  ww  . ja va 2 s .  com*/
    }
    return newRequest;
}

From source file:io.reactivex.netty.protocol.http.client.FollowRedirectHttpClientImpl.java

License:Apache License

private static <I> HttpClientRequest<I> createRedirectRequest(HttpClientRequest<I> original, String newURI,
        int statusCode) {
    HttpRequest nettyRequest = original.getNettyRequest();
    nettyRequest.setUri(newURI);
    if (statusCode == 303) {
        // according to HTTP spec, 303 mandates the change of request type to GET
        nettyRequest.setMethod(HttpMethod.GET);
    }//from ww w . j  a  va2 s  . c o  m
    HttpClientRequest<I> newRequest = new HttpClientRequest<I>(nettyRequest);
    if (statusCode != 303) {
        // if status code is 303, we can just leave the content factory to be null
        newRequest.contentFactory = original.contentFactory;
        newRequest.rawContentFactory = original.rawContentFactory;
    }
    return newRequest;
}

From source file:org.jboss.aerogear.unifiedpush.test.sender.ProxySetup.java

License:Apache License

public void startProxyServer() {
    if (backgroundThread == null) {
        backgroundThread = startBackgroundThread();
    }// w ww . jav a2 s.  c  o  m

    apnsServerSimulator = ApnsServerSimulator.prepareAndStart(CertificateLoader.apnsSocketFactory(),
            APNS_MOCK_GATEWAY_HOST.resolve(), APNS_MOCK_GATEWAY_PORT.resolve(),
            APNS_MOCK_FEEDBACK_HOST.resolve(), APNS_MOCK_FEEDBACK_PORT.resolve());

    server = DefaultHttpProxyServer.bootstrap().withAddress(resolveBindAddress())
            .withFiltersSource(new HttpFiltersSourceAdapter() {

                @Override
                public HttpFilters filterRequest(HttpRequest originalRequest) {

                    return new HttpFiltersAdapter(originalRequest) {

                        @Override
                        public HttpResponse clientToProxyRequest(HttpObject httpObject) {

                            HttpRequest request = (HttpRequest) httpObject;

                            logger.log(Level.WARNING, "clientToProxyRequest uri: " + request.getUri());
                            if (request.getUri().contains("google")) {
                                logger.log(Level.WARNING, "contains google!: " + request.getUri());
                                request.setUri(backgroundThread.getGcmMockServerHost() + ":"
                                        + backgroundThread.getGcmMockServePort());
                            }
                            logger.log(Level.WARNING, "clientToProxyRequest after if uri: " + request.getUri());

                            super.clientToProxyRequest(request);

                            return null;
                        }

                        @Override
                        public HttpResponse proxyToServerRequest(HttpObject httpObject) {
                            return null;
                        }

                        @Override
                        public HttpObject serverToProxyResponse(HttpObject httpObject) {

                            if (httpObject instanceof HttpResponse) {
                                originalRequest.getMethod();
                            } else if (httpObject instanceof HttpContent) {
                                ((HttpContent) httpObject).content().toString(Charset.forName("UTF-8"));
                            }

                            return httpObject;
                        }

                        @Override
                        public HttpObject proxyToClientResponse(HttpObject httpObject) {

                            if (httpObject instanceof HttpResponse) {
                                originalRequest.getMethod();
                            } else if (httpObject instanceof HttpContent) {
                                ((HttpContent) httpObject).content().toString(Charset.forName("UTF-8"));
                            }

                            return httpObject;
                        }
                    };
                }
            }).start();

    logger.log(Level.INFO, "Proxy server started.");
}

From source file:org.wso2.carbon.mss.internal.router.HttpResourceHandler.java

License:Open Source License

/**
 * Call the appropriate handler for handling the httprequest. 404 if path is not found. 405 if path is found but
 * httpMethod does not match what's configured.
 *
 * @param request   instance of {@code HttpRequest}
 * @param responder instance of {@code HttpResponder} to handle the request.
 * @return HttpMethodInfo object, null if urlRewriter rewrite returns false, also when method cannot be invoked.
 * @throws HandlerException If URL rewriting fails
 *//*from w w w . ja  va  2  s .c  o  m*/
public HttpMethodInfoBuilder getDestinationMethod(HttpRequest request, HttpResponder responder)
        throws HandlerException {
    if (urlRewriter != null) {
        try {
            request.setUri(URI.create(request.getUri()).normalize().toString());
            if (!urlRewriter.rewrite(request, responder)) {
                return null;
            }
        } catch (Throwable t) {
            log.error("Exception thrown during rewriting of uri {}", request.getUri(), t);
            throw new HandlerException(HttpResponseStatus.INTERNAL_SERVER_ERROR,
                    String.format("Caught exception processing request. Reason: %s", t.getMessage()));
        }
    }

    String acceptHeaderStr = request.headers().get(HttpHeaders.Names.ACCEPT);
    List<String> acceptHeader = (acceptHeaderStr != null)
            ? Arrays.asList(acceptHeaderStr.split("\\s*,\\s*")).stream()
                    .map(mediaType -> mediaType.split("\\s*;\\s*")[0]).collect(Collectors.toList())
            : null;

    String contentTypeHeaderStr = request.headers().get(HttpHeaders.Names.CONTENT_TYPE);
    //Trim specified charset since UTF-8 is assumed
    String contentTypeHeader = (contentTypeHeaderStr != null) ? contentTypeHeaderStr.split("\\s*;\\s*")[0]
            : null;

    try {
        String path = URI.create(request.getUri()).normalize().getPath();

        List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>> routableDestinations = patternRouter
                .getDestinations(path);

        List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>> matchedDestinations = getMatchedDestination(
                routableDestinations, request.getMethod(), path);

        if (!matchedDestinations.isEmpty()) {
            PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel> matchedDestination = matchedDestinations
                    .stream().filter(matchedDestination1 -> {
                        return matchedDestination1.getDestination().matchConsumeMediaType(contentTypeHeader)
                                && matchedDestination1.getDestination().matchProduceMediaType(acceptHeader);
                    }).findFirst().get();
            HttpResourceModel httpResourceModel = matchedDestination.getDestination();

            // Call preCall method of handler interceptors.
            boolean terminated = false;
            HandlerInfo handlerInfo = new HandlerInfo(
                    httpResourceModel.getMethod().getDeclaringClass().getName(), httpResourceModel.getMethod());
            for (Interceptor interceptor : interceptors) {
                if (!interceptor.preCall(request, responder, handlerInfo)) {
                    // Terminate further request processing if preCall returns false.
                    terminated = true;
                    break;
                }
            }

            // Call httpresource handle method, return the HttpMethodInfo Object.
            if (!terminated) {
                // Wrap responder to make post hook calls.
                responder = new WrappedHttpResponder(responder, interceptors, request, handlerInfo);
                return HttpMethodInfoBuilder.getInstance().httpResourceModel(httpResourceModel)
                        .httpRequest(request).httpResponder(responder)
                        .requestInfo(matchedDestination.getGroupNameValues(), contentTypeHeader, acceptHeader);
            }
        } else if (!routableDestinations.isEmpty()) {
            //Found a matching resource but could not find the right HttpMethod so return 405
            throw new HandlerException(HttpResponseStatus.METHOD_NOT_ALLOWED, request.getUri());
        } else {
            throw new HandlerException(HttpResponseStatus.NOT_FOUND,
                    String.format("Problem accessing: %s. Reason: Not Found", request.getUri()));
        }
    } catch (NoSuchElementException ex) {
        throw new HandlerException(HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE,
                String.format("Problem accessing: %s. Reason: Unsupported Media Type", request.getUri()), ex);
    }
    return null;
}

From source file:org.wso2.carbon.mss.internal.router.MicroserviceMetadata.java

License:Open Source License

/**
 * Call the appropriate handler for handling the httprequest. 404 if path is not found. 405 if path is found but
 * httpMethod does not match what's configured.
 *
 * @param request   instance of {@code HttpRequest}
 * @param responder instance of {@code HttpResponder} to handle the request.
 * @return HttpMethodInfo object, null if urlRewriter rewrite returns false, also when method cannot be invoked.
 * @throws HandlerException If URL rewriting fails
 *//*  w  w  w .j  a v a 2  s.  c  om*/
public HttpMethodInfoBuilder getDestinationMethod(HttpRequest request, HttpResponder responder)
        throws HandlerException {
    if (urlRewriter != null) {
        try {
            request.setUri(URI.create(request.getUri()).normalize().toString());
            if (!urlRewriter.rewrite(request, responder)) {
                return null;
            }
        } catch (Throwable t) {
            log.error("Exception thrown during rewriting of uri {}", request.getUri(), t);
            throw new HandlerException(HttpResponseStatus.INTERNAL_SERVER_ERROR,
                    String.format("Caught exception processing request. Reason: %s", t.getMessage()));
        }
    }

    String acceptHeaderStr = request.headers().get(HttpHeaders.Names.ACCEPT);
    List<String> acceptHeader = (acceptHeaderStr != null)
            ? Arrays.asList(acceptHeaderStr.split("\\s*,\\s*")).stream()
                    .map(mediaType -> mediaType.split("\\s*;\\s*")[0]).collect(Collectors.toList())
            : null;

    String contentTypeHeaderStr = request.headers().get(HttpHeaders.Names.CONTENT_TYPE);
    //Trim specified charset since UTF-8 is assumed
    String contentTypeHeader = (contentTypeHeaderStr != null) ? contentTypeHeaderStr.split("\\s*;\\s*")[0]
            : null;

    try {
        String path = URI.create(request.getUri()).normalize().getPath();

        List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>> routableDestinations = patternRouter
                .getDestinations(path);

        List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>> matchedDestinations = getMatchedDestination(
                routableDestinations, request.getMethod(), path);

        if (!matchedDestinations.isEmpty()) {
            PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel> matchedDestination = matchedDestinations
                    .stream().filter(matchedDestination1 -> {
                        return matchedDestination1.getDestination().matchConsumeMediaType(contentTypeHeader)
                                && matchedDestination1.getDestination().matchProduceMediaType(acceptHeader);
                    }).findFirst().get();
            HttpResourceModel httpResourceModel = matchedDestination.getDestination();

            // Call preCall method of handler interceptors.
            boolean terminated = false;
            ServiceMethodInfo serviceMethodInfo = new ServiceMethodInfo(
                    httpResourceModel.getMethod().getDeclaringClass().getName(), httpResourceModel.getMethod());
            for (Interceptor interceptor : interceptors) {
                if (!interceptor.preCall(request, responder, serviceMethodInfo)) {
                    // Terminate further request processing if preCall returns false.
                    terminated = true;
                    break;
                }
            }

            // Call httpresource handle method, return the HttpMethodInfo Object.
            if (!terminated) {
                // Wrap responder to make post hook calls.
                responder = new WrappedHttpResponder(responder, interceptors, request, serviceMethodInfo);
                return HttpMethodInfoBuilder.getInstance().httpResourceModel(httpResourceModel)
                        .httpRequest(request).httpResponder(responder)
                        .requestInfo(matchedDestination.getGroupNameValues(), contentTypeHeader, acceptHeader);
            }
        } else if (!routableDestinations.isEmpty()) {
            //Found a matching resource but could not find the right HttpMethod so return 405
            throw new HandlerException(HttpResponseStatus.METHOD_NOT_ALLOWED, request.getUri());
        } else {
            throw new HandlerException(HttpResponseStatus.NOT_FOUND,
                    String.format("Problem accessing: %s. Reason: Not Found", request.getUri()));
        }
    } catch (NoSuchElementException ex) {
        throw new HandlerException(HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE,
                String.format("Problem accessing: %s. Reason: Unsupported Media Type", request.getUri()), ex);
    }
    return null;
}