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:net.mms_projects.copy_it.api.oauth.HeaderVerifierTest.java

License:Open Source License

@Test(timeout = 750)
public void noRealm() throws OAuthException, URISyntaxException {
    String header = "OAuth oauth_consumer_key=\"401a131e03357df2a563fba48f98749448ed63d37e007f7353608cf81fa70a2d\", "
            + "oauth_nonce=\"" + Utils.generateNonce() + "\", " + "oauth_timestamp=\""
            + Long.toString(System.currentTimeMillis() / 1000) + "\", "
            + "oauth_signature_method=\"HMAC-SHA1\", " + "oauth_version=\"1.0\", "
            + "oauth_token=\"oauth_token\", " + "oauth_signature=\"CBTk%2FvzxEqqr0AvhnVgdWNHuKfw%3D\"";
    HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
            "http://127.0.0.1:8080/");
    request.headers().add(AUTHORIZATION, header);
    new HeaderVerifier(request, new URI(request.getUri()));
}

From source file:net.mms_projects.copy_it.api.oauth.HeaderVerifierTest.java

License:Open Source License

@Test(timeout = 750)
public void validRequest() throws OAuthException, URISyntaxException {
    String header = "OAuth realm=\"\", "
            + "oauth_consumer_key=\"401a131e03357df2a563fba48f98749448ed63d37e007f7353608cf81fa70a2d\", "
            + "oauth_nonce=\"" + Utils.generateNonce() + "\", " + "oauth_timestamp=\""
            + Long.toString(System.currentTimeMillis() / 1000) + "\", "
            + "oauth_signature_method=\"HMAC-SHA1\", " + "oauth_version=\"1.0\", "
            + "oauth_token=\"oauth_token\", " + "oauth_signature=\"CBTk%2FvzxEqqr0AvhnVgdWNHuKfw%3D\"";
    HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
            "http://127.0.0.1:8080/");
    request.headers().add(AUTHORIZATION, header);
    new HeaderVerifier(request, new URI(request.getUri()));
}

From source file:net.oebs.jalos.netty.HttpHandler.java

License:Open Source License

private FullHttpResponse handleRequest(HttpRequest request) {

    FullHttpResponse response = null;/*  w w  w.j  a va  2  s .c  om*/
    String uri = request.getUri();

    // lookup Handler class by URL
    Class cls = null;
    for (Route route : routes) {
        if (uri.matches(route.path)) {
            cls = route.handler;
            break;
        }
    }

    // no matching handler == 404
    if (cls == null) {
        log.info("No handler match found for uri {}", uri);
        return notFound();
    }

    Handler h;
    try {
        h = (Handler) cls.newInstance();
    } catch (InstantiationException | IllegalAccessException ex) {
        return internalError();
    }

    Map<String, String> params = null;
    HttpMethod method = request.getMethod();

    // dispatch based on request method
    try {
        if (method.equals(HttpMethod.POST)) {
            HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false),
                    request);
            params = httpDataToStringMap(decoder.getBodyHttpDatas());
            response = h.handlePost(uri, params);
        } else if (method.equals(HttpMethod.GET)) {
            params = new HashMap<>();
            response = h.handleGet(uri, params);
        } else {
            response = badRequest();
        }

    } catch (BadRequest ex) {
        response = badRequest();
    } catch (NotFound ex) {
        response = notFound();
    } catch (HandlerError ex) {
        response = internalError();
    }

    return response;
}

From source file:net.sourceforge.entrainer.socket.WebSocketHandler.java

License:Open Source License

@Override
public void channelRead1(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof FullHttpRequest) {
        handleHttpRequest(ctx, (FullHttpRequest) msg);
    } else if (msg instanceof WebSocketFrame) {
        handleWebSocketFrame(ctx, (WebSocketFrame) msg);
    } else if (msg instanceof HttpRequest) {
        HttpRequest dhr = (HttpRequest) msg;
        DefaultFullHttpRequest req = new DefaultFullHttpRequest(dhr.getProtocolVersion(), dhr.getMethod(),
                dhr.getUri());
        req.headers().add(dhr.headers());
        handleHttpRequest(ctx, req);//w w  w .  j  av a 2s . c om
    }
}

