io.netty.buffer.ByteBufOutputStream Java Examples

The following examples show how to use io.netty.buffer.ByteBufOutputStream. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Application.java    From xrpc with Apache License 2.0 6 votes vote down vote up
private static FullHttpResponse getDino(XrpcRequest request, List<Dino> dinos) {
  try {
    DinoGetRequest getRequest =
        DinoGetRequest.parseFrom(CodedInputStream.newInstance(request.body().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.byteBuf();
      resp.ensureWritable(CodedOutputStream.computeMessageSizeNoTag(getReply), true);
      getReply.writeTo(new ByteBufOutputStream(resp));

      return Recipes.newResponse(
          HttpResponseStatus.OK,
          request.byteBuf().writeBytes(resp),
          Recipes.ContentType.Application_Octet_Stream);
    }

  } catch (IOException e) {
    return Recipes.newResponseBadRequest("Malformed GetDino Request: " + e.getMessage());
  }

  return Recipes.newResponseOk("Dino not Found");
}
 
Example #2
Source File: Base64Renderer.java    From The-5zig-Mod with MIT License 6 votes vote down vote up
public static Base64Renderer getRenderer(BufferedImage icon, String id) {
	Base64Renderer renderer = CACHE.getIfPresent(id);
	if (renderer != null) {
		return renderer;
	}
	final Base64Renderer finalRenderer = new Base64Renderer(null, icon.getWidth(), icon.getHeight());
	CACHE.put(id, finalRenderer);
	try {
		ByteBuf decodedBuffer = Unpooled.buffer();
		ImageIO.write(icon, "PNG", new ByteBufOutputStream(decodedBuffer));
		ByteBuf encodedBuffer = Base64.encode(decodedBuffer);
		String imageDataString = encodedBuffer.toString(Charsets.UTF_8);

		finalRenderer.setBase64String(imageDataString, id);
	} catch (Exception e) {
		The5zigMod.logger.error("Could not load icon " + id, e);
	}
	return finalRenderer;
}
 
Example #3
Source File: SkinManager.java    From The-5zig-Mod with MIT License 6 votes vote down vote up
private void downloadBase64Skin(final String uuid) {
	executorService.submit(new Runnable() {
		@Override
		public void run() {
			try {
				URL url = new URL("https://cravatar.eu/avatar/" + uuid + "/64.png");
				BufferedImage image = ImageIO.read(url);
				// Converting Image byte array into Base64 String
				ByteBuf localByteBuf1 = Unpooled.buffer();
				ImageIO.write(image, "PNG", new ByteBufOutputStream(localByteBuf1));
				ByteBuf localByteBuf2 = Base64.encode(localByteBuf1);
				String imageDataString = localByteBuf2.toString(Charsets.UTF_8);
				setBase64EncodedSkin(uuid, imageDataString);
				The5zigMod.logger.debug("Got Base64 encoded skin for {}", uuid);
			} catch (Exception e) {
				The5zigMod.logger.warn("Could not get Base64 skin for " + uuid, e);
			}
		}
	});
}
 
Example #4
Source File: GrpcMessageMarshaller.java    From armeria with Apache License 2.0 6 votes vote down vote up
public ByteBuf serializeRequest(I message) throws IOException {
    switch (requestType) {
        case PROTOBUF:
            final PrototypeMarshaller<I> marshaller = (PrototypeMarshaller<I>) requestMarshaller;
            return serializeProto(marshaller, (Message) message);
        default:
            final CompositeByteBuf out = alloc.compositeBuffer();
            try (ByteBufOutputStream os = new ByteBufOutputStream(out)) {
                if (isProto) {
                    ByteStreams.copy(method.streamRequest(message), os);
                } else {
                    jsonMarshaller.serializeMessage(requestMarshaller, message, os);
                }
            }
            return out;
    }
}
 
Example #5
Source File: UpdateTradeSerializer_v340.java    From Protocol with Apache License 2.0 6 votes vote down vote up
@Override
public void serialize(ByteBuf buffer, UpdateTradePacket packet) {
    buffer.writeByte(packet.getWindowId());
    buffer.writeByte(packet.getWindowType());
    VarInts.writeInt(buffer, packet.getUnknownInt());
    VarInts.writeInt(buffer, packet.isScreen2() ? 40 : 0);
    VarInts.writeInt(buffer, packet.getTradeTier());
    buffer.writeBoolean(packet.isWilling());
    VarInts.writeLong(buffer, packet.getTraderUniqueEntityId());
    VarInts.writeLong(buffer, packet.getPlayerUniqueEntityId());
    BedrockUtils.writeString(buffer, packet.getDisplayName());
    try (NBTOutputStream writer = NbtUtils.createNetworkWriter(new ByteBufOutputStream(buffer))) {
        writer.write(packet.getOffers());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #6
Source File: Base64Renderer.java    From The-5zig-Mod with GNU General Public License v3.0 6 votes vote down vote up
public static Base64Renderer getRenderer(BufferedImage icon, String id) {
	Base64Renderer renderer = CACHE.getIfPresent(id);
	if (renderer != null) {
		return renderer;
	}
	final Base64Renderer finalRenderer = new Base64Renderer(null, icon.getWidth(), icon.getHeight());
	CACHE.put(id, finalRenderer);
	try {
		ByteBuf decodedBuffer = Unpooled.buffer();
		ImageIO.write(icon, "PNG", new ByteBufOutputStream(decodedBuffer));
		ByteBuf encodedBuffer = Base64.encode(decodedBuffer);
		String imageDataString = encodedBuffer.toString(Charsets.UTF_8);

		finalRenderer.setBase64String(imageDataString, id);
	} catch (Exception e) {
		The5zigMod.logger.error("Could not load icon " + id, e);
	}
	return finalRenderer;
}
 
Example #7
Source File: EinsLiveManager.java    From The-5zig-Mod with GNU General Public License v3.0 6 votes vote down vote up
private void resolveImage(ITunesSearchResultEntry searchEntry) {
	try {
		URL url = new URL(searchEntry.getArtworkUrl100());
		BufferedImage image = ImageIO.read(url);
		BufferedImage image1 = new BufferedImage(60, 60, image.getType());
		Graphics graphics = image1.getGraphics();
		try {
			graphics.drawImage(image, 0, 0, image1.getWidth(), image1.getHeight(), null);
		} finally {
			graphics.dispose();
		}
		// Converting Image byte array into Base64 String
		ByteBuf localByteBuf1 = Unpooled.buffer();
		ImageIO.write(image1, "PNG", new ByteBufOutputStream(localByteBuf1));
		ByteBuf localByteBuf2 = Base64.encode(localByteBuf1);
		String imageDataString = localByteBuf2.toString(Charsets.UTF_8);

		searchEntry.setImage(imageDataString);
	} catch (Exception e) {
		The5zigMod.logger.warn("Could not resolve image for track " + searchEntry.getTrackName() + "!");
	}
}
 
Example #8
Source File: UpdateTradeSerializer_v313.java    From Protocol with Apache License 2.0 6 votes vote down vote up
@Override
public void serialize(ByteBuf buffer, UpdateTradePacket packet) {
    buffer.writeByte(packet.getWindowId());
    buffer.writeByte(packet.getWindowType());
    VarInts.writeInt(buffer, packet.getUnknownInt());
    VarInts.writeInt(buffer, packet.isScreen2() ? 40 : 0);
    VarInts.writeInt(buffer, packet.getTradeTier());
    buffer.writeBoolean(packet.isWilling());
    VarInts.writeLong(buffer, packet.getTraderUniqueEntityId());
    VarInts.writeLong(buffer, packet.getPlayerUniqueEntityId());
    BedrockUtils.writeString(buffer, packet.getDisplayName());
    try (NBTOutputStream writer = NbtUtils.createNetworkWriter(new ByteBufOutputStream(buffer))) {
        writer.write(packet.getOffers());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #9
Source File: ILoveRadioManager.java    From The-5zig-Mod with GNU General Public License v3.0 6 votes vote down vote up
private String resolveCover(final String path) throws ExecutionException {
	return TRACK_IMAGE_LOOKUP.get(path, new Callable<String>() {
		@Override
		public String call() throws Exception {
			URL url = new URL(path);
			BufferedImage image = ImageIO.read(url);
			BufferedImage image1 = new BufferedImage(60, 60, image.getType());
			Graphics graphics = image1.getGraphics();
			try {
				graphics.drawImage(image, 0, 0, image1.getWidth(), image1.getHeight(), null);
			} finally {
				graphics.dispose();
			}
			// Converting Image byte array into Base64 String
			ByteBuf localByteBuf1 = Unpooled.buffer();
			ImageIO.write(image1, "PNG", new ByteBufOutputStream(localByteBuf1));
			ByteBuf localByteBuf2 = Base64.encode(localByteBuf1);
			return localByteBuf2.toString(Charsets.UTF_8);
		}
	});
}
 
Example #10
Source File: UpdateTradeSerializer_v361.java    From Protocol with Apache License 2.0 6 votes vote down vote up
@Override
public void serialize(ByteBuf buffer, UpdateTradePacket packet) {
    buffer.writeByte(packet.getWindowId());
    buffer.writeByte(packet.getWindowType());
    VarInts.writeInt(buffer, packet.getUnknownInt());
    VarInts.writeInt(buffer, packet.getTradeTier());
    VarInts.writeLong(buffer, packet.getTraderUniqueEntityId());
    VarInts.writeLong(buffer, packet.getPlayerUniqueEntityId());
    BedrockUtils.writeString(buffer, packet.getDisplayName());
    buffer.writeBoolean(packet.isScreen2());
    buffer.writeBoolean(packet.isWilling());
    try (NBTOutputStream writer = NbtUtils.createNetworkWriter(new ByteBufOutputStream(buffer))) {
        writer.write(packet.getOffers());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #11
Source File: SpigotMiscUtils.java    From ProtocolSupport with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public ItemStack createItemStackFromNetwork(NetworkItemStack stack) {
	net.minecraft.server.v1_16_R1.ItemStack nmsitemstack = new net.minecraft.server.v1_16_R1.ItemStack(Item.getById(stack.getTypeId()), stack.getAmount());
	NBTCompound rootTag = stack.getNBT();
	if (rootTag != null) {
		//TODO: a faster way to do that
		ByteBuf buffer = Unpooled.buffer();
		try {
			DefaultNBTSerializer.INSTANCE.serializeTag(new ByteBufOutputStream(buffer), rootTag);
			nmsitemstack.setTag(NBTCompressedStreamTools.a(new ByteBufInputStream(buffer), NBTReadLimiter.a));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	return CraftItemStack.asCraftMirror(nmsitemstack);
}
 
Example #12
Source File: NettyBsonDocumentWriter.java    From mongowp with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #13
Source File: UpdateTradeSerializer_v388.java    From Protocol with Apache License 2.0 6 votes vote down vote up
@Override
public void serialize(ByteBuf buffer, UpdateTradePacket packet) {
    buffer.writeByte(packet.getWindowId());
    buffer.writeByte(packet.getWindowType());
    VarInts.writeInt(buffer, packet.getUnknownInt());
    VarInts.writeInt(buffer, packet.getTradeTier());
    VarInts.writeLong(buffer, packet.getTraderUniqueEntityId());
    VarInts.writeLong(buffer, packet.getPlayerUniqueEntityId());
    BedrockUtils.writeString(buffer, packet.getDisplayName());
    buffer.writeBoolean(packet.isScreen2());
    buffer.writeBoolean(packet.isWilling());
    try (NBTOutputStream writer = NbtUtils.createNetworkWriter(new ByteBufOutputStream(buffer))) {
        writer.write(packet.getOffers());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #14
Source File: BatchRequest.java    From log4j2-elasticsearch with Apache License 2.0 6 votes vote down vote up
/**
 * Serializes and writes {@link #indexRequests} into {@link #buffer}
 *
 * @return underlying buffer filled with serialized indexRequests
 * @throws IOException if serialization failed
 */
public ItemSource serialize() throws IOException {

    ByteBufOutputStream byteBufOutputStream = new ByteBufOutputStream(buffer.getSource());

    // in current impl with no IDs, it's possible to reduce serialization by reusing first action
    IndexRequest identicalAction = uniformAction(indexRequests);
    byte[] actionTemplate = identicalAction != null ? objectWriter.writeValueAsBytes(identicalAction) : null;

    for (IndexRequest action : indexRequests) {

        if (actionTemplate == null) {
            objectWriter.writeValue((OutputStream) byteBufOutputStream, action);
        } else {
            byteBufOutputStream.write(actionTemplate);
        }
        byteBufOutputStream.writeByte(LINE_SEPARATOR);

        ByteBuf source = action.getSource().getSource();
        buffer.getSource().writeBytes(source);
        byteBufOutputStream.writeByte(LINE_SEPARATOR);

    }
    return buffer;
}
 
Example #15
Source File: Favicon.java    From ServerListPlus with GNU General Public License v3.0 6 votes vote down vote up
public static String create(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, false);
        try {
            return FAVICON_PREFIX + base64.toString(Charsets.UTF_8);
        } finally {
            base64.release();
        }
    } finally {
        buf.release();
    }
}
 
Example #16
Source File: Metrics.java    From Velocity with MIT License 6 votes vote down vote up
private static ByteBuf createResponseBody(JsonObject object) throws IOException {
  ByteBuf buf = Unpooled.buffer();
  try (Writer writer =
      new BufferedWriter(
          new OutputStreamWriter(
              new GZIPOutputStream(new ByteBufOutputStream(buf)), StandardCharsets.UTF_8
          )
      )
  ) {
    VelocityServer.GSON.toJson(object, writer);
  } catch (IOException e) {
    buf.release();
    throw e;
  }
  return buf;
}
 
Example #17
Source File: GrpcTestUtil.java    From armeria with Apache License 2.0 6 votes vote down vote up
public static byte[] compressedFrame(ByteBuf uncompressed) {
    final ByteBuf compressed = Unpooled.buffer();
    try (ByteBufInputStream is = new ByteBufInputStream(uncompressed, true);
         GZIPOutputStream os = new GZIPOutputStream(new ByteBufOutputStream(compressed))) {
        ByteStreams.copy(is, os);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
    final ByteBuf buf = Unpooled.buffer();
    buf.writeByte(1);
    buf.writeInt(compressed.readableBytes());
    buf.writeBytes(compressed);
    compressed.release();
    final byte[] result = ByteBufUtil.getBytes(buf);
    buf.release();
    return result;
}
 
Example #18
Source File: GeoWaveRedisRowWithTimestampCodec.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Override
public ByteBuf encode(final Object in) throws IOException {
  if (in instanceof GeoWaveRedisPersistedTimestampRow) {
    final GeoWaveRedisPersistedTimestampRow row = (GeoWaveRedisPersistedTimestampRow) in;
    final ByteBuf buf = ByteBufAllocator.DEFAULT.buffer();

    try (final ByteBufOutputStream out = new ByteBufOutputStream(buf)) {
      GeoWaveRedisRowCodec.encodeRow(out, row, visibilityEnabled);
      Varint.writeSignedVarInt((int) row.getSecondsSinceEpic(), out);
      Varint.writeSignedVarInt(row.getNanoOfSecond(), out);
      if (row.getDuplicateId() != null) {
        out.writeByte(row.getDuplicateId());
      }
      out.flush();
      return out.buffer();
    }
  }
  throw new IOException("Encoder only supports GeoWaveRedisPersistedTimestampRow");
}
 
Example #19
Source File: ObjectEncoderOutputStream.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
public void writeObject(Object obj) throws IOException {
    ByteBuf buf = Unpooled.buffer(estimatedLength);
    try {
        ObjectOutputStream oout = new CompactObjectOutputStream(new ByteBufOutputStream(buf));
        try {
            oout.writeObject(obj);
            oout.flush();
        } finally {
            oout.close();
        }

        int objectSize = buf.readableBytes();
        writeInt(objectSize);
        buf.getBytes(0, this, objectSize);
    } finally {
        buf.release();
    }
}
 
Example #20
Source File: NettyToJerseyBridge.java    From karyon with Apache License 2.0 6 votes vote down vote up
ContainerResponseWriter bridgeResponse(final HttpServerResponse<ByteBuf> serverResponse) {
    return new ContainerResponseWriter() {

        private final ByteBuf contentBuffer = serverResponse.getChannel().alloc().buffer();

        @Override
        public OutputStream writeStatusAndHeaders(long contentLength, ContainerResponse response) {
            int responseStatus = response.getStatus();
            serverResponse.setStatus(HttpResponseStatus.valueOf(responseStatus));
            HttpResponseHeaders responseHeaders = serverResponse.getHeaders();
            for(Map.Entry<String, List<Object>> header : response.getHttpHeaders().entrySet()){
                responseHeaders.setHeader(header.getKey(), header.getValue());
            }
            return new ByteBufOutputStream(contentBuffer);
        }

        @Override
        public void finish() {
            serverResponse.writeAndFlush(contentBuffer);
        }
    };
}
 
Example #21
Source File: DefaultChannelIdTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testSerialization() throws Exception {
    ChannelId a = DefaultChannelId.newInstance();
    ChannelId b;

    ByteBuf buf = Unpooled.buffer();
    ObjectOutputStream out = new ObjectOutputStream(new ByteBufOutputStream(buf));
    try {
        out.writeObject(a);
        out.flush();
    } finally {
        out.close();
    }

    ObjectInputStream in = new ObjectInputStream(new ByteBufInputStream(buf, true));
    try {
        b = (ChannelId) in.readObject();
    } finally {
        in.close();
    }

    assertThat(a, is(b));
    assertThat(a, is(not(sameInstance(b))));
    assertThat(a.asLongText(), is(b.asLongText()));
}
 
Example #22
Source File: CompatibleObjectEncoder.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@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();
    }
}
 
Example #23
Source File: UpdateTradeSerializer_v332.java    From Protocol with Apache License 2.0 6 votes vote down vote up
@Override
public void serialize(ByteBuf buffer, UpdateTradePacket packet) {
    buffer.writeByte(packet.getWindowId());
    buffer.writeByte(packet.getWindowType());
    VarInts.writeInt(buffer, packet.getUnknownInt());
    VarInts.writeInt(buffer, packet.isScreen2() ? 40 : 0);
    VarInts.writeInt(buffer, packet.getTradeTier());
    buffer.writeBoolean(packet.isWilling());
    VarInts.writeLong(buffer, packet.getTraderUniqueEntityId());
    VarInts.writeLong(buffer, packet.getPlayerUniqueEntityId());
    BedrockUtils.writeString(buffer, packet.getDisplayName());
    try (NBTOutputStream writer = NbtUtils.createNetworkWriter(new ByteBufOutputStream(buffer))) {
        writer.write(packet.getOffers());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #24
Source File: ObjectEncodingHandlerJsonImpl.java    From alibaba-rsocket-broker with Apache License 2.0 6 votes vote down vote up
@Override
@NotNull
public ByteBuf encodingResult(@Nullable Object result) throws EncodingException {
    if (result == null) {
        return EMPTY_BUFFER;
    }
    ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.buffer();
    try {
        ByteBufOutputStream bos = new ByteBufOutputStream(byteBuf);
        JsonUtils.objectMapper.writeValue((OutputStream) bos, result);
        return byteBuf;
    } catch (Exception e) {
        ReferenceCountUtil.safeRelease(byteBuf);
        throw new EncodingException(RsocketErrorCode.message("RST-700500", result.getClass().getCanonicalName(), "ByteBuf"), e);
    }
}
 
Example #25
Source File: Json.java    From rsocket-rpc-java with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
public static <T> Marshaller<T> marshaller(Class<T> clazz) {
  return t -> {
    ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer();
    OutputStream bos = new ByteBufOutputStream(byteBuf);
    try {
      Json.getInstance().mapper.writeValue(bos, t);
    } catch (IOException e) {
      throw Exceptions.propagate(e);
    }
    return byteBuf;
  };
}
 
Example #26
Source File: Cbor.java    From rsocket-rpc-java with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
public static <T> Marshaller<T> marshaller(Class<T> clazz) {
  return t -> {
    ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer();
    OutputStream bos = new ByteBufOutputStream(byteBuf);
    try {
      Cbor.getInstance().mapper.writeValue(bos, t);
    } catch (IOException e) {
      throw Exceptions.propagate(e);
    }
    return byteBuf;
  };
}
 
Example #27
Source File: GZip.java    From krpc with Apache License 2.0 5 votes vote down vote up
public void zip(byte[] in, ByteBuf out) throws IOException {

        try (ByteBufOutputStream bos = new ByteBufOutputStream(out);
             GZIPOutputStream gzip = new GZIPOutputStream(bos);) {
            gzip.write(in);
            gzip.finish();
        }
    }
 
Example #28
Source File: UpdateEquipSerializer_v388.java    From Protocol with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(ByteBuf buffer, UpdateEquipPacket packet) {
    buffer.writeByte(packet.getWindowId());
    buffer.writeByte(packet.getWindowType());
    VarInts.writeInt(buffer, packet.getUnknown0());
    VarInts.writeLong(buffer, packet.getUniqueEntityId());
    try (NBTOutputStream writer = NbtUtils.createNetworkWriter(new ByteBufOutputStream(buffer))) {
        writer.write(packet.getTag());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #29
Source File: ProtobufVarint32LengthFieldPrepender.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Override
protected void encode(
        ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
    int bodyLen = msg.readableBytes();
    int headerLen = CodedOutputStream.computeRawVarint32Size(bodyLen);
    out.ensureWritable(headerLen + bodyLen);

    CodedOutputStream headerOut =
            CodedOutputStream.newInstance(new ByteBufOutputStream(out), headerLen);
    headerOut.writeRawVarint32(bodyLen);
    headerOut.flush();

    out.writeBytes(msg, msg.readerIndex(), bodyLen);
}
 
Example #30
Source File: NBTType.java    From ViaRewind with MIT License 5 votes vote down vote up
@Override
public void write(ByteBuf buffer, CompoundTag nbt) throws Exception {
	if (nbt == null) {
		buffer.writeShort(-1);
	} else {
		ByteBuf buf = buffer.alloc().buffer();
		ByteBufOutputStream bytebufStream = new ByteBufOutputStream(buf);
		DataOutputStream dataOutputStream = new DataOutputStream(bytebufStream);
		NBTIO.writeTag((DataOutput) dataOutputStream, nbt);
		dataOutputStream.close();
		buffer.writeShort(buf.readableBytes());
		buffer.writeBytes(buf);
		buf.release();
	}
}