List of usage examples for io.netty.handler.codec.http HttpHeaders getAll
public List<String> getAll(CharSequence name)
From source file:co.paralleluniverse.comsat.webactors.netty.HttpRequestWrapper.java
License:Open Source License
static ImmutableListMultimap<String, String> extractHeaders(HttpHeaders headers) { if (headers != null) { final ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder(); for (final String n : headers.names()) builder.putAll(n, headers.getAll(n)); return builder.build(); }/*from w w w. j a v a 2 s . c o m*/ return null; }
From source file:co.paralleluniverse.comsat.webactors.netty.NettyHttpRequest.java
License:Open Source License
static ImmutableListMultimap<String, String> extractHeaders(HttpHeaders headers) { if (headers != null) { final ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder(); for (final String n : headers.names()) // Normalize header names by their conversion to lower case builder.putAll(n.toLowerCase(Locale.ENGLISH), headers.getAll(n)); return builder.build(); }// w w w . j a va 2 s . c om return null; }
From source file:com.buildria.mocking.stub.Call.java
License:Open Source License
public static Call fromRequest(HttpRequest req) { Objects.requireNonNull(req);//from w w w .j a va 2 s . c om Call call = new Call(); call.method = req.getMethod().name(); QueryStringDecoder decoder = new QueryStringDecoder(req.getUri()); call.path = QueryStringDecoder.decodeComponent(decoder.path()); Map<String, List<String>> params = decoder.parameters(); for (String name : params.keySet()) { List<String> values = params.get(name); for (String value : values) { call.parameters.add(new Pair(name, value)); } } HttpHeaders headers = req.headers(); for (String name : headers.names()) { List<String> values = headers.getAll(name); for (String value : values) { call.headers.add(new Pair(name, value)); } if (CONTENT_TYPE.equalsIgnoreCase(name)) { call.contentType = MediaType.parse(headers.get(CONTENT_TYPE)); } } if (req instanceof ByteBufHolder) { ByteBuf buf = ((ByteBufHolder) req).content(); if (buf != null) { call.body = new byte[buf.readableBytes()]; buf.readBytes(call.body); } } return call; }
From source file:com.mastfrog.netty.http.client.CookieStore.java
License:Open Source License
void extract(HttpHeaders headers) { List<String> hdrs = headers.getAll(Headers.SET_COOKIE.name()); if (!hdrs.isEmpty()) { Lock writeLock = lock.writeLock(); try {/*w w w . j ava2 s. c om*/ writeLock.lock(); for (String header : hdrs) { try { Cookie cookie = Headers.SET_COOKIE.toValue(header); add(cookie); } catch (Exception e) { if (errorHandler != null) { errorHandler.receive(e); } else { Exceptions.chuck(e); } } } } finally { writeLock.unlock(); } } }
From source file:com.netflix.recipes.rss.netty.NettyHandlerContainer.java
License:Open Source License
private InBoundHeaders getHeaders(FullHttpRequest httpRequest) { InBoundHeaders headers = new InBoundHeaders(); HttpHeaders httpHeaders = httpRequest.headers(); for (String name : httpHeaders.names()) { headers.put(name, httpHeaders.getAll(name)); }//from w w w . j av a 2 s .co m return headers; }
From source file:com.twocater.diamond.core.netty.http.HttpDecoder.java
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { LoggerConstant.nettyHandlerLog.debug("{}", new Object[] { ctx.channel() }); FullHttpRequest request = (FullHttpRequest) msg; try {//from w w w. ja va2 s. c o m if (request.getDecoderResult().isFailure()) { debug.debug("decoderfail:{}", request); ctx.close(); return; } // LoggingHandler HttpHeaders headers = request.headers(); // StringBuilder buf = new StringBuilder(); // 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"); // } // System.out.println(buf.toString()); // ? Map<String, List<String>> headersMap = new HashMap<String, List<String>>(); for (String name : headers.names()) { headersMap.put(name, headers.getAll(name)); } // ?? byte[] data = null; int n = request.content().readableBytes(); if (n > 0) { data = new byte[n]; request.content().readBytes(data); } HttpRequestMessage httpRequestMessage = new HttpRequestMessage(request.getMethod(), request.getProtocolVersion(), request.getUri(), headersMap, data); ctx.fireChannelRead(httpRequestMessage); } finally { // ???netty?? ReferenceCountUtil.release(msg); } }
From source file:divconq.http.multipart.HttpPostRequestEncoder.java
License:Apache License
/** * Finalize the request by preparing the Header in the request and returns the request ready to be sent.<br> * Once finalized, no data must be added.<br> * If the request does not need chunk (isChunked() == false), this request is the only object to send to the remote * server./*w w w . ja v a 2 s . c om*/ * * @return the request object (chunked or not according to size of body) * @throws ErrorDataEncoderException * if the encoding is in error or if the finalize were already done */ public HttpRequest finalizeRequest() throws ErrorDataEncoderException { // Finalize the multipartHttpDatas if (!headerFinalized) { if (isMultipart) { InternalAttribute internal = new InternalAttribute(charset); if (duringMixedMode) { internal.addValue("\r\n--" + multipartMixedBoundary + "--"); } internal.addValue("\r\n--" + multipartDataBoundary + "--\r\n"); multipartHttpDatas.add(internal); multipartMixedBoundary = null; currentFileUpload = null; duringMixedMode = false; globalBodySize += internal.size(); } headerFinalized = true; } else { throw new ErrorDataEncoderException("Header already encoded"); } HttpHeaders headers = request.headers(); List<String> contentTypes = headers.getAll(HttpHeaders.Names.CONTENT_TYPE); List<String> transferEncoding = headers.getAll(HttpHeaders.Names.TRANSFER_ENCODING); if (contentTypes != null) { headers.remove(HttpHeaders.Names.CONTENT_TYPE); for (String contentType : contentTypes) { // "multipart/form-data; boundary=--89421926422648" if (contentType.toLowerCase().startsWith(HttpHeaders.Values.MULTIPART_FORM_DATA.toString())) { // ignore } else if (contentType.toLowerCase() .startsWith(HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED.toString())) { // ignore } else { headers.add(HttpHeaders.Names.CONTENT_TYPE, contentType); } } } if (isMultipart) { String value = HttpHeaders.Values.MULTIPART_FORM_DATA + "; " + HttpHeaders.Values.BOUNDARY + '=' + multipartDataBoundary; headers.add(HttpHeaders.Names.CONTENT_TYPE, value); } else { // Not multipart headers.add(HttpHeaders.Names.CONTENT_TYPE, HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED); } // Now consider size for chunk or not long realSize = globalBodySize; if (isMultipart) { iterator = multipartHttpDatas.listIterator(); } else { realSize -= 1; // last '&' removed iterator = multipartHttpDatas.listIterator(); } headers.set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(realSize)); if (realSize > HttpPostBodyUtil.chunkSize || isMultipart) { isChunked = true; if (transferEncoding != null) { headers.remove(HttpHeaders.Names.TRANSFER_ENCODING); for (String v : transferEncoding) { if (HttpHeaders.equalsIgnoreCase(v, HttpHeaders.Values.CHUNKED)) { // ignore } else { headers.add(HttpHeaders.Names.TRANSFER_ENCODING, v); } } } HttpHeaders.setTransferEncodingChunked(request); // wrap to hide the possible content return new WrappedHttpRequest(request); } else { // get the only one body and set it to the request HttpContent chunk = nextChunk(); if (request instanceof FullHttpRequest) { FullHttpRequest fullRequest = (FullHttpRequest) request; ByteBuf chunkContent = chunk.content(); if (fullRequest.content() != chunkContent) { fullRequest.content().clear().writeBytes(chunkContent); chunkContent.release(); } return fullRequest; } else { return new WrappedFullHttpRequest(request, chunk); } } }
From source file:gribbit.http.request.Request.java
License:Open Source License
public Request(ChannelHandlerContext ctx, HttpRequest httpReq) throws ResponseException { this.reqReceivedTimeEpochMillis = System.currentTimeMillis(); this.httpRequest = httpReq; HttpHeaders headers = httpReq.headers(); // Netty changes the URI of the request to "/bad-request" if the HTTP request was malformed this.rawURL = httpReq.uri(); if (rawURL.equals("/bad-request")) { throw new BadRequestException(); } else if (rawURL.isEmpty()) { rawURL = "/"; }/*from www. ja va 2 s . c om*/ // Decode the URL RequestURL requestURL = new RequestURL(rawURL); this.normalizedURL = requestURL.getNormalizedPath(); this.queryParamToVals = requestURL.getQueryParams(); // TODO: figure out how to detect HTTP/2 connections this.httpVersion = httpReq.protocolVersion().toString(); // Get HTTP2 stream ID this.streamId = headers.getAsString(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text()); this.isSecure = ctx.pipeline().get(SslHandler.class) != null; // TODO: is this correct for HTTP2? // Decode cookies try { for (CharSequence cookieHeader : headers.getAll(COOKIE)) { for (Cookie cookie : ServerCookieDecoder.STRICT.decode(cookieHeader.toString())) { // Log.fine("Cookie in request: " + nettyCookie); if (cookieNameToCookies == null) { cookieNameToCookies = new HashMap<>(); } String cookieName = cookie.name(); // Multiple cookies may be present in the request with the same name but with different paths ArrayList<Cookie> cookiesWithThisName = cookieNameToCookies.get(cookieName); if (cookiesWithThisName == null) { cookieNameToCookies.put(cookieName, cookiesWithThisName = new ArrayList<>()); } cookiesWithThisName.add(cookie); } } } catch (IllegalArgumentException e) { // Malformed cookies cause ServerCookieDecoder to throw IllegalArgumentException // Log.info("Malformed cookie in request"); throw new BadRequestException(); } // Sort cookies into decreasing order of path length, in case client doesn't conform to RFC6295, // delivering the cookies in this order itself. This allows us to get the most likely single // cookie for a given cookie name by reading the first cookie in a list for a given name. if (cookieNameToCookies != null) { for (Entry<String, ArrayList<Cookie>> ent : cookieNameToCookies.entrySet()) { Collections.sort(ent.getValue(), COOKIE_COMPARATOR); } } this.method = httpReq.method(); // Force the GET method if HEAD is requested this.isHEADRequest = this.method == HttpMethod.HEAD; if (this.isHEADRequest) { this.method = HttpMethod.GET; } this.isKeepAlive = HttpUtil.isKeepAlive(httpReq) && httpReq.protocolVersion().equals(HttpVersion.HTTP_1_0); CharSequence host = headers.get(HOST); this.host = host == null ? null : host.toString(); this.xRequestedWith = headers.get("X-Requested-With"); this.accept = headers.get(ACCEPT); this.acceptCharset = headers.get(ACCEPT_CHARSET); this.acceptLanguage = headers.get(ACCEPT_LANGUAGE); this.origin = headers.get(ORIGIN); this.referer = headers.get(REFERER); this.userAgent = headers.get(USER_AGENT); InetSocketAddress requestorSocketAddr = (InetSocketAddress) ctx.channel().remoteAddress(); if (requestorSocketAddr != null) { InetAddress address = requestorSocketAddr.getAddress(); if (address != null) { this.requestor = address.getHostAddress(); } } CharSequence acceptEncoding = headers.get(ACCEPT_ENCODING); this.acceptEncodingGzip = acceptEncoding != null && acceptEncoding.toString().toLowerCase().contains("gzip"); this.ifModifiedSince = headers.get(IF_MODIFIED_SINCE); if (this.ifModifiedSince != null && this.ifModifiedSince.length() > 0) { this.ifModifiedSinceEpochSecond = ZonedDateTime .parse(this.ifModifiedSince, DateTimeFormatter.RFC_1123_DATE_TIME).toEpochSecond(); } // // If this is a hash URL, look up original URL whose served resource was hashed to give this hash URL. // // We only need to serve the resource at a hash URL once per resource per client, since resources served // // from hash URLs are indefinitely cached in the browser. // // TODO: Move cache-busting out of http package // this.urlHashKey = CacheExtension.getHashKey(this.urlPath); // this.urlPathUnhashed = this.urlHashKey != null ? CacheExtension.getOrigURL(this.urlPath) : this.urlPath; // // Get flash messages from cookie, if any // this.flashMessages = FlashMessage.fromCookieString(getCookieValue(Cookie.FLASH_COOKIE_NAME)); }
From source file:io.werval.server.netty.NettyHttpFactories.java
License:Apache License
private static Map<String, List<String>> headersToMap(HttpHeaders nettyHeaders) { Map<String, List<String>> headers = new HashMap<>(); for (String name : nettyHeaders.names()) { if (!headers.containsKey(name)) { headers.put(name, new ArrayList<>()); }//from w w w. ja v a 2 s . c o m for (String value : nettyHeaders.getAll(name)) { headers.get(name).add(value); } } return headers; }
From source file:org.apache.olingo.netty.server.core.ODataNettyHandlerImplTest.java
License:Apache License
@Test public void testNettyReqResp_POSTMethod() { EntityProcessor processor = mock(EntityProcessor.class); final ODataNetty odata = ODataNetty.newInstance(); final ServiceMetadata metadata = odata.createServiceMetadata(new EdmTechProvider(), Collections.<EdmxReference>emptyList()); ODataNettyHandler handler = odata.createNettyHandler(metadata); handler.register(processor);//from ww w .ja v a 2 s .c o m HttpRequest nettyRequest = mock(DefaultFullHttpRequest.class); io.netty.handler.codec.http.HttpMethod httpMethod = mock(io.netty.handler.codec.http.HttpMethod.class); when(httpMethod.name()).thenReturn("POST"); when(nettyRequest.method()).thenReturn(httpMethod); HttpVersion httpVersion = mock(HttpVersion.class); when(httpVersion.text()).thenReturn("HTTP/1.0"); when(nettyRequest.protocolVersion()).thenReturn(httpVersion); when(nettyRequest.uri()).thenReturn("/odata.svc/ESAllPrim"); HttpHeaders headers = mock(HttpHeaders.class); headers.set("Content-Type", "application/json"); Set<String> set = new HashSet<String>(); set.add("Content-Type"); when(headers.names()).thenReturn(set); List<String> headerValues = new ArrayList<String>(); headerValues.add("application/json"); when(headers.getAll("Content-Type")).thenReturn(headerValues); when(nettyRequest.headers()).thenReturn(headers); String content = "{\"@odata.context\": \"$metadata#ESAllPrim/$entity\"," + "\"PropertyInt16\": 32767," + "\"PropertyString\": \"First Resource &&&- positive values\"," + "\"PropertyBoolean\": true," + "\"PropertyByte\": 255," + "\"PropertySByte\": 127," + "\"PropertyInt32\": 2147483647," + "\"PropertyInt64\": 9223372036854775807," + "\"PropertySingle\": 17900000," + "\"PropertyDouble\": -179000," + "\"PropertyDecimal\": 34," + "\"PropertyBinary\": \"ASNFZ4mrze8=\"," + "\"PropertyDate\": \"2012-12-03\"," + "\"PropertyDateTimeOffset\": \"2012-12-03T07:16:23Z\"," + "\"PropertyDuration\": \"PT6S\"," + "\"PropertyGuid\": \"01234567-89ab-cdef-0123-456789abcdef\"," + "\"PropertyTimeOfDay\": \"03:26:05\"}"; byte[] arr = new byte[content.length()]; arr = content.getBytes(); when(((DefaultFullHttpRequest) nettyRequest).content()).thenReturn(Unpooled.copiedBuffer(arr)); HttpResponse nettyResponse = mock(DefaultFullHttpResponse.class); when(nettyResponse.status()).thenReturn(HttpResponseStatus.CREATED); when(nettyResponse.headers()).thenReturn(headers); when(((DefaultFullHttpResponse) nettyResponse).content()).thenReturn(Unpooled.buffer()); Map<String, String> requestParams = new HashMap<String, String>(); requestParams.put("contextPath", "/odata.svc"); handler.processNettyRequest(nettyRequest, nettyResponse, requestParams); nettyResponse.status(); assertEquals(HttpStatusCode.CREATED.getStatusCode(), HttpResponseStatus.CREATED.code()); }