List of usage examples for io.netty.buffer ByteBuf resetReaderIndex
public abstract ByteBuf resetReaderIndex();
From source file:gedi.remote.codec.DefaultDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (in.readableBytes() < Integer.BYTES) return;/*from ww w . j a v a 2 s. co m*/ in.markReaderIndex(); int size = in.readInt(); if (in.readableBytes() < size) { in.resetReaderIndex(); return; } // everything has arrived, decode char[] classname = new char[in.readInt()]; for (int i = 0; i < classname.length; i++) classname[i] = (char) (in.readByte() & 255); String clsName = String.valueOf(classname); if (clsName.length() == 1) { switch (clsName) { case "A": char[] re = new char[in.readInt()]; for (int i = 0; i < re.length; i++) re[i] = (char) (in.readByte() & 255); out.add(String.valueOf(re)); break; case "B": out.add(in.readByte()); break; case "S": out.add(in.readShort()); break; case "I": out.add(in.readInt()); break; case "L": out.add(in.readLong()); break; case "F": out.add(in.readFloat()); break; case "D": out.add(in.readDouble()); break; } } else { if (!ClassPathCache.getInstance().existsClass(clsName)) { in.resetReaderIndex(); return; } Class<?> cls = Class.forName(clsName); BinarySerializable re = (BinarySerializable) cls.newInstance(); BinaryBlob buff = new BinaryBlob(size - Integer.BYTES - classname.length); in.readBytes(buff.getBuffer()); buff.getBuffer().flip(); re.deserialize(buff); out.add(re); } }
From source file:gwlpr.protocol.NettyGWCodec.java
License:Open Source License
@Override public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> result) { ByteBuf buf = in.order(ByteOrder.LITTLE_ENDIAN); while (buf.isReadable()) { buf.markReaderIndex();/* ww w. j a va 2s. c om*/ // get the header failsafe int header = buf.readableBytes() >= 2 ? buf.readShort() : -1; // failcheck if (header == -1) { return; } // try get the message class Class<? extends GWMessage> messageClazz = getByHeader(header); // failcheck if (messageClazz == null) { buf.resetReaderIndex(); return; } // try retrieve the serialization filter NettySerializationFilter filter = GWMessageSerializationRegistry.getFilter(messageClazz); // failcheck if (filter == null) { buf.resetReaderIndex(); return; } // try create the message Message message; try { message = messageClazz.newInstance(); } catch (InstantiationException | IllegalAccessException ex) { LOGGER.error("Could not create an instance of an message.", ex); buf.resetReaderIndex(); return; } // dont forget to initialize the message message.init(ctx.channel()); // try serialize the message if (!filter.deserialize(buf, message)) { buf.resetReaderIndex(); return; } // finally add the message result.add(message); LOGGER.debug("Got: {}", message.toString()); } }
From source file:impl.underdark.transport.bluetooth.BtLink.java
License:Open Source License
private boolean formFrames(ByteBuf inputData) { final int headerSize = 4; while (true) { if (inputData.readableBytes() < headerSize) break; inputData.markReaderIndex();//from ww w. j a va 2 s . c o m int frameSize = inputData.readInt(); if (frameSize > Config.frameSizeMax) { Logger.warn("bt frame size limit reached."); return false; } if (inputData.readableBytes() < frameSize) { inputData.resetReaderIndex(); break; } final Frames.Frame frame; { final byte[] frameBody = new byte[frameSize]; inputData.readBytes(frameBody, 0, frameSize); try { frame = Frames.Frame.parseFrom(frameBody); } catch (Exception ex) { continue; } } if (this.state == State.CONNECTING) { if (frame.getKind() != Frames.Frame.Kind.HELLO) continue; this.nodeId = frame.getHello().getNodeId(); this.state = State.CONNECTED; Logger.debug("bt connected {}", BtLink.this.toString()); transport.queue.dispatch(new Runnable() { @Override public void run() { transport.linkConnected(BtLink.this, frame.getHello().getPeer()); } }); continue; } if (frame.getKind() == Frames.Frame.Kind.PAYLOAD) { if (!frame.hasPayload() || !frame.getPayload().hasPayload()) continue; final byte[] frameData = frame.getPayload().getPayload().toByteArray(); if (frameData.length == 0) continue; transport.queue.dispatch(new Runnable() { @Override public void run() { transport.linkDidReceiveFrame(BtLink.this, frameData); } }); continue; } transport.queue.dispatch(new Runnable() { @Override public void run() { transport.linkDidReceiveLinkFrame(BtLink.this, frame); } }); } // while return true; }
From source file:impl.underdark.transport.nsd.NsdLink.java
License:Open Source License
private boolean formFrames(ByteBuf inputData) { final int headerSize = 4; while (true) { if (inputData.readableBytes() < headerSize) break; inputData.markReaderIndex();//from w w w . java 2 s . co m int frameSize = inputData.readInt(); if (frameSize > Config.frameSizeMax) { Logger.warn("nsd frame size limit reached."); return false; } if (inputData.readableBytes() < frameSize) { inputData.resetReaderIndex(); break; } final Frames.Frame frame; { final byte[] frameBody = new byte[frameSize]; inputData.readBytes(frameBody, 0, frameSize); try { frame = Frames.Frame.parseFrom(frameBody); } catch (Exception ex) { continue; } } if (this.state == State.CONNECTING) { if (frame.getKind() != Frames.Frame.Kind.HELLO) continue; this.nodeId = frame.getHello().getNodeId(); this.state = State.CONNECTED; Logger.debug("nsd connected {}", NsdLink.this.toString()); server.queue.execute(new Runnable() { @Override public void run() { server.linkConnected(NsdLink.this); } }); continue; } if (frame.getKind() == Frames.Frame.Kind.PAYLOAD) { if (!frame.hasPayload() || !frame.getPayload().hasPayload()) continue; final byte[] frameData = frame.getPayload().getPayload().toByteArray(); if (frameData.length == 0) continue; server.queue.execute(new Runnable() { @Override public void run() { server.linkDidReceiveFrame(NsdLink.this, frameData); } }); continue; } if (frame.getKind() == Frames.Frame.Kind.HEARTBEAT) { continue; } /*server.queue.dispatch(new Runnable() { @Override public void run() { server.linkDidReceiveLinkFrame(NsdLink.this, frame); } });*/ } // while return true; }
From source file:info.zhoumin.dat.AbstractDoubleArrayTrie.java
License:Apache License
private boolean branchInTail(int sepNode, int c, ByteBuf suffix, V data) { /* adjust separate point in old path */ int oldTail = getTailIndex(sepNode); ByteBuf oldSuffix = tail.getSuffix(oldTail); if (oldSuffix == null) return false; byte oldByte, newByte; int s = sepNode; suffix.resetReaderIndex(); oldSuffix.resetReaderIndex();//from ww w. ja v a 2 s.c o m do { newByte = suffix.readByte(); oldByte = oldSuffix.readByte(); if (newByte != oldByte) break; int t = insertBranch(s, newByte + 1); if (TRIE_INDEX_ERROR == t) { // /* failed, undo previous insertions and return error */ // da_prune_upto (trie->da, sep_node, s); // trie_da_set_tail_index (trie->da, sep_node, old_tail); // throw new RuntimeException("error happened!"); return false; } s = t; } while (suffix.isReadable() && oldSuffix.isReadable()); int oldDA = insertBranch(s, oldByte + 1); if (TRIE_INDEX_ERROR == oldDA) { // /* failed, undo previous insertions and return error */ // da_prune_upto (trie->da, sep_node, s); // trie_da_set_tail_index (trie->da, sep_node, old_tail); // throw new RuntimeException("error happened!"); return false; } tail.setSuffix(oldTail, oldSuffix.discardReadBytes().copy()); setTailIndex(oldDA, oldTail); /* insert the new branch at the new separate point */ return branchInBranch(s, newByte + 1, suffix.discardReadBytes().copy(), data); }
From source file:info.zhoumin.dat.AbstractDoubleArrayTrie.java
License:Apache License
@Override public V put(K key, V value) { if (key == null) { throw new NullPointerException("Key cannot be null"); }/*from ww w. j av a 2s .c o m*/ int s = DOUBLE_ARRAY_ROOT; keyAnalyzer.setValue(key); while (keyAnalyzer.hasNext()) { if (daIsSeperate(s)) break; int c = (int) keyAnalyzer.next() + 1; int next = getNext(s, c); if (next < 0) { branchInBranch(s, c, keyAnalyzer.rest(), value); return value; } s = next; } /* walk through tail */ ByteBuf suffix = tail.getSuffix(getTailIndex(s)); suffix.resetReaderIndex(); ByteBuf tailBytes = keyAnalyzer.rest(); int c = (keyAnalyzer.hasNext() ? keyAnalyzer.next() : 0) + 1; while (suffix.isReadable() && tailBytes.isReadable()) { byte b = suffix.readByte(); if (b != tailBytes.readByte()) { branchInTail(s, c, tailBytes, value); return value; } } // , ? this.isDirty = true; return null; }
From source file:io.aos.netty5.socksproxy.SocksPortUnificationServerHandler.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { ChannelPipeline p = ctx.pipeline();/*www . j a v a2 s. c om*/ SocksProtocolVersion version = SocksProtocolVersion.valueOf(in.readByte()); System.out.println(version); in.resetReaderIndex(); switch (version) { case SOCKS4a: p.addLast(new Socks4CmdRequestDecoder()); p.addLast(Socks4MessageEncoder.INSTANCE); break; case SOCKS5: p.addLast(new Socks5InitRequestDecoder()); p.addLast(Socks5MessageEncoder.INSTANCE); break; case UNKNOWN: in.clear(); ctx.close(); return; } p.addLast(SocksServerHandler.INSTANCE); p.remove(this); }
From source file:io.atomix.cluster.messaging.impl.MessageDecoder.java
License:Apache License
@Override @SuppressWarnings("squid:S128") // suppress switch fall through warning protected void decode(ChannelHandlerContext context, ByteBuf buffer, List<Object> out) throws Exception { switch (currentState) { case READ_SENDER_VERSION: if (buffer.readableBytes() < SHORT_SIZE) { return; }/* w ww .j a va 2s . c om*/ version = buffer.readShort(); currentState = DecoderState.READ_SENDER_IP; case READ_SENDER_IP: if (buffer.readableBytes() < BYTE_SIZE) { return; } buffer.markReaderIndex(); int octetsLength = buffer.readByte(); if (buffer.readableBytes() < octetsLength) { buffer.resetReaderIndex(); return; } byte[] octets = new byte[octetsLength]; buffer.readBytes(octets); senderIp = InetAddress.getByAddress(octets); currentState = DecoderState.READ_SENDER_PORT; case READ_SENDER_PORT: if (buffer.readableBytes() < INT_SIZE) { return; } senderPort = buffer.readInt(); address = new Address(senderIp.getHostName(), senderPort, senderIp); currentState = DecoderState.READ_TYPE; case READ_TYPE: if (buffer.readableBytes() < BYTE_SIZE) { return; } type = InternalMessage.Type.forId(buffer.readByte()); currentState = DecoderState.READ_PREAMBLE; case READ_PREAMBLE: if (buffer.readableBytes() < INT_SIZE) { return; } preamble = buffer.readInt(); currentState = DecoderState.READ_MESSAGE_ID; case READ_MESSAGE_ID: if (buffer.readableBytes() < LONG_SIZE) { return; } messageId = buffer.readLong(); currentState = DecoderState.READ_CONTENT_LENGTH; case READ_CONTENT_LENGTH: if (buffer.readableBytes() < INT_SIZE) { return; } contentLength = buffer.readInt(); currentState = DecoderState.READ_CONTENT; case READ_CONTENT: if (buffer.readableBytes() < contentLength) { return; } if (contentLength > 0) { // TODO: Perform a sanity check on the size before allocating content = new byte[contentLength]; buffer.readBytes(content); } else { content = EMPTY_PAYLOAD; } switch (type) { case REQUEST: currentState = DecoderState.READ_SUBJECT_LENGTH; break; case REPLY: currentState = DecoderState.READ_STATUS; break; default: checkState(false, "Must not be here"); } break; default: break; } switch (type) { case REQUEST: switch (currentState) { case READ_SUBJECT_LENGTH: if (buffer.readableBytes() < SHORT_SIZE) { return; } subjectLength = buffer.readShort(); currentState = DecoderState.READ_SUBJECT; case READ_SUBJECT: if (buffer.readableBytes() < subjectLength) { return; } final String subject = readString(buffer, subjectLength, UTF_8); InternalRequest message = new InternalRequest(preamble, messageId, address, subject, content); out.add(message); currentState = DecoderState.READ_TYPE; break; default: break; } break; case REPLY: switch (currentState) { case READ_STATUS: if (buffer.readableBytes() < BYTE_SIZE) { return; } InternalReply.Status status = InternalReply.Status.forId(buffer.readByte()); InternalReply message = new InternalReply(preamble, messageId, content, status); out.add(message); currentState = DecoderState.READ_TYPE; break; default: break; } break; default: checkState(false, "Must not be here"); } }
From source file:io.awacs.protocol.binary.BinaryMessageDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { int readable = in.readableBytes(); if (readable > BinaryMessage.MAX_PACKET_SIZE) { in.skipBytes(readable);// w w w .j a v a 2 s. c o m throw new TooLongFrameException(); } //??? if (readable < 16) { return; } byte[] headerBytes = new byte[16]; in.readBytes(headerBytes, 0, 16); int bodyLength = BinaryMessage.bodyLength(headerBytes); //body??body if (in.readableBytes() < bodyLength) { in.resetReaderIndex(); return; } byte[] bodyBytes = new byte[bodyLength]; in.readBytes(bodyBytes, 0, bodyLength); // byte[] copy = new byte[16 + bodyLength]; // System.arraycopy(headerBytes, 0, copy, 0, 16); // System.arraycopy(bodyBytes, 0, copy, 16, bodyLength); Message m = BinaryMessage.parse(headerBytes, bodyBytes); in.markReaderIndex(); out.add(m); }
From source file:io.codis.nedis.handler.RedisResponseDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { in.markReaderIndex();/*from w ww . j av a 2 s .c o m*/ if (!decode(in, out, NULL_REPLY)) { in.resetReaderIndex(); } }