List of usage examples for io.netty.buffer ByteBufInputStream ByteBufInputStream
public ByteBufInputStream(ByteBuf buffer)
From source file:com.barchart.http.server.PooledServerRequest.java
License:BSD License
@Override public InputStream getInputStream() { return new ByteBufInputStream(nettyRequest.content()); }
From source file:com.barchart.netty.rest.server.util.SigningUtil.java
License:BSD License
public static byte[] bytesToSign(final HttpServerRequest request) throws Exception { final ByteBuf content = request.getContent(); content.markReaderIndex();// ww w . ja va 2s. co m final byte[] contentBytes = IOUtils.toByteArray(new ByteBufInputStream(content)); content.resetReaderIndex(); final String md5 = KerberosUtilities.bytesToHex(MessageDigest.getInstance("MD5").digest(contentBytes)); final StringBuilder sb = new StringBuilder(); sb.append(request.getMethod().name()).append("\n").append(request.getUri()).append("\n").append(md5) .append("\n").append(nullCheck(request.headers().get(HttpHeaders.Names.CONTENT_TYPE))).append("\n") .append(nullCheck(request.headers().get(HttpHeaders.Names.DATE))).append("\n"); return sb.toString().getBytes("UTF-8"); }
From source file:com.chiorichan.factory.event.PostImageProcessor.java
License:Mozilla Public License
@EventHandler() public void onEvent(PostEvalEvent event) { try {/*ww w . j av a 2s .com*/ if (event.context().contentType() == null || !event.context().contentType().toLowerCase().startsWith("image")) return; float x = -1; float y = -1; boolean cacheEnabled = AppConfig.get().getBoolean("advanced.processors.imageProcessorCache", true); boolean grayscale = false; ScriptingContext context = event.context(); HttpRequestWrapper request = context.request(); Map<String, String> rewrite = request.getRewriteMap(); if (rewrite != null) { if (rewrite.get("serverSideOptions") != null) { String[] params = rewrite.get("serverSideOptions").trim().split("_"); for (String p : params) if (p.toLowerCase().startsWith("width") && x < 0) x = Integer.parseInt(p.substring(5)); else if ((p.toLowerCase().startsWith("x") || p.toLowerCase().startsWith("w")) && p.length() > 1 && x < 0) x = Integer.parseInt(p.substring(1)); else if (p.toLowerCase().startsWith("height") && y < 0) y = Integer.parseInt(p.substring(6)); else if ((p.toLowerCase().startsWith("y") || p.toLowerCase().startsWith("h")) && p.length() > 1 && y < 0) y = Integer.parseInt(p.substring(1)); else if (p.toLowerCase().equals("thumb")) { x = 150; y = 0; break; } else if (p.toLowerCase().equals("bw") || p.toLowerCase().equals("grayscale")) grayscale = true; } if (request.getArgument("width") != null && request.getArgument("width").length() > 0) x = request.getArgumentInt("width"); if (request.getArgument("height") != null && request.getArgument("height").length() > 0) y = request.getArgumentInt("height"); if (request.getArgument("w") != null && request.getArgument("w").length() > 0) x = request.getArgumentInt("w"); if (request.getArgument("h") != null && request.getArgument("h").length() > 0) y = request.getArgumentInt("h"); if (request.getArgument("thumb") != null) { x = 150; y = 0; } if (request.hasArgument("bw") || request.hasArgument("grayscale")) grayscale = true; } // 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 (context.contentType() != null && !readerFormats.contains(context.contentType().split("/")[1].toLowerCase())) return; int inx = event.context().buffer().readerIndex(); BufferedImage img = ImageIO.read(new ByteBufInputStream(event.context().buffer())); event.context().buffer().readerIndex(inx); if (img == null) return; 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; } boolean resize = w1 > 0 && h1 > 0 && w1 != w && h1 != h; boolean argb = request.hasArgument("argb") && request.getArgument("argb").length() == 8; if (!resize && !argb && !grayscale) return; // Produce a unique encapsulated id based on this image processing request String encapId = SecureFunc.md5(context.filename() + w1 + h1 + request.getArgument("argb") + grayscale); File tmp = context.site() == null ? AppConfig.get().getDirectoryCache() : context.site().directoryTemp(); File file = new File(tmp, encapId + "_" + new File(context.filename()).getName()); if (cacheEnabled && file.exists()) { event.context().resetAndWrite(FileUtils.readFileToByteArray(file)); return; } Image image = resize ? img.getScaledInstance(Math.round(w1), Math.round(h1), AppConfig.get().getBoolean("advanced.processors.useFastGraphics", true) ? Image.SCALE_FAST : Image.SCALE_SMOOTH) : img; // TODO Report malformed parameters to user if (argb) { FilteredImageSource filteredSrc = new FilteredImageSource(image.getSource(), new RGBColorFilter((int) Long.parseLong(request.getArgument("argb"), 16))); image = Toolkit.getDefaultToolkit().createImage(filteredSrc); } BufferedImage rtn = new BufferedImage(Math.round(w1), Math.round(h1), img.getType()); Graphics2D graphics = rtn.createGraphics(); graphics.drawImage(image, 0, 0, null); graphics.dispose(); if (grayscale) { ColorConvertOp op = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null); op.filter(rtn, rtn); } if (resize) Log.get().info(EnumColor.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 (context.contentType() != null && writerFormats.contains(context.contentType().split("/")[1].toLowerCase())) ImageIO.write(rtn, context.contentType().split("/")[1].toLowerCase(), bs); else ImageIO.write(rtn, "png", bs); if (cacheEnabled && !file.exists()) FileUtils.writeByteArrayToFile(file, bs.toByteArray()); event.context().resetAndWrite(bs.toByteArray()); } } catch (Throwable e) { e.printStackTrace(); } return; }
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 ww .j a v a 2 s.com*/ 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.corundumstudio.socketio.parser.Decoder.java
License:Apache License
private Packet decodePacket(ByteBuf buffer, UUID uuid) throws IOException { if (buffer.readableBytes() < 3) { throw new DecoderException("Can't parse " + buffer.toString(CharsetUtil.UTF_8)); }//from w ww . j a v a2 s . c om PacketType type = getType(buffer); int readerIndex = buffer.readerIndex() + 1; // 'null' to avoid unnecessary StringBuilder creation boolean hasData = false; StringBuilder messageId = null; for (readerIndex += 1; readerIndex < buffer.readableBytes(); readerIndex++) { if (messageId == null) { messageId = new StringBuilder(4); } byte msg = buffer.getByte(readerIndex); if (msg == Packet.SEPARATOR) { break; } if (msg != (byte) '+') { messageId.append((char) msg); } else { hasData = true; } } Long id = null; if (messageId != null && messageId.length() > 0) { id = Long.valueOf(messageId.toString()); } // 'null' to avoid unnecessary StringBuilder creation StringBuilder endpointBuffer = null; for (readerIndex += 1; readerIndex < buffer.readableBytes(); readerIndex++) { if (endpointBuffer == null) { endpointBuffer = new StringBuilder(); } byte msg = buffer.getByte(readerIndex); if (msg == Packet.SEPARATOR) { break; } endpointBuffer.append((char) msg); } String endpoint = Namespace.DEFAULT_NAME; if (endpointBuffer != null && endpointBuffer.length() > 0) { endpoint = endpointBuffer.toString(); } if (buffer.readableBytes() == readerIndex) { buffer.readerIndex(buffer.readableBytes()); } else { readerIndex += 1; buffer.readerIndex(readerIndex); } Packet packet = new Packet(type); packet.setEndpoint(endpoint); if (id != null) { packet.setId(id); if (hasData) { packet.setAck(Packet.ACK_DATA); } else { packet.setAck(true); } } switch (type) { case ERROR: { if (!buffer.isReadable()) { break; } String[] pieces = buffer.toString(CharsetUtil.UTF_8).split("\\+"); if (pieces.length > 0 && pieces[0].trim().length() > 0) { ErrorReason reason = ErrorReason.valueOf(Integer.valueOf(pieces[0])); packet.setReason(reason); if (pieces.length > 1) { ErrorAdvice advice = ErrorAdvice.valueOf(Integer.valueOf(pieces[1])); packet.setAdvice(advice); } } break; } case MESSAGE: { if (buffer.isReadable()) { packet.setData(buffer.toString(CharsetUtil.UTF_8)); } else { packet.setData(""); } break; } case EVENT: { ByteBufInputStream in = new ByteBufInputStream(buffer); Event event = jsonSupport.readValue(in, Event.class); packet.setName(event.getName()); if (event.getArgs() != null) { packet.setArgs(event.getArgs()); } break; } case JSON: { ByteBufInputStream in = new ByteBufInputStream(buffer); JsonObject obj = jsonSupport.readValue(in, JsonObject.class); if (obj != null) { packet.setData(obj.getObject()); } else { in.reset(); Object object = jsonSupport.readValue(in, Object.class); packet.setData(object); } break; } case CONNECT: { if (buffer.isReadable()) { packet.setQs(buffer.toString(CharsetUtil.UTF_8)); } break; } case ACK: { if (!buffer.isReadable()) { break; } boolean validFormat = true; int plusIndex = -1; for (int i = buffer.readerIndex(); i < buffer.readerIndex() + buffer.readableBytes(); i++) { byte dataChar = buffer.getByte(i); if (!Character.isDigit(dataChar)) { if (dataChar == '+') { plusIndex = i; break; } else { validFormat = false; break; } } } if (!validFormat) { break; } if (plusIndex == -1) { packet.setAckId(parseLong(buffer)); break; } else { packet.setAckId(parseLong(buffer, plusIndex)); buffer.readerIndex(plusIndex + 1); ByteBufInputStream in = new ByteBufInputStream(buffer); AckCallback<?> callback = ackManager.getCallback(uuid, packet.getAckId()); AckArgs args = jsonSupport.readAckArgs(in, callback); packet.setArgs(args.getArgs()); } break; } case DISCONNECT: case HEARTBEAT: case NOOP: break; } buffer.readerIndex(buffer.readerIndex() + buffer.readableBytes()); return packet; }
From source file:com.corundumstudio.socketio.protocol.PacketDecoder.java
License:Apache License
private void parseBody(ClientHead head, ByteBuf frame, Packet packet) throws IOException { if (packet.getType() == PacketType.MESSAGE) { if (packet.getSubType() == PacketType.CONNECT || packet.getSubType() == PacketType.DISCONNECT) { packet.setNsp(readString(frame)); }//from ww w .j a v a 2s . co m if (packet.getSubType() == PacketType.ACK) { ByteBufInputStream in = new ByteBufInputStream(frame); AckCallback<?> callback = ackManager.getCallback(head.getSessionId(), packet.getAckId()); AckArgs args = jsonSupport.readAckArgs(in, callback); packet.setData(args.getArgs()); } if (packet.getSubType() == PacketType.EVENT || packet.getSubType() == PacketType.BINARY_EVENT) { if (packet.hasAttachments() && !packet.isAttachmentsLoaded()) { packet.setDataSource(Unpooled.copiedBuffer(frame)); frame.readerIndex(frame.readableBytes()); head.setLastBinaryPacket(packet); } else { ByteBufInputStream in = new ByteBufInputStream(frame); Event event = jsonSupport.readValue(packet.getNsp(), in, Event.class); packet.setName(event.getName()); packet.setData(event.getArgs()); } } } }
From source file:com.cu.http.container.core.adaptor.NettyServletInputStream.java
License:Apache License
public NettyServletInputStream(HttpContent httpContent) { this.byteBuf = httpContent.content(); this.in = new ByteBufInputStream(byteBuf); }
From source file:com.ebay.jetstream.messaging.transport.netty.serializer.StreamMessageDecoder.java
License:MIT License
@SuppressWarnings("resource") @Override//from w w w. j a va2 s .co m protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception { ByteBuf frame = (ByteBuf) super.decode(ctx, in); if (frame == null) { return null; } int readerIndex = frame.readerIndex(); byte version = frame.readByte(); frame.readerIndex(readerIndex); if (version == KRYO_STREAM_VERSION) { return decodeAsKryo(frame); } else { return new CompactObjectInputStream(new ByteBufInputStream(frame), classResolver).readObject(); } }
From source file:com.ebay.jetstream.messaging.transport.netty.serializer.StreamMessageDecoder.java
License:MIT License
private Object decodeAsKryo(ByteBuf frame) { Kryo kryo = kryoContextHolder.get().getKryo(); Input input = new Input(new ByteBufInputStream(frame)); input.readByte(); // skip first byte Object object = kryo.readClassAndObject(input); return object; }
From source file:com.eightkdata.mongowp.bson.netty.ByteBufByteSource.java
License:Open Source License
@Override public InputStream openStream() { return new ByteBufInputStream(byteBuf.slice()); }