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

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

Introduction

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

Prototype

@Deprecated
String getUri();

Source Link

Usage

From source file:org.apache.hadoop.hdfs.server.datanode.web.SimpleHttpProxyHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final HttpRequest req) {
    uri = req.getUri();
    final Channel client = ctx.channel();
    Bootstrap proxiedServer = new Bootstrap().group(client.eventLoop()).channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override/* ww w. j  ava2s .  com*/
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new HttpRequestEncoder(), new Forwarder(uri, client));
                }
            });
    ChannelFuture f = proxiedServer.connect(host);
    proxiedChannel = f.channel();
    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                ctx.channel().pipeline().remove(HttpResponseEncoder.class);
                HttpRequest newReq = new DefaultFullHttpRequest(HTTP_1_1, req.getMethod(), req.getUri());
                newReq.headers().add(req.headers());
                newReq.headers().set(CONNECTION, Values.CLOSE);
                future.channel().writeAndFlush(newReq);
            } else {
                DefaultHttpResponse resp = new DefaultHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR);
                resp.headers().set(CONNECTION, Values.CLOSE);
                LOG.info("Proxy " + uri + " failed. Cause: ", future.cause());
                ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
                client.close();
            }
        }
    });
}

From source file:org.apache.hadoop.hdfs.server.datanode.web.URLDispatcher.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpRequest req) throws Exception {
    String uri = req.getUri();
    ChannelPipeline p = ctx.pipeline();// www. j  a v a 2s.c o  m
    if (uri.startsWith(WEBHDFS_PREFIX)) {
        WebHdfsHandler h = new WebHdfsHandler(conf, confForCreate);
        p.replace(this, WebHdfsHandler.class.getSimpleName(), h);
        h.channelRead0(ctx, req);
    } else {
        SimpleHttpProxyHandler h = new SimpleHttpProxyHandler(proxyHost);
        p.replace(this, SimpleHttpProxyHandler.class.getSimpleName(), h);
        h.channelRead0(ctx, req);
    }
}

From source file:org.apache.hadoop.hdfs.server.datanode.web.webhdfs.WebHdfsHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final HttpRequest req) throws Exception {
    Preconditions.checkArgument(req.getUri().startsWith(WEBHDFS_PREFIX));
    QueryStringDecoder queryString = new QueryStringDecoder(req.getUri());
    params = new ParameterParser(queryString, conf);
    DataNodeUGIProvider ugiProvider = new DataNodeUGIProvider(params);
    ugi = ugiProvider.ugi();//from   w w  w  .  java 2 s  .  c  o  m
    path = params.path();

    injectToken();
    ugi.doAs(new PrivilegedExceptionAction<Void>() {
        @Override
        public Void run() throws Exception {
            handle(ctx, req);
            return null;
        }
    });
}

From source file:org.apache.hyracks.http.server.CLFLogger.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;
        clientIp = ((NioSocketChannel) ctx.channel()).remoteAddress().getAddress().toString().substring(1);
        requestTime = Instant.now();
        reqLine = req.method().toString() + " " + req.getUri() + " " + req.getProtocolVersion().toString();
        userAgentRef = headerValueOrDash("Referer", req) + " " + headerValueOrDash("User-Agent", req);
        lastChunk = false;/*  w  ww  . j a va 2  s .  c o  m*/
    }
    ctx.fireChannelRead(msg);
}

From source file:org.apache.tajo.pullserver.retriever.AdvancedDataRetriever.java

License:Apache License