From source file:netty.echo.http.HttpHelloWorldServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest request = (HttpRequest) msg;
        sb_debug.append("\n>> HTTP REQUEST -----------\n");
        sb_debug.append(request.getProtocolVersion().toString()).append(" ").append(request.getMethod().name())
                .append(" ").append(request.getUri());
        sb_debug.append("\n");
        HttpHeaders headers = request.headers();
        if (!headers.isEmpty()) {
            for (Map.Entry<String, String> header : headers) {
                sb_debug.append(header.getKey()).append(": ").append(header.getValue()).append("\n");
            }/*from  w ww . j  a v a 2 s.co  m*/
        }
        sb_debug.append("\n");
        System.out.println(sb_debug);
    } else if (msg instanceof HttpContent) {
        HttpContent content = (HttpContent) msg;
        ByteBuf thisContent = content.content();
        if (thisContent.isReadable()) {
            buffer_body.writeBytes(thisContent);
        }
        if (msg instanceof LastHttpContent) {
            sb_debug.append(buffer_body.toString(CharsetUtil.UTF_8));
            LastHttpContent trailer = (LastHttpContent) msg;
            if (!trailer.trailingHeaders().isEmpty()) {
                for (CharSequence name : trailer.trailingHeaders().names()) {
                    sb_debug.append(name).append("=");
                    for (CharSequence value : trailer.trailingHeaders().getAll(name)) {
                        sb_debug.append(value).append(",");
                    }
                    sb_debug.append("\n\n");
                }
            }
            sb_debug.append("\n<< HTTP REQUEST -----------");
        }
    }
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK,
            Unpooled.wrappedBuffer(sb_debug.toString().getBytes()));
    response.headers().set(CONTENT_TYPE, "text/plain");
    response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
    ctx.write(response);
}

From source file:netty.HttpServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;

        if (is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }//from w  w w .j  a v a  2  s  .c  om

        QueryStringDecoder decoderQuery = new QueryStringDecoder(req.getUri());
        Map<String, List<String>> uriAttributes = decoderQuery.parameters();
        String command = decoderQuery.path().substring(1);
        if (command.equals("favicon.ico")) {
            return;
        }
        String result = logicService.handleCommand(command, uriAttributes);
        // String result = command;
        ByteBuf buf = copiedBuffer(result, CharsetUtil.UTF_8);

        boolean keepAlive = isKeepAlive(req); // TODO important
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, buf);
        response.headers().set(CONTENT_TYPE, "text/plain");
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, Values.KEEP_ALIVE);
            ctx.write(response);
        }
    }
}

From source file:netty.HttpSnoopServerHandler.java

License:Apache License

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

        if (is100ContinueExpected(request)) {
            send100Continue(ctx);/*w w  w .java 2  s . c  om*/
        }

        buf.setLength(0);
        buf.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
        buf.append("===================================\r\n");

        buf.append("VERSION: ").append(request.getProtocolVersion()).append("\r\n");
        buf.append("HOSTNAME: ").append(getHost(request, "unknown")).append("\r\n");
        buf.append("REQUEST_URI: ").append(request.getUri()).append("\r\n\r\n");

        HttpHeaders headers = request.headers();
        if (!headers.isEmpty()) {
            for (Map.Entry<String, String> h : headers) {
                String key = h.getKey();
                String value = h.getValue();
                buf.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n");
            }
            buf.append("\r\n");
        }

        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri());
        Map<String, List<String>> params = queryStringDecoder.parameters();
        if (!params.isEmpty()) {
            for (Entry<String, List<String>> p : params.entrySet()) {
                String key = p.getKey();
                List<String> vals = p.getValue();
                for (String val : vals) {
                    buf.append("PARAM: ").append(key).append(" = ").append(val).append("\r\n");
                }
            }
            buf.append("\r\n");
        }

        appendDecoderResult(buf, request);
    }

    if (msg instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) msg;

        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            buf.append("CONTENT: ");
            buf.append(content.toString(CharsetUtil.UTF_8));
            buf.append("\r\n");
            appendDecoderResult(buf, request);
        }

        if (msg instanceof LastHttpContent) {
            buf.append("END OF CONTENT\r\n");

            LastHttpContent trailer = (LastHttpContent) msg;
            if (!trailer.trailingHeaders().isEmpty()) {
                buf.append("\r\n");
                for (String name : trailer.trailingHeaders().names()) {
                    for (String value : trailer.trailingHeaders().getAll(name)) {
                        buf.append("TRAILING HEADER: ");
                        buf.append(name).append(" = ").append(value).append("\r\n");
                    }
                }
                buf.append("\r\n");
            }

            writeResponse(trailer, ctx);
        }
    }
}

