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

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

Introduction

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

Prototype

@Override
    FullHttpRequest setUri(String uri);

Source Link

Usage

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

License:Open Source License

void redirect(Method method, URL url, RequestInfo info) {
    HttpRequest nue;//from   w ww.  ja v a 2  s. co m
    if (method.toString().equals(info.req.getMethod().toString())) {
        if (info.req instanceof DefaultFullHttpRequest) {
            DefaultFullHttpRequest dfrq = (DefaultFullHttpRequest) info.req;
            FullHttpRequest rq;
            try {
                rq = dfrq.copy();
            } catch (IllegalReferenceCountException e) { // Empty bytebuf
                rq = dfrq;
            }
            rq.setUri(url.getPathAndQuery());
            nue = rq;
        } else {
            nue = new DefaultHttpRequest(info.req.getProtocolVersion(), info.req.getMethod(),
                    url.getPathAndQuery());
        }
    } else {
        nue = new DefaultHttpRequest(info.req.getProtocolVersion(), HttpMethod.valueOf(method.name()),
                url.getPathAndQuery());
    }
    copyHeaders(info.req, nue);
    nue.headers().set(Headers.HOST.name(), url.toSimpleURL().getHost());
    submit(url, nue, info.cancelled, info.handle, info.r, info, info.remaining(), info.dontAggregate);
}

From source file:com.rackspacecloud.blueflood.http.HttpRequestWithDecodedQueryParams.java

License:Apache License

public static HttpRequestWithDecodedQueryParams create(FullHttpRequest request) {
    final QueryStringDecoder decoder = new QueryStringDecoder(request.getUri());
    request.setUri(decoder.path());
    return new HttpRequestWithDecodedQueryParams(request, decoder.parameters());
}

From source file:de.saxsys.synchronizefx.netty.websockets.WhiteSpaceInPathWebSocketClientHandshaker13.java

License:Open Source License

@Override
protected FullHttpRequest newHandshakeRequest() {
    FullHttpRequest request = super.newHandshakeRequest();
    request.setUri(super.uri().getRawPath());
    return request;
}

From source file:deathcap.wsmc.web.HTTPHandler.java

License:Apache License

public void httpRequest(ChannelHandlerContext context, FullHttpRequest request) throws IOException {
    if (!request.getDecoderResult().isSuccess()) {
        sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
        return;/*  w w w . j  av  a  2s  .  c o  m*/
    }
    if (request.getUri().equals("/server")) {
        context.fireChannelRead(request);
        return;
    }

    if ((request.getMethod() == OPTIONS || request.getMethod() == HEAD) && request.getUri().equals("/chunk")) {
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
        response.headers().add("Access-Control-Allow-Origin", "*");
        response.headers().add("Access-Control-Allow-Methods", "POST");
        if (request.getMethod() == OPTIONS) {
            response.headers().add("Access-Control-Allow-Headers", "origin, content-type, accept");
        }
        sendHttpResponse(context, request, response);
    }

    if (request.getMethod() != GET) {
        sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
        return;
    }

    // TODO: send browserified page
    if (request.getUri().equals("/")) {
        request.setUri("/index.html");
    }

    InputStream stream = null;
    /*
    if (request.getUri().startsWith("/resources/")) {
    File file = new File(
            plugin.getResourceDir(),
            request.getUri().substring("/resources/".length())
    );
    stream = new FileInputStream(file);
    } else {
    */
    stream = this.getClass().getClassLoader().getResourceAsStream("www" + request.getUri());
    if (stream == null) {
        sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND));
        return;
    }
    ByteBufOutputStream out = new ByteBufOutputStream(Unpooled.buffer());
    copyStream(stream, out);
    stream.close();
    out.close();

    ByteBuf buffer = out.buffer();
    if (request.getUri().equals("/index.html")) {
        String page = buffer.toString(CharsetUtil.UTF_8);
        page = page.replaceAll("%SERVERPORT%", Integer.toString(this.port));
        buffer.release();
        buffer = Unpooled.wrappedBuffer(page.getBytes(CharsetUtil.UTF_8));
    }

    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, buffer);
    if (request.getUri().startsWith("/resources/")) {
        response.headers().add("Access-Control-Allow-Origin", "*");
    }

    String ext = request.getUri().substring(request.getUri().lastIndexOf('.') + 1);
    String type = mimeTypes.containsKey(ext) ? mimeTypes.get(ext) : "text/plain";
    if (type.startsWith("text/")) {
        type += "; charset=UTF-8";
    }
    response.headers().set(CONTENT_TYPE, type);
    setContentLength(response, response.content().readableBytes());
    sendHttpResponse(context, request, response);

}

