List of usage examples for io.netty.buffer ByteBuf isReadable
public abstract boolean isReadable();
From source file:com.whizzosoftware.foscam.camera.protocol.OrderDecoder.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> list) throws Exception { Byte b;/*from w w w .j a v a 2 s . c om*/ if (buf.isReadable()) { do { b = buf.readByte(); } while (b != 'M' && buf.isReadable()); if (buf.readableBytes() > 0) { logger.trace("Found possible start of order"); b = buf.readByte(); if (b == 'O' && buf.isReadable()) { b = buf.readByte(); if (b == '_' && buf.isReadable()) { b = buf.readByte(); if (b == 'I' && buf.isReadable()) { Integer operationCode = popINT16(buf); if (operationCode != null) { if (popBytes(buf, 9)) { Integer length = popINT32(buf); if (length != null && popBytes(buf, 4)) { if (buf.readableBytes() >= length) { byte[] text = new byte[length]; buf.readBytes(text); switch (operationCode) { case 1: try { list.add(new SearchResponse(text, 0, length)); } catch (UnknownHostException e) { logger.error("Error processing search response", e); } break; } } } } } } } } } } }
From source file:com.whizzosoftware.wzwave.codec.ZWaveFrameDecoder.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (logger.isDebugEnabled()) { logger.debug("RCVD: {}", ByteUtil.createString(in)); }/*from w ww .j a va 2s .co m*/ ByteBuf data; // if there was data left from the last decode call, create a composite ByteBuf that contains both // previous and new data if (previousBuf != null) { CompositeByteBuf cbuf = Unpooled.compositeBuffer(2); cbuf.addComponent(previousBuf.copy()); cbuf.addComponent(in); cbuf.writerIndex(previousBuf.readableBytes() + in.readableBytes()); data = cbuf; // release the data from the previous decode call previousBuf.release(); previousBuf = null; } else { data = in; } while (data.isReadable()) { // check for single ACK/NAK/CAN if (data.readableBytes() == 1 && isSingleByteFrame(data, data.readerIndex())) { out.add(createSingleByteFrame(data)); } else { boolean foundFrame = false; // search for a valid frame in the data for (int searchStartIx = data.readerIndex(); searchStartIx < data.readerIndex() + data.readableBytes(); searchStartIx++) { if (data.getByte(searchStartIx) == DataFrame.START_OF_FRAME) { int frameEndIx = scanForFrame(data, searchStartIx); if (frameEndIx > 0) { if (searchStartIx > data.readerIndex() && isSingleByteFrame(data, searchStartIx - 1)) { data.readerIndex(searchStartIx - 1); out.add(createSingleByteFrame(data)); } else if (searchStartIx > data.readerIndex()) { data.readerIndex(searchStartIx); } DataFrame df = createDataFrame(data); if (df != null) { out.add(df); data.readByte(); // discard checksum foundFrame = true; } else { logger.debug("Unable to determine frame type"); } } } } if (!foundFrame) { previousBuf = data.copy(); break; } } } // make sure we read from the input ByteBuf so Netty doesn't throw an exception in.readBytes(in.readableBytes()); logger.trace("Done processing received data: {}", out); }
From source file:com.xx_dev.apn.proxy.utils.ByteBufLogUtil.java
License:Apache License
public static String toLogString(ByteBuf byteBuf) { StringBuilder sb = new StringBuilder(); byteBuf.readerIndex(0);/* ww w .j ava2s .co m*/ while (byteBuf.isReadable()) { sb.append(String.valueOf((int) byteBuf.readByte())).append(","); } byteBuf.readerIndex(0); return sb.toString(); }
From source file:com.zhuowenfeng.devtool.hs_server.handler.HttpServiceHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) { HSServerContext hsContext = new HSServerContext(); if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; hsContext.setRequest(request);/* w w w . jav a2 s. c o m*/ String uri = request.getUri(); hsContext.setRequestUri(uri); if (is100ContinueExpected(request)) { send100Continue(ctx); } QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri()); Map<String, List<String>> params = queryStringDecoder.parameters(); JSONObject pathVariables = new JSONObject(); if (!params.isEmpty()) { for (Entry<String, List<String>> p : params.entrySet()) { String key = p.getKey(); List<String> vals = p.getValue(); for (String val : vals) { pathVariables.put(key, val); } } } hsContext.setPathVariables(pathVariables); } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); JSONObject requestContent = new JSONObject(); if (content.isReadable()) { requestContent = JSONObject.fromObject(content.toString(CharsetUtil.UTF_8)); } hsContext.setRequestContent(requestContent); if (msg instanceof LastHttpContent) { LastHttpContent trailer = (LastHttpContent) msg; JSONObject result = HttpServiceDispatcher.dispatch(hsContext); writeResponse(trailer, ctx, result); } } }
From source file:com.zxcc.socket.protobuf.ProtobufVarint32FrameDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { in.markReaderIndex();//from ww w . j a v a2 s . c o m int bufLenght = 0; if (!in.isReadable()) { in.resetReaderIndex(); return; } if (in.readableBytes() < 4) { in.resetReaderIndex(); return; } bufLenght = in.readInt(); if (bufLenght < 0) { throw new CorruptedFrameException("negative length: " + bufLenght); } if (in.readableBytes() < bufLenght) { in.resetReaderIndex(); return; } else { out.add(in.readBytes(bufLenght)); return; } }
From source file:controlspy3.SpyAsServer.java
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println("\nrecibio algo Servidor"); ByteBuf in = (ByteBuf) msg; ArrayList in2 = new ArrayList(); String messageServer = ""; try {//from w w w . j a v a2s .c o m while (in.isReadable()) { // (1) byte rxByte = in.readByte(); in2.add(rxByte); } ux1 = new UnixTime1(in2); System.out.println("A"); SpyAsServer.channelSend(); messageServer = ""; for (int i = 0; i < in2.size(); i++) { byte rxByte = (byte) in2.get(i); messageServer += String.valueOf(Character.toChars(rxByte)); } } catch (Exception e) { System.out.println("Entro al ERROR RARO"); } finally { in.release(); // (2) } }
From source file:de.dfki.kiara.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().nioBuffer()); if (logger.isDebugEnabled()) { logger.debug("RECEIVED REQUEST WITH CONTENT {}", Util.bufferToString(transportMessage.getPayload())); }/*from w ww . ja v a 2s .c o m*/ synchronized (listeners) { if (!listeners.isEmpty()) { for (TransportMessageListener listener : listeners) { listener.onMessage(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:de.ocarthon.core.network.HttpClient.java
License:Apache License
public synchronized String postRequest(String query, List<Map.Entry<String, String>> postParameters, String filePostName, String fileName, ByteBuf fileData, String mime) { if (bootstrap == null) { setupBootstrap();//from ww w.ja v a2s . c om } if (channel == null || forceReconnect) { ChannelFuture cf = bootstrap.connect(host, port); forceReconnect = false; cf.awaitUninterruptibly(); channel = cf.channel(); channel.pipeline().addLast("handler", new SimpleChannelInboundHandler<HttpObject>() { @Override protected void messageReceived(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpResponse) { HttpResponse response = ((HttpResponse) msg); String connection = (String) response.headers().get(HttpHeaderNames.CONNECTION); if (connection != null && connection.equalsIgnoreCase(HttpHeaderValues.CLOSE.toString())) forceReconnect = true; } if (msg instanceof HttpContent) { HttpContent chunk = (HttpContent) msg; String message = chunk.content().toString(CharsetUtil.UTF_8); if (!message.isEmpty()) { result[0] = message; synchronized (result) { result.notify(); } } } } }); } boolean isFileAttached = fileData != null && fileData.isReadable(); HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, scheme + "://" + host + ":" + port + "/" + query); HttpPostRequestEncoder bodyReqEncoder; try { bodyReqEncoder = new HttpPostRequestEncoder(httpDataFactory, request, isFileAttached); for (Map.Entry<String, String> entry : postParameters) { bodyReqEncoder.addBodyAttribute(entry.getKey(), entry.getValue()); } if (isFileAttached) { if (mime == null) mime = "application/octet-stream"; MixedFileUpload mfu = new MixedFileUpload(filePostName, fileName, mime, "binary", null, fileData.capacity(), DefaultHttpDataFactory.MINSIZE); mfu.addContent(fileData, true); bodyReqEncoder.addBodyHttpData(mfu); } HttpHeaders headers = request.headers(); headers.set(HttpHeaderNames.HOST, host); headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); headers.set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP); headers.set(HttpHeaderNames.USER_AGENT, "OcarthonCore HttpClient"); request = bodyReqEncoder.finalizeRequest(); } catch (Exception e) { throw new NullPointerException("key or value is empty or null"); } channel.write(request); if (bodyReqEncoder.isChunked()) { channel.write(bodyReqEncoder); } channel.flush(); synchronized (result) { try { result.wait(); } catch (InterruptedException e) { return null; } } return result[0]; }
From source file:divconq.ctp.net.CtpHandler.java
License:Open Source License
@Override public void read() { this.readLock.lock(); if (serverMode) System.out.println("Start Server requested read!"); this.readRequested = false; // meaning read is covered until further notice try {//from ww w . ja v a 2 s . com ByteBuf rem = this.remnant; //CtpHandler.this.debug("checking remnant: " + rem); // if there are any unread bytes from the last read, check to see if we can collect a command if (rem != null) { //CtpHandler.this.debug("checking bytes: " + rem.readableBytes()); //System.out.println("Remnant ref cnt 1: " + rem.refCnt() + " for server: " + CtpHandler.this.serverMode); boolean ready = false; try { ready = this.adapter.decode(rem); } catch (Exception x) { // TODO error and close!! System.out.println("Error decoding message: " + x); return; } //System.out.println("Remnant ref cnt 2: " + rem.refCnt()); // if there are any unread bytes here we need to store them and combine with the next read if (!rem.isReadable()) { this.remnant = null; rem.release(); } //System.out.println("Remnant ref cnt 3: " + rem.refCnt()); if (!ready) { this.readRequested = true; this.chan.read(); } else this.adapter.handleCommand(); } else { this.readRequested = true; this.chan.read(); } if (serverMode) System.out.println("End Server requested read!"); } finally { this.readLock.unlock(); } }
From source file:divconq.ctp.net.CtpHandler.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { CtpHandler.this.readLock.lock(); try {/* ww w. ja va 2 s . c om*/ ByteBuf buf = (ByteBuf) msg; if (serverMode) System.out.println("Server got network read 1: " + buf.readableBytes()); ByteBuf rem = this.remnant; // if there are any unread bytes from the last read, combine with this read this.remnant = buf; // TODO there are maybe better ways to do this - a queue of buffers? if (rem != null) { if (rem.isReadable()) { this.remnant = Hub.instance.getBufferAllocator() .heapBuffer(rem.readableBytes() + buf.readableBytes()); this.remnant.writeBytes(rem); this.remnant.writeBytes(buf); buf.release(); } rem.release(); } if (serverMode) System.out.println("Server got network read 2: " + this.remnant.readableBytes()); if (!this.readRequested) return; if (this.remnant.readableBytes() > 256 * 1024) System.out.println( "CTP Buffer getting too large - possible issue!!!! " + this.remnant.readableBytes()); // read with the updated buffer this.read(); } finally { CtpHandler.this.readLock.unlock(); } }