List of usage examples for io.netty.buffer ByteBuf readableBytes
public abstract int readableBytes();
From source file:com.ibm.crail.datanode.netty.rpc.RdmaDecoderRx.java
License:Apache License
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) { switch (state) { case WAIT_FOR_HEADER: /* in case of init and bytes not ready, we return immediately */ if (in.readableBytes() < RdmaMsgRx.CSIZE) return; /* if enough bytes are around then allocate object and decode the header */ rxMsg = new RdmaMsgRx(); rxMsg.decodeHeader(in);/* w w w. ja v a 2 s. c o m*/ if (rxMsg.type() == MessageTypes.READ_REQ || rxMsg.type() == MessageTypes.WRITE_RESP) { out.add(rxMsg); state = DecoderState.WAIT_FOR_HEADER; rxMsg = null; } else { state = DecoderState.WAIT_FOR_PAYLOAD; } break; case WAIT_FOR_PAYLOAD: /* now we check for length when it exceed the expected length */ if (rxMsg.opLength() > in.readableBytes()) return; rxMsg.referenceRxPayloadAndRetain(in); out.add(rxMsg); state = DecoderState.WAIT_FOR_HEADER; rxMsg = null; break; } }
From source file:com.ibm.crail.namenode.rpc.netty.common.RequestDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception { /* here we have to do the same exercise */ if (NettyRequest.CSIZE > byteBuf.readableBytes()) { return;// ww w . j a va2 s . c o m } /* otherwise decode */ NettyRequest newReq = new NettyRequest(); newReq.update(byteBuf); list.add(newReq); }
From source file:com.ibm.crail.namenode.rpc.netty.common.ResponseDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception { if (byteBuf.readableBytes() < NettyResponse.CSIZE) { return;/*from ww w . j av a 2s.c om*/ } long cookie = byteBuf.readLong(); /* allocate a new response here and then proceed */ NettyResponse resp = this.group.retriveAndRemove(cookie); resp.update(cookie, byteBuf); resp.getNettyCommonFuture().markDone(); }
From source file:com.ibm.mqlight.api.security.PemFile.java
License:Apache License
/** * Obtains the private key data as a byte array from the PEM file. * <p>/*from ww w . j av a2s.com*/ * Within the PEM file the private key data is base 64 encoded. This method will decode the data for the returned private key * data. * <p> * Note that for an encrypted private key the data will remain encrypted. * * @return The private key data. * @throws KeyException If a private key cannot be found in the PEM file. * @throws IOException If the PEM file cannot be read for any reason. */ public byte[] getPrivateKeyBytes() throws KeyException, IOException { final String methodName = "getPrivateKeyBytes"; logger.entry(this, methodName); final String fileData = getPemFileData(); Matcher m = KEY_PATTERN.matcher(fileData); final byte[] keyBytes; final String base64KeyDataStr; if (m.find()) { base64KeyDataStr = m.group(1); } else { m = ENCRYPTED_KEY_PATTERN.matcher(fileData); if (m.find()) { base64KeyDataStr = m.group(1); } else { final KeyException exception = new KeyException("Private key not found in PEM file: " + pemFile); logger.throwing(this, methodName, exception); throw exception; } } final ByteBuf base64KeyData = Unpooled.copiedBuffer(base64KeyDataStr, Charset.forName("US-ASCII")); final ByteBuf keyData = Base64.decode(base64KeyData); base64KeyData.release(); keyBytes = new byte[keyData.readableBytes()]; keyData.readBytes(keyBytes).release(); logger.exit(this, methodName, keyBytes); return keyBytes; }
From source file:com.indigo.game.common.network.websocket.WebSocketIndexPageHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) { // Handle a bad request. if (!req.decoderResult().isSuccess()) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return;//w w w . j a v a 2 s . com } // Allow only GET methods. if (req.method() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; } // Send the index page if ("/".equals(req.uri()) || "/index.html".equals(req.uri())) { String webSocketLocation = getWebSocketLocation(ctx.pipeline(), req, websocketPath); ByteBuf content = WebSocketServerIndexPage.getContent(webSocketLocation); FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content); res.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8"); HttpUtil.setContentLength(res, content.readableBytes()); sendHttpResponse(ctx, req, res); } else { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND)); } }
From source file:com.informatica.surf.sources.http.HttpListener.java
License:Apache License
public byte[] nextMessage() throws InterruptedException { _logger.debug("Checking queued messages"); ByteBuf buf = _messageQueue.take(); byte b[] = new byte[buf.readableBytes()]; _logger.debug("Readable bytes = {}", b.length); buf.readBytes(b);/*from w w w .j a va 2s.c o m*/ buf.release(); return b; }
From source file:com.intuit.karate.netty.FeatureServerHandler.java
License:Open Source License
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) { long startTime = System.currentTimeMillis(); backend.getContext().logger.debug("handling method: {}, uri: {}", msg.method(), msg.uri()); FullHttpResponse nettyResponse;//ww w .j ava 2 s . c om if (msg.uri().startsWith(STOP_URI)) { backend.getContext().logger.info("stop uri invoked, shutting down"); ByteBuf responseBuf = Unpooled.copiedBuffer("stopped", CharsetUtil.UTF_8); nettyResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, responseBuf); stopFunction.run(); } else { StringUtils.Pair url = HttpUtils.parseUriIntoUrlBaseAndPath(msg.uri()); HttpRequest request = new HttpRequest(); if (url.left == null) { String requestScheme = ssl ? "https" : "http"; String host = msg.headers().get(HttpUtils.HEADER_HOST); request.setUrlBase(requestScheme + "://" + host); } else { request.setUrlBase(url.left); } request.setUri(url.right); request.setMethod(msg.method().name()); msg.headers().forEach(h -> request.addHeader(h.getKey(), h.getValue())); QueryStringDecoder decoder = new QueryStringDecoder(url.right); decoder.parameters().forEach((k, v) -> request.putParam(k, v)); HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); if (content.isReadable()) { byte[] bytes = new byte[content.readableBytes()]; content.readBytes(bytes); request.setBody(bytes); } HttpResponse response = backend.buildResponse(request, startTime); HttpResponseStatus httpResponseStatus = HttpResponseStatus.valueOf(response.getStatus()); byte[] responseBody = response.getBody(); if (responseBody != null) { ByteBuf responseBuf = Unpooled.copiedBuffer(responseBody); nettyResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, httpResponseStatus, responseBuf); } else { nettyResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, httpResponseStatus); } MultiValuedMap karateHeaders = response.getHeaders(); if (karateHeaders != null) { HttpHeaders nettyHeaders = nettyResponse.headers(); karateHeaders.forEach((k, v) -> nettyHeaders.add(k, v)); } } ctx.write(nettyResponse); ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); }
From source file:com.intuit.karate.netty.WebSocketClientHandler.java
License:Open Source License
@Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { Channel ch = ctx.channel();//from ww w. j a va2s .c o m if (!handshaker.isHandshakeComplete()) { try { handshaker.finishHandshake(ch, (FullHttpResponse) msg); logger.debug("websocket client connected"); handshakeFuture.setSuccess(); } catch (WebSocketHandshakeException e) { logger.debug("websocket client connect failed: {}", e.getMessage()); handshakeFuture.setFailure(e); } return; } if (msg instanceof FullHttpResponse) { FullHttpResponse response = (FullHttpResponse) msg; throw new IllegalStateException("unexpected FullHttpResponse (getStatus=" + response.status() + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')'); } WebSocketFrame frame = (WebSocketFrame) msg; if (frame instanceof TextWebSocketFrame) { if (logger.isTraceEnabled()) { logger.trace("websocket received text"); } TextWebSocketFrame textFrame = (TextWebSocketFrame) frame; listener.onMessage(textFrame.text()); } else if (frame instanceof PongWebSocketFrame) { if (logger.isTraceEnabled()) { logger.trace("websocket received pong"); } } else if (frame instanceof CloseWebSocketFrame) { logger.debug("websocket closing"); ch.close(); } else if (frame instanceof BinaryWebSocketFrame) { logger.debug("websocket received binary"); BinaryWebSocketFrame binaryFrame = (BinaryWebSocketFrame) frame; ByteBuf buf = binaryFrame.content(); byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); listener.onMessage(bytes); } }
From source file:com.irh.material.basics.netty.chapter14_1.codec.NettyMessageEncoder.java
License:Apache License
@Override protected void encode(ChannelHandlerContext ctx, NettyMessage msg, ByteBuf sendBuf) throws Exception { if (msg == null || msg.getHeader() == null) { throw new Exception("The encode message is null"); }// w w w. ja va2 s .co m sendBuf.writeInt((msg.getHeader().getCrcCode())); sendBuf.writeInt((msg.getHeader().getLength())); sendBuf.writeLong((msg.getHeader().getSessionID())); sendBuf.writeByte((msg.getHeader().getType())); sendBuf.writeByte((msg.getHeader().getPriority())); sendBuf.writeInt((msg.getHeader().getAttachment().size())); String key = null; byte[] keyArray = null; Object value = null; for (Map.Entry<String, Object> param : msg.getHeader().getAttachment().entrySet()) { key = param.getKey(); keyArray = key.getBytes("UTF-8"); sendBuf.writeInt(keyArray.length); sendBuf.writeBytes(keyArray); value = param.getValue(); marshallingEncoder.encode(value, sendBuf); } key = null; keyArray = null; value = null; if (msg.getBody() != null) { marshallingEncoder.encode(msg.getBody(), sendBuf); } else sendBuf.writeInt(0); sendBuf.setInt(4, sendBuf.readableBytes() - 8); }
From source file:com.jamierf.jsonrpc.util.JsonObjectDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (state == ST_CORRUPTED) { in.skipBytes(in.readableBytes()); return;/*from w w w. j a v a 2 s .c om*/ } // index of next byte to process. int idx = this.idx; int wrtIdx = in.writerIndex(); if (wrtIdx > maxObjectLength) { // buffer size exceeded maxObjectLength; discarding the complete buffer. in.skipBytes(in.readableBytes()); reset(); throw new TooLongFrameException( "object length exceeds " + maxObjectLength + ": " + wrtIdx + " bytes discarded"); } for (/* use current idx */; idx < wrtIdx; idx++) { byte c = in.getByte(idx); if (state == ST_DECODING_NORMAL) { decodeByte(c, in, idx); // All opening braces/brackets have been closed. That's enough to conclude // that the JSON object/array is complete. if (openBraces == 0) { ByteBuf json = extractObject(ctx, in, in.readerIndex(), idx + 1 - in.readerIndex()); if (json != null) { out.add(json); } // The JSON object/array was extracted => discard the bytes from // the input buffer. in.readerIndex(idx + 1); // Reset the object state to get ready for the next JSON object/text // coming along the byte stream. reset(); } } else if (state == ST_DECODING_ARRAY_STREAM) { decodeByte(c, in, idx); if (!insideString && (openBraces == 1 && c == ',' || openBraces == 0 && c == ']')) { // skip leading spaces. No range check is needed and the loop will terminate // because the byte at position idx is not a whitespace. for (int i = in.readerIndex(); Character.isWhitespace(in.getByte(i)); i++) { in.skipBytes(1); } // skip trailing spaces. int idxNoSpaces = idx - 1; while (idxNoSpaces >= in.readerIndex() && Character.isWhitespace(in.getByte(idxNoSpaces))) { idxNoSpaces--; } ByteBuf json = extractObject(ctx, in, in.readerIndex(), idxNoSpaces + 1 - in.readerIndex()); if (json != null) { out.add(json); } in.readerIndex(idx + 1); if (c == ']') { reset(); } } // JSON object/array detected. Accumulate bytes until all braces/brackets are closed. } else if (c == '{' || c == '[') { initDecoding(c); if (state == ST_DECODING_ARRAY_STREAM) { // Discard the array bracket in.skipBytes(1); } // Discard leading spaces in front of a JSON object/array. } else if (Character.isWhitespace(c)) { in.skipBytes(1); } else { state = ST_CORRUPTED; throw new CorruptedFrameException( "invalid JSON received at byte position " + idx + ": " + ByteBufUtil.hexDump(in)); } } if (in.readableBytes() == 0) { this.idx = 0; } else { this.idx = idx; } }