List of usage examples for io.netty.buffer ByteBuf toString
public abstract String toString(Charset charset);
From source file:me.ferrybig.javacoding.webmapper.netty.WebServerHandler.java
public Optional<Object> decodeRequest(Optional<String> contentTypeHeader, ByteBuf post) { try {/*from w w w . j a v a 2s.c o m*/ if (!contentTypeHeader.isPresent()) { return Optional.empty(); } int responseSize = post.readableBytes(); if (responseSize > 1 * 1024 * 1024) { return Optional.empty(); } String[] header = contentTypeHeader.get().split(";"); String type = header[0].trim(); String charset = "UFT-8"; for (int i = 1; i < header.length; i++) { String[] split = header[i].split("="); if (split.length != 2) { continue; } split[0] = split[0].trim(); split[1] = split[1].trim(); if (split[0].equals("charset")) { charset = split[1]; } } charset = charset.toUpperCase(); Charset set = null; for (Map.Entry<String, Charset> key : Charset.availableCharsets().entrySet()) { if (charset.equals(key.getKey().toUpperCase())) { set = key.getValue(); break; } } if (set == null) { return Optional.empty(); } switch (type.toLowerCase()) { case "application/json": { String input = post.toString(set); try { return Optional.of(new JSONObject(input)); } catch (JSONException ex) { return Optional.empty(); } } case "application/x-www-form-urlencoded": { String input = post.toString(set); return Optional.of(new QueryStringDecoder(input)); } default: return Optional.empty(); } } finally { // Consume bytes remaining... post.skipBytes(post.readableBytes()); } }
From source file:me.zhuoran.amoeba.netty.server.HttpServerHandler.java
License:Apache License
protected void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception { AmoebaHttpRequest request = null;// ww w. j a v a 2s . c o m if (msg instanceof HttpRequest) { HttpRequest httpContent = (HttpRequest) msg; if (!httpContent.getDecoderResult().isSuccess()) { sendHttpResponse(ctx, httpContent, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST)); return; } if (httpContent.getMethod() != HttpMethod.GET && httpContent.getMethod() != HttpMethod.POST) { sendHttpResponse(ctx, httpContent, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN)); return; } if (HttpHeaders.is100ContinueExpected(httpContent)) { ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE)); } String uri = HttpRequestHandler.sanitizeUri(httpContent.getUri()); if (!HttpServer.executorNameList.contains(uri)) { DefaultFullHttpResponse response1 = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND); sendHttpResponse(ctx, httpContent, response1); return; } request = new AmoebaHttpRequest(httpContent, ctx.channel().id().asLongText()); } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); request.setHttpContent(content); request.setContent(content.toString(CharsetUtil.UTF_8)); if (msg instanceof LastHttpContent) { FullHttpResponse response = this.getHttpResponse(request); this.writeResponse(request, response, ctx); } } }
From source file:metricsdb.core.http.HttpSnoopServerHandler.java
License:Apache License
private void handleHttpRequest(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { this.httpRequest = (HttpRequest) msg; }//from w w w . j av a 2s . c o m if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); this.json = content.toString(CharsetUtil.UTF_8); this.uri = httpRequest.getUri(); try { reader = createInputStream(json); } catch (IOException e) { logger.info("Cannot create reader object"); } JsonParser jsonParser = new JsonParser(reader); dataStore = new MetricsDB(); //JsonParserBuilder jsonBuilder = new JsonParserBuilder(jsonParser); RequestFactory requestFactory = new RequestFactory(jsonParser, dataStore); Request request = requestFactory.createRequest(uri); String response = request.execute(); } if (msg instanceof LastHttpContent) { LastHttpContent trailer = (LastHttpContent) msg; writeResponse(trailer, ctx); } }
From source file:nenea.client.file.FileClientHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println("channelRead0"); ByteBuf buf = (ByteBuf) msg; System.out.println(buf.readableBytes()); System.out.println(msg);//w w w . j av a 2 s . co m System.out.println(buf.toString(CharsetUtil.UTF_8)); System.out.println((ByteBufUtil.hexDump(buf))); // byte[] msgg = buf.array(); // System.out.println(buf.readInt()); int header1 = buf.readInt(); String header2 = buf.readBytes(header1).toString(CharsetUtil.UTF_8); long header3 = buf.readLong(); System.err.println(header1); System.err.println(header2); System.err.println(header3); }
From source file:net.floodlightcontroller.hasupport.ServerChannelInboundHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf message) throws Exception { ByteBuf rep = Unpooled.copiedBuffer(message); ByteBuf resp = Unpooled.copiedBuffer(processServerMessage(rep.toString(CharsetUtil.UTF_8)).getBytes()); ctx.writeAndFlush(resp);// www .ja va 2 s . c o m message.clear(); }
From source file:net.minecrell.quartz.status.QuartzFavicon.java
License:MIT License
private static String encode(BufferedImage favicon) throws IOException { checkArgument(favicon.getWidth() == 64, "favicon must be 64 pixels wide"); checkArgument(favicon.getHeight() == 64, "favicon must be 64 pixels high"); ByteBuf buf = Unpooled.buffer();/*from w w w . java 2s .co m*/ try { ImageIO.write(favicon, "PNG", new ByteBufOutputStream(buf)); ByteBuf base64 = Base64.encode(buf); try { return FAVICON_PREFIX + base64.toString(Charsets.UTF_8); } finally { base64.release(); } } finally { buf.release(); } }
From source file:netty.HttpSnoopServerHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (is100ContinueExpected(request)) { send100Continue(ctx);//from w w w .j a v a 2s . c o m } buf.setLength(0); buf.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); buf.append("===================================\r\n"); buf.append("VERSION: ").append(request.getProtocolVersion()).append("\r\n"); buf.append("HOSTNAME: ").append(getHost(request, "unknown")).append("\r\n"); buf.append("REQUEST_URI: ").append(request.getUri()).append("\r\n\r\n"); HttpHeaders headers = request.headers(); 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"); } QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri()); Map<String, List<String>> params = queryStringDecoder.parameters(); if (!params.isEmpty()) { for (Entry<String, List<String>> p : params.entrySet()) { String key = p.getKey(); List<String> vals = p.getValue(); for (String val : vals) { buf.append("PARAM: ").append(key).append(" = ").append(val).append("\r\n"); } } buf.append("\r\n"); } appendDecoderResult(buf, request); } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); if (content.isReadable()) { buf.append("CONTENT: "); buf.append(content.toString(CharsetUtil.UTF_8)); buf.append("\r\n"); appendDecoderResult(buf, request); } if (msg instanceof LastHttpContent) { buf.append("END OF CONTENT\r\n"); LastHttpContent trailer = (LastHttpContent) msg; if (!trailer.trailingHeaders().isEmpty()) { buf.append("\r\n"); for (String name : trailer.trailingHeaders().names()) { for (String value : trailer.trailingHeaders().getAll(name)) { buf.append("TRAILING HEADER: "); buf.append(name).append(" = ").append(value).append("\r\n"); } } buf.append("\r\n"); } writeResponse(trailer, ctx); } } }
From source file:nl.thijsalders.spigotproxy.haproxy.HAProxyMessageDecoder.java
License:Apache License
@Override protected final void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { // determine the specification version if (version == -1) { if ((version = findVersion(in)) == -1) { return; }/* www. j ava 2s. c o m*/ } ByteBuf decoded; if (version == 1) { decoded = decodeLine(ctx, in); } else { decoded = decodeStruct(ctx, in); } if (decoded != null) { finished = true; try { if (version == 1) { out.add(HAProxyMessage.decodeHeader(decoded.toString(CharsetUtil.US_ASCII))); } else { out.add(HAProxyMessage.decodeHeader(decoded)); } } catch (HAProxyProtocolException e) { fail(ctx, null, e); } } }
From source file:org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnector.java
License:Apache License
private static String base64(byte[] data) { ByteBuf encodedData = Unpooled.wrappedBuffer(data); ByteBuf encoded = Base64.encode(encodedData); String encodedString = encoded.toString(StandardCharsets.UTF_8); encoded.release();/*from www .j a va 2s . c om*/ return encodedString; }
From source file:org.apache.bookkeeper.bookie.storage.ldb.WriteCacheTest.java
License:Apache License
@Test public void testWriteReadsInMultipleSegments() { // Create cache with max size 4 KB and each segment is 128 bytes WriteCache cache = new WriteCache(allocator, 4 * 1024, 128); for (int i = 0; i < 48; i++) { boolean inserted = cache.put(1, i, Unpooled.wrappedBuffer(("test-" + i).getBytes())); assertTrue(inserted);//from w ww .ja v a2 s . c o m } assertEquals(48, cache.count()); for (int i = 0; i < 48; i++) { ByteBuf b = cache.get(1, i); assertEquals("test-" + i, b.toString(Charset.forName("UTF-8"))); } cache.close(); }