List of usage examples for io.netty.buffer ByteBufInputStream ByteBufInputStream
public ByteBufInputStream(ByteBuf buffer)
From source file:com.spotify.ffwd.riemann.RiemannSerialization.java
License:Apache License
public Proto.Msg parse0(ByteBuf buffer) throws IOException { final InputStream inputStream = new ByteBufInputStream(buffer); try {/*from w w w . j a va 2 s . co m*/ return Proto.Msg.parseFrom(inputStream); } catch (final InvalidProtocolBufferException e) { throw new IOException("Invalid protobuf message", e); } }
From source file:com.spotify.heroic.rpc.nativerpc.NativeRpcDecoder.java
License:Apache License
@Override protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) throws Exception { final int length = in.readableBytes(); if (length == 0) { return;//from ww w . j ava2 s . c om } try (final ByteBufInputStream stream = new ByteBufInputStream(in)) { final Unpacker unpacker = messagePack.createUnpacker(stream); final byte type = unpacker.readByte(); switch (type) { case NativeRpc.HEARTBEAT: out.add(NativeRpcHeartBeat.unpack(unpacker)); return; case NativeRpc.REQUEST: out.add(NativeRpcRequest.unpack(unpacker)); return; case NativeRpc.RESPONSE: out.add(NativeRpcResponse.unpack(unpacker)); return; case NativeRpc.ERR_RESPONSE: out.add(NativeRpcError.unpack(unpacker)); return; default: throw new IllegalArgumentException("Invalid RPC message type: " + type); } } }
From source file:com.tencent.mars.proxy.NetMsgHeaderHandler.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { try {//from ww w . j a v a 2 s. c om // decode request final NetMsgHeader msgXp = new NetMsgHeader(); final InputStream socketInput = new ByteBufInputStream((ByteBuf) msg); boolean ret = msgXp.decode(socketInput); IOUtils.closeQuietly(socketInput); if (!ret) return; linkTimeout.remove(ctx); linkTimeout.put(ctx, System.currentTimeMillis()); logger.info(LogUtils.format("client req, cmdId=%d, seq=%d", msgXp.cmdId, msgXp.seq)); final ProxySession proxySession = ProxySession.Manager.get(ctx); if (proxySession == null) { } String webCgi = CMD_PATH_MAP.get(msgXp.cmdId); switch (msgXp.cmdId) { case Main.CmdID.CMD_ID_HELLO_VALUE: InputStream requestDataStream = new ByteArrayInputStream(msgXp.body); InputStream inputStream = doHttpRequest(webCgi, requestDataStream); if (inputStream != null) { msgXp.body = IOUtils.toByteArray(inputStream); IOUtils.closeQuietly(requestDataStream); byte[] respBuf = msgXp.encode(); logger.info(LogUtils.format("client resp, cmdId=%d, seq=%d, resp.len=%d", msgXp.cmdId, msgXp.seq, msgXp.body == null ? 0 : msgXp.body.length)); ctx.writeAndFlush(ctx.alloc().buffer().writeBytes(respBuf)); } else { } break; case Main.CmdID.CMD_ID_SEND_MESSAGE_VALUE: requestDataStream = new ByteArrayInputStream(msgXp.body); inputStream = doHttpRequest(webCgi, requestDataStream); if (inputStream != null) { msgXp.body = IOUtils.toByteArray(inputStream); Chat.SendMessageResponse response = Chat.SendMessageResponse.parseFrom(msgXp.body); if (response != null && response.getErrCode() == Chat.SendMessageResponse.Error.ERR_OK_VALUE) { TopicChats.getInstance().pushMessage(response.getTopic(), response.getText(), response.getFrom(), ctx); } IOUtils.closeQuietly(requestDataStream); byte[] respBuf = msgXp.encode(); logger.info(LogUtils.format("client resp, cmdId=%d, seq=%d, resp.len=%d", msgXp.cmdId, msgXp.seq, msgXp.body == null ? 0 : msgXp.body.length)); ctx.writeAndFlush(ctx.alloc().buffer().writeBytes(respBuf)); } else { } break; case NetMsgHeader.CMDID_NOOPING: byte[] respBuf = msgXp.encode(); logger.info(LogUtils.format("client resp, cmdId=%d, seq=%d, resp.len=%d", msgXp.cmdId, msgXp.seq, msgXp.body == null ? 0 : msgXp.body.length)); ctx.writeAndFlush(ctx.alloc().buffer().writeBytes(respBuf)); break; default: break; } } catch (Exception e) { e.printStackTrace(); } finally { ReferenceCountUtil.release(msg); } }
From source file:com.twitter.http2.HttpHeaderBlockDecoder.java
License:Apache License
public void decode(ByteBuf headerBlock, final HttpHeaderBlockFrame frame) throws IOException { HeaderListener headerListener = NULL_HEADER_LISTENER; if (frame != null) { headerListener = new HeaderListenerImpl(frame.headers()); }//from w w w . j ava2s. com if (cumulation == null) { decoder.decode(new ByteBufInputStream(headerBlock), headerListener); if (headerBlock.isReadable()) { cumulation = Unpooled.buffer(headerBlock.readableBytes()); cumulation.writeBytes(headerBlock); } } else { cumulation.writeBytes(headerBlock); decoder.decode(new ByteBufInputStream(cumulation), headerListener); if (cumulation.isReadable()) { cumulation.discardReadBytes(); } else { cumulation.release(); cumulation = null; } } }
From source file:com.yy.httpproxy.emitter.JsonJacksonCodecWithClass.java
License:Apache License
public JsonJacksonCodecWithClass(final Class clazz) { decoder = new Decoder<Object>() { @Override// w w w .j a va 2s. co m public Object decode(ByteBuf buf, State state) throws IOException { return mapObjectMapper.readValue(new ByteBufInputStream(buf), clazz); } }; init(mapObjectMapper); // type info inclusion TypeResolverBuilder<?> mapTyper = new DefaultTypeResolverBuilder(DefaultTyping.NON_FINAL) { public boolean useForType(JavaType t) { switch (_appliesFor) { case NON_CONCRETE_AND_ARRAYS: while (t.isArrayType()) { t = t.getContentType(); } // fall through case OBJECT_AND_NON_CONCRETE: return (t.getRawClass() == Object.class) || !t.isConcrete(); case NON_FINAL: while (t.isArrayType()) { t = t.getContentType(); } // to fix problem with wrong long to int conversion if (t.getRawClass() == Long.class) { return true; } return !t.isFinal(); // includes Object.class default: //case JAVA_LANG_OBJECT: return (t.getRawClass() == Object.class); } } }; mapTyper.init(JsonTypeInfo.Id.CLASS, null); mapTyper.inclusion(JsonTypeInfo.As.PROPERTY); mapObjectMapper.setDefaultTyping(mapTyper); }
From source file:com.zaradai.distributor.messaging.netty.handler.MessageDecoder.java
License:Apache License
private void readEvent(Message res, ByteBuf frame) throws EncodingException { try {//w w w . java2s .co m ByteBufInputStream in = new ByteBufInputStream(frame); res.setEvent(serializer.deserialize(in)); } catch (Exception e) { throw new EncodingException("Unable to read event", e); } }
From source file:de.sanandrew.core.manpack.network.PacketProcessor.java
License:Creative Commons License
public void processPacket(ByteBuf data, INetHandler handler) { short packetId = -1; try (ByteBufInputStream bbis = new ByteBufInputStream(data)) { packetId = bbis.readShort();//w w w .j av a 2 s . com if (this.packetMap.containsKey(packetId)) { this.packetMap.get(packetId).getConstructor().newInstance().process(bbis, data, handler); } } catch (IOException ioe) { ManPackLoadingPlugin.MOD_LOG.log(Level.ERROR, "The packet with the ID %d from %s cannot be processed!", packetId, this.modId); ioe.printStackTrace(); } catch (IllegalAccessException | InstantiationException rex) { ManPackLoadingPlugin.MOD_LOG.log(Level.ERROR, "The packet with the ID %d from %s cannot be instantiated!", packetId, this.modId); rex.printStackTrace(); } catch (NoSuchMethodException | InvocationTargetException e) { e.printStackTrace(); } }
From source file:de.sanandrew.mods.particledeco.network.PacketProcessor.java
License:Creative Commons License
public static void processPacket(ByteBuf data, Side side, INetHandler handler) { short packetId = -1; try (ByteBufInputStream bbis = new ByteBufInputStream(data)) { packetId = bbis.readShort();/*from w w w .jav a2 s. c o m*/ if (ID_TO_PACKET_MAP_.containsKey(packetId)) { IPacket pktInst = ID_TO_PACKET_MAP_.get(packetId).newInstance(); pktInst.process(bbis, data, handler); } } catch (IOException ioe) { FMLLog.log(PDM_Main.MOD_LOG, Level.ERROR, "The packet with the ID %d cannot be processed!", packetId); ioe.printStackTrace(); } catch (IllegalAccessException | InstantiationException rex) { FMLLog.log(PDM_Main.MOD_LOG, Level.ERROR, "The packet with the ID %d cannot be instantiated!", packetId); rex.printStackTrace(); } }
From source file:discord4j.voice.VoiceGatewayClient.java
License:Open Source License
private Mono<Void> handle(WebsocketInbound in, WebsocketOutbound out) { Mono<Void> inboundThen = in.aggregateFrames().receiveFrames().map(WebSocketFrame::content) .flatMap(buf -> Mono.fromCallable(() -> mapper.readValue((InputStream) new ByteBufInputStream(buf), VoiceGatewayPayload.class))) .doOnNext(gatewayFSM::onEvent).then(); Mono<Void> outboundThen = out.options(NettyPipeline.SendOptions::flushOnEach) .sendObject(sender.flatMap(payload -> Mono.fromCallable( () -> new TextWebSocketFrame(Unpooled.wrappedBuffer(mapper.writeValueAsBytes(payload)))))) .then();//from ww w .j av a 2 s. c o m return Mono.zip(inboundThen, outboundThen).then(); }
From source file:divconq.net.ssl.JdkSslClientContext.java
License:Apache License
public JdkSslClientContext(File certChainFile, TrustManagerFactory trustManagerFactory, Iterable<String> ciphers, Iterable<String> nextProtocols, long sessionCacheSize, long sessionTimeout) throws SSLException { super(ciphers); if (nextProtocols != null && nextProtocols.iterator().hasNext()) { throw new SSLException("NPN/ALPN unsupported: " + nextProtocols); } else {/*from w ww .ja v a 2 s . c o m*/ this.nextProtocols = Collections.emptyList(); } try { if (certChainFile == null) { ctx = SSLContext.getInstance(PROTOCOL); if (trustManagerFactory == null) { ctx.init(null, null, null); } else { trustManagerFactory.init((KeyStore) null); ctx.init(null, trustManagerFactory.getTrustManagers(), null); } } else { KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, null); CertificateFactory cf = CertificateFactory.getInstance("X.509"); ByteBuf[] certs = PemReader.readCertificates(certChainFile); try { for (ByteBuf buf : certs) { X509Certificate cert = (X509Certificate) cf .generateCertificate(new ByteBufInputStream(buf)); X500Principal principal = cert.getSubjectX500Principal(); ks.setCertificateEntry(principal.getName("RFC2253"), cert); } } finally { for (ByteBuf buf : certs) { buf.release(); } } // Set up trust manager factory to use our key store. if (trustManagerFactory == null) { trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); } trustManagerFactory.init(ks); // Initialize the SSLContext to work with the trust managers. ctx = SSLContext.getInstance(PROTOCOL); ctx.init(null, trustManagerFactory.getTrustManagers(), null); } SSLSessionContext sessCtx = ctx.getClientSessionContext(); if (sessionCacheSize > 0) { sessCtx.setSessionCacheSize((int) Math.min(sessionCacheSize, Integer.MAX_VALUE)); } if (sessionTimeout > 0) { sessCtx.setSessionTimeout((int) Math.min(sessionTimeout, Integer.MAX_VALUE)); } } catch (Exception e) { throw new SSLException("failed to initialize the server-side SSL context", e); } }