List of usage examples for io.netty.buffer Unpooled wrappedBuffer
public static ByteBuf wrappedBuffer(ByteBuffer... buffers)
From source file:com.netflix.iep.http.ServerSentEvent.java
License:Apache License
private static ByteBuf toByteBuf(String s) { try {//from w w w . java 2 s. c om return Unpooled.wrappedBuffer(s.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
From source file:com.netty4.http.helloword.HttpHelloWorldServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); }/*from w w w .j ava 2s . c o m*/ boolean keepAlive = HttpHeaders.isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT)); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, Values.KEEP_ALIVE); ctx.write(response); } } if (msg instanceof HttpContent) { } }
From source file:com.nextcont.ecm.fileengine.http.nettyServer.HttpUploadServerHandler.java
License:Apache License
private void doGet(ChannelHandlerContext ctx, HttpRequest httpRequest) throws URISyntaxException { String uri = new URI(request.getUri()).getPath(); if (uri.equals("/ping")) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT)); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }//www . java2 s . c o m }
From source file:com.ning.http.client.providers.netty_4.NettyAsyncHttpProvider.java
License:Apache License
private static HttpRequest construct(AsyncHttpClientConfig config, Request request, HttpMethod m, URI uri, ByteBuf buffer, ProxyServer proxyServer) throws IOException { String host = AsyncHttpProviderUtils.getHost(uri); boolean webSocket = isWebSocket(uri); if (request.getVirtualHost() != null) { host = request.getVirtualHost(); }//from w w w .j ava 2 s. c o m FullHttpRequest nettyRequest; if (m.equals(HttpMethod.CONNECT)) { nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, m, AsyncHttpProviderUtils.getAuthority(uri)); } else { String path = null; if (proxyServer != null && !(isSecure(uri) && config.isUseRelativeURIsWithSSLProxies())) path = uri.toString(); else if (uri.getRawQuery() != null) path = uri.getRawPath() + "?" + uri.getRawQuery(); else path = uri.getRawPath(); nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, m, path); } if (webSocket) { nettyRequest.headers().add(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET); nettyRequest.headers().add(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE); nettyRequest.headers().add("Origin", "http://" + uri.getHost() + ":" + (uri.getPort() == -1 ? isSecure(uri.getScheme()) ? 443 : 80 : uri.getPort())); nettyRequest.headers().add(WEBSOCKET_KEY, WebSocketUtil.getKey()); nettyRequest.headers().add("Sec-WebSocket-Version", "13"); } if (host != null) { if (uri.getPort() == -1) { nettyRequest.headers().set(HttpHeaders.Names.HOST, host); } else if (request.getVirtualHost() != null) { nettyRequest.headers().set(HttpHeaders.Names.HOST, host); } else { nettyRequest.headers().set(HttpHeaders.Names.HOST, host + ":" + uri.getPort()); } } else { host = "127.0.0.1"; } if (!m.equals(HttpMethod.CONNECT)) { FluentCaseInsensitiveStringsMap h = request.getHeaders(); if (h != null) { for (String name : h.keySet()) { if (!"host".equalsIgnoreCase(name)) { for (String value : h.get(name)) { nettyRequest.headers().add(name, value); } } } } if (config.isCompressionEnabled()) { nettyRequest.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); } } else { List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION); if (isNonEmpty(auth) && auth.get(0).startsWith("NTLM")) { nettyRequest.headers().add(HttpHeaders.Names.PROXY_AUTHORIZATION, auth.get(0)); } } Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm(); if (realm != null && realm.getUsePreemptiveAuth()) { String domain = realm.getNtlmDomain(); if (proxyServer != null && proxyServer.getNtlmDomain() != null) { domain = proxyServer.getNtlmDomain(); } String authHost = realm.getNtlmHost(); if (proxyServer != null && proxyServer.getHost() != null) { host = proxyServer.getHost(); } switch (realm.getAuthScheme()) { case BASIC: nettyRequest.headers().set(HttpHeaders.Names.AUTHORIZATION, AuthenticatorUtils.computeBasicAuthentication(realm)); break; case DIGEST: if (isNonEmpty(realm.getNonce())) { try { nettyRequest.headers().set(HttpHeaders.Names.AUTHORIZATION, AuthenticatorUtils.computeDigestAuthentication(realm)); } catch (NoSuchAlgorithmException e) { throw new SecurityException(e); } } break; case NTLM: try { String msg = ntlmEngine.generateType1Msg("NTLM " + domain, authHost); nettyRequest.headers().set(HttpHeaders.Names.AUTHORIZATION, "NTLM " + msg); } catch (NTLMEngineException e) { IOException ie = new IOException(); ie.initCause(e); throw ie; } break; case KERBEROS: case SPNEGO: String challengeHeader = null; String server = proxyServer == null ? host : proxyServer.getHost(); try { challengeHeader = getSpnegoEngine().generateToken(server); } catch (Throwable e) { IOException ie = new IOException(); ie.initCause(e); throw ie; } nettyRequest.headers().set(HttpHeaders.Names.AUTHORIZATION, "Negotiate " + challengeHeader); break; case NONE: break; default: throw new IllegalStateException("Invalid Authentication " + realm); } } if (!webSocket && !request.getHeaders().containsKey(HttpHeaders.Names.CONNECTION)) { nettyRequest.headers().set(HttpHeaders.Names.CONNECTION, AsyncHttpProviderUtils.keepAliveHeaderValue(config)); } if (proxyServer != null) { if (!request.getHeaders().containsKey("Proxy-Connection")) { nettyRequest.headers().set("Proxy-Connection", AsyncHttpProviderUtils.keepAliveHeaderValue(config)); } if (proxyServer.getPrincipal() != null) { if (isNonEmpty(proxyServer.getNtlmDomain())) { List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION); if (!(isNonEmpty(auth) && auth.get(0).startsWith("NTLM"))) { try { String msg = ntlmEngine.generateType1Msg(proxyServer.getNtlmDomain(), proxyServer.getHost()); nettyRequest.headers().set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + msg); } catch (NTLMEngineException e) { IOException ie = new IOException(); ie.initCause(e); throw ie; } } } else { nettyRequest.headers().set(HttpHeaders.Names.PROXY_AUTHORIZATION, AuthenticatorUtils.computeBasicAuthentication(proxyServer)); } } } // Add default accept headers. if (request.getHeaders().getFirstValue("Accept") == null) { nettyRequest.headers().set(HttpHeaders.Names.ACCEPT, "*/*"); } if (request.getHeaders().getFirstValue("User-Agent") != null) { nettyRequest.headers().set("User-Agent", request.getHeaders().getFirstValue("User-Agent")); } else if (config.getUserAgent() != null) { nettyRequest.headers().set("User-Agent", config.getUserAgent()); } else { nettyRequest.headers().set("User-Agent", AsyncHttpProviderUtils.constructUserAgent(NettyAsyncHttpProvider.class, config)); } if (!m.equals(HttpMethod.CONNECT)) { if (isNonEmpty(request.getCookies())) { CookieEncoder httpCookieEncoder = new CookieEncoder(false); Iterator<Cookie> ic = request.getCookies().iterator(); Cookie c; org.jboss.netty.handler.codec.http.Cookie cookie; while (ic.hasNext()) { c = ic.next(); cookie = new DefaultCookie(c.getName(), c.getValue()); cookie.setPath(c.getPath()); cookie.setMaxAge(c.getMaxAge()); cookie.setDomain(c.getDomain()); httpCookieEncoder.addCookie(cookie); } nettyRequest.headers().set(HttpHeaders.Names.COOKIE, httpCookieEncoder.encode()); } String reqType = request.getMethod(); if (!"HEAD".equals(reqType) && !"OPTION".equals(reqType) && !"TRACE".equals(reqType)) { String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding(); // We already have processed the body. if (buffer != null && buffer.writerIndex() != 0) { nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, buffer.writerIndex()); nettyRequest.setContent(buffer); } else if (request.getByteData() != null) { nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getByteData().length)); nettyRequest.setContent(Unpooled.wrappedBuffer(request.getByteData())); } else if (request.getStringData() != null) { nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getStringData().getBytes(bodyCharset).length)); nettyRequest.setContent(Unpooled.wrappedBuffer(request.getStringData().getBytes(bodyCharset))); } else if (request.getStreamData() != null) { int[] lengthWrapper = new int[1]; byte[] bytes = AsyncHttpProviderUtils.readFully(request.getStreamData(), lengthWrapper); int length = lengthWrapper[0]; nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(length)); nettyRequest.setContent(Unpooled.wrappedBuffer(bytes, 0, length)); } else if (isNonEmpty(request.getParams())) { StringBuilder sb = new StringBuilder(); for (final Entry<String, List<String>> paramEntry : request.getParams()) { final String key = paramEntry.getKey(); for (final String value : paramEntry.getValue()) { if (sb.length() > 0) { sb.append("&"); } UTF8UrlEncoder.appendEncoded(sb, key); sb.append("="); UTF8UrlEncoder.appendEncoded(sb, value); } } nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sb.length())); nettyRequest.setContent(Unpooled.wrappedBuffer(sb.toString().getBytes(bodyCharset))); if (!request.getHeaders().containsKey(HttpHeaders.Names.CONTENT_TYPE)) { nettyRequest.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded"); } } else if (request.getParts() != null) { int lenght = computeAndSetContentLength(request, nettyRequest); if (lenght == -1) { lenght = MAX_BUFFERED_BYTES; } MultipartRequestEntity mre = AsyncHttpProviderUtils .createMultipartRequestEntity(request.getParts(), request.getParams()); nettyRequest.headers().set(HttpHeaders.Names.CONTENT_TYPE, mre.getContentType()); nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(mre.getContentLength())); /** * TODO: AHC-78: SSL + zero copy isn't supported by the MultiPart class and pretty complex to implements. */ if (isSecure(uri)) { ByteBuf b = Unpooled.buffer(lenght); mre.writeRequest(new ByteBufOutputStream(b)); nettyRequest.setContent(b); } } else if (request.getEntityWriter() != null) { int lenght = computeAndSetContentLength(request, nettyRequest); if (lenght == -1) { lenght = MAX_BUFFERED_BYTES; } ByteBuf b = Unpooled.buffer(lenght); request.getEntityWriter().writeEntity(new ByteBufOutputStream(b)); nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, b.writerIndex()); nettyRequest.setContent(b); } else if (request.getFile() != null) { File file = request.getFile(); if (!file.isFile()) { throw new IOException( String.format("File %s is not a file or doesn't exist", file.getAbsolutePath())); } nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, file.length()); } } } return nettyRequest; }
From source file:com.ning.http.client.providers.netty_4.NettyResponse.java
License:Apache License
public ByteBuf getResponseBodyAsByteBuf() throws IOException { ByteBuf b = null;/*from w w w . j a v a 2s . c o m*/ switch (bodyParts.size()) { case 0: b = Unpooled.EMPTY_BUFFER; break; case 1: b = ResponseBodyPart.class.cast(bodyParts.get(0)).getChannelBuffer(); break; default: ByteBuf[] channelBuffers = new ByteBuf[bodyParts.size()]; for (int i = 0; i < bodyParts.size(); i++) { channelBuffers[i] = ResponseBodyPart.class.cast(bodyParts.get(i)).getChannelBuffer(); } b = Unpooled.wrappedBuffer(channelBuffers); } return b; }
From source file:com.ociweb.pronghorn.adapter.netty.impl.HttpStaticFileServerHandler.java
License:Apache License
public static void sendFile(ChannelHandlerContext ctx, FullHttpRequest request, File file) throws ParseException, IOException { long lastModified = file.lastModified(); String path = file.getPath(); // Cache Validation String ifModifiedSince = request.headers().get(HttpHeaderNames.IF_MODIFIED_SINCE); if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince); // Only compare up to the second because the datetime format we send to the client // does not have milliseconds long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000; long fileLastModifiedSeconds = lastModified / 1000; if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) { sendNotModified(ctx);/*from w ww .ja v a2s. c om*/ return; } } RandomAccessFile raf; try { raf = new RandomAccessFile(file, "r"); } catch (FileNotFoundException ignore) { sendError(ctx, NOT_FOUND); return; } long fileLength = file.length(); beginHTTPResponse(ctx, request, lastModified, path, fileLength); // Write the content. ChannelFuture sendFileFuture; ChannelFuture lastContentFuture; if (ctx.pipeline().get(SslHandler.class) == null) { sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise()); // Write the end marker. lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } else { FileInputStream input = new FileInputStream(file); byte[] data = new byte[(int) fileLength]; //big hack to convert into byteBuf int pos = 0; int remaining = (int) fileLength; while (remaining > 0) { int len = input.read(data, pos, remaining); remaining -= len; pos += len; } sendFileFuture = ctx.write(Unpooled.wrappedBuffer(data), ctx.newProgressivePromise()); lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } progressAndClose(request, sendFileFuture, lastContentFuture); }
From source file:com.ociweb.pronghorn.adapter.netty.impl.HttpStaticFileServerHandler.java
License:Apache License
public static void sendResource(ChannelHandlerContext ctx, FullHttpRequest request, String name) throws ParseException, IOException { InputStream resourceAsStream = HttpStaticFileServerHandler.class.getResourceAsStream(name); if (null == resourceAsStream) { throw new FileNotFoundException("Unable to find resource: " + name); } else {/* w w w .ja v a 2 s .com*/ System.err.println("found resource: " + name); } int fileLength = resourceAsStream.available(); // String path = file.getPath(); long lastModified = STARTUP_TIME - 3000; String path = name; // Cache Validation String ifModifiedSince = request.headers().get(HttpHeaderNames.IF_MODIFIED_SINCE); if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince); // Only compare up to the second because the datetime format we send to the client // does not have milliseconds long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000; long fileLastModifiedSeconds = lastModified / 1000; if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) { sendNotModified(ctx); return; } } beginHTTPResponse(ctx, request, lastModified, path, fileLength); // Write the content. ChannelFuture sendFileFuture; ChannelFuture lastContentFuture; byte[] data = new byte[(int) fileLength]; //big hack to convert into byteBuf int pos = 0; int remaining = fileLength; while (remaining > 0) { int len = resourceAsStream.read(data, pos, remaining); remaining -= len; pos += len; } resourceAsStream.close(); sendFileFuture = ctx.write(Unpooled.wrappedBuffer(data), ctx.newProgressivePromise()); lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); progressAndClose(request, sendFileFuture, lastContentFuture); }
From source file:com.phei.netty.nio.http.helloworld.HttpHelloWorldServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; if (HttpHeaderUtil.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); }//from w ww.j av a2 s . c o m boolean keepAlive = HttpHeaderUtil.isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT)); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE); ctx.write(response); } } }
From source file:com.qq.servlet.demo.netty.sample.http.helloworld.HttpHelloWorldServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println(msg);/*from ww w. j a va 2 s. c o m*/ System.out.println("\n\n\n\n============" + msg.getClass().getName() + "=================\n\n\n"); if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; String uri = req.getUri(); System.out.println("uri--->>>" + uri); if (is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); } boolean keepAlive = isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer("".getBytes())); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, Values.KEEP_ALIVE); ctx.write(response); } } else if (msg instanceof DefaultLastHttpContent) { DefaultLastHttpContent httpContent = (DefaultLastHttpContent) msg; String body = httpContent.content().toString(CharsetUtil.UTF_8); System.out.println("body===>>> " + body); } }
From source file:com.quavo.osrs.network.handler.listener.UpdateListener.java
License:Open Source License
@Override public void handleMessage(ChannelHandlerContext ctx, UpdateRequest msg) { int type = msg.getType(); int id = msg.getId(); ByteBuf container = null;/*from w w w . ja v a2s . co m*/ try { if (type == 0xff && id == 0xff) { container = Unpooled.wrappedBuffer(CacheManager.getChecksumBuffer()); } else { container = Unpooled.wrappedBuffer(CacheManager.getCache().getStore().read(type, id)); if (type != 0xff) { container = container.slice(0, container.readableBytes() - 2); } } } catch (IOException e) { e.printStackTrace(); } ctx.write(new UpdateResponse(type, id, msg.isPriority(), container)); }