From source file:nettydb2webservice.NettyDB2WebServiceHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    byte[] CONTENT = "".getBytes();
    if (msg instanceof HttpRequest) {
        KVPTable kvp = new KVPTable();
        HttpRequest req = (HttpRequest) msg;

        if (HttpHeaders.is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }/*from   w ww  .j  av  a  2 s .  co m*/
        boolean keepAlive = HttpHeaders.isKeepAlive(req);
        HttpMethod method = req.getMethod();
        if (req.getUri().equalsIgnoreCase("/api")) {
            CONTENT = kvp.toJSON().toJSONString().getBytes();
        }
        if (req.getUri().matches("/api/(.+)$")) {
            String[] parts = req.getUri().split("/");
            String key = parts[parts.length - 1];
            CONTENT = kvp.toJSON(key).toJSONString().getBytes();
        }
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT));
        response.headers().set(CONTENT_TYPE, "application/json");
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
            ctx.write(response);
        }
    }
}

From source file:nettyone.HttpRouterServerHandler.java

License:Apache License

private static HttpResponse createResponse(HttpRequest req, Router<String> router) {
    RouteResult<String> routeResult = router.route(req.getMethod(), req.getUri());

    // Display debug info.
    ////from   www  . j  a  va  2s  . c  o  m
    // For simplicity of this example, route targets are just simple strings.
    // But you can make them classes, and here once you get a target class,
    // you can create an instance of it and dispatch the request to the instance etc.
    StringBuilder content = new StringBuilder();
    content.append("router: \n" + router + "\n");
    content.append("req: " + req + "\n\n");
    content.append("routeResult: \n");
    content.append("target: " + routeResult.target() + "\n");
    content.append("pathParams: " + routeResult.pathParams() + "\n");
    content.append("queryParams: " + routeResult.queryParams() + "\n\n");
    content.append("allowedMethods: " + router.allowedMethods(req.getUri()));

    FullHttpResponse res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
            Unpooled.copiedBuffer(content.toString(), CharsetUtil.UTF_8));

    res.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
    res.headers().set(HttpHeaders.Names.CONTENT_LENGTH, res.content().readableBytes());

    return res;
}

From source file:org.apache.activemq.jms.example.HttpStaticFileServerHandler.java

License:Apache License

@Override
public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e) throws Exception {
    HttpRequest request = (HttpRequest) e.getMessage();
    if (request.getMethod() != HttpMethod.GET) {
        sendError(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED);
        return;// www .  ja  v  a 2s. c  om
    }

    if (request.isChunked()) {
        sendError(ctx, HttpResponseStatus.BAD_REQUEST);
        return;
    }

    String path = sanitizeUri(request.getUri());
    if (path == null) {
        sendError(ctx, HttpResponseStatus.FORBIDDEN);
        return;
    }

    File file = new File(path);
    if (file.isHidden() || !file.exists()) {
        sendError(ctx, HttpResponseStatus.NOT_FOUND);
        return;
    }
    if (!file.isFile()) {
        sendError(ctx, HttpResponseStatus.FORBIDDEN);
        return;
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException fnfe) {
        sendError(ctx, HttpResponseStatus.NOT_FOUND);
        return;
    }
    long fileLength = raf.length();

    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    response.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(fileLength));

    Channel ch = e.getChannel();

    // Write the initial line and the header.
    ch.write(response);

    // Write the content.
    ChannelFuture writeFuture = ch.write(new ChunkedFile(raf, 0, fileLength, 8192));

    // Decide whether to close the connection or not.
    boolean close = HttpHeaders.Values.CLOSE.equalsIgnoreCase(request.getHeader(HttpHeaders.Names.CONNECTION))
            || request.getProtocolVersion().equals(HttpVersion.HTTP_1_0) && !HttpHeaders.Values.KEEP_ALIVE
                    .equalsIgnoreCase(request.getHeader(HttpHeaders.Names.CONNECTION));

    if (close) {
        // Close the connection when the whole content is written out.
        writeFuture.addListener(ChannelFutureListener.CLOSE);
    }
}