List of usage examples for io.netty.handler.codec.http HttpRequest getUri
@Deprecated String getUri();
From source file:com.github.ambry.rest.NettyRequest.java
License:Open Source License
/** * Wraps the {@code request} in an implementation of {@link RestRequest} so that other layers can understand the * request./*from w w w. ja v a2s. c om*/ * <p/> * Note on content size: The content size is deduced in the following order:- * 1. From the {@link RestUtils.Headers#BLOB_SIZE} header. * 2. If 1 fails, from the {@link HttpHeaders.Names#CONTENT_LENGTH} header. * 3. If 2 fails, it is set to -1 which means that the content size is unknown. * If content size is set in the header (i.e. not -1), the actual content size should match that value. Otherwise, an * exception will be thrown. * @param request the {@link HttpRequest} that needs to be wrapped. * @param nettyMetrics the {@link NettyMetrics} instance to use. * @throws IllegalArgumentException if {@code request} is null. * @throws RestServiceException if the {@link HttpMethod} defined in {@code request} is not recognized as a * {@link RestMethod}. */ public NettyRequest(HttpRequest request, NettyMetrics nettyMetrics) throws RestServiceException { if (request == null) { throw new IllegalArgumentException("Received null HttpRequest"); } restRequestMetricsTracker.nioMetricsTracker.markRequestReceived(); HttpMethod httpMethod = request.getMethod(); if (httpMethod == HttpMethod.GET) { restMethod = RestMethod.GET; } else if (httpMethod == HttpMethod.POST) { restMethod = RestMethod.POST; } else if (httpMethod == HttpMethod.DELETE) { restMethod = RestMethod.DELETE; } else if (httpMethod == HttpMethod.HEAD) { restMethod = RestMethod.HEAD; } else { nettyMetrics.unsupportedHttpMethodError.inc(); throw new RestServiceException("http method not supported: " + httpMethod, RestServiceErrorCode.UnsupportedHttpMethod); } this.request = request; this.query = new QueryStringDecoder(request.getUri()); this.nettyMetrics = nettyMetrics; if (HttpHeaders.getHeader(request, RestUtils.Headers.BLOB_SIZE, null) != null) { size = Long.parseLong(HttpHeaders.getHeader(request, RestUtils.Headers.BLOB_SIZE)); } else { size = HttpHeaders.getContentLength(request, -1); } // query params. for (Map.Entry<String, List<String>> e : query.parameters().entrySet()) { StringBuilder value = null; if (e.getValue() != null) { StringBuilder combinedValues = combineVals(new StringBuilder(), e.getValue()); if (combinedValues.length() > 0) { value = combinedValues; } } allArgs.put(e.getKey(), value); } Set<io.netty.handler.codec.http.Cookie> nettyCookies = null; // headers. for (Map.Entry<String, String> e : request.headers()) { StringBuilder sb; if (e.getKey().equals(HttpHeaders.Names.COOKIE)) { String value = e.getValue(); if (value != null) { nettyCookies = CookieDecoder.decode(value); } } else { boolean valueNull = request.headers().get(e.getKey()) == null; if (!valueNull && allArgs.get(e.getKey()) == null) { sb = new StringBuilder(e.getValue()); allArgs.put(e.getKey(), sb); } else if (!valueNull) { sb = (StringBuilder) allArgs.get(e.getKey()); sb.append(MULTIPLE_HEADER_VALUE_DELIMITER).append(e.getValue()); } else if (!allArgs.containsKey(e.getKey())) { allArgs.put(e.getKey(), null); } } } // turn all StringBuilders into String for (Map.Entry<String, Object> e : allArgs.entrySet()) { if (allArgs.get(e.getKey()) != null) { allArgs.put(e.getKey(), (e.getValue()).toString()); } } // add cookies to the args as java cookies if (nettyCookies != null) { Set<javax.servlet.http.Cookie> cookies = convertHttpToJavaCookies(nettyCookies); allArgs.put(RestUtils.Headers.COOKIE, cookies); } allArgsReadOnly = Collections.unmodifiableMap(allArgs); }
From source file:com.github.mike10004.seleniumhelp.TrafficMonitorFilter.java
License:Apache License
protected void captureQueryParameters(HttpRequest httpRequest, HarRequest harRequest) { // capture query parameters. it is safe to assume the query string is UTF-8, since it "should" be in US-ASCII (a subset of UTF-8), // but sometimes does include UTF-8 characters. QueryStringDecoder queryStringDecoder = new QueryStringDecoder(httpRequest.getUri(), StandardCharsets.UTF_8); try {/*from w w w . ja v a2s . co m*/ for (Map.Entry<String, List<String>> entry : queryStringDecoder.parameters().entrySet()) { for (String value : entry.getValue()) { harRequest.getQueryString().add(new HarNameValuePair(entry.getKey(), value)); } } } catch (IllegalArgumentException e) { // QueryStringDecoder will throw an IllegalArgumentException if it cannot interpret a query string. rather than cause the entire request to // fail by propagating the exception, simply skip the query parameter capture. log.info("Unable to decode query parameters on URI: " + httpRequest.getUri(), e); } }
From source file:com.github.mike10004.seleniumhelp.TrafficMonitorFilter.java
License:Apache License
protected void captureRequestContent(HttpRequest httpRequest, byte[] fullMessage, HarRequest harRequest) { if (fullMessage.length == 0) { return;//w ww . j ava 2 s . co m } String contentType = HttpHeaders.getHeader(httpRequest, HttpHeaders.Names.CONTENT_TYPE); if (contentType == null) { log.warn("No content type specified in request to {}. Content will be treated as {}", httpRequest.getUri(), BrowserMobHttpUtil.UNKNOWN_CONTENT_TYPE); contentType = BrowserMobHttpUtil.UNKNOWN_CONTENT_TYPE; } HarPostData postData = new HarPostData(); harRequest.setPostData(postData); postData.setMimeType(contentType); final boolean urlEncoded = contentType.startsWith(HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED); Charset charset; try { charset = BrowserMobHttpUtil.readCharsetInContentTypeHeader(contentType); } catch (UnsupportedCharsetException e) { log.warn( "Found unsupported character set in Content-Type header '{}' in HTTP request to {}. Content will not be captured in HAR.", contentType, httpRequest.getUri(), e); return; } if (charset == null) { // no charset specified, so use the default -- but log a message since this might not encode the data correctly charset = BrowserMobHttpUtil.DEFAULT_HTTP_CHARSET; log.debug("No charset specified; using charset {} to decode contents to {}", charset, httpRequest.getUri()); } if (urlEncoded) { String textContents = BrowserMobHttpUtil.getContentAsString(fullMessage, charset); QueryStringDecoder queryStringDecoder = new QueryStringDecoder(textContents, charset, false); ImmutableList.Builder<HarPostDataParam> paramBuilder = ImmutableList.builder(); for (Map.Entry<String, List<String>> entry : queryStringDecoder.parameters().entrySet()) { for (String value : entry.getValue()) { paramBuilder.add(new HarPostDataParam(entry.getKey(), value)); } } harRequest.getPostData().setParams(paramBuilder.build()); } else { //TODO: implement capture of files and multipart form data // not URL encoded, so let's grab the body of the POST and capture that String postBody = BrowserMobHttpUtil.getContentAsString(fullMessage, charset); harRequest.getPostData().setText(postBody); } }
From source file:com.github.mike10004.seleniumhelp.TrafficMonitorFilter.java
License:Apache License
/** * Populates the serverIpAddress field of the harEntry using the internal hostname to IP address cache. * * @param httpRequest HTTP request to take the hostname from *//* ww w . jav a 2 s.co m*/ protected void populateAddressFromCache(HttpRequest httpRequest) { String serverHost = getHost(httpRequest); if (serverHost != null && !serverHost.isEmpty()) { String resolvedAddress = ResolvedHostnameCacheFilter.getPreviouslyResolvedAddressForHost(serverHost); if (resolvedAddress != null) { serverIpAddress = (resolvedAddress); } else { // the resolvedAddress may be null if the ResolvedHostnameCacheFilter has expired the entry (which is unlikely), // or in the far more common case that the proxy is using a chained proxy to connect to connect to the // remote host. since the chained proxy handles IP address resolution, the IP address in the HAR must be blank. log.trace("Unable to find cached IP address for host: {}. IP address in HAR entry will be blank.", serverHost); } } else { log.warn("Unable to identify host from request uri: {}", httpRequest.getUri()); } }
From source file:com.helome.messagecenter.master.HttpServerHandler.java
License:Apache License
@Override protected void messageReceived(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (is100ContinueExpected(request)) { send100Continue(ctx);/*from w ww . j a v a 2 s. c om*/ } buf.setLength(0); if ("/connection".equals(request.getUri())) { buf.append("{\"state\":1,\"connection\":\"192.168.1.13:9000\"}"); } else { buf.append("{\"state\":0}"); } writeResponse(request, ctx); } }
From source file:com.imaginarycode.minecraft.bungeejson.impl.httpserver.HttpServerHandler.java
License:Open Source License
private HttpResponse getResponse(ChannelHandlerContext channelHandlerContext, HttpRequest hr) { QueryStringDecoder query = new QueryStringDecoder(hr.getUri()); Multimap<String, String> params = createMultimapFromMap(query.parameters()); Object reply;/*from w w w.ja v a 2 s . c om*/ HttpResponseStatus hrs; final RequestHandler handler = BungeeJSONPlugin.getRequestManager().getHandlerForEndpoint(query.path()); if (handler == null) { reply = BungeeJSONUtilities.error("No such endpoint exists."); hrs = HttpResponseStatus.NOT_FOUND; } else { final ApiRequest ar = new HttpServerApiRequest( ((InetSocketAddress) channelHandlerContext.channel().remoteAddress()).getAddress(), params, bodyBuilder.toString()); try { reply = handler.handle(ar); hrs = HttpResponseStatus.OK; } catch (Throwable throwable) { hrs = HttpResponseStatus.INTERNAL_SERVER_ERROR; reply = BungeeJSONUtilities .error("An internal error has occurred. Information has been logged to the console."); BungeeJSONPlugin.getPlugin().getLogger().log(Level.WARNING, "Error while handling " + hr.getUri() + " from " + ar.getRemoteIp(), throwable); } } String json = BungeeJSONPlugin.getPlugin().getGson().toJson(reply); DefaultFullHttpResponse hreply = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, hrs, Unpooled.wrappedBuffer(json.getBytes(CharsetUtil.UTF_8))); // Add a reminder that we're still running the show. hreply.headers().set("Content-Type", "application/json; charset=UTF-8"); hreply.headers().set("Access-Control-Allow-Origin", "*"); hreply.headers().set("Server", "BungeeJSON/0.1"); hreply.headers().set("Content-Length", json.length()); return hreply; }
From source file:com.jt.flash.proxy.handler.ProxyFrontendHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext ctx, Object msg) { final Channel inboundChannel = ctx.channel(); log.info("read {}", msg); if (msg instanceof HttpRequest) { HttpRequest request = (HttpRequest) msg; final String uri = request.getUri(); String host = request.headers().get("Host"); if (host.contains(":")) { host = host.substring(0, host.indexOf(":")); }/* w w w .j a v a 2s .c om*/ final Map<Location, Upstream> mapping = ConfigService.getProxyContext().getMapping(); for (Map.Entry<Location, Upstream> entry : mapping.entrySet()) { if (uri.startsWith(entry.getKey().getUri())) { if ("localhost".equalsIgnoreCase(host) || host.equals(entry.getKey().getHost())) { final BlockingQueue<UpstreamNode> upstreamNodes = entry.getValue().getUpstreamNodes(); UpstreamNode choose = getNode(upstreamNodes); if (choose != null) { remoteHost = choose.getIp(); remotePort = choose.getPort(); } } } } log.info("uri {}, host {} {}, port {}|inboundChannel|{}", uri, host, remoteHost, remotePort, inboundChannel); if (remoteHost != null) { processRequest(ctx, msg, inboundChannel, remoteHost, remotePort); } else { log.warn("no upstream|inboundChannel|" + inboundChannel + "|remoteHost|" + remoteHost); ctx.close(); } } }
From source file:com.linkedin.flashback.netty.builder.RecordedHttpRequestBuilder.java
License:Open Source License
public void interpretHttpRequest(HttpRequest nettyHttpRequest) { _httpMethod = nettyHttpRequest.getMethod().toString(); try {//w w w. j av a2 s . c o m URI uri = new URI(nettyHttpRequest.getUri()); if (uri.isAbsolute()) { _uri = uri; } else { String hostName = getHeader(HttpHeaders.Names.HOST); if (!Strings.isNullOrEmpty(hostName)) { _uri = new URI(String.format("https://%s%s", hostName, uri)); } else { _path = uri.toString(); } } } catch (URISyntaxException e) { throw new IllegalStateException("Invalid URI in underlying request", e); } }
From source file:com.linkedin.mitm.proxy.connectionflow.ConnectionFlowProcessor.java
License:Open Source License
/** * Resolve remote address//from w w w .j a v a2s.c om * */ private static InetSocketAddress getRemoteAddress(HttpRequest httpRequest) { String uri = httpRequest.getUri(); String uriWithoutProtocol; if (HTTP_PREFIX.matcher(uri).matches()) { uriWithoutProtocol = StringUtils.substringAfter(uri, "://"); } else { uriWithoutProtocol = uri; } String hostAndPort; if (uriWithoutProtocol.contains("/")) { hostAndPort = uriWithoutProtocol.substring(0, uriWithoutProtocol.indexOf("/")); } else { hostAndPort = uriWithoutProtocol; } String hostName; int port; if (hostAndPort.contains(":")) { int index = hostAndPort.indexOf(":"); hostName = hostAndPort.substring(0, index); port = Integer.parseInt(hostAndPort.substring(index + 1)); } else { hostName = hostAndPort; port = 80; } return new InetSocketAddress(hostName, port); }
From source file:com.litgh.httprouter.Router.java
License:Open Source License
public void serverHttp(HttpRequest req, FullHttpResponse resp) { try {/*from w w w .j a va2s . co m*/ Node root = this.trees.get(req.getMethod().toString()); if (root != null) { String path = req.getUri(); Action action = cache.get(path); if (action == null) { action = root.getValue(path); } if (action.getHandler() != null) { action.getHandler().handle(req, resp, action.getP()); return; } } } catch (Exception e) { e.printStackTrace(); } }