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.camel.component.netty4.http.handlers.HttpServerChannelHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    HttpRequest request = (HttpRequest) msg;

    LOG.debug("Message received: {}", request);

    if (consumer.isSuspended()) {
        // are we suspended?
        LOG.debug("Consumer suspended, cannot service request {}", request);
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, SERVICE_UNAVAILABLE);
        response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
        response.headers().set(Exchange.CONTENT_LENGTH, 0);
        ctx.writeAndFlush(response);//  w ww  .j  a v a  2  s.c  o m
        ctx.channel().close();
        return;
    }

    // if its an OPTIONS request then return which methods is allowed
    boolean isRestrictedToOptions = consumer.getEndpoint().getHttpMethodRestrict() != null
            && consumer.getEndpoint().getHttpMethodRestrict().contains("OPTIONS");
    if ("OPTIONS".equals(request.getMethod().name()) && !isRestrictedToOptions) {
        String s;
        if (consumer.getEndpoint().getHttpMethodRestrict() != null) {
            s = "OPTIONS," + consumer.getEndpoint().getHttpMethodRestrict();
        } else {
            // allow them all
            s = "GET,HEAD,POST,PUT,DELETE,TRACE,OPTIONS,CONNECT,PATCH";
        }
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
        response.headers().set("Allow", s);
        response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
        response.headers().set(Exchange.CONTENT_LENGTH, 0);
        ctx.writeAndFlush(response);
        return;
    }
    if (consumer.getEndpoint().getHttpMethodRestrict() != null
            && !consumer.getEndpoint().getHttpMethodRestrict().contains(request.getMethod().name())) {
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED);
        response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
        response.headers().set(Exchange.CONTENT_LENGTH, 0);
        ctx.writeAndFlush(response);
        ctx.channel().close();
        return;
    }
    if ("TRACE".equals(request.getMethod().name()) && !consumer.getEndpoint().isTraceEnabled()) {
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED);
        response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
        response.headers().set(Exchange.CONTENT_LENGTH, 0);
        ctx.writeAndFlush(response);
        ctx.channel().close();
        return;
    }
    // must include HOST header as required by HTTP 1.1
    if (!request.headers().contains(HttpHeaders.Names.HOST)) {
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, BAD_REQUEST);
        //response.setChunked(false);
        response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
        response.headers().set(Exchange.CONTENT_LENGTH, 0);
        ctx.writeAndFlush(response);
        ctx.channel().close();
        return;
    }

    // is basic auth configured
    NettyHttpSecurityConfiguration security = consumer.getEndpoint().getSecurityConfiguration();
    if (security != null && security.isAuthenticate() && "Basic".equalsIgnoreCase(security.getConstraint())) {
        String url = request.getUri();

        // drop parameters from url
        if (url.contains("?")) {
            url = ObjectHelper.before(url, "?");
        }

        // we need the relative path without the hostname and port
        URI uri = new URI(request.getUri());
        String target = uri.getPath();

        // strip the starting endpoint path so the target is relative to the endpoint uri
        String path = consumer.getConfiguration().getPath();
        if (path != null && target.startsWith(path)) {
            target = target.substring(path.length());
        }

        // is it a restricted resource?
        String roles;
        if (security.getSecurityConstraint() != null) {
            // if restricted returns null, then the resource is not restricted and we should not authenticate the user
            roles = security.getSecurityConstraint().restricted(target);
        } else {
            // assume any roles is valid if no security constraint has been configured
            roles = "*";
        }
        if (roles != null) {
            // basic auth subject
            HttpPrincipal principal = extractBasicAuthSubject(request);

            // authenticate principal and check if the user is in role
            Subject subject = null;
            boolean inRole = true;
            if (principal != null) {
                subject = authenticate(security.getSecurityAuthenticator(),
                        security.getLoginDeniedLoggingLevel(), principal);
                if (subject != null) {
                    String userRoles = security.getSecurityAuthenticator().getUserRoles(subject);
                    inRole = matchesRoles(roles, userRoles);
                }
            }

            if (principal == null || subject == null || !inRole) {
                if (principal == null) {
                    LOG.debug("Http Basic Auth required for resource: {}", url);
                } else if (subject == null) {
                    LOG.debug("Http Basic Auth not authorized for username: {}", principal.getUsername());
                } else {
                    LOG.debug("Http Basic Auth not in role for username: {}", principal.getUsername());
                }
                // restricted resource, so send back 401 to require valid username/password
                HttpResponse response = new DefaultHttpResponse(HTTP_1_1, UNAUTHORIZED);
                response.headers().set("WWW-Authenticate", "Basic realm=\"" + security.getRealm() + "\"");
                response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
                response.headers().set(Exchange.CONTENT_LENGTH, 0);
                ctx.writeAndFlush(response);
                // close the channel
                ctx.channel().close();
                return;
            } else {
                LOG.debug("Http Basic Auth authorized for username: {}", principal.getUsername());
            }
        }
    }

    // let Camel process this message
    super.channelRead0(ctx, msg);
}