From source file:org.wso2.carbon.apimgt.gateway.handlers.WebsocketInboundHandler.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from  ww  w .java  2 s.c om
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

    //check if the request is a handshake
    if (msg instanceof FullHttpRequest) {
        FullHttpRequest req = (FullHttpRequest) msg;
        uri = req.getUri();
        URI uriTemp = new URI(uri);
        apiContextUri = new URI(uriTemp.getScheme(), uriTemp.getAuthority(), uriTemp.getPath(), null,
                uriTemp.getFragment()).toString();

        if (req.getUri().contains("/t/")) {
            tenantDomain = MultitenantUtils.getTenantDomainFromUrl(req.getUri());
        } else {
            tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
        }

        String useragent = req.headers().get(HttpHeaders.USER_AGENT);
        String authorization = req.headers().get(HttpHeaders.AUTHORIZATION);

        // '-' is used for empty values to avoid possible errors in DAS side.
        // Required headers are stored one by one as validateOAuthHeader()
        // removes some of the headers from the request
        useragent = useragent != null ? useragent : "-";
        headers.add(HttpHeaders.AUTHORIZATION, authorization);
        headers.add(HttpHeaders.USER_AGENT, useragent);

        if (validateOAuthHeader(req)) {
            if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
                // carbon-mediation only support websocket invocation from super tenant APIs.
                // This is a workaround to mimic the the invocation came from super tenant.
                req.setUri(req.getUri().replaceFirst("/", "-"));
                String modifiedUri = uri.replaceFirst("/t/", "-t/");
                req.setUri(modifiedUri);
                msg = req;
            } else {
                req.setUri(uri); // Setting endpoint appended uri
            }

            if (StringUtils.isNotEmpty(token)) {
                ((FullHttpRequest) msg).headers().set(APIMgtGatewayConstants.WS_JWT_TOKEN_HEADER, token);
            }
            ctx.fireChannelRead(msg);

            // publish google analytics data
            GoogleAnalyticsData.DataBuilder gaData = new GoogleAnalyticsData.DataBuilder(null, null, null, null)
                    .setDocumentPath(uri).setDocumentHostName(DataPublisherUtil.getHostAddress())
                    .setSessionControl("end").setCacheBuster(APIMgtGoogleAnalyticsUtils.getCacheBusterId())
                    .setIPOverride(ctx.channel().remoteAddress().toString());
            APIMgtGoogleAnalyticsUtils gaUtils = new APIMgtGoogleAnalyticsUtils();
            gaUtils.init(tenantDomain);
            gaUtils.publishGATrackingData(gaData, req.headers().get(HttpHeaders.USER_AGENT), authorization);
        } else {
            ctx.writeAndFlush(
                    new TextWebSocketFrame(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE));
            throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS,
                    APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
        }
    } else if (msg instanceof WebSocketFrame) {
        boolean isThrottledOut = doThrottle(ctx, (WebSocketFrame) msg);
        String clientIp = getRemoteIP(ctx);

        if (isThrottledOut) {
            ctx.fireChannelRead(msg);
        } else {
            ctx.writeAndFlush(new TextWebSocketFrame("Websocket frame throttled out"));
        }

        // publish analytics events if analytics is enabled
        if (APIUtil.isAnalyticsEnabled()) {
            publishRequestEvent(infoDTO, clientIp, isThrottledOut);
        }
    }
}

From source file:server.http.HttpFullRequestHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object fullHttpRequest) throws Exception {
    //System.out.println("HttpFullRequestHandler : " + fullHttpRequest.getClass().toString());
    FullHttpRequest req = (FullHttpRequest) fullHttpRequest;

    directChannel.attr(HttpServer.REQ_PATH_KEY).set(req.getUri());

    //Host//from  ww w. j  a  va 2  s.c  o m
    String oldHost = req.headers().get("Host");
    req.headers().set("Host", "www.google.com");
    //Referer
    if (req.headers().contains("Referer")) {
        String r = req.headers().get("Referer");
        req.headers().set("Referer", r.replace(oldHost, "www.google.com"));
    }
    //?
    if (req.getUri().trim().equals("/")) {
        req.setUri("/?gws_rd=ssl");
    }

    Console.debug("HttpFullRequestHandler", "Request " + req.getUri());
    /*Console.debug("", "----------------------------------------------------------------");
    for(Map.Entry<String,String> entry: req.headers().entries()){
    Console.debug("HttpFullRequestHandler", entry.getKey() + ": " + entry.getValue());
    }
    Console.debug("", "----------------------------------------------------------------");*/

    //?
    if (req.getUri().startsWith("/gen_204")) {
        Console.debug("HttpFullRequestHandler", "204----------------------------------------------");
        ctx.pipeline().addFirst("tmp-response-encoder", new HttpResponseEncoder());
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT);
        HttpHeaders.setContentLength(response, 0);
        ctx.channel().writeAndFlush(response).addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture future) {
                ctx.pipeline().remove("tmp-response-encoder");
            }
        });
    } else if (req.getUri().startsWith("/url?")) {
        String redirectURL = HttpUtil.getParameter("url", req);
        Console.debug("HttpFullRequestHandler", "302------------------" + redirectURL);
        ctx.pipeline().addFirst("tmp-response-encoder", new HttpResponseEncoder());
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, SEE_OTHER);
        response.headers().add(LOCATION, redirectURL);
        HttpHeaders.setContentLength(response, 0);
        ctx.channel().writeAndFlush(response).addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture future) {
                ctx.pipeline().remove("tmp-response-encoder");
            }
        });
    } else {
        if (directChannel.isActive()) {
            directChannel.writeAndFlush(fullHttpRequest);
        } else {
            Console.debug("HttpFullRequestHandler", "directChannel inactive while write raw request.");
            ChannelUtil.closeOnFlush(ctx.channel());
        }
    }
}