List of usage examples for io.netty.buffer ByteBuf getBytes
public abstract ByteBuf getBytes(int index, ByteBuffer dst);
From source file:org.graylog2.gelfclient.encoder.GelfMessageJsonEncoderTest.java
License:Apache License
@Test public void testOptionalFullMessage() throws Exception { final EmbeddedChannel channel = new EmbeddedChannel(new GelfMessageJsonEncoder()); final GelfMessage message = new GelfMessageBuilder("test").build(); assertTrue(channel.writeOutbound(message)); assertTrue(channel.finish());//from www . ja va2 s . c o m final ByteBuf byteBuf = (ByteBuf) channel.readOutbound(); final byte[] bytes = new byte[byteBuf.readableBytes()]; byteBuf.getBytes(0, bytes).release(); final JsonFactory json = new JsonFactory(); final JsonParser parser = json.createParser(bytes); String version = null; Number timestamp = null; String host = null; String short_message = null; String full_message = null; Number level = null; while (parser.nextToken() != JsonToken.END_OBJECT) { String key = parser.getCurrentName(); if (key == null) { continue; } parser.nextToken(); switch (key) { case "version": version = parser.getText(); break; case "timestamp": timestamp = parser.getNumberValue(); break; case "host": host = parser.getText(); break; case "short_message": short_message = parser.getText(); break; case "full_message": full_message = parser.getText(); break; case "level": level = parser.getNumberValue(); break; default: throw new Exception("Found unexpected field in JSON payload: " + key); } } assertEquals(message.getVersion().toString(), version); assertEquals(message.getTimestamp(), timestamp); assertEquals(message.getHost(), host); assertEquals(message.getMessage(), short_message); assertNull(full_message); assertEquals(message.getLevel().getNumericLevel(), level); }
From source file:org.graylog2.gelfclient.encoder.GelfMessageJsonEncoderTest.java
License:Apache License
@Test public void testNullLevel() throws Exception { final EmbeddedChannel channel = new EmbeddedChannel(new GelfMessageJsonEncoder()); final GelfMessage message = new GelfMessageBuilder("test").build(); message.setLevel(null);// w w w. j a va 2 s . c om assertTrue(channel.writeOutbound(message)); assertTrue(channel.finish()); final ByteBuf byteBuf = (ByteBuf) channel.readOutbound(); final byte[] bytes = new byte[byteBuf.readableBytes()]; byteBuf.getBytes(0, bytes).release(); final JsonFactory json = new JsonFactory(); final JsonParser parser = json.createParser(bytes); String version = null; Number timestamp = null; String host = null; String short_message = null; String full_message = null; Number level = null; while (parser.nextToken() != JsonToken.END_OBJECT) { String key = parser.getCurrentName(); if (key == null) { continue; } parser.nextToken(); switch (key) { case "version": version = parser.getText(); break; case "timestamp": timestamp = parser.getNumberValue(); break; case "host": host = parser.getText(); break; case "short_message": short_message = parser.getText(); break; case "full_message": full_message = parser.getText(); break; case "level": level = parser.getNumberValue(); break; default: throw new Exception("Found unexpected field in JSON payload: " + key); } } assertEquals(message.getVersion().toString(), version); assertEquals(message.getTimestamp(), timestamp); assertEquals(message.getHost(), host); assertEquals(message.getMessage(), short_message); assertNull(full_message); assertNull(level); }
From source file:org.hornetq.amqp.test.minimalserver.MinimalConnectionSPI.java
License:Apache License
@Override public void output(final ByteBuf bytes, final ChannelFutureListener futureCompletion) { if (DebugInfo.debug) { // some debug byte[] frame = new byte[bytes.writerIndex()]; int readerOriginalPos = bytes.readerIndex(); bytes.getBytes(0, frame); try {/* w w w . ja v a 2 s . co m*/ System.err.println( "Buffer Outgoing: " + "\n" + ByteUtil.formatGroup(ByteUtil.bytesToHex(frame), 4, 16)); } catch (Exception e) { e.printStackTrace(); } bytes.readerIndex(readerOriginalPos); } // ^^ debug channel.writeAndFlush(bytes).addListener(futureCompletion); }
From source file:org.iotivity.cloud.base.protocols.http.HCProxyProcessor.java
License:Open Source License
/** * This function returns a created HTTP response * translated from the CoAP response./*from w ww . j a v a2s . com*/ * * @param response * @return httpResponse */ public HttpResponse getHttpResponse(IResponse response) { HttpResponse httpResponse = null; ResponseStatus coapResponseStatus = response.getStatus(); ContentFormat coapContentFormat = response.getContentFormat(); byte[] coapPayload = response.getPayload(); boolean isPayload = false; HttpVersion httpVersion = HttpVersion.HTTP_1_1; if (coapPayload != null && coapPayload.length > 0) { isPayload = true; HttpResponseStatus httpStatus = getHttpResponseStatus(coapResponseStatus, isPayload); String httpContentType = null; ByteBuf httpContent = Unpooled.EMPTY_BUFFER; if (coapContentFormat == ContentFormat.APPLICATION_CBOR) { // Content-Type: application/json httpContentType = APPLICATION_JSON; String payloadString = null; try { // Cbor: Map to JSON string if (getTargetCoapPath().contains(DISCOVER_URI)) { Log.v("Cbor decoding using ArrayList.class"); ArrayList<Object> cborMap = mStackCborArray.parsePayloadFromCbor(coapPayload, ArrayList.class); ObjectMapper cborMapper = new ObjectMapper(); payloadString = cborMapper.writerWithDefaultPrettyPrinter().writeValueAsString(cborMap); } else { Log.v("Cbor decoding using HashMap.class"); HashMap<String, Object> cborMap = mStackCborMap.parsePayloadFromCbor(coapPayload, HashMap.class); ObjectMapper cborMapper = new ObjectMapper(); payloadString = cborMapper.writerWithDefaultPrettyPrinter().writeValueAsString(cborMap); } } catch (JsonProcessingException e) { e.printStackTrace(); } if (payloadString == null || payloadString.trim().equalsIgnoreCase("null")) { payloadString = ""; } byte[] payloadBytes = payloadString.getBytes(); httpContent = Unpooled.wrappedBuffer(payloadBytes); } else { if (response instanceof CoapResponse) { // Content-Type: // application/coap-payload;cf=<Content-Format value> httpContentType = COAP_FORMAT_TYPE + ((CoapResponse) response).getContentFormatValue(); } else { httpContentType = coapContentFormat.toString(); } httpContent = Unpooled.wrappedBuffer(coapPayload); } httpResponse = new DefaultFullHttpResponse(httpVersion, httpStatus, httpContent); // Default: Non-persistent connection httpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, httpContentType); httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, httpContent.readableBytes()); byte[] bytes = new byte[httpContent.readableBytes()]; httpContent.getBytes(httpContent.readerIndex(), bytes); StringBuilder contentStrBuilder = new StringBuilder(new String(bytes)); mCtx.channel().attr(HCProxyProcessor.ctxStrContent).set(contentStrBuilder); } else { isPayload = false; HttpResponseStatus httpStatus = getHttpResponseStatus(coapResponseStatus, isPayload); httpResponse = new DefaultFullHttpResponse(httpVersion, httpStatus); // Default: Non-persistent connection httpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); // Some clients requires content-length=0 // to decide a proper size of one response message. httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.NONE); httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, HttpHeaderValues.ZERO); } /* * If HTTP request was sign-in and HTTP response is 200 OK, * then set HTTP Cookie in the response for the session. */ if (mTargetCoapPath != null && mTargetCoapPath.contains(SIGNIN_URI) && httpResponse.status() == HttpResponseStatus.OK) { long timeoutSeconds = SESSION_TIMEOUT; String createdSid = setSessionId(httpResponse, timeoutSeconds); // Set SessionExpiredTime in HttpDevice // and put it into httpDeviceMap using the session id as a key Device device = mCtx.channel().attr(ServerSystem.keyDevice).get(); if (device != null) { ((HttpDevice) device).setSessionExpiredTime(timeoutSeconds); HttpServer.httpDeviceMap.put(createdSid, (HttpDevice) device); mCtx.channel().attr(ServerSystem.keyDevice).set(device); } } // Put HttpDevice into httpDeviceMap using the session id as a key HttpDevice httpDevice = (HttpDevice) mCtx.channel().attr(ServerSystem.keyDevice).get(); if (httpDevice != null && mSessionId != null) { HttpServer.httpDeviceMap.put(mSessionId, httpDevice); } return httpResponse; }
From source file:org.jdiameter.client.impl.transport.tls.netty.StartTlsClientHandler.java
License:Open Source License
@SuppressWarnings("unchecked") @Override// w w w . j ava 2s .co m public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception { logger.debug("StartTlsClientHandler"); ByteBuf buf = (ByteBuf) msg; byte[] bytes = new byte[buf.readableBytes()]; buf.getBytes(buf.readerIndex(), bytes); if ("StartTlsResponse".equals(new String(bytes))) { logger.debug("received StartTlsResponse"); SslContext sslContext = SslContextFactory.getSslContextForClient(this.tlsTransportClient.getConfig()); SSLEngine sslEngine = sslContext.newEngine(ctx.alloc()); sslEngine.setUseClientMode(true); SslHandler sslHandler = new SslHandler(sslEngine, false); final ChannelPipeline pipeline = ctx.pipeline(); pipeline.remove("startTlsClientHandler"); pipeline.addLast("sslHandler", sslHandler); logger.debug("StartTls starting handshake"); sslHandler.handshakeFuture().addListener(new GenericFutureListener() { @Override public void operationComplete(Future future) throws Exception { if (future.isSuccess()) { logger.debug("StartTls handshake succesfull"); tlsTransportClient.setTlsHandshakingState(TlsHandshakingState.SHAKEN); logger.debug("restoring all handlers"); pipeline.addLast("decoder", new DiameterMessageDecoder( StartTlsClientHandler.this.tlsTransportClient.getParent(), StartTlsClientHandler.this.tlsTransportClient.getParser())); pipeline.addLast("msgHandler", new DiameterMessageHandler( StartTlsClientHandler.this.tlsTransportClient.getParent(), true)); pipeline.addLast("encoder", new DiameterMessageEncoder( StartTlsClientHandler.this.tlsTransportClient.getParser())); pipeline.addLast("inbandWriter", new InbandSecurityHandler()); } } }); } }
From source file:org.jdiameter.client.impl.transport.tls.netty.StartTlsServerHandler.java
License:Open Source License
@SuppressWarnings({ "unchecked", "rawtypes" }) @Override// ww w.java2s . c om public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { logger.debug("StartTlsServerHandler"); ByteBuf buf = (ByteBuf) msg; byte[] bytes = new byte[buf.readableBytes()]; buf.getBytes(buf.readerIndex(), bytes); if ("StartTlsRequest".equals(new String(bytes))) { logger.debug("Received StartTlsRequest"); SslContext sslContext = SslContextFactory.getSslContextForServer(this.tlsTransportClient.getConfig()); SSLEngine sslEngine = sslContext.newEngine(ctx.alloc()); sslEngine.setUseClientMode(false); SslHandler sslHandler = new SslHandler(sslEngine, false); final ChannelPipeline pipeline = ctx.pipeline(); pipeline.remove("decoder"); pipeline.remove("msgHandler"); pipeline.remove("encoder"); pipeline.remove("inbandWriter"); pipeline.remove(this); pipeline.addLast("sslHandler", sslHandler); sslHandler.handshakeFuture().addListener(new GenericFutureListener() { @Override public void operationComplete(Future future) throws Exception { if (future.isSuccess()) { logger.debug("StartTls server handshake succesfull"); tlsTransportClient.setTlsHandshakingState(TlsHandshakingState.SHAKEN); logger.debug("restoring all handlers"); pipeline.addLast("decoder", new DiameterMessageDecoder( StartTlsServerHandler.this.tlsTransportClient.getParent(), StartTlsServerHandler.this.tlsTransportClient.getParser())); pipeline.addLast("msgHandler", new DiameterMessageHandler( StartTlsServerHandler.this.tlsTransportClient.getParent(), true)); pipeline.addLast("encoder", new DiameterMessageEncoder( StartTlsServerHandler.this.tlsTransportClient.getParser())); pipeline.addLast("inbandWriter", new InbandSecurityHandler()); } } }); ReferenceCountUtil.release(msg); logger.debug("Sending StartTlsResponse"); ctx.writeAndFlush(Unpooled.wrappedBuffer("StartTlsResponse".getBytes())) .addListener(new GenericFutureListener() { @Override public void operationComplete(Future f) throws Exception { if (!f.isSuccess()) { logger.error(f.cause().getMessage(), f.cause()); } } }); } else { ctx.fireChannelRead(msg); } }
From source file:org.l2junity.gameserver.network.client.Crypt.java
License:Open Source License
private void onPacketSent(ByteBuf buf) { byte[] data = new byte[buf.writerIndex()]; buf.getBytes(0, data); EventDispatcher.getInstance().notifyEvent(new OnPacketSent(_client, data)); }
From source file:org.l2junity.gameserver.network.client.Crypt.java
License:Open Source License
private void onPacketReceive(ByteBuf buf) { byte[] data = new byte[buf.writerIndex()]; buf.getBytes(0, data); EventDispatcher.getInstance().notifyEvent(new OnPacketReceived(_client, data)); }
From source file:org.lmdbjava.ByteBufProxy.java
License:Apache License
@Override protected byte[] getBytes(final ByteBuf buffer) { final byte[] dest = new byte[buffer.capacity()]; buffer.getBytes(0, dest); return dest;//from w w w .ja v a2 s . com }
From source file:org.onosproject.ovsdb.lib.utils.JsonRpcReaderUtil.java
License:Apache License
/** * Check whether the encoding is valid./*from w w w .j a va 2 s. c om*/ * @param in input of bytes * @throws IOException */ private static void checkEncoding(ByteBuf in) throws IOException { fliterCharaters(in); byte[] buff = new byte[4]; in.getBytes(in.readerIndex(), buff); ByteSourceJsonBootstrapper strapper = new ByteSourceJsonBootstrapper( new IOContext(new BufferRecycler(), null, false), buff, 0, 4); JsonEncoding jsonEncoding = strapper.detectEncoding(); if (!JsonEncoding.UTF8.equals(jsonEncoding)) { throw new UnsupportedEncodingException("Only UTF-8 encoding is supported."); } }