From source file:org.apache.camel.component.netty4.http.handlers.HttpServerMultiplexChannelHandler.java

License:Apache License

private HttpServerChannelHandler getHandler(HttpRequest request) {
    HttpServerChannelHandler answer = null;

    // need to strip out host and port etc, as we only need the context-path for matching
    String method = request.getMethod().name();
    if (method == null) {
        return null;
    }//from  w  w  w. j a v a2s .  c  o m

    String path = request.getUri();
    int idx = path.indexOf(token);
    if (idx > -1) {
        path = path.substring(idx + len);
    }
    // use the path as key to find the consumer handler to use
    path = pathAsKey(path);

    List<Map.Entry<ContextPathMatcher, HttpServerChannelHandler>> candidates = new ArrayList<Map.Entry<ContextPathMatcher, HttpServerChannelHandler>>();

    // first match by http method
    for (Map.Entry<ContextPathMatcher, HttpServerChannelHandler> entry : consumers.entrySet()) {
        NettyHttpConsumer consumer = entry.getValue().getConsumer();
        String restrict = consumer.getEndpoint().getHttpMethodRestrict();
        if (entry.getKey().matchMethod(method, restrict)) {
            candidates.add(entry);
        }
    }

    // then see if we got a direct match
    List<HttpServerChannelHandler> directMatches = new LinkedList<HttpServerChannelHandler>();
    for (Map.Entry<ContextPathMatcher, HttpServerChannelHandler> entry : candidates) {
        if (entry.getKey().matchesRest(path, false)) {
            directMatches.add(entry.getValue());
        }
    }
    if (directMatches.size() == 1) { // Single match found, just return it without any further analysis.
        answer = directMatches.get(0);
    } else if (directMatches.size() > 1) { // possible if the prefix match occurred
        List<HttpServerChannelHandler> directMatchesWithOptions = handlersWithExplicitOptionsMethod(
                directMatches);
        if (!directMatchesWithOptions.isEmpty()) { // prefer options matches
            answer = handlerWithTheLongestMatchingPrefix(directMatchesWithOptions);
        } else {
            answer = handlerWithTheLongestMatchingPrefix(directMatches);
        }
    }

    // then match by non wildcard path
    if (answer == null) {
        Iterator<Map.Entry<ContextPathMatcher, HttpServerChannelHandler>> it = candidates.iterator();
        while (it.hasNext()) {
            Map.Entry<ContextPathMatcher, HttpServerChannelHandler> entry = it.next();
            if (!entry.getKey().matchesRest(path, true)) {
                it.remove();
            }
        }

        // there should only be one
        if (candidates.size() == 1) {
            answer = candidates.get(0).getValue();
        }
    }

    // fallback to regular matching
    if (answer == null) {
        for (Map.Entry<ContextPathMatcher, HttpServerChannelHandler> entry : consumers.entrySet()) {
            if (entry.getKey().matches(path)) {
                answer = entry.getValue();
                break;
            }
        }
    }

    return answer;
}

