List of usage examples for io.netty.handler.codec.http HttpRequest getUri
@Deprecated String getUri();
From source file:org.iotivity.cloud.base.protocols.proxy.CoapHttpProxyHandler.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // in case of Receive Request from http if (msg instanceof HttpRequest) { // Check uri query param that contains coap device uuid // then search those and create coapRequest and send HttpRequest httpRequest = (HttpRequest) msg; QueryStringDecoder queryStringDecoder = new QueryStringDecoder(httpRequest.getUri()); List<String> didList = queryStringDecoder.parameters().get("di"); if (didList != null) { ChannelHandlerContext coapClient = sessionManager.querySession(didList.get(0)); if (coapClient != null) { List<String> uriList = queryStringDecoder.parameters().get("href"); if (uriList != null) { coapClient.channel().attr(keyHttpCtx).set(ctx); coapClient.writeAndFlush(httpRequestToCoAPRequest(uriList.get(0), (HttpRequest) msg)); return; }//from w w w . j a v a 2s. co m } else { Logger.d("Unable to find session: " + didList.get(0)); } } // Prints available sessions to html ctx.writeAndFlush(printsAvailableSessions()).addListener(ChannelFutureListener.CLOSE); return; } if (msg instanceof CoapResponse) { ctx.channel().attr(keyHttpCtx).get().writeAndFlush(coapResponseToHttpResponse((CoapResponse) msg)) .addListener(ChannelFutureListener.CLOSE); return; } // Pass to upper-layer super.channelRead(ctx, msg); }
From source file:org.ireland.jnetty.JNettyServerHandler.java
License:Apache License
@Override public void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (is100ContinueExpected(request)) { send100Continue(ctx);//from w w w.j av a2 s. co m } 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"); List<Map.Entry<String, String>> headers = request.headers().entries(); if (!headers.isEmpty()) { for (Map.Entry<String, String> h : request.headers().entries()) { 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.data(); 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(ctx, trailer); } } }
From source file:org.jboss.aerogear.unifiedpush.test.sender.ProxySetup.java
License:Apache License
public void startProxyServer() { if (backgroundThread == null) { backgroundThread = startBackgroundThread(); }// w w w. ja v a 2 s . com 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.kaaproject.kaa.server.transports.http.transport.netty.RequestDecoder.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, HttpObject httpObject) throws Exception { DecoderResult result = httpObject.getDecoderResult(); if (!result.isSuccess()) { throw new BadRequestException(result.cause()); }/*from w ww .j a v a 2 s .c om*/ Attribute<UUID> sessionUuidAttr = ctx.channel().attr(AbstractNettyServer.UUID_KEY); if (httpObject instanceof HttpRequest) { HttpRequest httpRequest = (HttpRequest) httpObject; LOG.trace("Session: {} got valid HTTP request:\n{}", sessionUuidAttr.get().toString(), httpRequest.headers().toString()); if (httpRequest.getMethod().equals(HttpMethod.POST)) { String uri = httpRequest.getUri(); AbstractCommand cp = (AbstractCommand) commandFactory.getCommandProcessor(uri); cp.setSessionUuid(sessionUuidAttr.get()); cp.setRequest(httpRequest); cp.parse(); ctx.fireChannelRead(cp); } else { LOG.error("Got invalid HTTP method: expecting only POST"); throw new BadRequestException( "Incorrect method " + httpRequest.getMethod().toString() + ", expected POST"); } } else { LOG.warn("Session: {} got invalid HTTP object:\n{}", sessionUuidAttr.get().toString(), httpObject); } }
From source file:org.kuali.test.proxyserver.TestProxyServer.java
License:Educational Community License
/** * * @param request/*from w w w . j a v a2s. c o m*/ * @return */ protected boolean isValidTestRequest(HttpRequest request) { boolean retval = false; String method = request.getMethod().toString(); if (Constants.VALID_HTTP_REQUEST_METHOD_SET.contains(method)) { if (!Utils.isGetImageRequest(method, request.getUri()) && !Utils.isGetJavascriptRequest(method, request.getUri()) && !Utils.isGetCssRequest(method, request.getUri())) { int status = HttpStatus.OK_200; if (!httpStatus.isEmpty()) { status = httpStatus.pop().intValue(); } if (status == HttpStatus.OK_200) { // jump through a few hoops here to prefix the uri with the hostname if (!Utils.isIgnoreUrl(urlPatternsToIgnore, request.getUri())) { io.netty.handler.codec.http.HttpHeaders headers = request.headers(); String host = headers.get(HttpHeaders.HOST); if (StringUtils.isNotBlank(host) && !request.getUri().contains(host)) { retval = !Utils.isIgnoreUrl(urlPatternsToIgnore, host + request.getUri()); } else { retval = true; } } } } } return retval; }
From source file:org.kuali.test.proxyserver.TestProxyServer.java
License:Educational Community License
/** * //ww w. j a va 2 s . co m * @param request * @return * @throws IOException */ public String buildFullUrl(HttpRequest request) throws IOException { StringBuilder retval = new StringBuilder(128); if (!request.getUri().startsWith(Constants.HTTP)) { String platformUrl = webTestPanel.getPlatform().getWebUrl(); String host = request.headers().get(HttpHeaders.HOST); String protocol = Constants.HTTPS; String platformHost = null; if (StringUtils.isNotBlank(platformUrl)) { int pos = platformUrl.indexOf("://"); if (pos > -1) { protocol = platformUrl.substring(0, pos); } else { int pos2 = platformUrl.indexOf(Constants.FORWARD_SLASH, pos + 3); platformHost = platformUrl.substring(pos + 1, pos2); } } String myhost = platformHost; if (StringUtils.isNotBlank(host)) { myhost = host; } if (hostsRequiringHttps.contains(myhost)) { protocol = Constants.HTTPS; } retval.append(protocol); retval.append("://"); if (StringUtils.isNotBlank(host)) { retval.append(host); } else { retval.append(platformHost); } } retval.append(request.getUri()); return retval.toString(); }
From source file:org.mitre.svmp.webrtc.http.PeerConnectionServerHandler.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { //System.out.println(msg.getClass().getName()); DefaultFullHttpResponse response = null; if (msg instanceof HttpRequest) { // All HTTP messages used by the peerconnection_client: ////from w w w . j a v a 2 s .c o m // "GET /sign_in?%s HTTP/1.0\r\n\r\n", client_name_.c_str()); // "POST /message?peer_id=%i&to=%i HTTP/1.0\r\n" // "GET /sign_out?peer_id=%i HTTP/1.0\r\n\r\n", my_id_); // "GET /wait?peer_id=%i HTTP/1.0\r\n\r\n", my_id_); HttpRequest request = (HttpRequest) msg; System.out.println(request.toString()); HttpMethod method = request.getMethod(); String uri = request.getUri(); // QueryStringDecoder queryDecoder = new QueryStringDecoder(uri); // Map<String, List<String>> params = queryDecoder.parameters(); System.out.println("Incoming HTTP request:\n" + method + " " + uri); if (method.equals(HttpMethod.GET)) { // Case: GET /sign_in?%s if (uri.startsWith("/sign_in")) { // should have a username parameter and it should be "fbstreamer" String username = uri.split("[?]")[1]; // return a comma delimited list of name,peer_id,is_connected // where the first line is the info of the peer we're talking to // and all subsequent lines are the set of other connected peers // since fbstreamer on the HTTP side will always be the first peer to connect // lie about the other peer being there ByteBuf content = copiedBuffer( username + "," + FBSTREAM_PEER_ID + ",1\n" + "svmpclient," + CLIENT_PEER_ID + ",1", CharsetUtil.US_ASCII); response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK, content); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().set(CONNECTION, "close"); response.headers().set(PRAGMA, FBSTREAM_PEER_ID); // do we have to set the content-length header ourselves? // if so, how do we calculate it? } // Case: GET /sign_out?peer_id=%i else if (uri.startsWith("/sign_out")) { // TODO might be worth checking that the peer_id is actually FBSTREAM_PEER_ID // doesn't really matter though response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK); response.headers().set(CONNECTION, "close"); response.headers().set(CONTENT_LENGTH, 0); // create a BYE message, no other peers to notify // add it to the sendQueue // TODO } // Case: GET /wait?peer_id=%i else if (uri.startsWith("/wait")) { // pull something off receiveQueue SVMPProtocol.Request pbMsg = receiveQueue.take(); // convert it to JSON String json = Translator.ProtobufToJSON(pbMsg.getWebrtcMsg()); ByteBuf content = copiedBuffer(json, CharsetUtil.US_ASCII); System.out.println("JSON from client:\n" + json); // make HTTP response response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK, content); response.headers().set(CONTENT_TYPE, "text/plain"); // if it's a peer presence info message, set pragma to the client's ID // function handleServerNotification(data) {(String) // trace("Server notification: " + data); // var parsed = data.split(','); // if (parseInt(parsed[2]) != 0) // other_peers[parseInt(parsed[1])] = parsed[0]; // } // shouldn't be any presence messages since we're hard coding // it above in the sign_in case // if it's a message from another peer, set pragma to that peer's ID response.headers().set(PRAGMA, CLIENT_PEER_ID); // peerconnection_server appears to set "Connection: close" for these response.headers().set(CONNECTION, "close"); // send in HTTP response response = null; } else { // some other bad URL response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.NOT_FOUND); } // send response System.out.println("HTTP response:\n" + response.toString()); ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else if (method.equals(HttpMethod.POST) && uri.startsWith("/message")) { // Case: POST /message?peer_id=%i&to=%i isProcessingPost = true; } else { // some other HTTP request we don't support // send an error or something response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.BAD_REQUEST); // send response System.out.println("HTTP response:\n" + response.toString()); ctx.write(response).addListener(ChannelFutureListener.CLOSE); } } else if (msg instanceof HttpContent && isProcessingPost) { // handle body of the POST /message // decode the JSON payload String content = ((HttpContent) msg).content().toString(CharsetUtil.UTF_8); System.out.println("JSON in from fbstream:\n" + content); // convert it to protobuf SVMPProtocol.Response.Builder pbResp = SVMPProtocol.Response.newBuilder(); pbResp.setType(ResponseType.WEBRTC); pbResp.setWebrtcMsg(Translator.JSONToProtobuf(content)); // add it to sendQueue sendQueue.add(pbResp.build()); // generate appropriate HTTP response response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK); response.headers().set(CONNECTION, "close"); // send response System.out.println("HTTP response:\n" + response.toString()); ctx.write(response).addListener(ChannelFutureListener.CLOSE); isProcessingPost = false; } }
From source file:org.mockserver.integration.testserver.TestServerHandler.java
License:Apache License
@Override public void channelRead0(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 ww .j a v a 2s. c o m FullHttpResponse response; if (req.getUri().equals("/unknown")) { response = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND); } else if (req.getUri().equals("/test_headers_and_body")) { response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer("an_example_body".getBytes(Charsets.UTF_8))); response.headers().set("X-Test", "test_headers_and_body"); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); } else if (req.getUri().equals("/test_headers_only")) { response = new DefaultFullHttpResponse(HTTP_1_1, OK); response.headers().set("X-Test", "test_headers_only"); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); } else { response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer("Hello World".getBytes(Charsets.UTF_8))); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); } ctx.write(response).addListener(ChannelFutureListener.CLOSE); } }
From source file:org.nosceon.titanite.WebsocketHandler.java
License:Apache License
private static FullHttpRequest toFullHttpRequest(HttpRequest request) { DefaultFullHttpRequest fullRequest = new DefaultFullHttpRequest(request.getProtocolVersion(), request.getMethod(), request.getUri()); fullRequest.headers().set(request.headers()); return fullRequest; }
From source file:org.opendaylight.netconf.sal.streams.websockets.WebSocketServerHandler.java
License:Open Source License
/** * Get web socket location from HTTP request. * * @param req/* w w w . j av a2s .c o m*/ * HTTP request from which the location will be returned * @return String representation of web socket location. */ private static String getWebSocketLocation(final HttpRequest req) { return "ws://" + req.headers().get(HOST) + req.getUri(); }