List of usage examples for io.netty.handler.codec.http HttpHeaders add
public HttpHeaders add(CharSequence name, Iterable<?> values)
From source file:br.unifei.edu.eco009.steamlansync.cache.HttpChunkContents.java
public FullHttpResponse getFullHttpResponse() { DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.copiedBuffer(bytes)); HttpHeaders head = response.headers(); for (Entry<String, String> entry : headers.entrySet()) { head.add(entry.getKey(), entry.getValue()); }//from w w w . j av a 2s.c om return response; }
From source file:cf.component.http.JsonTextResponseRequestHandler.java
License:Open Source License
@Override public HttpResponse handleRequest(HttpRequest request, Matcher uriMatcher, ByteBuf body) throws RequestException { final String responseBody = handle(request, uriMatcher, body); final ByteBuf buffer = Unpooled.copiedBuffer(responseBody, CharsetUtil.UTF_8); final HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buffer);// w w w . java 2 s . c o m final HttpHeaders headers = response.headers(); headers.add(HttpHeaders.Names.CONTENT_TYPE, "application/json; charset=UTF-8"); headers.add(HttpHeaders.Names.CONTENT_LENGTH, buffer.readableBytes()); return response; }
From source file:cf.dropsonde.firehose.NettyFirehoseOnSubscribe.java
License:Open Source License
public NettyFirehoseOnSubscribe(URI uri, String token, String subscriptionId, boolean skipTlsValidation, EventLoopGroup eventLoopGroup, Class<? extends SocketChannel> channelClass) { try {/*from www .ja va 2 s .c om*/ final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost(); final String scheme = uri.getScheme() == null ? "ws" : uri.getScheme(); final int port = getPort(scheme, uri.getPort()); final URI fullUri = uri.resolve("/firehose/" + subscriptionId); final SslContext sslContext; if ("wss".equalsIgnoreCase(scheme)) { final SslContextBuilder sslContextBuilder = SslContextBuilder.forClient(); if (skipTlsValidation) { sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE); } else { TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init((KeyStore) null); sslContextBuilder.trustManager(trustManagerFactory); } sslContext = sslContextBuilder.build(); } else { sslContext = null; } bootstrap = new Bootstrap(); if (eventLoopGroup == null) { this.eventLoopGroup = new NioEventLoopGroup(); bootstrap.group(this.eventLoopGroup); } else { this.eventLoopGroup = null; bootstrap.group(eventLoopGroup); } bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000) .channel(channelClass == null ? NioSocketChannel.class : channelClass).remoteAddress(host, port) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel c) throws Exception { final HttpHeaders headers = new DefaultHttpHeaders(); headers.add(HttpHeaders.Names.AUTHORIZATION, token); final WebSocketClientHandler handler = new WebSocketClientHandler( WebSocketClientHandshakerFactory.newHandshaker(fullUri, WebSocketVersion.V13, null, false, headers)); final ChannelPipeline pipeline = c.pipeline(); if (sslContext != null) { pipeline.addLast(sslContext.newHandler(c.alloc(), host, port)); } pipeline.addLast(new ReadTimeoutHandler(30)); pipeline.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192)); pipeline.addLast(HANDLER_NAME, handler); channel = c; } }); } catch (NoSuchAlgorithmException | SSLException | KeyStoreException e) { throw new RuntimeException(e); } }
From source file:com.athena.dolly.websocket.client.test.WebSocketClient.java
License:Apache License
private void initialize() throws InterruptedException { group = new NioEventLoopGroup(); Bootstrap bootstrap = new Bootstrap(); String protocol = uri.getScheme(); if (!"ws".equals(protocol)) { throw new IllegalArgumentException("Unsupported protocol: " + protocol); }// ww w .j a va 2 s . c o m HttpHeaders customHeaders = new DefaultHttpHeaders(); customHeaders.add("MyHeader", "MyValue"); // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00. // If you change it to V00, ping is not supported and remember to change // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline. final WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory .newHandshaker(uri, WebSocketVersion.V13, null, false, customHeaders)); bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("http-codec", new HttpClientCodec()); pipeline.addLast("aggregator", new HttpObjectAggregator(8192)); pipeline.addLast("ws-handler", handler); } }); System.out.println("WebSocket Client connecting"); ch = bootstrap.connect(uri.getHost(), uri.getPort()).sync().channel(); handler.handshakeFuture().sync(); }
From source file:com.buildria.mocking.stub.CallTest.java
License:Open Source License
@Test public void testFromRequest() throws Exception { DefaultFullHttpRequest req = mock(DefaultFullHttpRequest.class); when(req.getUri()).thenReturn("/api/p?name=%E3%81%82"); when(req.getMethod()).thenReturn(GET); HttpHeaders headers = new DefaultHttpHeaders(); headers.add("key", "value1"); headers.add("key", "value2"); when(req.headers()).thenReturn(headers); ByteBuf buf = ByteBufAllocator.DEFAULT.buffer(); buf.writeByte((byte) 0xff); when(req.content()).thenReturn(buf); Call call = Call.fromRequest(req);/*w w w .j av a 2 s. c o m*/ assertThat(call.getPath(), is("/api/p")); assertThat(call.getParameters().size(), is(1)); assertThat(call.getParameters().get(0).getName(), is("name")); assertThat(call.getParameters().get(0).getValue(), is("\u3042")); assertThat(call.getMethod(), is(equalToIgnoringCase("GET"))); assertThat(call.getHeaders(), hasSize(2)); assertThat(call.getHeaders().get(0).getName(), is("key")); assertThat(call.getHeaders().get(0).getValue(), is("value1")); assertThat(call.getHeaders().get(1).getName(), is("key")); assertThat(call.getHeaders().get(1).getValue(), is("value2")); assertThat(call.getBody()[0], is((byte) 0xff)); }
From source file:com.buildria.mocking.stub.CallTest.java
License:Open Source License
@Test public void testFromRequestContentEmpty() throws Exception { DefaultFullHttpRequest req = mock(DefaultFullHttpRequest.class); when(req.getUri()).thenReturn("/api/p?name=%E3%81%82"); when(req.getMethod()).thenReturn(GET); HttpHeaders headers = new DefaultHttpHeaders(); headers.add("key", "value"); when(req.headers()).thenReturn(headers); when(req.content()).thenReturn(null); Call call = Call.fromRequest(req);/* www.j a va 2 s. c o m*/ assertThat(call.getBody().length, is(0)); }
From source file:com.buildria.mocking.stub.CallTest.java
License:Open Source License
@Test public void testFromRequestNoContent() throws Exception { HttpRequest req = mock(HttpRequest.class); when(req.getUri()).thenReturn("/api/p?name=%E3%81%82"); when(req.getMethod()).thenReturn(GET); HttpHeaders headers = new DefaultHttpHeaders(); headers.add("key", "value"); when(req.headers()).thenReturn(headers); Call call = Call.fromRequest(req);/* ww w . j a v a 2 s .c o m*/ assertThat(call.getBody().length, is(0)); }
From source file:com.chiorichan.http.HttpResponseWrapper.java
License:Mozilla Public License
public void sendMultipart(byte[] bytesToWrite) throws IOException { if (request.method() == HttpMethod.HEAD) throw new IllegalStateException("You can't start MULTIPART mode on a HEAD Request."); if (stage != HttpResponseStage.MULTIPART) { stage = HttpResponseStage.MULTIPART; HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); HttpHeaders h = response.headers(); try {//from w w w .ja v a 2 s. c om request.getSession().save(); } catch (SessionException e) { e.printStackTrace(); } for (HttpCookie c : request.getCookies()) if (c.needsUpdating()) h.add("Set-Cookie", c.toHeaderValue()); if (h.get("Server") == null) h.add("Server", Versioning.getProduct() + " Version " + Versioning.getVersion()); h.add("Access-Control-Allow-Origin", request.getLocation().getConfig().getString("site.web-allowed-origin", "*")); h.add("Connection", "close"); h.add("Cache-Control", "no-cache"); h.add("Cache-Control", "private"); h.add("Pragma", "no-cache"); h.set("Content-Type", "multipart/x-mixed-replace; boundary=--cwsframe"); // if ( isKeepAlive( request ) ) { // response.headers().set( CONNECTION, HttpHeaders.Values.KEEP_ALIVE ); } request.getChannel().write(response); } else { StringBuilder sb = new StringBuilder(); sb.append("--cwsframe\r\n"); sb.append("Content-Type: " + httpContentType + "\r\n"); sb.append("Content-Length: " + bytesToWrite.length + "\r\n\r\n"); ByteArrayOutputStream ba = new ByteArrayOutputStream(); ba.write(sb.toString().getBytes(encoding)); ba.write(bytesToWrite); ba.flush(); ChannelFuture sendFuture = request.getChannel().write( new ChunkedStream(new ByteArrayInputStream(ba.toByteArray())), request.getChannel().newProgressivePromise()); ba.close(); sendFuture.addListener(new ChannelProgressiveFutureListener() { @Override public void operationComplete(ChannelProgressiveFuture future) throws Exception { NetworkManager.getLogger().info("Transfer complete."); } @Override public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) { if (total < 0) NetworkManager.getLogger().info("Transfer progress: " + progress); else NetworkManager.getLogger().info("Transfer progress: " + progress + " / " + total); } }); } }
From source file:com.chiorichan.http.HttpResponseWrapper.java
License:Mozilla Public License
/** * Sends the data to the client. Internal Use. * * @throws IOException//from w w w. j av a 2s .co m * if there was a problem sending the data, like the connection was unexpectedly closed. */ public void sendResponse() throws IOException { if (stage == HttpResponseStage.CLOSED || stage == HttpResponseStage.WRITTEN) return; FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, httpStatus, output); HttpHeaders h = response.headers(); if (request.hasSession()) { Session session = request.getSession(); /** * Initiate the Session Persistence Method. * This is usually done with a cookie but we should make a param optional */ session.processSessionCookie(request.getDomain()); for (HttpCookie c : session.getCookies().values()) if (c.needsUpdating()) h.add("Set-Cookie", c.toHeaderValue()); if (session.getSessionCookie().needsUpdating()) h.add("Set-Cookie", session.getSessionCookie().toHeaderValue()); } if (h.get("Server") == null) h.add("Server", Versioning.getProduct() + " Version " + Versioning.getVersion()); // This might be a temporary measure - TODO Properly set the charset for each request. h.set("Content-Type", httpContentType + "; charset=" + encoding.name()); h.add("Access-Control-Allow-Origin", request.getLocation().getConfig().getString("site.web-allowed-origin", "*")); for (Entry<String, String> header : headers.entrySet()) h.add(header.getKey(), header.getValue()); // Expires: Wed, 08 Apr 2015 02:32:24 GMT // DateTimeFormatter formatter = DateTimeFormat.forPattern( "EE, dd-MMM-yyyy HH:mm:ss zz" ); // h.set( HttpHeaders.Names.EXPIRES, formatter.print( DateTime.now( DateTimeZone.UTC ).plusDays( 1 ) ) ); // h.set( HttpHeaders.Names.CACHE_CONTROL, "public, max-age=86400" ); h.setInt(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); h.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); stage = HttpResponseStage.WRITTEN; request.getChannel().writeAndFlush(response); }
From source file:com.github.ambry.admin.AdminIntegrationTest.java
License:Open Source License
/** * Tests blob POST, GET, HEAD and DELETE operations. * @throws ExecutionException//from ww w . j a va 2 s .co m * @throws InterruptedException */ @Test public void postGetHeadDeleteTest() throws ExecutionException, InterruptedException { ByteBuffer content = ByteBuffer.wrap(RestTestUtils.getRandomBytes(1024)); String serviceId = "postGetHeadDeleteServiceID"; String contentType = "application/octet-stream"; String ownerId = "postGetHeadDeleteOwnerID"; HttpHeaders headers = new DefaultHttpHeaders(); setAmbryHeaders(headers, content.capacity(), 7200, false, serviceId, contentType, ownerId); headers.set(HttpHeaders.Names.CONTENT_LENGTH, content.capacity()); headers.add(RestUtils.Headers.USER_META_DATA_HEADER_PREFIX + "key1", "value1"); headers.add(RestUtils.Headers.USER_META_DATA_HEADER_PREFIX + "key2", "value2"); String blobId = postBlobAndVerify(headers, content); getBlobAndVerify(blobId, headers, content); getHeadAndVerify(blobId, headers); deleteBlobAndVerify(blobId); // check GET, HEAD and DELETE after delete. verifyOperationsAfterDelete(blobId); }