List of usage examples for io.netty.buffer ByteBuf isReadable
public abstract boolean isReadable();
From source file:org.code_house.ebus.netty.codec.OutboundEBusHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // receive/*from w ww. j av a 2 s .co m*/ if (msg instanceof MasterHeader) { this.masterHeader = (MasterHeader) msg; } else if (msg instanceof MasterData) { this.masterData = (MasterData) msg; } if (msg instanceof ByteBuf) { ByteBuf buffer = (ByteBuf) msg; if (writeInProgress && buffer.capacity() == 1) { byte aByte = buffer.getByte(0); if (device.getMaster().getAddress() == aByte) { // we got access to bus, lets try to flush something accessGranted = true; flush(ctx); return; } } writeInProgress = false; if (buffer.isReadable()) { byte lastByte = buffer.getByte(buffer.readerIndex()); if (lastByte == Constants.SYN) { // we received SYN symbol, try to write own address writeInProgress = true; ctx.writeAndFlush(Unpooled.wrappedBuffer(new byte[] { device.getMaster().getAddress() })); // force writing master address to bus } } } ctx.fireChannelRead(msg); }
From source file:org.diorite.impl.connection.packets.PacketSizer.java
License:Open Source License
@Override protected void decode(final ChannelHandlerContext context, final ByteBuf byteBuf, final List<Object> objects) { byteBuf.markReaderIndex();/*from w w w .ja va 2 s . c o m*/ final byte[] arrayOfByte = new byte[3]; for (int i = 0; i < arrayOfByte.length; i++) { if (!byteBuf.isReadable()) { byteBuf.resetReaderIndex(); return; } arrayOfByte[i] = byteBuf.readByte(); if (arrayOfByte[i] >= 0) { final PacketDataSerializer dataSerializer = new PacketDataSerializer( Unpooled.wrappedBuffer(arrayOfByte)); try { final int size = dataSerializer.readVarInt(); if (byteBuf.readableBytes() < size) { byteBuf.resetReaderIndex(); return; } objects.add(byteBuf.readBytes(size)); return; } finally { dataSerializer.release(); } } } throw new CorruptedFrameException("length wider than 21-bit"); }
From source file:org.ebayopensource.scc.cache.BaseResponseSerializer.java
License:Apache License
protected void copyBody(CacheResponse cacheResp, ByteBuf... chunks) { int totalSize = 0; for (ByteBuf c : chunks) { if (c.isReadable()) { totalSize += c.readableBytes(); }/*from ww w .ja v a 2 s . com*/ } ByteBuffer nioBuffer = ByteBuffer.allocate(totalSize); for (ByteBuf c : chunks) { if (c.isReadable()) { c.getBytes(c.readerIndex(), nioBuffer); } } if (nioBuffer.hasArray()) { cacheResp.setContent(nioBuffer.array()); } // reset Content-Length List<CacheEntry<String, String>> headers = cacheResp.getHeaders(); for (Iterator<CacheEntry<String, String>> it = headers.iterator(); it.hasNext();) { CacheEntry<String, String> header = it.next(); if (HttpHeaders.Names.CONTENT_LENGTH.equals(header.getKey())) { it.remove(); } } headers.add(new CacheEntry<String, String>(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(totalSize))); }
From source file:org.eclipse.neoscada.protocol.iec60870.apci.MessageChannel.java
License:Open Source License
private ByteBuf encode(final ChannelHandlerContext ctx, final Object msg) { ByteBuf buf = ctx.alloc().buffer(255); try {/* ww w . ja v a2 s .c om*/ this.manager.encodeMessage(msg, buf); if (buf.isReadable()) { // copy away the reference so it does not get released final ByteBuf buf2 = buf; buf = null; return buf2; } } finally { ReferenceCountUtil.release(buf); } return null; }
From source file:org.eclipse.scada.protocol.syslog.SyslogCodec.java
License:Open Source License
private String[] decodeProcess(final ByteBuf msg) { // split by colon final int spaceIndex = msg.bytesBefore(COLON); if (spaceIndex < 0) { throw new CodecException("Unable to find process name"); }/*ww w . ja v a 2s. c om*/ final String process = msg.readSlice(spaceIndex).toString(StandardCharsets.US_ASCII); msg.skipBytes(1); // COLON if (msg.isReadable()) { msg.skipBytes(1); // SPACE } final Matcher m = PROCESS_PATTERN.matcher(process); if (m.matches()) { return new String[] { m.group(1), m.group(2) }; } return new String[] { process }; }
From source file:org.fengbaoxp.netty.official.DiscardServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf in = (ByteBuf) msg; try {/*from ww w . j a v a 2 s . c o m*/ StringBuilder smsg = new StringBuilder(); while (in.isReadable()) { smsg.append((char) in.readByte()); } logger.info(smsg.toString()); } finally { ReferenceCountUtil.release(msg); } }
From source file:org.fengbaoxp.netty.official.EchoServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf in = (ByteBuf) msg; StringBuilder smsg = new StringBuilder(); while (in.isReadable()) { smsg.append((char) in.readByte()); }/*from w w w .ja v a 2 s . c o m*/ logger.info(smsg.toString()); final ByteBuf out = ctx.alloc().buffer(); out.writeBytes(smsg.toString().getBytes()); ctx.write(out); ctx.flush(); }
From source file:org.fiware.kiara.transport.http.HttpHandler.java
License:Open Source License
@Override protected void channelRead0(final ChannelHandlerContext ctx, Object msg) throws Exception { logger.debug("Handler: {} / Channel: {}", this, ctx.channel()); if (mode == Mode.SERVER) { if (msg instanceof FullHttpRequest) { final FullHttpRequest request = (FullHttpRequest) msg; HttpRequestMessage transportMessage = new HttpRequestMessage(this, request); transportMessage.setPayload(request.content().copy().nioBuffer()); if (logger.isDebugEnabled()) { logger.debug("RECEIVED CONTENT {}", HexDump.dumpHexString(transportMessage.getPayload())); //logger.debug("RECEIVED REQUEST WITH CONTENT {}", Util.bufferToString(transportMessage.getPayload())); }/*www .j a va 2 s. co m*/ notifyListeners(transportMessage); boolean keepAlive = HttpHeaders.isKeepAlive(request); } } else { // CLIENT if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; headers = response.headers(); //if (!response.headers().isEmpty()) { // contentType = response.headers().get("Content-Type"); //} } if (msg instanceof HttpContent) { HttpContent content = (HttpContent) msg; ByteBuf buf = content.content(); if (buf.isReadable()) { if (buf.hasArray()) { bout.write(buf.array(), buf.readerIndex(), buf.readableBytes()); } else { byte[] bytes = new byte[buf.readableBytes()]; buf.getBytes(buf.readerIndex(), bytes); bout.write(bytes); } } if (content instanceof LastHttpContent) { //ctx.close(); bout.flush(); HttpResponseMessage response = new HttpResponseMessage(this, headers); response.setPayload(ByteBuffer.wrap(bout.toByteArray(), 0, bout.size())); onResponse(response); bout.reset(); } } } }
From source file:org.freeswitch.esl.client.transport.message.EslFrameDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception { State state = state();//from w ww .ja v a 2s . c o m log.trace("decode() : state [{}]", state); switch (state) { case READ_HEADER: if (currentMessage == null) { currentMessage = new EslMessage(); } /* * read '\n' terminated lines until reach a single '\n' */ boolean reachedDoubleLF = false; while (!reachedDoubleLF) { // this will read or fail String headerLine = readToLineFeedOrFail(buffer, maxHeaderSize); log.debug("read header line [{}]", headerLine); if (!headerLine.isEmpty()) { // split the header line String[] headerParts = HeaderParser.splitHeader(headerLine); Name headerName = Name.fromLiteral(headerParts[0]); if (headerName == null) { if (treatUnknownHeadersAsBody) { // cache this 'header' as a body line <-- useful for Outbound client mode currentMessage.addBodyLine(headerLine); } else { throw new IllegalStateException("Unhandled ESL header [" + headerParts[0] + ']'); } } currentMessage.addHeader(headerName, headerParts[1]); } else { reachedDoubleLF = true; } // do not read in this line again checkpoint(); } // have read all headers - check for content-length if (currentMessage.hasContentLength()) { checkpoint(State.READ_BODY); log.debug("have content-length, decoding body .."); // force the next section break; } else { // end of message checkpoint(State.READ_HEADER); // send message upstream EslMessage decodedMessage = currentMessage; currentMessage = null; out.add(decodedMessage); break; } case READ_BODY: /* * read the content-length specified */ int contentLength = currentMessage.getContentLength(); ByteBuf bodyBytes = buffer.readBytes(contentLength); log.debug("read [{}] body bytes", bodyBytes.writerIndex()); // most bodies are line based, so split on LF while (bodyBytes.isReadable()) { String bodyLine = readLine(bodyBytes, contentLength); log.debug("read body line [{}]", bodyLine); currentMessage.addBodyLine(bodyLine); } // end of message checkpoint(State.READ_HEADER); // send message upstream EslMessage decodedMessage = currentMessage; currentMessage = null; out.add(decodedMessage); break; default: throw new Error("Illegal state: [" + state + ']'); } }
From source file:org.freeswitch.esl.client.transport.message.EslFrameDecoder.java
License:Apache License
private String readLine(ByteBuf buffer, int maxLineLength) throws TooLongFrameException { StringBuilder sb = new StringBuilder(64); while (buffer.isReadable()) { // this read should always succeed byte nextByte = buffer.readByte(); if (nextByte == LF) { return sb.toString(); } else {//from www .j av a2s. c om // Abort decoding if the decoded line is too large. if (sb.length() >= maxLineLength) { throw new TooLongFrameException("ESL message line is longer than " + maxLineLength + " bytes."); } sb.append((char) nextByte); } } return sb.toString(); }