From source file:org.apache.camel.component.netty4.http.NettyHttpProducer.java

License:Apache License

@Override
protected Object getRequestBody(Exchange exchange) throws Exception {
    // creating the url to use takes 2-steps
    String uri = NettyHttpHelper.createURL(exchange, getEndpoint());
    URI u = NettyHttpHelper.createURI(exchange, uri, getEndpoint());

    HttpRequest request = getEndpoint().getNettyHttpBinding().toNettyRequest(exchange.getIn(), u.toString(),
            getConfiguration());// ww w . j  ava 2s  .c  om
    String actualUri = request.getUri();
    exchange.getIn().setHeader(Exchange.HTTP_URL, actualUri);
    // Need to check if we need to close the connection or not
    if (!HttpHeaders.isKeepAlive(request)) {
        // just want to make sure we close the channel if the keepAlive is not true
        exchange.setProperty(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, true);
    }
    if (getConfiguration().isBridgeEndpoint()) {
        // Need to remove the Host key as it should be not used when bridging/proxying
        exchange.getIn().removeHeader("host");
    }

    return request;
}

From source file:org.apache.cxf.transport.http.netty.server.NettyHttpServletHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    HttpRequest request = (HttpRequest) msg;
    if (HttpHeaders.is100ContinueExpected(request)) {
        ctx.write(new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
    }/*ww w . j  ava2  s  .  c o m*/

    // find the nettyHttpContextHandler by lookup the request url
    NettyHttpContextHandler nettyHttpContextHandler = pipelineFactory.getNettyHttpHandler(request.getUri());
    if (nettyHttpContextHandler != null) {
        handleHttpServletRequest(ctx, request, nettyHttpContextHandler);
    } else {
        throw new RuntimeException(
                new Fault(new Message("NO_NETTY_SERVLET_HANDLER_FOUND", LOG, request.getUri())));
    }
}

From source file:org.apache.cxf.transport.http.netty.server.servlet.NettyHttpServletRequest.java

License:Apache License

public NettyHttpServletRequest(HttpRequest request, String contextPath, ChannelHandlerContext ctx) {
    this.originalRequest = request;
    this.contextPath = contextPath;
    this.uriParser = new URIParser(contextPath);
    uriParser.parse(request.getUri());
    this.inputStream = new NettyServletInputStream((HttpContent) request);
    this.reader = new BufferedReader(new InputStreamReader(inputStream));
    this.queryStringDecoder = new QueryStringDecoder(request.getUri());
    // setup the SSL security attributes
    this.channelHandlerContext = ctx;
    SslHandler sslHandler = channelHandlerContext.pipeline().get(SslHandler.class);
    if (sslHandler != null) {
        SSLSession session = sslHandler.engine().getSession();
        if (session != null) {
            attributes.put(SSL_CIPHER_SUITE_ATTRIBUTE, session.getCipherSuite());
            try {
                attributes.put(SSL_PEER_CERT_CHAIN_ATTRIBUTE, session.getPeerCertificates());
            } catch (SSLPeerUnverifiedException ex) {
                // do nothing here
            }/*from   w  w  w . java 2 s  . c om*/
        }
    }
}

From source file:org.apache.dubbo.qos.command.decoder.HttpCommandDecoderTest.java

License:Apache License

@Test
public void decodeGet() throws Exception {
    HttpRequest request = mock(HttpRequest.class);
    when(request.getUri()).thenReturn("localhost:80/test");
    when(request.getMethod()).thenReturn(HttpMethod.GET);
    CommandContext context = HttpCommandDecoder.decode(request);
    assertThat(context.getCommandName(), equalTo("test"));
    assertThat(context.isHttp(), is(true));
    when(request.getUri()).thenReturn("localhost:80/test?a=b&c=d");
    context = HttpCommandDecoder.decode(request);
    assertThat(context.getArgs(), arrayContaining("b", "d"));
}