@Override
public FileChunk[] handle(ChannelHandlerContext ctx, HttpRequest request) throws IOException {

    final Map<String, List<String>> params = new QueryStringDecoder(request.getUri()).parameters();

    if (!params.containsKey("qid")) {
        throw new FileNotFoundException("No such qid: " + params.containsKey("qid"));
    }/*w w w. j  a  v a  2 s  .c om*/

    if (params.containsKey("sid")) {
        List<FileChunk> chunks = Lists.newArrayList();
        List<String> taskIds = splitMaps(params.get("qid"));
        for (String eachTaskId : taskIds) {
            String[] taskIdSeqTokens = eachTaskId.split("_");
            ExecutionBlockId ebId = TajoIdUtils.createExecutionBlockId(params.get("sid").get(0));
            TaskId quid = new TaskId(ebId, Integer.parseInt(taskIdSeqTokens[0]));

            TaskAttemptId attemptId = new TaskAttemptId(quid, Integer.parseInt(taskIdSeqTokens[1]));

            RetrieverHandler handler = handlerMap.get(attemptId.toString());
            FileChunk chunk = handler.get(params);
            chunks.add(chunk);
        }
        return chunks.toArray(new FileChunk[chunks.size()]);
    } else {
        RetrieverHandler handler = handlerMap.get(params.get("qid").get(0));
        FileChunk chunk = handler.get(params);
        if (chunk == null) {
            if (params.containsKey("qid")) { // if there is no content corresponding to the query
                return null;
            } else { // if there is no
                throw new FileNotFoundException("No such a file corresponding to " + params.get("qid"));
            }
        }

        File file = chunk.getFile();
        if (file.isHidden() || !file.exists()) {
            throw new FileNotFoundException("No such file: " + file.getAbsolutePath());
        }
        if (!file.isFile()) {
            throw new FileAccessForbiddenException(file.getAbsolutePath() + " is not file");
        }

        return new FileChunk[] { chunk };
    }
}

From source file:org.apache.tajo.pullserver.retriever.DirectoryRetriever.java

License:Apache License

@Override
public FileChunk[] handle(ChannelHandlerContext ctx, HttpRequest request) throws IOException {
    final String path = HttpDataServerHandler.sanitizeUri(request.getUri());
    if (path == null) {
        throw new IllegalArgumentException("Wrong uri: " + request.getUri());
    }//from   w  ww.j  a va2s.co  m

    File file = new File(baseDir, path);
    if (file.isHidden() || !file.exists()) {
        throw new FileNotFoundException("No such file: " + baseDir + "/" + path);
    }
    if (!file.isFile()) {
        throw new FileAccessForbiddenException("No such file: " + baseDir + "/" + path);
    }

    return new FileChunk[] { new FileChunk(file, 0, file.length()) };
}

From source file:org.asanka.service.ContextAnnotationSample.java

License:Open Source License

@GET
@Path("HttpRequest")
public String HttpRequest(@Context HttpRequest request) {

    System.out.println(request.getUri());
    return request.getUri();
}

From source file:org.asynchttpclient.netty.channel.NettyConnectListener.java

License:Open Source License

private void writeRequest(Channel channel) {

    if (futureIsAlreadyCancelled(channel)) {
        return;/* w  ww  . j  a v a 2 s  .com*/
    }

    if (LOGGER.isDebugEnabled()) {
        HttpRequest httpRequest = future.getNettyRequest().getHttpRequest();
        LOGGER.debug("Using new Channel '{}' for '{}' to '{}'", channel, httpRequest.getMethod(),
                httpRequest.getUri());
    }

    Channels.setAttribute(channel, future);

    channelManager.registerOpenChannel(channel, partitionKey);
    future.attachChannel(channel, false);
    requestSender.writeRequest(future, channel);
}

From source file:org.asynchttpclient.netty.request.NettyRequestSender.java

License:Open Source License

private <T> ListenableFuture<T> sendRequestWithOpenChannel(Request request, ProxyServer proxy,
        NettyResponseFuture<T> future, AsyncHandler<T> asyncHandler, Channel channel) {

    if (asyncHandler instanceof AsyncHandlerExtensions)
        AsyncHandlerExtensions.class.cast(asyncHandler).onConnectionPooled(channel);

    scheduleRequestTimeout(future);//from ww w .  j a v a  2  s  .c o  m
    future.setChannelState(ChannelState.POOLED);
    future.attachChannel(channel, false);

    if (LOGGER.isDebugEnabled()) {
        HttpRequest httpRequest = future.getNettyRequest().getHttpRequest();
        LOGGER.debug("Using open Channel {} for {} '{}'", channel, httpRequest.getMethod(),
                httpRequest.getUri());
    }

    // channelInactive might be called between isChannelValid and writeRequest
    // so if we don't store the Future now, channelInactive won't perform handleUnexpectedClosedChannel
    Channels.setAttribute(channel, future);

    if (Channels.isChannelValid(channel)) {
        writeRequest(future, channel);
    } else {
        // bad luck, the channel was closed in-between
        // there's a very good chance onClose was already notified but the
        // future wasn't already registered
        handleUnexpectedClosedChannel(channel, future);
    }

    return future;
}

