List of usage examples for io.netty.buffer ByteBuf readableBytes
public abstract int readableBytes();
From source file:com.caricah.iotracah.server.httpserver.transform.IOTHttpTransformerImpl.java
License:Apache License
@Override public FullHttpMessage toServerMessage(IOTMessage internalMessage) { JSONObject json = new JSONObject(); switch (internalMessage.getMessageType()) { case AcknowledgeMessage.MESSAGE_TYPE: AcknowledgeMessage ackMsg = (AcknowledgeMessage) internalMessage; json.put("messageId", ackMsg.getMessageId()); json.put("qos", ackMsg.getQos()); json.put("message", "published"); break;//from ww w . j a v a2s .c o m case ConnectAcknowledgeMessage.MESSAGE_TYPE: ConnectAcknowledgeMessage conAck = (ConnectAcknowledgeMessage) internalMessage; json.put("sessionId", conAck.getSessionId()); json.put("authKey", conAck.getAuthKey()); json.put("message", conAck.getReturnCode().name()); break; case SubscribeAcknowledgeMessage.MESSAGE_TYPE: SubscribeAcknowledgeMessage subAck = (SubscribeAcknowledgeMessage) internalMessage; json.put("message", "subscribed"); final JSONArray jsonGrantedQos = new JSONArray(); subAck.getGrantedQos().forEach(jsonGrantedQos::put); json.put("grantedQos", jsonGrantedQos); break; case UnSubscribeAcknowledgeMessage.MESSAGE_TYPE: UnSubscribeAcknowledgeMessage unSubAck = (UnSubscribeAcknowledgeMessage) internalMessage; json.put("message", "unsubscribed"); break; case DisconnectMessage.MESSAGE_TYPE: DisconnectMessage discMsg = (DisconnectMessage) internalMessage; json.put("sessionId", discMsg.getSessionId()); json.put("message", "disconnected"); break; default: /** * * Internally these are not expected to get here. * In such cases we just return a null * and log this anomaly as a gross error. * **/ json.put("message", "UnExpected outcome"); break; } ByteBuf buffer = Unpooled.copiedBuffer(json.toString(), CharsetUtil.UTF_8); // Build the response object. FullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buffer); httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8"); httpResponse.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, buffer.readableBytes()); return httpResponse; }
From source file:com.cc.nettytest.proxy.decoder.CCLengthFieldBasedFrameDecoder.java
License:Apache License
@Override public Object decode(ChannelHandlerContext ctx, ByteBuf inBuffer) throws Exception { if (discardingTooLongFrame) { long bytesToDiscard = this.bytesToDiscard; int localBytesToDiscard = (int) Math.min(bytesToDiscard, inBuffer.readableBytes()); inBuffer.skipBytes(localBytesToDiscard); bytesToDiscard -= localBytesToDiscard; this.bytesToDiscard = bytesToDiscard; failIfNecessary(ctx, false);// ww w. j ava2s . c o m return null; } if (inBuffer.readableBytes() < lengthFieldEndOffset) { return null; } int actualLengthFieldOffset = inBuffer.readerIndex() + lengthFieldOffset; long frameLength; switch (lengthFieldLength) { case 1: frameLength = inBuffer.getUnsignedByte(actualLengthFieldOffset); break; case 2: frameLength = inBuffer.getUnsignedShort(actualLengthFieldOffset); break; case 3: frameLength = inBuffer.getUnsignedMedium(actualLengthFieldOffset); break; case 4: frameLength = ByteBufUtil.swapInt((int) inBuffer.getUnsignedInt(actualLengthFieldOffset)); //SWAP FOR UIMANAGER break; case 8: frameLength = inBuffer.getLong(actualLengthFieldOffset); break; default: throw new Error("should not reach here"); } if (frameLength < 0) { inBuffer.skipBytes(lengthFieldEndOffset); throw new CorruptedFrameException("negative pre-adjustment length field: " + frameLength); } frameLength += lengthAdjustment + lengthFieldEndOffset; if (frameLength < lengthFieldEndOffset) { inBuffer.skipBytes(lengthFieldEndOffset); throw new CorruptedFrameException("Adjusted frame length (" + frameLength + ") is less " + "than lengthFieldEndOffset: " + lengthFieldEndOffset); } if (frameLength > maxFrameLength) { // Enter the discard mode and discard everything received so far. discardingTooLongFrame = true; tooLongFrameLength = frameLength; bytesToDiscard = frameLength - inBuffer.readableBytes(); inBuffer.skipBytes(inBuffer.readableBytes()); failIfNecessary(ctx, true); return null; } // never overflows because it's less than maxFrameLength int frameLengthInt = (int) frameLength; if (inBuffer.readableBytes() < frameLengthInt) { return null; } if (initialBytesToStrip > frameLengthInt) { inBuffer.skipBytes(frameLengthInt); throw new CorruptedFrameException("Adjusted frame length (" + frameLength + ") is less " + "than initialBytesToStrip: " + initialBytesToStrip); } inBuffer.skipBytes(initialBytesToStrip); // extract frame int readerIndex = inBuffer.readerIndex(); int actualFrameLength = frameLengthInt - initialBytesToStrip; ByteBuf frame = extractFrame(inBuffer, readerIndex, actualFrameLength); inBuffer.readerIndex(readerIndex + actualFrameLength); return frame; }
From source file:com.cc.nettytest.proxy.encoder.CCLengthFieldPrepender.java
License:Apache License
@Override public void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception { int length = lengthIncludesLengthFieldLength ? msg.readableBytes() + lengthFieldLength : msg.readableBytes();/*from ww w . j a v a2 s . co m*/ switch (lengthFieldLength) { case 1: if (length >= 256) { throw new IllegalArgumentException("length does not fit into a byte: " + length); } out.writeByte((byte) length); break; case 2: if (length >= 65536) { throw new IllegalArgumentException("length does not fit into a short integer: " + length); } out.writeShort((short) length); break; case 3: if (length >= 16777216) { throw new IllegalArgumentException("length does not fit into a medium integer: " + length); } out.writeMedium(length); break; case 4: out.writeInt(ByteBufUtil.swapInt((int) length)); //SWAP FOR UIMANAGER break; case 8: out.writeLong(length); break; default: throw new Error("should not reach here"); } out.writeBytes(msg, msg.readerIndex(), msg.readableBytes()); }
From source file:com.chat.common.netty.handler.decode.LengthFieldBasedFrameDecoder.java
License:Apache License
/** * Create a frame out of the {@link ByteBuf} and return it. * * @param ctx the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to * @param in the {@link ByteBuf} from which to read data * @return frame the {@link ByteBuf} which represent the frame or {@code null} if no frame could * be created.//www . j a v a 2s . com */ protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception { if (discardingTooLongFrame) { long bytesToDiscard = this.bytesToDiscard; int localBytesToDiscard = (int) Math.min(bytesToDiscard, in.readableBytes()); in.skipBytes(localBytesToDiscard); bytesToDiscard -= localBytesToDiscard; this.bytesToDiscard = bytesToDiscard; failIfNecessary(false); } if (in.readableBytes() < lengthFieldEndOffset) { return null; } int actualLengthFieldOffset = in.readerIndex() + lengthFieldOffset; long frameLength = getUnadjustedFrameLength(in, actualLengthFieldOffset, lengthFieldLength, byteOrder); if (frameLength < 0) { in.skipBytes(lengthFieldEndOffset); throw new CorruptedFrameException("negative pre-adjustment length field: " + frameLength); } frameLength += lengthAdjustment + lengthFieldEndOffset; if (frameLength < lengthFieldEndOffset) { in.skipBytes(lengthFieldEndOffset); throw new CorruptedFrameException("Adjusted frame length (" + frameLength + ") is less " + "than lengthFieldEndOffset: " + lengthFieldEndOffset); } if (frameLength > maxFrameLength) { long discard = frameLength - in.readableBytes(); tooLongFrameLength = frameLength; if (discard < 0) { // buffer contains more bytes then the frameLength so we can discard all now in.skipBytes((int) frameLength); } else { // Enter the discard mode and discard everything received so far. discardingTooLongFrame = true; bytesToDiscard = discard; in.skipBytes(in.readableBytes()); } failIfNecessary(true); return null; } // never overflows because it's less than maxFrameLength int frameLengthInt = (int) frameLength; if (in.readableBytes() < frameLengthInt) { return null; } if (initialBytesToStrip > frameLengthInt) { in.skipBytes(frameLengthInt); throw new CorruptedFrameException("Adjusted frame length (" + frameLength + ") is less " + "than initialBytesToStrip: " + initialBytesToStrip); } in.skipBytes(initialBytesToStrip); // extract frame int readerIndex = in.readerIndex(); int actualFrameLength = frameLengthInt - initialBytesToStrip; ByteBuf frame = extractFrame(ctx, in, readerIndex, actualFrameLength); in.readerIndex(readerIndex + actualFrameLength); return frame; }
From source file:com.chat.common.netty.handler.decode.ProtobufDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception { final byte[] array; final int offset; final int length = msg.readableBytes(); if (msg.hasArray()) { array = msg.array();//from w ww.ja v a2 s. c o m offset = msg.arrayOffset() + msg.readerIndex(); } else { array = new byte[length]; msg.getBytes(msg.readerIndex(), array, 0, length); offset = 0; } if (extensionRegistry == null) { if (HAS_PARSER) { out.add(prototype.getParserForType().parseFrom(array, offset, length)); } else { out.add(prototype.newBuilderForType().mergeFrom(array, offset, length).build()); } } else { if (HAS_PARSER) { out.add(prototype.getParserForType().parseFrom(array, offset, length, extensionRegistry)); } else { out.add(prototype.newBuilderForType().mergeFrom(array, offset, length, extensionRegistry).build()); } } }
From source file:com.chat.common.netty.handler.decode.ProtobufVarint32FrameDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { in.markReaderIndex();// w w w. j a va 2 s. co m int preIndex = in.readerIndex(); int length = readRawVarint32(in); if (preIndex == in.readerIndex()) { return; } if (length < 0) { throw new CorruptedFrameException("negative length: " + length); } if (in.readableBytes() < length) { in.resetReaderIndex(); } else { out.add(in.readRetainedSlice(length)); } }
From source file:com.chat.common.netty.handler.encode.LengthFieldPrepender.java
License:Apache License
@Override protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception { int length = msg.readableBytes() + lengthAdjustment; if (lengthIncludesLengthFieldLength) { length += lengthFieldLength;// ww w.j ava 2 s . com } if (length < 0) { throw new IllegalArgumentException("Adjusted frame length (" + length + ") is less than zero"); } switch (lengthFieldLength) { case 1: if (length >= 256) { throw new IllegalArgumentException("length does not fit into a byte: " + length); } out.add(ctx.alloc().buffer(1).order(byteOrder).writeByte((byte) length)); break; case 2: if (length >= 65536) { throw new IllegalArgumentException("length does not fit into a short integer: " + length); } out.add(ctx.alloc().buffer(2).order(byteOrder).writeShort((short) length)); break; case 3: if (length >= 16777216) { throw new IllegalArgumentException("length does not fit into a medium integer: " + length); } out.add(ctx.alloc().buffer(3).order(byteOrder).writeMedium(length)); break; case 4: out.add(ctx.alloc().buffer(4).order(byteOrder).writeInt(length)); break; case 8: out.add(ctx.alloc().buffer(8).order(byteOrder).writeLong(length)); break; default: throw new Error("should not reach here"); } out.add(msg.retain()); }
From source file:com.chat.common.netty.handler.encode.ProtobufVarint32LengthFieldPrepender.java
License:Apache License
@Override protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception { int bodyLen = msg.readableBytes(); int headerLen = computeRawVarint32Size(bodyLen); out.ensureWritable(headerLen + bodyLen); writeRawVarint32(out, bodyLen);//from ww w. java 2s . co m out.writeBytes(msg, msg.readerIndex(), bodyLen); }
From source file:com.chenyang.proxy.EchoClientHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ByteBuf msg2 = (ByteBuf) msg; if (msg2.readableBytes() < AgentTest.SIZE) { System.out.println("client receive length : " + msg2.readableBytes()); }// w ww . j a v a 2 s. c o m ctx.write(msg); }
From source file:com.chiorichan.factory.FileInterpreter.java
License:Mozilla Public License
public static String readLine(ByteBuf buf) { if (!buf.isReadable() || buf.readableBytes() < 1) return null; String op = ""; while (buf.isReadable() && buf.readableBytes() > 0) { byte bb = buf.readByte(); if (bb == '\n') break; op += (char) bb; }/*from w w w. ja v a 2 s . co m*/ return op; }