List of usage examples for io.netty.buffer ByteBufOutputStream ByteBufOutputStream
public ByteBufOutputStream(ByteBuf buffer)
From source file:com.ebay.jetstream.http.netty.client.HttpClient.java
License:MIT License
public void post(URI uri, Object content, Map<String, String> headers, ResponseFuture responsefuture) throws Exception { if (m_shutDown.get()) { throw new IOException("IO has been Shutdown = "); }// w w w . j a v a 2 s. co m if (uri == null) throw new NullPointerException("uri is null or incorrect"); if (!m_started.get()) { synchronized (this) { if (!m_started.get()) { start(); m_started.set(true); } } } ByteBuf byteBuf = Unpooled.buffer(m_config.getInitialRequestBufferSize()); ByteBufOutputStream outputStream = new ByteBufOutputStream(byteBuf); // transform to json try { m_mapper.writeValue(outputStream, content); } catch (JsonGenerationException e) { throw e; } catch (JsonMappingException e) { throw e; } catch (IOException e) { throw e; } finally { outputStream.close(); } EmbeddedChannel encoder; String contenteEncoding; if ("gzip".equals(m_config.getCompressEncoder())) { encoder = new EmbeddedChannel(ZlibCodecFactory.newZlibEncoder(ZlibWrapper.GZIP, 1)); contenteEncoding = "gzip"; } else if ("deflate".equals(m_config.getCompressEncoder())) { encoder = new EmbeddedChannel(ZlibCodecFactory.newZlibEncoder(ZlibWrapper.ZLIB, 1)); contenteEncoding = "deflate"; } else { encoder = null; contenteEncoding = null; } if (encoder != null) { encoder.config().setAllocator(UnpooledByteBufAllocator.DEFAULT); encoder.writeOutbound(byteBuf); encoder.finish(); byteBuf = (ByteBuf) encoder.readOutbound(); encoder.close(); } DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uri.toString(), byteBuf); if (contenteEncoding != null) { HttpHeaders.setHeader(request, HttpHeaders.Names.CONTENT_ENCODING, contenteEncoding); } HttpHeaders.setHeader(request, HttpHeaders.Names.ACCEPT_ENCODING, "gzip, deflate"); HttpHeaders.setHeader(request, HttpHeaders.Names.CONTENT_TYPE, "application/json"); HttpHeaders.setContentLength(request, byteBuf.readableBytes()); if (isKeepAlive()) HttpHeaders.setHeader(request, HttpHeaders.Names.CONNECTION, "keep-alive"); if (headers != null) { @SuppressWarnings("rawtypes") Iterator it = headers.entrySet().iterator(); while (it.hasNext()) { @SuppressWarnings("rawtypes") Map.Entry pairs = (Map.Entry) it.next(); HttpHeaders.setHeader(request, (String) pairs.getKey(), pairs.getValue()); } } if (responsefuture != null) { RequestId reqid = RequestId.newRequestId(); m_responseDispatcher.add(reqid, responsefuture); HttpHeaders.setHeader(request, "X_EBAY_REQ_ID", reqid.toString()); // we expect this to be echoed in the response used for correlation. } if (m_dataQueue.size() < m_workQueueCapacity) { ProcessHttpWorkRequest workRequest = new ProcessHttpWorkRequest(this, uri, request); if (!m_dataQueue.offer(workRequest)) { if (responsefuture != null) { responsefuture.setFailure(); m_responseDispatcher.remove(request.headers().get("X_EBAY_REQ_ID")); } } } else { throw new IOException("downstream Queue is full "); } }
From source file:com.ebay.jetstream.http.netty.server.DefaultHttpServletResponse.java
License:MIT License
private void initOutputstream() { if (m_writer == null) { m_bufStream = new ByteBufOutputStream(m_buffer); m_writer = new PrintWriter(m_bufStream); m_servletOutputStream = new JetstreamServletOutputStream(m_bufStream); }// w w w . ja v a 2s .c o m }
From source file:com.ebay.jetstream.messaging.transport.netty.serializer.KryoObjectEncoder.java
License:MIT License
@Override protected void encode(ChannelHandlerContext ctx, Serializable msg, ByteBuf out) throws Exception { KryoContext kryoContext = kryoContextHolder.get(); Kryo kryo = kryoContext.getKryo();// w ww . j a va 2s . com 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); }
From source file:com.eucalyptus.ws.handlers.IoSoapMarshallingHandler.java
License:Open Source License
@Override public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) throws Exception { if (msg instanceof IoMessage) { final IoMessage ioMessage = (IoMessage) msg; final FullHttpMessage httpMessage = ioMessage.getHttpMessage(); final ByteBuf buffer = httpMessage.content().clear(); try (final ByteBufOutputStream out = new ByteBufOutputStream(buffer); final LockResource lockResource = LockResource.lock(HoldMe.canHas)) { ioMessage.getSoapEnvelope().serialize(out); //HACK: does this need fixing for xml brokeness? }//w w w . ja v a 2 s. c o m httpMessage.headers().add(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(buffer.readableBytes())); httpMessage.headers().add(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=UTF-8"); } super.write(ctx, msg, promise); }
From source file:com.example.grpc.server.PrometheusServer.java
License:Apache License
public void start() { final ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() { @Override/*from w ww . j ava 2s .c o m*/ protected void initChannel(SocketChannel socketChannel) throws Exception { ChannelPipeline pipeline = socketChannel.pipeline(); pipeline.addLast("decoder", new HttpRequestDecoder()); pipeline.addLast("encoder", new HttpResponseEncoder()); pipeline.addLast("prometheus", new SimpleChannelInboundHandler<Object>() { @Override protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception { if (!(o instanceof HttpRequest)) { return; } HttpRequest request = (HttpRequest) o; if (!"/metrics".equals(request.uri())) { final FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND); channelHandlerContext.writeAndFlush(response) .addListener(ChannelFutureListener.CLOSE); return; } if (!HttpMethod.GET.equals(request.method())) { final FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_ACCEPTABLE); channelHandlerContext.writeAndFlush(response) .addListener(ChannelFutureListener.CLOSE); return; } ByteBuf buf = Unpooled.buffer(); ByteBufOutputStream os = new ByteBufOutputStream(buf); OutputStreamWriter writer = new OutputStreamWriter(os); TextFormat.write004(writer, registry.metricFamilySamples()); writer.close(); os.close(); final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf); response.headers().set(HttpHeaderNames.CONTENT_TYPE, TextFormat.CONTENT_TYPE_004); channelHandlerContext.writeAndFlush(response) .addListener(ChannelFutureListener.CLOSE); } }); } }); try { this.channel = bootstrap.bind(this.port).sync().channel(); } catch (InterruptedException e) { // do nothing } }
From source file:com.heliosapm.streams.json.JSONOps.java
License:Apache License
/** * 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//w w w. j ava 2 s.c o m */ 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; }
From source file:com.heliosapm.streams.json.JSONOps.java
License:Apache License
/** * 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//from ww w . ja v a 2s . c om */ 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; }
From source file:com.heliosapm.streams.json.JSONOps.java
License:Apache License
/** * Serializes the passed object to an off-heap buffer and returns an InputStream to read it back * @param obj The object to serialize//from w w w .jav a 2 s . c om * @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 */} } }; }
From source file:com.heliosapm.streams.metrichub.RequestBuilder.java
License:Apache License
/** * Renders the whole JSON query except the tsuids and closers to post the request * @return the query json header doc//from www . jav a 2 s . c om */ public JsonGenerator renderHeader() { OutputStream os = null; try { final ByteBuf header = BufferManager.getInstance().buffer(1024); os = new ByteBufOutputStream(header); JsonGenerator jg = JSON.getFactory().createGenerator(os); jg.writeStartObject(); // start of request // write start and end times startT(jg); endT(jg); // Other request options if (!includeAnnotations) jg.writeBooleanField("no_annotations", true); if (includeGlobalAnnotations) jg.writeBooleanField("global_annotations", true); if (msResolution) jg.writeBooleanField("ms", true); if (includeTsuids) jg.writeBooleanField("show_tsuids", true); if (showSummary) jg.writeBooleanField("show_summary", true); if (showQuery) jg.writeBooleanField("show_query", true); if (deletion) jg.writeBooleanField("delete", true); jg.writeArrayFieldStart("queries"); // jg.writeStartObject(); // start of query // jg.flush(); // os.flush(); // jg.writeEndArray(); // end of tsuids array // jg.writeEndObject(); // end of query return jg; } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:com.heliosapm.tsdblite.json.JSON.java
License:Apache License
/** * Serializes the passed object as JSON into the passed buffer * @param obj The object to serialize//from w w w . j a va2 s . c o m * @param buf The buffer to serialize into. If null, a new buffer is created * @return The buffer the object was written to */ public static ByteBuf serializeToBuf(final Object obj, final ByteBuf buf) { if (obj == null) throw new IllegalArgumentException("The passed object was null"); final ByteBuf b = buf == null ? Unpooled.directBuffer(2048) : buf; OutputStream os = null; try { os = new ByteBufOutputStream(b); serialize(obj, os); os.flush(); return b; } catch (Exception ex) { throw new RuntimeException("Failed to bufferize serialized object", ex); } finally { if (os != null) try { os.close(); } catch (Exception x) { /* No Op */} } }