From source file:org.atmosphere.nettosphere.BridgeRuntime.java

License:Apache License

private AtmosphereRequest createAtmosphereRequest(final ChannelHandlerContext ctx, final HttpRequest request,
        byte[] body) throws URISyntaxException, UnsupportedEncodingException, MalformedURLException {
    final String base = getBaseUri(request);
    final URI requestUri = new URI(base.substring(0, base.length() - 1) + request.getUri());
    final String ct = HttpHeaders.getHeader(request, "Content-Type", "text/plain");
    final long cl = HttpHeaders.getContentLength(request, 0);
    String method = request.getMethod().name();

    String queryString = requestUri.getQuery();
    Map<String, String[]> qs = new HashMap<String, String[]>();
    if (queryString != null) {
        parseQueryString(qs, queryString);
    }/*from w  ww. ja  va2s  .  c  om*/

    if (ct.equalsIgnoreCase("application/x-www-form-urlencoded")) {
        if (FullHttpRequest.class.isAssignableFrom(request.getClass())) {
            parseQueryString(qs, new String(body));
        }
    }

    String u = requestUri.toURL().toString();
    int last = u.indexOf("?") == -1 ? u.length() : u.indexOf("?");
    String url = u.substring(0, last);
    int l;

    if (url.contains(config.mappingPath())) {
        l = requestUri.getAuthority().length() + requestUri.getScheme().length() + 3
                + config.mappingPath().length();
    } else {
        l = requestUri.getAuthority().length() + requestUri.getScheme().length() + 3;
    }

    HttpSession session = null;
    if (framework.getAtmosphereConfig().isSupportSession()) {
        String[] transport = qs.get(HeaderConfig.X_ATMOSPHERE_TRANSPORT);
        if (transport != null && transport.length > 0) {
            String[] uuid = qs.get(HeaderConfig.X_ATMOSPHERE_TRACKING_ID);
            if (uuid != null && uuid.length > 0) {
                // TODO: Session is only supported until an unsubscribe is received.
                if (transport[0].equalsIgnoreCase(HeaderConfig.DISCONNECT_TRANSPORT_MESSAGE)) {
                    sessions.remove(uuid[0]);
                } else {
                    session = sessions.get(uuid[0]);

                    if (session == null) {
                        session = new FakeHttpSession("-1", null, System.currentTimeMillis(), -1);
                    }
                }
            }
        }
    }

    final Map<String, Object> attributes = new HashMap<String, Object>();
    AtmosphereRequestImpl.Builder requestBuilder = new AtmosphereRequestImpl.Builder();
    requestBuilder.requestURI(url.substring(l)).requestURL(url).pathInfo(url.substring(l))
            .headers(getHeaders(request)).method(method).contentType(ct).contentLength(cl)
            // We need to read attribute after doComet
            .destroyable(false).attributes(attributes).servletPath(config.mappingPath()).session(session)
            .cookies(getCookies(request)).queryStrings(qs)
            .remoteInetSocketAddress(new Callable<InetSocketAddress>() {
                @Override
                public InetSocketAddress call() throws Exception {
                    return (InetSocketAddress) ctx.channel().remoteAddress();
                }
            }).localInetSocketAddress(new Callable<InetSocketAddress>() {

                @Override
                public InetSocketAddress call() throws Exception {
                    return (InetSocketAddress) ctx.channel().localAddress();
                }
            });

    if (body.length > 0) {
        requestBuilder.body(body);
    }

    return requestBuilder.build();

}