io.netty.buffer.ByteBufInputStream Java Examples
The following examples show how to use
io.netty.buffer.ByteBufInputStream.
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: StructureTemplateDataExportResponseSerializer_v361.java From Protocol with Apache License 2.0 | 6 votes |
@Override public void deserialize(ByteBuf buffer, StructureTemplateDataExportResponsePacket packet) { packet.setName(BedrockUtils.readString(buffer)); boolean save = buffer.readBoolean(); packet.setSave(save); if (save) { try (NBTInputStream reader = NbtUtils.createNetworkReader(new ByteBufInputStream(buffer))) { Tag<?> tag = reader.readTag(); if (tag instanceof CompoundTag) { packet.setTag((CompoundTag) tag); } else { throw new IllegalArgumentException("Tag received was not a CompoundTag"); } } catch (IOException e) { throw new RuntimeException(e); } } }
Example #2
Source File: ProtoDecoder.java From xrpc with Apache License 2.0 | 6 votes |
/** * Decode a ByteBuf body from protobuf format to an object of designated Class type. * * @param body current http request * @param clazz target class for decoding * @return object of type clazz */ @Override @SuppressWarnings("unchecked") public <T> T decode(ByteBuf body, CharSequence contentType, Class<T> clazz) throws IOException { // TODO (AD): given a Content-Type of application/protobuf; proto=org.some.Message, // we currently ignore the 2nd part, but should at least validate it in the future. if (!MessageLite.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException( String.format("%s does not extend from MessageLite", clazz.getName())); } MessageLite message = protoDefaultInstances.get(clazz); Parser<?> parser = message.getParserForType(); try (ByteBufInputStream stream = new ByteBufInputStream(body)) { return (T) parser.parseFrom(stream); } }
Example #3
Source File: ObjectEncodingHandlerCborImpl.java From alibaba-rsocket-broker with Apache License 2.0 | 6 votes |
@Override @Nullable public Object decodeResult(ByteBuf data, @Nullable Class<?> targetClass) throws EncodingException { if (data.readableBytes() > 0 && targetClass != null) { try { //Kotlin Cbor Serializer if (ktCbor && KotlinSerializerSupport.isKotlinSerializable(targetClass)) { byte[] bytes = new byte[data.readableBytes()]; data.readBytes(bytes); return KotlinSerializerSupport.decodeFromCbor(bytes, targetClass); } return objectMapper.readValue((InputStream) new ByteBufInputStream(data), targetClass); } catch (Exception e) { throw new EncodingException(RsocketErrorCode.message("RST-700501", "ByteBuf", targetClass.getName()), e); } } return null; }
Example #4
Source File: HttpSender.java From arcusplatform with Apache License 2.0 | 6 votes |
public void sendChunkedHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); HttpUtil.setTransferEncodingChunked(response, true); response.headers().set(HttpHeaderNames.CONTENT_TYPE, res.headers().get(HttpHeaderNames.CONTENT_TYPE)); if(HttpUtil.isKeepAlive(req)) { response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } ctx.write(response); ctx.write(new ChunkedStream(new ByteBufInputStream(res.content()))); ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); if(!HttpUtil.isKeepAlive(req)) { future.addListener(ChannelFutureListener.CLOSE); } metrics.incHTTPResponseCounter(className, res.status().code()); }
Example #5
Source File: SslContext.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
private static X509Certificate[] getCertificatesFromBuffers(ByteBuf[] certs) throws CertificateException { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate[] x509Certs = new X509Certificate[certs.length]; int i = 0; try { for (; i < certs.length; i++) { InputStream is = new ByteBufInputStream(certs[i], true); try { x509Certs[i] = (X509Certificate) cf.generateCertificate(is); } finally { try { is.close(); } catch (IOException e) { // This is not expected to happen, but re-throw in case it does. throw new RuntimeException(e); } } } } finally { for (; i < certs.length; i++) { certs[i].release(); } } return x509Certs; }
Example #6
Source File: ODataNettyHandlerImpl.java From olingo-odata4 with Apache License 2.0 | 6 votes |
/** * Extract the information part of Netty Request and fill OData Request * @param odRequest * @param httpRequest * @param split * @param contextPath * @return * @throws ODataLibraryException */ private ODataRequest fillODataRequest(final ODataRequest odRequest, final HttpRequest httpRequest, final int split, final String contextPath) throws ODataLibraryException { final int requestHandle = debugger.startRuntimeMeasurement("ODataHttpHandlerImpl", "fillODataRequest"); try { ByteBuf byteBuf = ((HttpContent)httpRequest).content(); ByteBufInputStream inputStream = new ByteBufInputStream(byteBuf); odRequest.setBody(inputStream); odRequest.setProtocol(httpRequest.protocolVersion().text()); odRequest.setMethod(extractMethod(httpRequest)); int innerHandle = debugger.startRuntimeMeasurement("ODataNettyHandlerImpl", "copyHeaders"); copyHeaders(odRequest, httpRequest); debugger.stopRuntimeMeasurement(innerHandle); innerHandle = debugger.startRuntimeMeasurement("ODataNettyHandlerImpl", "fillUriInformation"); fillUriInformationFromHttpRequest(odRequest, httpRequest, split, contextPath); debugger.stopRuntimeMeasurement(innerHandle); return odRequest; } finally { debugger.stopRuntimeMeasurement(requestHandle); } }
Example #7
Source File: GrpcTestUtil.java From armeria with Apache License 2.0 | 6 votes |
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 #8
Source File: DefaultNettyDecoder.java From PeonyFramwork with Apache License 2.0 | 6 votes |
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> list) throws Exception { try { int readAble = in.readableBytes(); if (readAble < headSize) { return; } in.markReaderIndex(); int size = in.readInt(); if (readAble < (size + headSize)) { in.resetReaderIndex(); return; } // FIXME wjm 最好改了 try (ObjectInputStream oin = new ObjectInputStream(new ByteBufInputStream(in.readBytes(size), true))) { list.add(oin.readObject()); } } catch (Throwable e) { logger.error("decode error ", e); } }
Example #9
Source File: NanoNikProtector.java From ehacks-pro with GNU General Public License v3.0 | 6 votes |
@Override public boolean isPacketOk(Object packet, PacketHandler.Side side) { try { if (packet instanceof C17PacketCustomPayload && "nGuard".equals(((C17PacketCustomPayload) packet).func_149559_c()) && side == PacketHandler.Side.OUT) { ByteBuf buf = Unpooled.copiedBuffer(((C17PacketCustomPayload) packet).func_149558_e()); DataInputStream is = new DataInputStream(new ByteBufInputStream(buf)); String data = is.readUTF(); String aim = data.split(";")[0]; if (data.split(";")[1].equals("https://i.imgur.com/BqOhWwR.png")) { return true; } ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream outputStream = new DataOutputStream(bos); outputStream.writeUTF(aim + ";https://i.imgur.com/BqOhWwR.png"); Wrapper.INSTANCE.player().sendQueue.addToSendQueue(new C17PacketCustomPayload("nGuard", bos.toByteArray())); InteropUtils.log(String.format("You have been screened with aim: '%s'; Admins have been flek$$ed!", aim), "NanoNikGuard"); return false; } else { return true; } } catch (Exception e) { return false; } }
Example #10
Source File: WebSocketClientHandler.java From zheshiyigeniubidexiangmu with MIT License | 6 votes |
public String decodeByteBuff(ByteBuf buf) throws IOException, DataFormatException { byte[] temp = new byte[buf.readableBytes()]; ByteBufInputStream bis = new ByteBufInputStream(buf); bis.read(temp); bis.close(); Inflater decompresser = new Inflater(true); decompresser.setInput(temp, 0, temp.length); StringBuilder sb = new StringBuilder(); byte[] result = new byte[1024]; while (!decompresser.finished()) { int resultLength = decompresser.inflate(result); sb.append(new String(result, 0, resultLength, "UTF-8")); } decompresser.end(); return sb.toString(); }
Example #11
Source File: JsonObjectMapperDecoder.java From ffwd with Apache License 2.0 | 6 votes |
private Object decode0(ByteBuf in, List<Object> out) throws IOException { final JsonNode tree; try (final InputStream input = new ByteBufInputStream(in)) { tree = mapper.readTree(input); } final JsonNode typeNode = tree.get("type"); if (typeNode == null) { throw new IllegalArgumentException("Missing field 'type'"); } final String type = typeNode.asText(); if ("metric".equals(type)) { return decodeMetric(tree, out); } throw new IllegalArgumentException("Invalid metric type '" + type + "'"); }
Example #12
Source File: UpdateTradeSerializer_v313.java From Protocol with Apache License 2.0 | 6 votes |
@Override public void deserialize(ByteBuf buffer, UpdateTradePacket packet) { packet.setWindowId(buffer.readUnsignedByte()); packet.setWindowType(buffer.readUnsignedByte()); packet.setUnknownInt(VarInts.readInt(buffer)); packet.setScreen2(VarInts.readInt(buffer) >= 40); packet.setTradeTier(VarInts.readInt(buffer)); packet.setWilling(buffer.readBoolean()); packet.setTraderUniqueEntityId(VarInts.readLong(buffer)); packet.setPlayerUniqueEntityId(VarInts.readLong(buffer)); packet.setDisplayName(BedrockUtils.readString(buffer)); try (NBTInputStream reader = NbtUtils.createNetworkReader(new ByteBufInputStream(buffer))) { packet.setOffers(reader.readTag()); } catch (IOException e) { throw new RuntimeException(e); } }
Example #13
Source File: HttpResponseStreamHandlerTest.java From docker-java with Apache License 2.0 | 6 votes |
@Test public void testNoBytesSkipped() throws Exception { ResultCallbackTest callback = new ResultCallbackTest(); HttpResponseStreamHandler streamHandler = new HttpResponseStreamHandler(callback); ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class); ByteBuf buffer = generateByteBuf(); ByteBuf readBuffer = buffer.copy(); assertEquals(buffer.refCnt(), 1); streamHandler.channelRead(ctx, buffer); streamHandler.channelInactive(ctx); assertEquals(buffer.refCnt(), 0); try (InputStream inputStream = callback.getInputStream()) { assertTrue(IOUtils.contentEquals(inputStream, new ByteBufInputStream(readBuffer))); } ReferenceCountUtil.release(readBuffer); }
Example #14
Source File: ResultDecoder.java From extract with MIT License | 6 votes |
@Override public Object decode(final ByteBuf buffer, final State state) throws IOException { String result = new String (new char[] {(char) buffer.readByte()}); ExtractionStatus extractionStatus = ExtractionStatus.parse(result); if (buffer.capacity() == 1) { return new Report(extractionStatus); } else { buffer.readByte(); // pipe char | ByteBuf exceptionPayload = buffer.getBytes(0, new byte[buffer.capacity() - 2]); try (ObjectInputStream objectInputStream = new ObjectInputStream(new ByteBufInputStream(exceptionPayload))) { Exception ex = (Exception) objectInputStream.readObject(); return new Report(extractionStatus, ex); } catch (ClassNotFoundException e) { logger.warn("cannot read object : ", e); return new Report(extractionStatus); } } }
Example #15
Source File: UpdateTradeSerializer_v332.java From Protocol with Apache License 2.0 | 6 votes |
@Override public void deserialize(ByteBuf buffer, UpdateTradePacket packet) { packet.setWindowId(buffer.readUnsignedByte()); packet.setWindowType(buffer.readUnsignedByte()); packet.setUnknownInt(VarInts.readInt(buffer)); packet.setScreen2(VarInts.readInt(buffer) >= 40); packet.setTradeTier(VarInts.readInt(buffer)); packet.setWilling(buffer.readBoolean()); packet.setTraderUniqueEntityId(VarInts.readLong(buffer)); packet.setPlayerUniqueEntityId(VarInts.readLong(buffer)); packet.setDisplayName(BedrockUtils.readString(buffer)); try (NBTInputStream reader = NbtUtils.createNetworkReader(new ByteBufInputStream(buffer))) { packet.setOffers(reader.readTag()); } catch (IOException e) { throw new RuntimeException(e); } }
Example #16
Source File: UpdateTradeSerializer_v388.java From Protocol with Apache License 2.0 | 6 votes |
@Override public void deserialize(ByteBuf buffer, UpdateTradePacket packet) { packet.setWindowId(buffer.readUnsignedByte()); packet.setWindowType(buffer.readUnsignedByte()); packet.setUnknownInt(VarInts.readInt(buffer)); packet.setTradeTier(VarInts.readInt(buffer)); packet.setWilling(buffer.readBoolean()); packet.setTraderUniqueEntityId(VarInts.readLong(buffer)); packet.setPlayerUniqueEntityId(VarInts.readLong(buffer)); packet.setDisplayName(BedrockUtils.readString(buffer)); packet.setScreen2(buffer.readBoolean()); packet.setWilling(buffer.readBoolean()); try (NBTInputStream reader = NbtUtils.createNetworkReader(new ByteBufInputStream(buffer))) { packet.setOffers(reader.readTag()); } catch (IOException e) { throw new RuntimeException(e); } }
Example #17
Source File: WebSocketClientHandler.java From zheshiyigeniubidexiangmu with MIT License | 6 votes |
public String decodeByteBuff(ByteBuf buf) throws IOException, DataFormatException { byte[] temp = new byte[buf.readableBytes()]; ByteBufInputStream bis = new ByteBufInputStream(buf); bis.read(temp); bis.close(); Inflater decompresser = new Inflater(true); decompresser.setInput(temp, 0, temp.length); StringBuilder sb = new StringBuilder(); byte[] result = new byte[1024]; while (!decompresser.finished()) { int resultLength = decompresser.inflate(result); sb.append(new String(result, 0, resultLength, "UTF-8")); } decompresser.end(); return sb.toString(); }
Example #18
Source File: LevelEventGenericSerializer_v388.java From Protocol with Apache License 2.0 | 5 votes |
@Override public void deserialize(ByteBuf buffer, LevelEventGenericPacket packet) { packet.setEventId(VarInts.readInt(buffer)); try (NBTInputStream reader = NbtUtils.createNetworkReader(new ByteBufInputStream(buffer))) { packet.setTag(reader.readTag()); } catch (IOException e) { throw new RuntimeException(e); } }
Example #19
Source File: Cbor.java From rsocket-rpc-java with Apache License 2.0 | 5 votes |
public static <T> Unmarshaller<T> unmarshaller(Class<T> clazz) { return byteBuf -> { InputStream bis = new ByteBufInputStream(byteBuf); try { return Cbor.getInstance().mapper.readValue(bis, clazz); } catch (Throwable t) { throw Exceptions.propagate(t); } }; }
Example #20
Source File: RpcDecoder.java From Bats with Apache License 2.0 | 5 votes |
public static int readRawVarint32(ByteBufInputStream is) throws IOException { byte tmp = is.readByte(); if (tmp >= 0) { return tmp; } int result = tmp & 0x7f; if ((tmp = is.readByte()) >= 0) { result |= tmp << 7; } else { result |= (tmp & 0x7f) << 7; if ((tmp = is.readByte()) >= 0) { result |= tmp << 14; } else { result |= (tmp & 0x7f) << 14; if ((tmp = is.readByte()) >= 0) { result |= tmp << 21; } else { result |= (tmp & 0x7f) << 21; result |= (tmp = is.readByte()) << 28; if (tmp < 0) { // Discard upper 32 bits. for (int i = 0; i < 5; i++) { if (is.readByte() >= 0) { return result; } } throw new CorruptedFrameException("Encountered a malformed varint."); } } } } return result; }
Example #21
Source File: JsonUtils.java From alibaba-rsocket-broker with Apache License 2.0 | 5 votes |
public static Object[] readJsonArray(ByteBuf byteBuf, Class<?>[] targetClasses) throws IOException { Object[] targets = new Object[targetClasses.length]; List<JsonNode> jsonNodes = objectMapper.readValue(new ByteBufInputStream(byteBuf), new TypeReference<List<JsonNode>>() { }); for (int i = 0; i < targetClasses.length; i++) { targets[i] = objectMapper.treeToValue(jsonNodes.get(i), targetClasses[i]); } return targets; }
Example #22
Source File: ByteBufHttpEntity.java From log4j2-elasticsearch with Apache License 2.0 | 5 votes |
/** * Returns extended {@code io.netty.buffer.ByteBufInputStream} that resets the {@code io.netty.buffer.ByteBuf} on close * * @return {@code io.netty.buffer.ByteBufInputStream} */ @Override public InputStream getContent() { return new ByteBufInputStream(this.content) { @Override public void close() throws IOException { super.close(); // let's make it actually repeatable content.readerIndex(0); } }; }
Example #23
Source File: UpdateEquipSerializer_v313.java From Protocol with Apache License 2.0 | 5 votes |
@Override public void deserialize(ByteBuf buffer, UpdateEquipPacket packet) { packet.setWindowId(buffer.readUnsignedByte()); packet.setWindowType(buffer.readUnsignedByte()); packet.setUnknown0(VarInts.readInt(buffer)); packet.setUniqueEntityId(VarInts.readLong(buffer)); try (NBTInputStream reader = NbtUtils.createNetworkReader(new ByteBufInputStream(buffer))) { packet.setTag(reader.readTag()); } catch (IOException e) { throw new RuntimeException(e); } }
Example #24
Source File: AvailableEntityIdentifiersSerializer_v313.java From Protocol with Apache License 2.0 | 5 votes |
@Override public void deserialize(ByteBuf buffer, AvailableEntityIdentifiersPacket packet) { try (NBTInputStream reader = NbtUtils.createNetworkReader(new ByteBufInputStream(buffer))) { packet.setTag(reader.readTag()); } catch (IOException e) { throw new RuntimeException(e); } }
Example #25
Source File: DefaultRpcCodec.java From krpc with Apache License 2.0 | 5 votes |
public RpcMeta decodeMeta(ByteBuf bb) { int len = bb.readableBytes(); if (len < 8) { throw new RuntimeException("package_len_error"); } int b0 = bb.readByte(); int b1 = bb.readByte(); int metaLen = bb.readShort(); int packageLen = bb.readInt(); if (b0 != 'K' && b1 != 'R') { throw new RuntimeException("package_flag_error"); } if (metaLen <= 0 || metaLen > packageLen || packageLen + 8 != len) { throw new RuntimeException("package_len_not_match"); } RpcMeta meta = null; try { ByteBuf metaBytes = bb.readSlice(metaLen); ByteBufInputStream is = new ByteBufInputStream(metaBytes); meta = RpcMeta.parseFrom(is); } catch (Exception e) { throw new RuntimeException("decode_meta_error"); } if (meta.getDirection() == RpcMeta.Direction.INVALID_DIRECTION) { throw new RuntimeException("package_direction_error"); } if (meta.getServiceId() < 1) { throw new RuntimeException("package_serviceId_error"); } if (meta.getMsgId() < 1) { throw new RuntimeException("package_msgId_error"); } return meta; }
Example #26
Source File: BookkeeperCommitLog.java From herddb with Apache License 2.0 | 5 votes |
private LogEntry readLogEntry(org.apache.bookkeeper.client.api.LedgerEntry e) throws IOException { LogEntry statusEdit; try (InputStream entryData = new ByteBufInputStream(e.getEntryBuffer(), false /* * releaseOnClose */); ExtendedDataInputStream in = new ExtendedDataInputStream(entryData)) { statusEdit = LogEntry.deserialize(in); } return statusEdit; }
Example #27
Source File: BlockEntityDataSerializer_v332.java From Protocol with Apache License 2.0 | 5 votes |
@Override public void deserialize(ByteBuf buffer, BlockEntityDataPacket packet) { packet.setBlockPosition(BedrockUtils.readBlockPosition(buffer)); try (NBTInputStream reader = NbtUtils.createNetworkReader(new ByteBufInputStream(buffer))) { packet.setData(reader.readTag()); } catch (IOException e) { throw new RuntimeException(e); } }
Example #28
Source File: ArmeriaServerCallTest.java From armeria with Apache License 2.0 | 5 votes |
@Test public void messageReadAfterClose_stream() { call.close(Status.ABORTED, new Metadata()); // messageRead is always called from the event loop. eventLoop.get().submit(() -> { call.messageRead(new DeframedMessage(new ByteBufInputStream(GrpcTestUtil.requestByteBuf(), true), 0)); verify(listener, never()).onMessage(any()); }).syncUninterruptibly(); }
Example #29
Source File: AmqpJmsBytesMessageFacadeTest.java From qpid-jms with Apache License 2.0 | 5 votes |
private InputStream substituteMockInputStream(AmqpJmsBytesMessageFacade bytesMessage) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { InputStream mock = Mockito.mock(ByteBufInputStream.class); Field ishField = bytesMessage.getClass().getDeclaredField("bytesIn"); ishField.setAccessible(true); ishField.set(bytesMessage, mock); return mock; }
Example #30
Source File: GeoWaveRedisRowCodec.java From geowave with Apache License 2.0 | 5 votes |
@Override public Object decode(final ByteBuf buf, final State state) throws IOException { try (final ByteBufInputStream in = new ByteBufInputStream(buf)) { final byte[] dataId = new byte[in.readUnsignedByte()]; final byte[] fieldMask = new byte[in.readUnsignedByte()]; final byte[] visibility; if (visibilityEnabled) { visibility = new byte[in.readUnsignedByte()]; } else { visibility = new byte[0]; } final byte[] value = new byte[Varint.readUnsignedVarInt(in)]; final int numDuplicates = in.readUnsignedByte(); if ((dataId.length > 0) && (in.read(dataId) != dataId.length)) { LOGGER.warn("unable to read data ID"); } if ((fieldMask.length > 0) && (in.read(fieldMask) != fieldMask.length)) { LOGGER.warn("unable to read fieldMask"); } if (visibilityEnabled && (visibility.length > 0) && (in.read(visibility) != visibility.length)) { LOGGER.warn("unable to read visibility"); } if ((value.length > 0) && (in.read(value) != value.length)) { LOGGER.warn("unable to read value"); } return new GeoWaveRedisPersistedRow( (short) numDuplicates, dataId, new GeoWaveValueImpl(fieldMask, visibility, value), in.available() > 0 ? (short) in.readUnsignedByte() : null); } }