List of usage examples for io.netty.buffer ByteBuf readerIndex
public abstract int readerIndex();
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();/*from w ww. j a v a 2s .c o 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.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);// w w w.j a v a 2 s . com out.writeBytes(msg, msg.readerIndex(), bodyLen); }
From source file:com.chiorichan.factory.FileInterpreter.java
License:Mozilla Public License
public final void interpretParamsFromFile(File file) throws IOException { if (file == null) throw new FileNotFoundException("File path was null"); FileInputStream is = null;/* w w w . j a v a 2s . c o m*/ try { cachedFile = file; annotations.put("file", file.getAbsolutePath()); if (file.isDirectory()) annotations.put("shell", "embedded"); else { if (!annotations.containsKey("shell") || annotations.get("shell") == null) { String shell = determineShellFromName(file.getName()); if (shell != null && !shell.isEmpty()) annotations.put("shell", shell); } is = new FileInputStream(file); ByteBuf buf = Unpooled.wrappedBuffer(IOUtils.toByteArray(is)); boolean beginContent = false; int lastInx; int lineCnt = 0; data = Unpooled.buffer(); do { lastInx = buf.readerIndex(); String l = readLine(buf); if (l == null) break; if (l.trim().startsWith("@")) try { lineCnt++; /* Only solution I could think of for CSS files since they use @annotations too, so we share them. */ if (ContentTypes.getContentType(file).equalsIgnoreCase("text/css")) data.writeBytes((l + "\n").getBytes()); /* Only solution I could think of for CSS files since they use @annotations too, so we share them. */ String key; String val = ""; if (l.contains(" ")) { key = l.trim().substring(1, l.trim().indexOf(" ")); val = l.trim().substring(l.trim().indexOf(" ") + 1); } else key = l; if (val.endsWith(";")) val = val.substring(0, val.length() - 1); if (val.startsWith("'") && val.endsWith("'")) val = val.substring(1, val.length() - 1); annotations.put(key.toLowerCase(), val); Log.get().finer("Setting param '" + key + "' to '" + val + "'"); if (key.equals("encoding")) if (Charset.isSupported(val)) setEncoding(Charsets.toCharset(val)); else Log.get() .severe("The file '" + file.getAbsolutePath() + "' requested encoding '" + val + "' but it's not supported by the JVM!"); } catch (NullPointerException | ArrayIndexOutOfBoundsException e) { } else if (l.trim().isEmpty()) lineCnt++; // Continue reading, this line is empty. else { // We encountered the beginning of the file content. beginContent = true; buf.readerIndex(lastInx); // This rewinds the buffer to the last reader index } } while (!beginContent); data.writeBytes(Strings.repeat('\n', lineCnt).getBytes()); data.writeBytes(buf); } } finally { if (is != null) is.close(); } }
From source file:com.chiorichan.factory.postprocessors.ImagePostProcessor.java
License:Mozilla Public License
@Override public ByteBuf process(EvalMetaData meta, ByteBuf buf) throws Exception { float x = 0;//from w w w.j av a 2 s. c o m float y = 0; if (meta.params != null) { if (meta.params.get("serverSideOptions") != null) { String[] params = meta.params.get("serverSideOptions").trim().split("_"); for (String p : params) { if (p.toLowerCase().startsWith("width") && p.length() > 1) x = Integer.parseInt(p.substring(5)); else if ((p.toLowerCase().startsWith("x") || p.toLowerCase().startsWith("w")) && p.length() > 1) x = Integer.parseInt(p.substring(1)); else if (p.toLowerCase().startsWith("height") && p.length() > 1) y = Integer.parseInt(p.substring(6)); else if ((p.toLowerCase().startsWith("y") || p.toLowerCase().startsWith("h")) && p.length() > 1) y = Integer.parseInt(p.substring(1)); else if (p.toLowerCase().equals("thumb")) { x = 150; y = 0; break; } } } if (meta.params.get("width") != null) x = Integer.parseInt(meta.params.get("width")); if (meta.params.get("height") != null) y = Integer.parseInt(meta.params.get("height")); if (meta.params.get("w") != null) x = Integer.parseInt(meta.params.get("w")); if (meta.params.get("h") != null) y = Integer.parseInt(meta.params.get("h")); if (meta.params.get("thumb") != null) { x = 150; y = 0; } } // Tests if our Post Processor can process the current image. List<String> readerFormats = Arrays.asList(ImageIO.getReaderFormatNames()); List<String> writerFormats = Arrays.asList(ImageIO.getWriterFormatNames()); if (meta.contentType != null && !readerFormats.contains(meta.contentType.split("/")[1].toLowerCase())) return null; try { int inx = buf.readerIndex(); BufferedImage img = ImageIO.read(new ByteBufInputStream(buf)); buf.readerIndex(inx); if (img != null) { float w = img.getWidth(); float h = img.getHeight(); float w1 = w; float h1 = h; if (x < 1 && y < 1) { x = w; y = h; } else if (x > 0 && y < 1) { w1 = x; h1 = x * (h / w); } else if (y > 0 && x < 1) { w1 = y * (w / h); h1 = y; } else if (x > 0 && y > 0) { w1 = x; h1 = y; } if (w1 < 1 || h1 < 1 || (w1 == w && h1 == h)) return null; Image image = img.getScaledInstance(Math.round(w1), Math.round(h1), Loader.getConfig().getBoolean("advanced.processors.useFastGraphics", true) ? Image.SCALE_FAST : Image.SCALE_SMOOTH); BufferedImage rtn = new BufferedImage(Math.round(w1), Math.round(h1), img.getType()); Graphics2D graphics = rtn.createGraphics(); graphics.drawImage(image, 0, 0, null); graphics.dispose(); Loader.getLogger().info(ConsoleColor.GRAY + "Resized image from " + Math.round(w) + "px by " + Math.round(h) + "px to " + Math.round(w1) + "px by " + Math.round(h1) + "px"); if (rtn != null) { ByteArrayOutputStream bs = new ByteArrayOutputStream(); if (meta.contentType != null && writerFormats.contains(meta.contentType.split("/")[1].toLowerCase())) ImageIO.write(rtn, meta.contentType.split("/")[1].toLowerCase(), bs); else ImageIO.write(rtn, "png", bs); return Unpooled.buffer().writeBytes(bs.toByteArray()); } } } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:com.chiorichan.http.ssl.SniNegotiator.java
License:Mozilla Public License
private String sniHostNameFromHandshakeInfo(ByteBuf in) { int readerIndex = in.readerIndex(); try {//w w w. j av a 2 s . co m int command = in.getUnsignedByte(readerIndex); // tls, but not handshake command switch (command) { case SslConstants.SSL_CONTENT_TYPE_CHANGE_CIPHER_SPEC: case SslConstants.SSL_CONTENT_TYPE_ALERT: case SslConstants.SSL_CONTENT_TYPE_APPLICATION_DATA: return null; case SslConstants.SSL_CONTENT_TYPE_HANDSHAKE: break; default: //not tls or sslv3, do not try sni handshaken = true; return null; } int majorVersion = in.getUnsignedByte(readerIndex + 1); // SSLv3 or TLS if (majorVersion == 3) { int packetLength = in.getUnsignedShort(readerIndex + 3) + 5; if (in.readableBytes() >= packetLength) { // decode the ssl client hello packet // we have to skip some var-length fields int offset = readerIndex + 43; int sessionIdLength = in.getUnsignedByte(offset); offset += sessionIdLength + 1; int cipherSuitesLength = in.getUnsignedShort(offset); offset += cipherSuitesLength + 2; int compressionMethodLength = in.getUnsignedByte(offset); offset += compressionMethodLength + 1; int extensionsLength = in.getUnsignedShort(offset); offset += 2; int extensionsLimit = offset + extensionsLength; while (offset < extensionsLimit) { int extensionType = in.getUnsignedShort(offset); offset += 2; int extensionLength = in.getUnsignedShort(offset); offset += 2; // SNI if (extensionType == 0) { handshaken = true; int serverNameType = in.getUnsignedByte(offset + 2); if (serverNameType == 0) { int serverNameLength = in.getUnsignedShort(offset + 3); return in.toString(offset + 5, serverNameLength, CharsetUtil.UTF_8); } else // invalid enum value return null; } offset += extensionLength; } handshaken = true; return null; } else // client hello incomplete return null; } else { handshaken = true; return null; } } catch (Throwable e) { // unexpected encoding, ignore sni and use default if (logger.isDebugEnabled()) logger.debug("Unexpected client hello packet: " + ByteBufUtil.hexDump(in), e); handshaken = true; return null; } }
From source file:com.chiorichan.util.ObjectUtil.java
License:Mozilla Public License
public static String hexDump(ByteBuf buf) { return hexDump(buf, buf.readerIndex()); }
From source file:com.chiorichan.util.ServerFunc.java
License:Mozilla Public License
public static byte[] byteBuf2Bytes(ByteBuf buf) { byte[] bytes = new byte[buf.readableBytes()]; int readerIndex = buf.readerIndex(); buf.getBytes(readerIndex, bytes);//from w w w .ja v a 2 s . c om return bytes; }
From source file:com.cloudera.livy.client.local.rpc.KryoMessageCodec.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (in.readableBytes() < 4) { return;/* w w w .j a va 2s . c o m*/ } in.markReaderIndex(); int msgSize = in.readInt(); checkSize(msgSize); if (in.readableBytes() < msgSize) { // Incomplete message in buffer. in.resetReaderIndex(); return; } try { ByteBuffer nioBuffer = maybeDecrypt(in.nioBuffer(in.readerIndex(), msgSize)); Object msg = serializer.deserialize(nioBuffer); LOG.debug("Decoded message of type {} ({} bytes)", msg != null ? msg.getClass().getName() : msg, msgSize); out.add(msg); } finally { in.skipBytes(msgSize); } }
From source file:com.cloudhopper.smpp.pdu.BufferHelper.java
License:Apache License
static public byte[] createByteArray(ByteBuf buffer) throws Exception { byte[] bytes = new byte[buffer.readableBytes()]; // temporarily read bytes from the buffer buffer.getBytes(buffer.readerIndex(), bytes); return bytes; }
From source file:com.cloudhopper.smpp.transcoder.DefaultPduTranscoder.java
License:Apache License
@Override public Pdu decode(ByteBuf buffer) throws UnrecoverablePduException, RecoverablePduException { // wait until the length prefix is available if (buffer.readableBytes() < SmppConstants.PDU_INT_LENGTH) { return null; }/*from w w w . j a v a 2s. c o m*/ // parse the command length (first 4 bytes) int commandLength = buffer.getInt(buffer.readerIndex()); //logger.trace("PDU commandLength [" + commandLength + "]"); // valid command length is >= 16 bytes if (commandLength < SmppConstants.PDU_HEADER_LENGTH) { throw new UnrecoverablePduException( "Invalid PDU length [0x" + HexUtil.toHexString(commandLength) + "] parsed"); } // wait until the whole pdu is available (entire pdu) if (buffer.readableBytes() < commandLength) { return null; } // at this point, we have the entire PDU and length already in the buffer // we'll create a new "view" of this PDU and read the data from the actual buffer // NOTE: this should be super fast since the underlying byte array doesn't get copied ByteBuf buffer0 = buffer.readSlice(commandLength); return doDecode(commandLength, buffer0); }