List of usage examples for io.netty.buffer ByteBuf getBytes
public abstract ByteBuf getBytes(int index, ByteBuffer dst);
From source file:org.opendaylight.protocol.util.ByteArray.java
License:Open Source License
/** * Helper method missing from netty ByteBuf methods. Directly returns byte array part of the given buffer, starting * at reader index, with given length. Does not modify reader or writer index of the buffer. * * @param buffer ByteBuf from which the bytes are going to be taken * @param length length of the returned byte array * @return byte array//w ww . ja v a 2s. com */ public static byte[] getBytes(final ByteBuf buffer, final int length) { Preconditions.checkArgument(buffer != null && buffer.readableBytes() >= length, "Buffer cannot be read for %s bytes.", length); final byte[] result = new byte[length]; buffer.getBytes(buffer.readerIndex(), result); return result; }
From source file:org.proton.plug.test.minimalserver.MinimalConnectionSPI.java
License:Apache License
@Override public void onTransport(final ByteBuf bytes, final AMQPConnectionContext connection) { final int bufferSize = bytes.writerIndex(); if (DebugInfo.debug) { // some debug byte[] frame = new byte[bytes.writerIndex()]; int readerOriginalPos = bytes.readerIndex(); bytes.getBytes(0, frame); try {// w w w . j a 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); } latch.countUp(); // ^^ debug channel.writeAndFlush(bytes).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { latch.countDown(); // https://issues.apache.org/jira/browse/PROTON-645 // connection.outputDone(bufferSize); // if (connection.capacity() > 0) // { // channel.read(); // } } }); channel.flush(); if (connection.isSyncOnFlush()) { try { if (!latch.await(5, TimeUnit.SECONDS)) { // TODO logs System.err.println("Flush took longer than 5 seconds!!!"); } } catch (Throwable e) { e.printStackTrace(); } } connection.outputDone(bufferSize); // if (connection.capacity() > 0) // { // channel.read(); // } }
From source file:org.redisson.cache.LocalCachedMapUpdate.java
License:Apache License
public LocalCachedMapUpdate(ByteBuf keyBuf, ByteBuf valueBuf) { byte[] key = new byte[keyBuf.readableBytes()]; keyBuf.getBytes(keyBuf.readerIndex(), key); byte[] value = new byte[valueBuf.readableBytes()]; valueBuf.getBytes(valueBuf.readerIndex(), value); entries = Collections.singletonList(new Entry(key, value)); }
From source file:org.restcomm.media.control.mgcp.network.netty.MgcpMessageDecoder.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out) throws Exception { final ByteBuf content = msg.content(); final InetSocketAddress recipient = msg.recipient(); final InetSocketAddress sender = msg.sender(); // Get data from buffer byte[] payload = new byte[content.readableBytes()]; content.getBytes(0, payload); // Check message type based on first byte byte b = payload[0]; // Produce message according to type MgcpMessage message;/*from w ww. ja va 2 s . c o m*/ if (b >= 48 && b <= 57) { message = handleResponse(payload); } else { message = handleRequest(payload); } if (log.isDebugEnabled()) { log.debug("Incoming MGCP message from " + sender.toString() + ":\n\n" + message.toString() + "\n"); } MgcpMessageEnvelope envelope = new MgcpMessageEnvelope(message, recipient, sender); // Pass message to next handler out.add(envelope); }
From source file:org.restcomm.media.rtp.netty.RtpDemultiplexer.java
License:Open Source License
private void handleDtlsPacket(ChannelHandlerContext ctx, ByteBuf buffer) { // Retrieve data from network final int length = buffer.readableBytes(); final int offset = buffer.arrayOffset(); // Wrap data into a DTLS packet byte[] data = new byte[length - offset]; buffer.getBytes(offset, data); DtlsPacket dtlsPacket = new DtlsPacket(data); ctx.fireChannelRead(dtlsPacket);//from w w w .ja va2 s . co m }
From source file:org.restexpress.Request.java
License:Apache License
/** * Returns the byte array underlying the Netty ByteBuf for this request. * However, if the ByteBuf returns false to hasArray(), this * method returns null.//w ww.j a v a 2 s . c o m * @author actolap All ByteBufs may not have backing array (i.e. direct memory) * * @return an array of byte, or null, if the ByteBuf is not backed by a byte array. */ public byte[] getBodyAsBytes() { ByteBuf buf = getBody(); int length = buf.readableBytes(); byte[] bytes; if (buf.hasArray()) { bytes = buf.array(); } else { bytes = new byte[length]; buf.getBytes(buf.readerIndex(), bytes); } return bytes; }
From source file:org.rzo.netty.ahessian.log.OutLogger.java
License:Apache License
static private void encodeBuffer(ByteBuf buffer, StringBuilder sb) { if (buffer == null) return;/*from ww w. java 2s .c o m*/ sb.append("(" + buffer.readableBytes() + ") "); int size = Math.min(MSG_LOG_LENGTH, buffer.readableBytes()); byte[] b = new byte[size]; buffer.getBytes(0, b); for (int i = 0; i < b.length && i < MSG_LOG_LENGTH; i++) { toDebugChar(sb, b[i]); } }
From source file:org.shelloid.vpt.agent.VPTClient.java
License:Open Source License
@Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { Channel ch = ctx.channel();/*from ww w. java 2s.c o m*/ if (!handshaker.isHandshakeComplete()) { handshaker.finishHandshake(ch, (FullHttpResponse) msg); handshakeFuture.setSuccess(); onWsAuthenticated(); Platform.shelloidLogger.debug("Client connected using " + ch + ". Now sending init ACK"); sendAckMessage(ch, messenger.getLastSendAckNum()); setChannel(ch); return; } if (msg instanceof FullHttpResponse) { FullHttpResponse response = (FullHttpResponse) msg; throw new IllegalStateException("Unexpected FullHttpResponse (getStatus=" + response.getStatus() + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')'); } WebSocketFrame frame = (WebSocketFrame) msg; if (frame instanceof BinaryWebSocketFrame) { BinaryWebSocketFrame binFrame = (BinaryWebSocketFrame) frame; ByteBuf b = binFrame.content(); byte[] bytes = new byte[b.capacity()]; b.getBytes(0, bytes); handleShelloidClientMsg(bytes, ctx.channel()); } else if (frame instanceof TextWebSocketFrame) { throw new Exception("TextWebSocketFrame" + ((TextWebSocketFrame) frame).text()); } else if (frame instanceof PingWebSocketFrame) { ctx.channel().writeAndFlush(new PongWebSocketFrame()); } else if (frame instanceof PongWebSocketFrame) { Platform.shelloidLogger.info("WebSocket Client received pong"); } else if (frame instanceof CloseWebSocketFrame) { Platform.shelloidLogger.info("WebSocket Client received closing"); try { ch.close().sync(); ctx.close().sync(); } catch (InterruptedException ex) { Platform.shelloidLogger.error("InterruptedException while closing channel (channelInactive)"); } } else { throw new Exception("Frame type not supported: " + msg); } }
From source file:org.shelloid.vpt.rms.server.VPTServerHandler.java
License:Open Source License
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception { if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); } else if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); } else if (frame instanceof BinaryWebSocketFrame) { BinaryWebSocketFrame binFrame = (BinaryWebSocketFrame) frame; ByteBuf b = binFrame.content(); byte[] bytes = new byte[b.capacity()]; b.getBytes(0, bytes); processWebSocketTextFrame(ctx.channel(), bytes); } else if (frame instanceof PongWebSocketFrame) { /* Do nothing */ } else if (frame instanceof TextWebSocketFrame) { throw new Exception("TextWebSocketFrame" + ((TextWebSocketFrame) frame).text()); } else {// w w w. ja v a 2 s .c o m throw new UnsupportedOperationException( String.format("%s frame types not supported", frame.getClass().getName())); } }
From source file:org.thingsplode.synapse.endpoint.handlers.RequestHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Request request) throws Exception { Response response = null;// w w w . j a v a 2s . co m boolean fileDownload = filePattern.matcher(request.getHeader().getUri().getPath()).find(); if (!fileDownload) { try { if (request.getBody() != null && (request.getBody() instanceof ByteBuf)) { //the body is in unmarshalled //eg. http case ByteBuf content = (ByteBuf) request.getBody(); byte[] dst = new byte[content.capacity()]; content.getBytes(0, dst); String jsonBody = new String(dst, Charset.forName("UTF-8")); response = registry.invokeWithParsable(request.getHeader(), jsonBody); } else { //the complete body is unmarshalled already for an object //eg. websocket case response = registry.invokeWithObject(request.getHeader(), request.getBody()); } //else { // response = new Response(new Response.ResponseHeader(request.getHeader(), HttpResponseStatus.valueOf(HttpStatus.BAD_REQUEST.value()), new MediaType("text/plain; charset=UTF-8")), RequestHandler.class.getSimpleName() + ": Body type not supported."); //} } catch (MethodNotFoundException mex) { //simple listing, no stack trace (normal issue) logger.warn("Couldn't process request due to " + mex.getClass().getSimpleName() + " with message: " + mex.getMessage()); response = new Response( new Response.ResponseHeader(request.getHeader(), HttpResponseStatus.valueOf(mex.getResponseStatus().value()), MediaType.TEXT_PLAIN), mex.getClass().getSimpleName() + ": " + mex.getMessage()); } catch (SynapseException ex) { //it could be an internal issue logger.error("Error processing REST request: " + ex.getMessage(), ex); response = new Response( new Response.ResponseHeader(request.getHeader(), HttpResponseStatus.valueOf(ex.getResponseStatus().value()), MediaType.TEXT_PLAIN), ex.getClass().getSimpleName() + ": " + ex.getMessage()); } } if (fileDownload || response == null || isFileDownloadRetriable(response)) { FileRequest fr = new FileRequest(request.getHeader()); ctx.fireChannelRead(fr); } else { ctx.fireChannelRead(response); } }