@Override public ByteBuf encode(Object in) throws IOException { Kryo kryo = null; ByteBuf out = ByteBufAllocator.DEFAULT.buffer(); try { ByteBufOutputStream baos = new ByteBufOutputStream(out); Output output = new Output(baos); kryo = kryoPool.get(); kryo.writeClassAndObject(output, in); output.close(); return baos.buffer(); } catch (Exception e) { out.release(); if (e instanceof RuntimeException) { throw (RuntimeException) e; } throw new RedissonKryoCodecException(e); } finally { if (kryo != null) { kryoPool.yield(kryo); } } }
private static FullHttpResponse getDino(XrpcRequest request, List<Dino> dinos) { try { DinoGetRequest getRequest = DinoGetRequest.parseFrom(CodedInputStream.newInstance(request.getData().nioBuffer())); Optional<Dino> dinoOptional = dinos.stream().filter(xs -> xs.getName().equals(getRequest.getName())).findFirst(); if (dinoOptional.isPresent()) { DinoGetReply getReply = DinoGetReply.newBuilder().setDino(dinoOptional.get()).build(); ByteBuf resp = request.getByteBuf(); resp.ensureWritable(CodedOutputStream.computeMessageSizeNoTag(getReply), true); getReply.writeTo(new ByteBufOutputStream(resp)); return Recipes.newResponse( HttpResponseStatus.OK, request.getByteBuf().writeBytes(resp), Recipes.ContentType.Application_Octet_Stream); } } catch (IOException e) { return Recipes.newResponseBadRequest("Malformed GetDino Request: " + e.getMessage()); } return Recipes.newResponseOk("Dino not Found"); }
/** * Writes a compressed NBTTagCompound to this buffer */ public void writeNBTTagCompoundToBuffer(NBTTagCompound nbt) { if (nbt == null) { this.writeByte(0); } else { try { CompressedStreamTools.write(nbt, new ByteBufOutputStream(this)); } catch (IOException ioexception) { throw new EncoderException(ioexception); } } }
private HttpResponse processRequest(FullHttpRequest request) throws JsonProcessingException { HttpResponse response; ByteBuf responseContent = Unpooled.buffer(); HttpResponseStatus responseStatus = HttpResponseStatus.OK; try (ByteBufOutputStream os = new ByteBufOutputStream(responseContent); ByteBufInputStream is = new ByteBufInputStream(request.content().retain())){ int result = jsonRpcServer.handleRequest(is, os); responseStatus = HttpResponseStatus.valueOf(DefaultHttpStatusCodeProvider.INSTANCE.getHttpStatusCode(result)); } catch (Exception e) { LOGGER.error("Unexpected error", e); responseContent = buildErrorContent(JSON_RPC_SERVER_ERROR_HIGH_CODE, HttpResponseStatus.INTERNAL_SERVER_ERROR.reasonPhrase()); responseStatus = HttpResponseStatus.INTERNAL_SERVER_ERROR; } finally { response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, responseStatus, responseContent ); } return response; }
@Override public void write(RakNetByteBuf out) { super.write(out); RakNetOutputStream os = new RakNetOutputStream(new BufferedOutputStream(new DeflaterOutputStream(new ByteBufOutputStream(out)))); RakNetByteBuf payload = RakNetByteBuf.buffer(); body.write(payload); try { int bodySize = payload.readableBytes(); byte[] bytes = new byte[bodySize]; payload.readBytes(bytes); os.writeUnsignedVarInt(bodySize); os.write(bytes); } catch (Exception ignored) { } finally { payload.release(); } }
@Override protected void encode(ChannelHandlerContext ctx, T msg, ByteBuf out) throws Exception { int lengthIndex = out.writerIndex(); // length field, will be filled in later. out.writeInt(0); int startIndex = out.writerIndex(); ByteBufOutputStream os = new ByteBufOutputStream(out); TCompactProtocol thriftProtocol = new TCompactProtocol(new TIOStreamTransport(os)); msg.write(thriftProtocol); os.close(); int endIndex = out.writerIndex(); // update the length field int length = endIndex - startIndex; out.setInt(lengthIndex, length); }
/** * Writes a compressed NBTTagCompound to this buffer */ public PacketBuffer writeNBTTagCompoundToBuffer(@Nullable NBTTagCompound nbt) { if (nbt == null) { this.writeByte(0); } else { try { CompressedStreamTools.write(nbt, new ByteBufOutputStream(this)); } catch (IOException ioexception) { throw new EncoderException(ioexception); } } return this; }
public static void writeNBTTagCompoundToBuffer(ByteBuf buf, NBTTagCompound tag) { if (tag == null) { buf.writeByte(0); return; } try { CompressedStreamTools.write(tag, new ByteBufOutputStream(buf)); } catch (IOException ioexception) { ModLogger.error("IOException while trying to write a NBTTagCompound to ByteBuf"); throw new EncoderException(ioexception); } }
private void writeResourceReport(Channel channel) { ByteBuf content = Unpooled.buffer(); Writer writer = new OutputStreamWriter(new ByteBufOutputStream(content), CharsetUtil.UTF_8); try { reportAdapter.toJson(resourceReport.get(), writer); writer.close(); } catch (IOException e) { LOG.error("error writing resource report", e); writeAndClose(channel, new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR, Unpooled.copiedBuffer(e.getMessage(), StandardCharsets.UTF_8))); return; } FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content); HttpUtil.setContentLength(response, content.readableBytes()); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8"); channel.writeAndFlush(response); }
@Override public void toBytes(ByteBuf buf) { ByteBufOutputStream output = new ByteBufOutputStream(buf); try { output.writeUTF(this.filename); output.writeInt(this.frames.size()); for (Frame frame : this.frames) { frame.toBytes(output); } } catch (IOException e) { e.printStackTrace(); } }
/** * Serializes the passed object to the passed byte buffer or a new one if the passed one is null * @param object The object to serialize * @param buff The buffer to write to, or null to create a new one * @return the written buffer */ public static ByteBuf serialize(final Object object, final ByteBuf buff) { if (object == null) throw new IllegalArgumentException("Object was null"); final ByteBuf _buff = buff==null ? byteBufAllocator.buffer() : buff; final OutputStream os = new ByteBufOutputStream(_buff); try { serialize(object, os); os.flush(); os.close(); } catch (Exception ex) { throw new RuntimeException("Failed to write object to buffer", ex); } finally { try { os.close(); } catch (Exception x) {/* No Op */} } return _buff; }
/** * Serializes the passed object to an off-heap buffer and returns an InputStream to read it back * @param obj The object to serialize * @return an InputStream to read back the JSON serialized object */ public static InputStream serializeOffHeapLoopBack(final Object obj) { if(obj==null) throw new IllegalArgumentException("The passed object was null"); final ByteBuf cb = byteBufAllocator.buffer(); final OutputStream os = new ByteBufOutputStream(cb); try { serialize(obj, os); os.flush(); os.close(); } catch (Exception ex) { throw new RuntimeException("Failed to write object to buffer", ex); } return new ByteBufInputStream(cb) { @Override public void close() throws IOException { super.close(); try { cb.release(); } catch (Exception x) {/* No Op */} } }; }
/** * Serializes and gzips the passed object to the passed byte buffer or a new one if the passed one is null * @param object The object to serialize * @param buff The buffer to write to, or null to create a new one * @return the written buffer */ public static ByteBuf serializeAndGzip(final Object object, final ByteBuf buff) { if (object == null) throw new IllegalArgumentException("Object was null"); final ByteBuf _buff = buff==null ? byteBufAllocator.buffer() : buff; final OutputStream os = new ByteBufOutputStream(_buff); try { final GZIPOutputStream gos = new GZIPOutputStream(os); serialize(object, gos); gos.finish(); gos.flush(); gos.close(); os.flush(); os.close(); } catch (Exception ex) { throw new RuntimeException("Failed to write object to buffer", ex); } finally { try { os.close(); } catch (Exception x) {/* No Op */} } return _buff; }
@Override protected ByteBuf getPayload(ChannelHandlerContext ctx, Batch batch) throws IOException { ByteBuf payload = super.getPayload(ctx, batch); Deflater deflater = new Deflater(); ByteBufOutputStream output = new ByteBufOutputStream(ctx.alloc().buffer()); DeflaterOutputStream outputDeflater = new DeflaterOutputStream(output, deflater); byte[] chunk = new byte[payload.readableBytes()]; payload.readBytes(chunk); outputDeflater.write(chunk); outputDeflater.close(); ByteBuf content = ctx.alloc().buffer(); content.writeByte(batch.getProtocol()); content.writeByte('C'); content.writeInt(output.writtenBytes()); content.writeBytes(output.buffer()); return content; }
@Override public void channelActive(ChannelHandlerContext context) throws Exception { ByteBuf buffer = context.alloc().ioBuffer(1024); boolean success = false; try { ByteBufOutputStream out = new ByteBufOutputStream(buffer); for (String path : myLockedPaths) out.writeUTF(path); out.writeUTF(PATHS_EOT_RESPONSE); out.close(); success = true; } finally { if (!success) { buffer.release(); } } context.writeAndFlush(buffer); }
/** * Encodes the buffered image into the encoded favicon string. * * @param image the buffered image * @return the favicon string */ private static String encode(BufferedImage image) throws IOException { checkArgument(image.getWidth() == 64, "favicon must be 64 pixels wide"); checkArgument(image.getHeight() == 64, "favicon must be 64 pixels high"); ByteBuf buf = Unpooled.buffer(); try { ImageIO.write(image, "PNG", new ByteBufOutputStream(buf)); ByteBuf base64 = Base64.encode(buf); try { return FAVICON_PREFIX + base64.toString(StandardCharsets.UTF_8); } finally { base64.release(); } } finally { buf.release(); } }
@Override public void toBytes(ByteBuf buf) { CivLog.info("toBytes(), side == " + FMLCommonHandler.instance().getEffectiveSide()); ByteBuf b = Unpooled.buffer(); NBTTagCompound nbt = new NBTTagCompound(); TechTree.currentTree.save(nbt); try { CompressedStreamTools.writeCompressed(nbt, new ByteBufOutputStream(b)); } catch (IOException e) { e.printStackTrace(); } int i = b.readableBytes(); buf.writeInt(i); buf.writeBytes(b); }
@Override protected void encode(ChannelHandlerContext ctx, Serializable msg, ByteBuf out) throws Exception { Attribute<ObjectOutputStream> oosAttr = ctx.attr(OOS); ObjectOutputStream oos = oosAttr.get(); if (oos == null) { oos = newObjectOutputStream(new ByteBufOutputStream(out)); ObjectOutputStream newOos = oosAttr.setIfAbsent(oos); if (newOos != null) { oos = newOos; } } synchronized (oos) { if (resetInterval != 0) { // Resetting will prevent OOM on the receiving side. writtenObjects ++; if (writtenObjects % resetInterval == 0) { oos.reset(); } } oos.writeObject(msg); oos.flush(); } }
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if(msg instanceof DatagramPacket){ ctx.write(msg, promise); return; } ByteBuf buf = ctx.alloc().heapBuffer(); // int startIdx = buf.writerIndex(); ByteBufOutputStream bout = new ByteBufOutputStream(buf); // bout.write(LENGTH_PLACEHOLDER); ObjectOutputStream oout = new CompactObjectOutputStream(bout); oout.writeObject(msg); oout.flush(); oout.close(); // int endIdx = buf.writerIndex(); // buf.setInt(startIdx, endIdx - startIdx - 4); Object data = new DatagramPacket(buf, new InetSocketAddress("255.255.255.255", port)); ctx.write(data, promise); }
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if(msg instanceof DatagramPacket){ ctx.write(msg, promise); return; } ByteBuf buf = ctx.alloc().heapBuffer(); // int startIdx = buf.writerIndex(); ByteBufOutputStream bout = new ByteBufOutputStream(buf); // bout.write(LENGTH_PLACEHOLDER); ObjectOutputStream oout = new CompactObjectOutputStream(bout); oout.writeObject(msg); oout.flush(); oout.close(); // int endIdx = buf.writerIndex(); // buf.setInt(startIdx, endIdx - startIdx - 4); Object data = new DatagramPacket(buf, multicastAddress); ctx.write(data, promise); }
private void a(ServerPing serverping) { File file = this.d("server-icon.png"); if (file.isFile()) { ByteBuf bytebuf = Unpooled.buffer(); try { BufferedImage bufferedimage = ImageIO.read(file); Validate.validState(bufferedimage.getWidth() == 64, "Must be 64 pixels wide", new Object[0]); Validate.validState(bufferedimage.getHeight() == 64, "Must be 64 pixels high", new Object[0]); ImageIO.write(bufferedimage, "PNG", new ByteBufOutputStream(bytebuf)); ByteBuf bytebuf1 = Base64.encode(bytebuf); serverping.setFavicon("data:image/png;base64," + bytebuf1.toString(Charsets.UTF_8)); } catch (Exception exception) { MinecraftServer.LOGGER.error("Couldn\'t load server icon", exception); } finally { bytebuf.release(); } } }
private ByteBuf writeCompressed(ByteBuf message) throws IOException { CompositeByteBuf compressed = alloc.compositeBuffer(); try (OutputStream compressingStream = compressor.compress(new ByteBufOutputStream(compressed))) { compressingStream.write(ByteBufUtil.getBytes(message)); } finally { message.release(); } int numCompressedBytes = compressed.readableBytes(); if (maxOutboundMessageSize >= 0 && numCompressedBytes > maxOutboundMessageSize) { compressed.release(); throw Status.RESOURCE_EXHAUSTED .withDescription( String.format( "message too large %d > %d", numCompressedBytes, maxOutboundMessageSize)) .asRuntimeException(); } ByteBuf header = alloc.buffer(HEADER_LENGTH); header.writeByte(COMPRESSED); header.writeInt(numCompressedBytes); compressed.addComponent(true, 0, header); return compressed; }
@Override protected void encode(ChannelHandlerContext ctx, Serializable msg, ByteBuf out) throws Exception { KryoContext kryoContext = kryoContextHolder.get(); Kryo kryo = kryoContext.getKryo(); Output output = kryoContext.getOut(); output.clear(); ByteBufOutputStream bout = new ByteBufOutputStream(out); int startIdx = out.writerIndex(); bout.write(LENGTH_PLACEHOLDER); output.setOutputStream(bout); output.writeByte(StreamMessageDecoder.KRYO_STREAM_VERSION); kryo.writeClassAndObject(output, msg); output.flush(); bout.flush(); bout.close(); output.close(); int endIdx = out.writerIndex(); out.setInt(startIdx, endIdx - startIdx - 4); }
private void func_147138_a(ServerStatusResponse p_147138_1_) { File var2 = this.getFile("server-icon.png"); if (var2.isFile()) { ByteBuf var3 = Unpooled.buffer(); try { BufferedImage var4 = ImageIO.read(var2); Validate.validState(var4.getWidth() == 64, "Must be 64 pixels wide", new Object[0]); Validate.validState(var4.getHeight() == 64, "Must be 64 pixels high", new Object[0]); ImageIO.write(var4, "PNG", new ByteBufOutputStream(var3)); ByteBuf var5 = Base64.encode(var3); p_147138_1_.func_151320_a("data:image/png;base64," + var5.toString(Charsets.UTF_8)); } catch (Exception var6) { logger.error("Couldn\'t load server icon", var6); } } }
@Override public Void visit(BsonBinary value, ByteBuf arg) { NonIoByteSource byteSource = value.getByteSource(); UnsignedInteger unsignedSize; unsignedSize = UnsignedInteger.valueOf(byteSource.size()); arg.writeInt(unsignedSize.intValue()).writeByte(value.getNumericSubType()); try (OutputStream os = new ByteBufOutputStream(arg)) { value.getByteSource().copyTo(os); } catch (IOException ex) { throw new AssertionError("Unexpected IOException", ex); } return null; }
/** * Copy OData content to netty content * @param input * @param response */ static void copyContent(final ReadableByteChannel input, final HttpResponse response) { WritableByteChannel output = null; try { ByteBuffer inBuffer = ByteBuffer.allocate(COPY_BUFFER_SIZE); output = Channels.newChannel(new ByteBufOutputStream(((HttpContent)response).content())); while (input.read(inBuffer) > 0) { inBuffer.flip(); output.write(inBuffer); inBuffer.clear(); } } catch (IOException e) { throw new ODataRuntimeException("Error on reading request content", e); } finally { closeStream(input); closeStream(output); } }
public static void writeNBTTagCompoundToBuffer(ByteBuf buf, NBTTagCompound tag) { if (tag == null) { buf.writeByte(0); return; } try { CompressedStreamTools.write(tag, new ByteBufOutputStream(buf)); } catch (IOException ioexception) { EnderUtilities.logger.error("IOException while trying to write a NBTTagCompound to ByteBuf"); throw new EncoderException(ioexception); } }