List of usage examples for io.netty.handler.codec.http HttpHeaders contains
public boolean contains(CharSequence name)
From source file:cc.changic.platform.etl.schedule.http.HttpHeaderUtil.java
License:Apache License
/** * Returns the content length of the specified web socket message. If the * specified message is not a web socket message, {@code -1} is returned. *//* www . ja v a 2s.c om*/ private static int getWebSocketContentLength(HttpMessage message) { // WebSockset messages have constant content-lengths. HttpHeaders h = message.headers(); if (message instanceof HttpRequest) { HttpRequest req = (HttpRequest) message; if (HttpMethod.GET.equals(req.method()) && h.contains(Names.SEC_WEBSOCKET_KEY1) && h.contains(Names.SEC_WEBSOCKET_KEY2)) { return 8; } } else if (message instanceof HttpResponse) { HttpResponse res = (HttpResponse) message; if (res.status().code() == 101 && h.contains(Names.SEC_WEBSOCKET_ORIGIN) && h.contains(Names.SEC_WEBSOCKET_LOCATION)) { return 16; } } // Not a web socket message return -1; }
From source file:com.github.ambry.admin.AdminIntegrationTest.java
License:Open Source License
/** * Gets the headers of the blob with blob ID {@code blobId} and verifies them against what is expected. * @param blobId the blob ID of the blob to HEAD. * @param expectedHeaders the expected headers in the response. * @throws ExecutionException/* ww w . ja v a 2 s. c o m*/ * @throws InterruptedException */ private void getHeadAndVerify(String blobId, HttpHeaders expectedHeaders) throws ExecutionException, InterruptedException { FullHttpRequest httpRequest = buildRequest(HttpMethod.HEAD, blobId, null, null); Queue<HttpObject> responseParts = nettyClient.sendRequest(httpRequest, null, null).get(); HttpResponse response = (HttpResponse) responseParts.poll(); discardContent(responseParts, 1); assertEquals("Unexpected response status", HttpResponseStatus.OK, response.getStatus()); checkCommonGetHeadHeaders(response.headers(), expectedHeaders); assertEquals("Content-Length does not match blob size", Long.parseLong(expectedHeaders.get(RestUtils.Headers.BLOB_SIZE)), HttpHeaders.getContentLength(response)); assertEquals("Blob size does not match", expectedHeaders.get(RestUtils.Headers.BLOB_SIZE), HttpHeaders.getHeader(response, RestUtils.Headers.BLOB_SIZE)); assertEquals(RestUtils.Headers.SERVICE_ID + " does not match", expectedHeaders.get(RestUtils.Headers.SERVICE_ID), HttpHeaders.getHeader(response, RestUtils.Headers.SERVICE_ID)); assertEquals(RestUtils.Headers.PRIVATE + " does not match", expectedHeaders.get(RestUtils.Headers.PRIVATE), HttpHeaders.getHeader(response, RestUtils.Headers.PRIVATE)); assertEquals(RestUtils.Headers.AMBRY_CONTENT_TYPE + " does not match", expectedHeaders.get(RestUtils.Headers.AMBRY_CONTENT_TYPE), HttpHeaders.getHeader(response, RestUtils.Headers.AMBRY_CONTENT_TYPE)); assertTrue("No " + RestUtils.Headers.CREATION_TIME, HttpHeaders.getHeader(response, RestUtils.Headers.CREATION_TIME, null) != null); if (Long.parseLong(expectedHeaders.get(RestUtils.Headers.TTL)) != Utils.Infinite_Time) { assertEquals(RestUtils.Headers.TTL + " does not match", expectedHeaders.get(RestUtils.Headers.TTL), HttpHeaders.getHeader(response, RestUtils.Headers.TTL)); } if (expectedHeaders.contains(RestUtils.Headers.OWNER_ID)) { assertEquals(RestUtils.Headers.OWNER_ID + " does not match", expectedHeaders.get(RestUtils.Headers.OWNER_ID), HttpHeaders.getHeader(response, RestUtils.Headers.OWNER_ID)); } }
From source file:com.github.ambry.frontend.FrontendIntegrationTest.java
License:Open Source License
/** * Verifies blob properties from output, to that sent in during input * @param expectedHeaders the expected headers in the response. * @param response the {@link HttpResponse} that contains the headers. *///from w w w. j av a2s .c om private void verifyBlobProperties(HttpHeaders expectedHeaders, HttpResponse response) { assertEquals("Blob size does not match", Long.parseLong(expectedHeaders.get(RestUtils.Headers.BLOB_SIZE)), Long.parseLong(HttpHeaders.getHeader(response, RestUtils.Headers.BLOB_SIZE))); assertEquals(RestUtils.Headers.SERVICE_ID + " does not match", expectedHeaders.get(RestUtils.Headers.SERVICE_ID), HttpHeaders.getHeader(response, RestUtils.Headers.SERVICE_ID)); assertEquals(RestUtils.Headers.PRIVATE + " does not match", expectedHeaders.get(RestUtils.Headers.PRIVATE), HttpHeaders.getHeader(response, RestUtils.Headers.PRIVATE)); assertEquals(RestUtils.Headers.AMBRY_CONTENT_TYPE + " does not match", expectedHeaders.get(RestUtils.Headers.AMBRY_CONTENT_TYPE), HttpHeaders.getHeader(response, RestUtils.Headers.AMBRY_CONTENT_TYPE)); assertTrue("No " + RestUtils.Headers.CREATION_TIME, HttpHeaders.getHeader(response, RestUtils.Headers.CREATION_TIME, null) != null); if (Long.parseLong(expectedHeaders.get(RestUtils.Headers.TTL)) != Utils.Infinite_Time) { assertEquals(RestUtils.Headers.TTL + " does not match", expectedHeaders.get(RestUtils.Headers.TTL), HttpHeaders.getHeader(response, RestUtils.Headers.TTL)); } if (expectedHeaders.contains(RestUtils.Headers.OWNER_ID)) { assertEquals(RestUtils.Headers.OWNER_ID + " does not match", expectedHeaders.get(RestUtils.Headers.OWNER_ID), HttpHeaders.getHeader(response, RestUtils.Headers.OWNER_ID)); } }
From source file:com.github.ambry.frontend.FrontendIntegrationTest.java
License:Open Source License
/** * Verifies User metadata headers from output, to that sent in during input * @param expectedHeaders the expected headers in the response. * @param response the {@link HttpResponse} which contains the headers of the response. * @param usermetadata if non-null, this is expected to come as the body. * @param content the content accompanying the response. *//*from ww w . j a v a2s. co m*/ private void verifyUserMetadata(HttpHeaders expectedHeaders, HttpResponse response, byte[] usermetadata, Queue<HttpObject> content) { if (usermetadata == null) { assertEquals("Content-Length is not 0", 0, HttpHeaders.getContentLength(response)); for (Map.Entry<String, String> header : expectedHeaders) { String key = header.getKey(); if (key.startsWith(RestUtils.Headers.USER_META_DATA_HEADER_PREFIX)) { assertEquals("Value for " + key + " does not match in user metadata", header.getValue(), HttpHeaders.getHeader(response, key)); } } for (Map.Entry<String, String> header : response.headers()) { String key = header.getKey(); if (key.startsWith(RestUtils.Headers.USER_META_DATA_HEADER_PREFIX)) { assertTrue("Key " + key + " does not exist in expected headers", expectedHeaders.contains(key)); } } discardContent(content, 1); } else { assertEquals("Content-Length is not as expected", usermetadata.length, HttpHeaders.getContentLength(response)); byte[] receivedMetadata = getContent(response, content).array(); assertArrayEquals("User metadata does not match original", usermetadata, receivedMetadata); } }
From source file:com.github.ambry.rest.NettyRequestTest.java
License:Open Source License
/** * Validates the various expected properties of the provided {@code nettyRequest}. * @param nettyRequest the {@link NettyRequest} that needs to be validated. * @param restMethod the expected {@link RestMethod} in {@code nettyRequest}. * @param uri the expected URI in {@code nettyRequest}. * @param headers the {@link HttpHeaders} passed with the request that need to be in {@link NettyRequest#getArgs()}. * @param params the parameters passed with the request that need to be in {@link NettyRequest#getArgs()}. * @param httpCookies Set of {@link Cookie} set in the request */// w w w . j a v a2s .c o m private void validateRequest(NettyRequest nettyRequest, RestMethod restMethod, String uri, HttpHeaders headers, Map<String, List<String>> params, Set<Cookie> httpCookies) { long contentLength = headers.contains(HttpHeaders.Names.CONTENT_LENGTH) ? Long.parseLong(headers.get(HttpHeaders.Names.CONTENT_LENGTH)) : 0; assertTrue("Request channel is not open", nettyRequest.isOpen()); assertEquals("Mismatch in content length", contentLength, nettyRequest.getSize()); assertEquals("Mismatch in rest method", restMethod, nettyRequest.getRestMethod()); assertEquals("Mismatch in path", uri.substring(0, uri.indexOf("?")), nettyRequest.getPath()); assertEquals("Mismatch in uri", uri, nettyRequest.getUri()); Set<javax.servlet.http.Cookie> actualCookies = (Set<javax.servlet.http.Cookie>) nettyRequest.getArgs() .get(HttpHeaders.Names.COOKIE); compareCookies(httpCookies, actualCookies); Map<String, List<String>> receivedArgs = new HashMap<String, List<String>>(); for (Map.Entry<String, Object> e : nettyRequest.getArgs().entrySet()) { if (!e.getKey().equals(HttpHeaders.Names.COOKIE)) { if (!receivedArgs.containsKey(e.getKey())) { receivedArgs.put(e.getKey(), new LinkedList<String>()); } if (e.getValue() != null) { List<String> values = Arrays .asList(e.getValue().toString().split(NettyRequest.MULTIPLE_HEADER_VALUE_DELIMITER)); receivedArgs.get(e.getKey()).addAll(values); } } } Map<String, Integer> keyValueCount = new HashMap<String, Integer>(); for (Map.Entry<String, List<String>> param : params.entrySet()) { assertTrue("Did not find key: " + param.getKey(), receivedArgs.containsKey(param.getKey())); if (!keyValueCount.containsKey(param.getKey())) { keyValueCount.put(param.getKey(), 0); } if (param.getValue() != null) { boolean containsAllValues = receivedArgs.get(param.getKey()).containsAll(param.getValue()); assertTrue("Did not find all values expected for key: " + param.getKey(), containsAllValues); keyValueCount.put(param.getKey(), keyValueCount.get(param.getKey()) + param.getValue().size()); } } for (Map.Entry<String, String> e : headers) { if (!e.getKey().equals(HttpHeaders.Names.COOKIE)) { assertTrue("Did not find key: " + e.getKey(), receivedArgs.containsKey(e.getKey())); if (!keyValueCount.containsKey(e.getKey())) { keyValueCount.put(e.getKey(), 0); } if (headers.get(e.getKey()) != null) { assertTrue("Did not find value '" + e.getValue() + "' expected for key: '" + e.getKey() + "'", receivedArgs.get(e.getKey()).contains(e.getValue())); keyValueCount.put(e.getKey(), keyValueCount.get(e.getKey()) + 1); } } } assertEquals("Number of args does not match", keyValueCount.size(), receivedArgs.size()); for (Map.Entry<String, Integer> e : keyValueCount.entrySet()) { assertEquals("Value count for key " + e.getKey() + " does not match", e.getValue().intValue(), receivedArgs.get(e.getKey()).size()); } }
From source file:com.github.ambry.rest.PublicAccessLogHandlerTest.java
License:Open Source License
/** * Sends the provided {@code httpRequest} and verifies that the response is as expected. * @param channel the {@link EmbeddedChannel} to send the request over. * @param httpRequest the {@link HttpRequest} that has to be sent * @param uri, Uri to be used for the request * @param headers {@link HttpHeaders} that is set in the request to be used for verification purposes * @param testErrorCase true if error case has to be tested, false otherwise *//*from w ww . j a va2 s. c o m*/ private void sendRequestCheckResponse(EmbeddedChannel channel, HttpRequest httpRequest, String uri, HttpHeaders headers, boolean testErrorCase, boolean chunkedResponse) { channel.writeInbound(httpRequest); if (uri.equals(EchoMethodHandler.DISCONNECT_URI)) { channel.disconnect(); } else { channel.writeInbound(new DefaultLastHttpContent()); } String lastLogEntry = publicAccessLogger.getLastPublicAccessLogEntry(); // verify remote host, http method and uri String subString = testErrorCase ? "Error" : "Info" + ":embedded" + " " + httpRequest.getMethod() + " " + uri; Assert.assertTrue("Public Access log entry doesn't have expected remote host/method/uri ", lastLogEntry.startsWith(subString)); // verify request headers verifyPublicAccessLogEntryForRequestHeaders(lastLogEntry, headers, httpRequest.getMethod(), true); // verify response subString = "Response ("; for (String responseHeader : RESPONSE_HEADERS.split(",")) { if (headers.contains(responseHeader)) { subString += "[" + responseHeader + "=" + headers.get(responseHeader) + "] "; } } subString += "[isChunked=" + chunkedResponse + "]), status=" + HttpResponseStatus.OK.code(); if (!testErrorCase) { Assert.assertTrue("Public Access log entry doesn't have response set correctly", lastLogEntry.contains(subString)); } else { Assert.assertTrue("Public Access log entry doesn't have error set correctly ", lastLogEntry.contains(": Channel closed while request in progress.")); } }
From source file:com.king.platform.net.http.netty.requestbuilder.BuiltNettyClientRequest.java
License:Apache License
private <T> Future<FutureResult<T>> internalExecute(HttpCallback<T> httpCallback, NioCallback nioCallback, ResponseBodyConsumer<T> responseBodyConsumer) { String completeUri = UriUtil.getUriWithParameters(uri, queryParameters); ServerInfo serverInfo = null;/* w w w.j ava 2 s . c o m*/ try { serverInfo = ServerInfo.buildFromUri(completeUri); } catch (URISyntaxException e) { return nettyHttpClient.dispatchError(httpCallback, e); } String relativePath = UriUtil.getRelativeUri(completeUri); DefaultHttpRequest defaultHttpRequest = new DefaultHttpRequest(httpVersion, httpMethod, relativePath); HttpBody httpBody = null; if (requestBodyBuilder != null) { httpBody = requestBodyBuilder.createHttpBody(contentType, bodyCharset, serverInfo.isSecure()); } NettyHttpClientRequest<T> nettyHttpClientRequest = new NettyHttpClientRequest<>(serverInfo, defaultHttpRequest, httpBody); HttpHeaders headers = nettyHttpClientRequest.getNettyHeaders(); for (Param headerParameter : headerParameters) { headers.add(headerParameter.getName(), headerParameter.getValue()); } if (acceptCompressedResponse && !headers.contains(HttpHeaders.Names.ACCEPT_ENCODING)) { headers.set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP + "," + HttpHeaders.Values.DEFLATE); } if (httpBody != null) { if (httpBody.getContentLength() < 0) { headers.set(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED); } else { headers.set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(httpBody.getContentLength())); } if (httpBody.getContentType() != null) { headers.set(HttpHeaders.Names.CONTENT_TYPE, httpBody.getContentType()); } } if (!headers.contains(HttpHeaders.Names.ACCEPT)) { headers.set(HttpHeaders.Names.ACCEPT, "*/*"); } if (!headers.contains(HttpHeaders.Names.USER_AGENT)) { headers.set(HttpHeaders.Names.USER_AGENT, defaultUserAgent); } headers.set(HttpHeaders.Names.HOST, serverInfo.getHost() + ":" + serverInfo.getPort()); nettyHttpClientRequest.setKeepAlive(keepAlive); return nettyHttpClient.execute(nettyHttpClientRequest, httpCallback, nioCallback, responseBodyConsumer, idleTimeoutMillis, totalRequestTimeoutMillis, followRedirects, keepAlive); }
From source file:com.navercorp.pinpoint.plugin.netty.interceptor.http.HttpEncoderInterceptor.java
License:Apache License
private void addHeaderIfNotExist(HttpHeaders headers, String key, Object value) { if (!headers.contains(key)) { headers.set(key, value);/*from ww w. j a v a 2s. c o m*/ } }
From source file:com.navercorp.pinpoint.plugin.netty.interceptor.http.HttpMessageClientHeaderAdaptor.java
License:Apache License
@Override public void setHeader(HttpMessage httpMessage, String name, String value) { final HttpHeaders headers = httpMessage.headers(); if (headers != null && !headers.contains(name)) { headers.set(name, value);/*from w w w. ja va 2 s. c o m*/ if (isDebug) { logger.debug("Set header {}={}", name, value); } } }
From source file:com.navercorp.pinpoint.plugin.netty.NettyClientRequestTrace.java
License:Apache License
@Override public void setHeader(final String name, final String value) { final HttpHeaders headers = this.httpMessage.headers(); if (headers != null && !headers.contains(name)) { headers.set(name, value);/*w w w. j a v a 2 s.c om*/ if (isDebug) { logger.debug("Set header {}={}", name, value); } } }