org.jboss.netty.handler.codec.http.HttpHeaders Java Examples
The following examples show how to use
org.jboss.netty.handler.codec.http.HttpHeaders.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HlsStreamsHandler.java From feeyo-hlsserver with Apache License 2.0 | 6 votes |
@Override public void execute(ChannelHandlerContext ctx, MessageEvent e) throws Exception { VelocityBuilder velocityBuilder = new VelocityBuilder(); Map<String,Object> model = new HashMap<String, Object>(); model.put("streams", HlsLiveStreamMagr.INSTANCE().getAllLiveStream()); String htmlText = velocityBuilder.generate("streams.vm", "UTF8", model); HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, htmlText.length()); response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html; charset=UTF-8"); ChannelBuffer buffer = ChannelBuffers.copiedBuffer(htmlText, Charset.defaultCharset());// CharsetUtil.UTF_8); response.setContent(buffer); ChannelFuture channelFuture = ctx.getChannel().write(response); if (channelFuture.isSuccess()) { channelFuture.getChannel().close(); } }
Example #2
Source File: WelcomeHandler.java From feeyo-hlsserver with Apache License 2.0 | 6 votes |
@Override public void execute(ChannelHandlerContext ctx, MessageEvent e) { VelocityBuilder velocityBuilder = new VelocityBuilder(); String htmlText = velocityBuilder.generate("index.vm", "UTF8", null); HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, htmlText.length()); response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html; charset=UTF-8"); ChannelBuffer buffer = ChannelBuffers.copiedBuffer(htmlText, CharsetUtil.UTF_8); response.setContent(buffer); ChannelFuture channelFuture = ctx.getChannel().write(response); if (channelFuture.isSuccess()) { channelFuture.getChannel().close(); } }
Example #3
Source File: HttpServerRequestHandler.java From feeyo-hlsserver with Apache License 2.0 | 6 votes |
private void sendResponse(ChannelHandlerContext ctx, HttpResponse httpResponse){ boolean close = false; ChannelFuture channelFuture = null; try { channelFuture = ctx.getChannel().write(httpResponse); } catch (Exception e) { LOGGER.error("write response fail.", e); close = true; } finally { // close connection if (close || httpResponse == null || !Values.KEEP_ALIVE.equals(httpResponse.headers().get(HttpHeaders.Names.CONNECTION))) { if (channelFuture.isSuccess()) { channelFuture.getChannel().close(); } } } }
Example #4
Source File: HttpServerHandler.java From netty-servlet with Apache License 2.0 | 6 votes |
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent event) throws Exception { if (event.getMessage() instanceof HttpRequest) { try { HttpServletRequest httpServletRequest = new NettyHttpServletRequestAdaptor((HttpRequest) event.getMessage(), ctx.getChannel()); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); response.setContent(new DynamicChannelBuffer(200)); HttpServletResponse httpServletResponse = new NettyHttpServletResponseAdaptor(response, ctx.getChannel()); dispatcher.dispatch(httpServletRequest,httpServletResponse); response.headers().set(HttpHeaders.Names.CONTENT_LENGTH,response.getContent().writerIndex()); ChannelFuture future = ctx.getChannel().write(response); future.addListener(ChannelFutureListener.CLOSE); } catch (Exception e) { e.printStackTrace(); } } }
Example #5
Source File: TestDelegationTokenRemoteFetcher.java From hadoop with Apache License 2.0 | 6 votes |
@Override public void handle(Channel channel, Token<DelegationTokenIdentifier> token, String serviceUrl) throws IOException { Assert.assertEquals(testToken, token); Credentials creds = new Credentials(); creds.addToken(new Text(serviceUrl), token); DataOutputBuffer out = new DataOutputBuffer(); creds.write(out); int fileLength = out.getData().length; ChannelBuffer cbuffer = ChannelBuffers.buffer(fileLength); cbuffer.writeBytes(out.getData()); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); response.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(fileLength)); response.setContent(cbuffer); channel.write(response).addListener(ChannelFutureListener.CLOSE); }
Example #6
Source File: TestDelegationTokenRemoteFetcher.java From big-c with Apache License 2.0 | 6 votes |
@Override public void handle(Channel channel, Token<DelegationTokenIdentifier> token, String serviceUrl) throws IOException { Assert.assertEquals(testToken, token); Credentials creds = new Credentials(); creds.addToken(new Text(serviceUrl), token); DataOutputBuffer out = new DataOutputBuffer(); creds.write(out); int fileLength = out.getData().length; ChannelBuffer cbuffer = ChannelBuffers.buffer(fileLength); cbuffer.writeBytes(out.getData()); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); response.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(fileLength)); response.setContent(cbuffer); channel.write(response).addListener(ChannelFutureListener.CLOSE); }
Example #7
Source File: ShuffleHandler.java From tez with Apache License 2.0 | 5 votes |
protected void setResponseHeaders(HttpResponse response, boolean keepAliveParam, long contentLength) { if (connectionKeepAliveEnabled || keepAliveParam) { response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(contentLength)); response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); response.headers().set(HttpHeaders.Values.KEEP_ALIVE, "timeout=" + connectionKeepAliveTimeOut); if (LOG.isDebugEnabled()) { LOG.debug("Content Length in shuffle : " + contentLength); } } else { if (LOG.isDebugEnabled()) { LOG.debug("Setting connection close header..."); } response.headers().set(HttpHeaders.Names.CONNECTION, CONNECTION_CLOSE); } }
Example #8
Source File: ShuffleHandler.java From tez with Apache License 2.0 | 5 votes |
protected void setResponseHeaders(HttpResponse response, boolean keepAliveParam, long contentLength) { if (!connectionKeepAliveEnabled && !keepAliveParam) { LOG.info("Setting connection close header..."); response.headers().set(HttpHeaders.Names.CONNECTION, CONNECTION_CLOSE); } else { response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(contentLength)); response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); response.headers().set(HttpHeaders.Values.KEEP_ALIVE, "timeout=" + connectionKeepAliveTimeOut); LOG.info("Content Length in shuffle : " + contentLength); } }
Example #9
Source File: WebSocketChannelHandler.java From usergrid with Apache License 2.0 | 5 votes |
private String getWebSocketLocation( HttpRequest req ) { String path = req.getUri(); if ( path.equals( "/" ) ) { path = null; } if ( path != null ) { path = removeEnd( path, "/" ); } String location = ( ssl ? "wss://" : "ws://" ) + req.getHeader( HttpHeaders.Names.HOST ) + ( path != null ? path : "" ); logger.info( location ); return location; }
Example #10
Source File: HttpAction.java From elasticsearch-helper with Apache License 2.0 | 5 votes |
protected HttpRequest newRequest(HttpMethod method, URL url, String path, ChannelBuffer buffer) { HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, method, path); request.headers().add(HttpHeaders.Names.HOST, url.getHost()); request.headers().add(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); request.headers().add(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); if (buffer != null) { request.setContent(buffer); int length = request.getContent().readableBytes(); request.headers().add(HttpHeaders.Names.CONTENT_TYPE, "application/json"); request.headers().add(HttpHeaders.Names.CONTENT_LENGTH, length); } return request; }
Example #11
Source File: HttpServerHandler.java From glowroot with Apache License 2.0 | 5 votes |
private void writeResponse(MessageEvent e) throws Exception { HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); response.setContent(ChannelBuffers.copiedBuffer("Hello world", CharsetUtil.UTF_8)); addHeader(response, HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8"); ChannelFuture future = e.getChannel().write(response); future.addListener(ChannelFutureListener.CLOSE); }
Example #12
Source File: NettyAsyncHttpProvider.java From ck with Apache License 2.0 | 5 votes |
private final static int computeAndSetContentLength(Request request, HttpRequest r) { int lenght = (int) request.getLength(); if (lenght == -1 && r.getHeader(HttpHeaders.Names.CONTENT_LENGTH) != null) { lenght = Integer.valueOf(r.getHeader(HttpHeaders.Names.CONTENT_LENGTH)); } if (lenght != -1) { r.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(lenght)); } return lenght; }
Example #13
Source File: TestDelegationTokenRemoteFetcher.java From big-c with Apache License 2.0 | 5 votes |
@Override public void handle(Channel channel, Token<DelegationTokenIdentifier> token, String serviceUrl) throws IOException { Assert.assertEquals(testToken, token); byte[] bytes = EXP_DATE.getBytes(); ChannelBuffer cbuffer = ChannelBuffers.buffer(bytes.length); cbuffer.writeBytes(bytes); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); response.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(bytes.length)); response.setContent(cbuffer); channel.write(response).addListener(ChannelFutureListener.CLOSE); }
Example #14
Source File: TestDelegationTokenRemoteFetcher.java From hadoop with Apache License 2.0 | 5 votes |
@Override public void handle(Channel channel, Token<DelegationTokenIdentifier> token, String serviceUrl) throws IOException { Assert.assertEquals(testToken, token); byte[] bytes = EXP_DATE.getBytes(); ChannelBuffer cbuffer = ChannelBuffers.buffer(bytes.length); cbuffer.writeBytes(bytes); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); response.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(bytes.length)); response.setContent(cbuffer); channel.write(response).addListener(ChannelFutureListener.CLOSE); }
Example #15
Source File: ESHttpContentDecompressor.java From Elasticsearch with Apache License 2.0 | 5 votes |
@Override protected DecoderEmbedder<ChannelBuffer> newContentDecoder(String contentEncoding) throws Exception { if (compression) { // compression is enabled so handle the request according to the headers (compressed and uncompressed) return super.newContentDecoder(contentEncoding); } else { // if compression is disabled only allow "indentity" (uncompressed) requests if (HttpHeaders.Values.IDENTITY.equals(contentEncoding)) { // nothing to handle here return null; } else { throw new TransportException("Support for compressed content is disabled. You can enable it with http.compression=true"); } } }
Example #16
Source File: AuthHandler.java From feeyo-hlsserver with Apache License 2.0 | 5 votes |
private Map<String, Cookie> getCookies(HttpRequest request) { // 解析 Cookie Map<String, Cookie> cookies = new HashMap<String, Cookie>(); List<String> allCookieHeaders = request.headers().getAll( HttpHeaders.Names.COOKIE ); for (String aCookieHeader : allCookieHeaders) { Cookie c = ClientCookieDecoder.STRICT.decode(aCookieHeader); if (c != null) { cookies.put(c.name(), c); } } return cookies; }
Example #17
Source File: CorsHandler.java From Elasticsearch with Apache License 2.0 | 4 votes |
private static boolean isPreflightRequest(final HttpRequest request) { final HttpHeaders headers = request.headers(); return request.getMethod().equals(HttpMethod.OPTIONS) && headers.contains(HttpHeaders.Names.ORIGIN) && headers.contains(HttpHeaders.Names.ACCESS_CONTROL_REQUEST_METHOD); }
Example #18
Source File: NettyHttpChannel.java From Elasticsearch with Apache License 2.0 | 4 votes |
@Override public void doSendResponse(RestResponse response) { // if the response object was created upstream, then use it; // otherwise, create a new one HttpResponse resp = newResponse(); resp.setStatus(getStatus(response.status())); CorsHandler.setCorsResponseHeaders(nettyRequest, resp, transport.getCorsConfig()); String opaque = nettyRequest.headers().get("X-Opaque-Id"); if (opaque != null) { resp.headers().add("X-Opaque-Id", opaque); } // Add all custom headers Map<String, List<String>> customHeaders = response.getHeaders(); if (customHeaders != null) { for (Map.Entry<String, List<String>> headerEntry : customHeaders.entrySet()) { for (String headerValue : headerEntry.getValue()) { resp.headers().add(headerEntry.getKey(), headerValue); } } } BytesReference content = response.content(); ChannelBuffer buffer; boolean addedReleaseListener = false; try { buffer = content.toChannelBuffer(); resp.setContent(buffer); // If our response doesn't specify a content-type header, set one if (!resp.headers().contains(HttpHeaders.Names.CONTENT_TYPE)) { resp.headers().add(HttpHeaders.Names.CONTENT_TYPE, response.contentType()); } // If our response has no content-length, calculate and set one if (!resp.headers().contains(HttpHeaders.Names.CONTENT_LENGTH)) { resp.headers().add(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(buffer.readableBytes())); } if (transport.resetCookies) { String cookieString = nettyRequest.headers().get(HttpHeaders.Names.COOKIE); if (cookieString != null) { CookieDecoder cookieDecoder = new CookieDecoder(); Set<Cookie> cookies = cookieDecoder.decode(cookieString); if (!cookies.isEmpty()) { // Reset the cookies if necessary. CookieEncoder cookieEncoder = new CookieEncoder(true); for (Cookie cookie : cookies) { cookieEncoder.addCookie(cookie); } resp.headers().add(HttpHeaders.Names.SET_COOKIE, cookieEncoder.encode()); } } } ChannelFuture future; if (orderedUpstreamMessageEvent != null) { OrderedDownstreamChannelEvent downstreamChannelEvent = new OrderedDownstreamChannelEvent(orderedUpstreamMessageEvent, 0, true, resp); future = downstreamChannelEvent.getFuture(); channel.getPipeline().sendDownstream(downstreamChannelEvent); } else { future = channel.write(resp); } if (content instanceof Releasable) { future.addListener(new ReleaseChannelFutureListener((Releasable) content)); addedReleaseListener = true; } if (isCloseConnection()) { future.addListener(ChannelFutureListener.CLOSE); } } finally { if (!addedReleaseListener && content instanceof Releasable) { ((Releasable) content).close(); } } }
Example #19
Source File: StreamChunkAggregator.java From restcommander with Apache License 2.0 | 4 votes |
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { Object msg = e.getMessage(); if (!(msg instanceof HttpMessage) && !(msg instanceof HttpChunk)) { ctx.sendUpstream(e); return; } HttpMessage currentMessage = this.currentMessage; File localFile = this.file; if (currentMessage == null) { HttpMessage m = (HttpMessage) msg; if (m.isChunked()) { final String localName = UUID.randomUUID().toString(); // A chunked message - remove 'Transfer-Encoding' header, // initialize the cumulative buffer, and wait for incoming chunks. List<String> encodings = m.getHeaders(HttpHeaders.Names.TRANSFER_ENCODING); encodings.remove(HttpHeaders.Values.CHUNKED); if (encodings.isEmpty()) { m.removeHeader(HttpHeaders.Names.TRANSFER_ENCODING); } this.currentMessage = m; this.file = new File(Play.tmpDir, localName); this.out = new FileOutputStream(file, true); } else { // Not a chunked message - pass through. ctx.sendUpstream(e); } } else { // TODO: If less that threshold then in memory // Merge the received chunk into the content of the current message. final HttpChunk chunk = (HttpChunk) msg; if (maxContentLength != -1 && (localFile.length() > (maxContentLength - chunk.getContent().readableBytes()))) { currentMessage.setHeader(HttpHeaders.Names.WARNING, "play.netty.content.length.exceeded"); } else { IOUtils.copyLarge(new ChannelBufferInputStream(chunk.getContent()), this.out); if (chunk.isLast()) { this.out.flush(); this.out.close(); currentMessage.setHeader( HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(localFile.length())); currentMessage.setContent(new FileChannelBuffer(localFile)); this.out = null; this.currentMessage = null; this.file = null; Channels.fireMessageReceived(ctx, currentMessage, e.getRemoteAddress()); } } } }
Example #20
Source File: AuthCheckFilter.java From feeyo-hlsserver with Apache License 2.0 | 4 votes |
@Override public boolean doFilter(ChannelHandlerContext ctx, MessageEvent messageEvent) { boolean isPass = true; HttpRequest request = (DefaultHttpRequest) messageEvent.getMessage(); String access_string = request.headers().get(Token.ACCESS_STRING); if ( access_string == null ) { // 解析 Cookie String value = request.headers().get( HttpHeaders.Names.COOKIE ); Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(value != null ? value : ""); Iterator<Cookie> it = cookies.iterator(); while( it.hasNext() ) { Cookie c = it.next(); if ( Token.ACCESS_STRING.equals( c.name() ) ) { access_string = c.value(); break; } } } if (access_string != null) { try { Token token = TokenMagr.getInstance().getToken(access_string); if (token != null) { int now = (int) (System.currentTimeMillis() / 1000L); int expires = token.getCreateAt() + (token.getExpiresIn() * 60 * 60 * 24); if (expires < now) { TokenMagr.getInstance().deleteToken(access_string); isPass = false; } } else { isPass = false; } } catch (Exception e) { LOGGER.error("filter error -- > " + request.getUri(), e); } } else { isPass = false; } return isPass; }
Example #21
Source File: HttpKeepAliveHandler.java From zuul-netty with Apache License 2.0 | 4 votes |
@Override public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception { HttpRequest request = (HttpRequest) ctx.getAttachment(); if (e.getMessage() instanceof HttpResponse) { HttpResponse response = (HttpResponse) e.getMessage(); if (!response.isChunked()) { if (isKeepAliveSupported && isKeepAlive(request)) { LOG.debug("keep-alive IS implemented for this connection"); // Add 'Content-Length' header only for a keep-alive connection. response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes()); // Add keep alive header as per: // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection response.setHeader(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } else { //not chunked and keep alive not supported, closing connection LOG.debug("keep-alive NOT implemented for this connection"); e.getFuture().addListener(ChannelFutureListener.CLOSE); } } else { //response is chunked //don't send a content-length for chunked transfer-encoding response.removeHeader(CONTENT_LENGTH); //keep-alive explicitly off if (!isKeepAliveSupported || !isKeepAlive(request)) { response.removeHeader(CONNECTION); LOG.debug("keep-alive NOT implemented for this connection as it is explicitly turned off"); } else { LOG.debug("keep-alive IMPLIED for this connection as it is chunked"); } } } else if (e.getMessage() instanceof HttpChunk) { LOG.debug("found chunk"); if (((HttpChunk) e.getMessage()).isLast()) { if (!isKeepAliveSupported || !isKeepAlive(request)) { //keep alive explicitly off LOG.debug("reached the last chunk and keep alive is turned off so closing the connection"); e.getFuture().addListener(ChannelFutureListener.CLOSE); } } } else { LOG.debug("found something else"); } super.writeRequested(ctx, e); }
Example #22
Source File: HttpServerRequestHandler.java From feeyo-hlsserver with Apache License 2.0 | 4 votes |
private void sendRedirect(ChannelHandlerContext ctx, String newUri) { HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FOUND); response.headers().set(HttpHeaders.Names.LOCATION, newUri); ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE); }
Example #23
Source File: HlsVodHandler.java From feeyo-hlsserver with Apache License 2.0 | 4 votes |
@Override public void execute(ChannelHandlerContext ctx, MessageEvent e) throws Exception { HttpRequest request = (DefaultHttpRequest) e.getMessage(); if ( !request.getUri().matches(regex) ) { LOGGER.warn("bad request: " + request.getUri()); HttpUtil.sendError(ctx, HttpResponseStatus.NOT_FOUND); return; } String[] path = request.getUri().split("/"); String alias = path[3]; final String reqFileName = path[4]; Long streamId = HlsLiveStreamMagr.INSTANCE().getStreamIdByAlias(alias); if( streamId == null ) { LOGGER.warn(" aac vod, lookup alias failed: " + alias); HttpUtil.sendError(ctx, HttpResponseStatus.NOT_FOUND); return; } OssUtil ossOperation = new OssUtil(); byte[] content = null; if (reqFileName.endsWith(".m3u8")) { if ( !ossOperation.doesObjectExist(reqFileName, streamId) ) { boolean needWaite = false; // the very first listener of a specific m3u8 will create the m3u8 file and the ts file // the reset will be in a waiter set synchronized (m3u8WaiteSet) { if (!m3u8WaiteSet.add(reqFileName)) { needWaite = true; } } if (needWaite) { synchronized (m3u8WaiteSet) { while (m3u8WaiteSet.contains(reqFileName)) { m3u8WaiteSet.wait(1000); } } } else { content = generateTsFiles(reqFileName, streamId); } } } if (content == null) { content = cachedVodTsFiles.get(reqFileName); if (content == null) { if (ossOperation.doesObjectExist(reqFileName, streamId)){ InputStream inputStream = ossOperation.readObject(reqFileName, streamId); ObjectMetadata objectMetadata = ossOperation.getObjectMetadata(reqFileName,streamId); int len = (int)objectMetadata.getContentLength(); content = new byte[len]; int writePtr = 0; for (;;) { int ret = inputStream.read(content, writePtr,len-writePtr); if ((ret == -1) || (writePtr += ret) >= len) break; } } else { LOGGER.warn("request file not on OSS: " + request.getUri()); HttpUtil.sendError(ctx, HttpResponseStatus.NOT_FOUND); return; } } } ossOperation.closeOSSClient(); long timeMillis = System.currentTimeMillis(); DefaultHttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); response.headers().set(HttpHeaders.Names.DATE, HttpUtil.getDateString(timeMillis)); response.headers().set(HttpHeaders.Names.CONTENT_TYPE, HttpUtil.getMimeType(reqFileName)); response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, content.length); response.headers().set(HttpHeaders.Names.LAST_MODIFIED, HttpUtil.getDateString(timeMillis)); response.headers().set(HttpHeaders.Names.EXPIRES, HttpUtil.getDateString(timeMillis + VOD_CACHE_TIME)); response.headers().set(HttpHeaders.Names.CACHE_CONTROL, "max-age=" + (VOD_CACHE_TIME/1000)); response.setContent(ChannelBuffers.copiedBuffer(content)); e.getChannel().write(response); }