From source file:org.apache.dubbo.qos.server.handler.HttpProcessHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception {
    CommandContext commandContext = HttpCommandDecoder.decode(msg);
    // return 404 when fail to construct command context
    if (commandContext == null) {
        log.warn("can not found commandContext url: " + msg.getUri());
        FullHttpResponse response = http404();
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    } else {//from  ww w  .  ja  v a 2s.  c o  m
        commandContext.setRemote(ctx.channel());
        try {
            String result = commandExecutor.execute(commandContext);
            FullHttpResponse response = http200(result);
            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        } catch (NoSuchCommandException ex) {
            log.error("can not find commandContext: " + commandContext, ex);
            FullHttpResponse response = http404();
            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        } catch (Exception qosEx) {
            log.error("execute commandContext: " + commandContext + " got exception", qosEx);
            FullHttpResponse response = http500(qosEx.getMessage());
            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        }
    }
}

From source file:org.apache.dubbo.qos.server.handler.HttpProcessHandlerTest.java

License:Apache License

@Test
public void test1() throws Exception {
    ChannelHandlerContext context = mock(ChannelHandlerContext.class);
    ChannelFuture future = mock(ChannelFuture.class);
    when(context.writeAndFlush(any(FullHttpResponse.class))).thenReturn(future);
    HttpRequest message = Mockito.mock(HttpRequest.class);
    when(message.getUri()).thenReturn("test");
    HttpProcessHandler handler = new HttpProcessHandler();
    handler.channelRead0(context, message);
    verify(future).addListener(ChannelFutureListener.CLOSE);
    ArgumentCaptor<FullHttpResponse> captor = ArgumentCaptor.forClass(FullHttpResponse.class);
    verify(context).writeAndFlush(captor.capture());
    FullHttpResponse response = captor.getValue();
    assertThat(response.getStatus().code(), equalTo(404));
}

From source file:org.apache.dubbo.qos.server.handler.HttpProcessHandlerTest.java

License:Apache License

@Test
public void test2() throws Exception {
    ChannelHandlerContext context = mock(ChannelHandlerContext.class);
    ChannelFuture future = mock(ChannelFuture.class);
    when(context.writeAndFlush(any(FullHttpResponse.class))).thenReturn(future);
    HttpRequest message = Mockito.mock(HttpRequest.class);
    when(message.getUri()).thenReturn("localhost:80/greeting");
    when(message.getMethod()).thenReturn(HttpMethod.GET);
    HttpProcessHandler handler = new HttpProcessHandler();
    handler.channelRead0(context, message);
    verify(future).addListener(ChannelFutureListener.CLOSE);
    ArgumentCaptor<FullHttpResponse> captor = ArgumentCaptor.forClass(FullHttpResponse.class);
    verify(context).writeAndFlush(captor.capture());
    FullHttpResponse response = captor.getValue();
    assertThat(response.getStatus().code(), equalTo(200));
}

From source file:org.apache.dubbo.qos.server.handler.HttpProcessHandlerTest.java

License:Apache License

@Test
public void test3() throws Exception {
    ChannelHandlerContext context = mock(ChannelHandlerContext.class);
    ChannelFuture future = mock(ChannelFuture.class);
    when(context.writeAndFlush(any(FullHttpResponse.class))).thenReturn(future);
    HttpRequest message = Mockito.mock(HttpRequest.class);
    when(message.getUri()).thenReturn("localhost:80/test");
    when(message.getMethod()).thenReturn(HttpMethod.GET);
    HttpProcessHandler handler = new HttpProcessHandler();
    handler.channelRead0(context, message);
    verify(future).addListener(ChannelFutureListener.CLOSE);
    ArgumentCaptor<FullHttpResponse> captor = ArgumentCaptor.forClass(FullHttpResponse.class);
    verify(context).writeAndFlush(captor.capture());
    FullHttpResponse response = captor.getValue();
    assertThat(response.getStatus().code(), equalTo(404));
}