Example usage for io.netty.buffer ByteBufOutputStream ByteBufOutputStream

List of usage examples for io.netty.buffer ByteBufOutputStream ByteBufOutputStream

Introduction

In this page you can find the example usage for io.netty.buffer ByteBufOutputStream ByteBufOutputStream.

Prototype

public ByteBufOutputStream(ByteBuf buffer) 

Source Link

Document

Creates a new stream which writes data to the specified buffer .

Usage

From source file:com.mastfrog.scamper.Sender.java

License:Open Source License

/**
 * Send a message using the passed channel.
 *
 * @param channel The channel//from  w w w . j  a v  a2  s. c  o  m
 * @param message A future which will be notified when the message is
 * flushed to the socket
 * @param sctpChannel The ordinal of the sctp channel
 * @return a future that will be notified when the message write is
 * completed
 * @throws IOException if something goes wrong
 */
@SuppressWarnings("unchecked")
public ChannelFuture send(Channel channel, final Message<?> message, int sctpChannel) throws IOException {
    Checks.notNull("channel", channel);
    Checks.notNull("message", message);
    Checks.nonNegative("sctpChannel", sctpChannel);
    ByteBufAllocator alloc = channel.alloc();
    ByteBuf outbound = alloc.buffer();
    if (message.body != null) {
        if (message.body instanceof ByteBuf) {
            outbound = (ByteBuf) message.body;
        } else {
            outbound = alloc.buffer();
            try (ByteBufOutputStream out = new ByteBufOutputStream(outbound)) {
                mapper.writeValue(message.body, out);
            }
        }
    }
    ByteBuf encodedBuffer = encoder.encode(message.type, outbound, channel);
    NioSctpChannel ch = (NioSctpChannel) channel;
    if (!ch.isOpen()) {
        return ch.newFailedFuture(new ClosedChannelException());
    }
    if (ch.association() == null) {
        return channel.newFailedFuture(new IOException("Association closed - client has disconnected"));
    }
    MessageInfo info = MessageInfo.createOutgoing(ch.association(), ch.remoteAddress(), sctpChannel);
    info.unordered(true);

    SctpMessage sctpMessage = new SctpMessage(info, encodedBuffer);
    logger.log(Level.FINE, "Send message to {0} type {1}",
            new Object[] { channel.remoteAddress(), message.type });
    ChannelFuture result = channel.writeAndFlush(sctpMessage);
    if (logger.isLoggable(Level.FINER)) {
        result.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.cause() != null) {
                    logger.log(Level.SEVERE, "Send to " + ch.remoteAddress() + " failed", future.cause());
                } else {
                    logger.log(Level.FINER, "Send completed to {0}", ch.remoteAddress());
                }
            }

        });
    }
    return result;
}

From source file:com.navercorp.redis.cluster.connection.RedisConnectionAsync.java

License:Open Source License

RedisConnectionAsync() {
    outputBuf = ALLOCATOR.buffer();
    outputStream = new RedisOutputStream(new ByteBufOutputStream(outputBuf));
}

From source file:com.ning.http.client.providers.netty_4.NettyAsyncHttpProvider.java

License:Apache License

private static HttpRequest construct(AsyncHttpClientConfig config, Request request, HttpMethod m, URI uri,
        ByteBuf buffer, ProxyServer proxyServer) throws IOException {

    String host = AsyncHttpProviderUtils.getHost(uri);
    boolean webSocket = isWebSocket(uri);

    if (request.getVirtualHost() != null) {
        host = request.getVirtualHost();
    }/*w  w w  .  j  av  a 2s. c o m*/

    FullHttpRequest nettyRequest;
    if (m.equals(HttpMethod.CONNECT)) {
        nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, m,
                AsyncHttpProviderUtils.getAuthority(uri));
    } else {
        String path = null;
        if (proxyServer != null && !(isSecure(uri) && config.isUseRelativeURIsWithSSLProxies()))
            path = uri.toString();
        else if (uri.getRawQuery() != null)
            path = uri.getRawPath() + "?" + uri.getRawQuery();
        else
            path = uri.getRawPath();
        nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, m, path);
    }

    if (webSocket) {
        nettyRequest.headers().add(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET);
        nettyRequest.headers().add(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE);
        nettyRequest.headers().add("Origin", "http://" + uri.getHost() + ":"
                + (uri.getPort() == -1 ? isSecure(uri.getScheme()) ? 443 : 80 : uri.getPort()));
        nettyRequest.headers().add(WEBSOCKET_KEY, WebSocketUtil.getKey());
        nettyRequest.headers().add("Sec-WebSocket-Version", "13");
    }

    if (host != null) {
        if (uri.getPort() == -1) {
            nettyRequest.headers().set(HttpHeaders.Names.HOST, host);
        } else if (request.getVirtualHost() != null) {
            nettyRequest.headers().set(HttpHeaders.Names.HOST, host);
        } else {
            nettyRequest.headers().set(HttpHeaders.Names.HOST, host + ":" + uri.getPort());
        }
    } else {
        host = "127.0.0.1";
    }

    if (!m.equals(HttpMethod.CONNECT)) {
        FluentCaseInsensitiveStringsMap h = request.getHeaders();
        if (h != null) {
            for (String name : h.keySet()) {
                if (!"host".equalsIgnoreCase(name)) {
                    for (String value : h.get(name)) {
                        nettyRequest.headers().add(name, value);
                    }
                }
            }
        }

        if (config.isCompressionEnabled()) {
            nettyRequest.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
        }
    } else {
        List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION);
        if (isNonEmpty(auth) && auth.get(0).startsWith("NTLM")) {
            nettyRequest.headers().add(HttpHeaders.Names.PROXY_AUTHORIZATION, auth.get(0));
        }
    }
    Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();

    if (realm != null && realm.getUsePreemptiveAuth()) {

        String domain = realm.getNtlmDomain();
        if (proxyServer != null && proxyServer.getNtlmDomain() != null) {
            domain = proxyServer.getNtlmDomain();
        }

        String authHost = realm.getNtlmHost();
        if (proxyServer != null && proxyServer.getHost() != null) {
            host = proxyServer.getHost();
        }

        switch (realm.getAuthScheme()) {
        case BASIC:
            nettyRequest.headers().set(HttpHeaders.Names.AUTHORIZATION,
                    AuthenticatorUtils.computeBasicAuthentication(realm));
            break;
        case DIGEST:
            if (isNonEmpty(realm.getNonce())) {
                try {
                    nettyRequest.headers().set(HttpHeaders.Names.AUTHORIZATION,
                            AuthenticatorUtils.computeDigestAuthentication(realm));
                } catch (NoSuchAlgorithmException e) {
                    throw new SecurityException(e);
                }
            }
            break;
        case NTLM:
            try {
                String msg = ntlmEngine.generateType1Msg("NTLM " + domain, authHost);
                nettyRequest.headers().set(HttpHeaders.Names.AUTHORIZATION, "NTLM " + msg);
            } catch (NTLMEngineException e) {
                IOException ie = new IOException();
                ie.initCause(e);
                throw ie;
            }
            break;
        case KERBEROS:
        case SPNEGO:
            String challengeHeader = null;
            String server = proxyServer == null ? host : proxyServer.getHost();
            try {
                challengeHeader = getSpnegoEngine().generateToken(server);
            } catch (Throwable e) {
                IOException ie = new IOException();
                ie.initCause(e);
                throw ie;
            }
            nettyRequest.headers().set(HttpHeaders.Names.AUTHORIZATION, "Negotiate " + challengeHeader);
            break;
        case NONE:
            break;
        default:
            throw new IllegalStateException("Invalid Authentication " + realm);
        }
    }

    if (!webSocket && !request.getHeaders().containsKey(HttpHeaders.Names.CONNECTION)) {
        nettyRequest.headers().set(HttpHeaders.Names.CONNECTION,
                AsyncHttpProviderUtils.keepAliveHeaderValue(config));
    }

    if (proxyServer != null) {
        if (!request.getHeaders().containsKey("Proxy-Connection")) {
            nettyRequest.headers().set("Proxy-Connection", AsyncHttpProviderUtils.keepAliveHeaderValue(config));
        }

        if (proxyServer.getPrincipal() != null) {
            if (isNonEmpty(proxyServer.getNtlmDomain())) {

                List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION);
                if (!(isNonEmpty(auth) && auth.get(0).startsWith("NTLM"))) {
                    try {
                        String msg = ntlmEngine.generateType1Msg(proxyServer.getNtlmDomain(),
                                proxyServer.getHost());
                        nettyRequest.headers().set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + msg);
                    } catch (NTLMEngineException e) {
                        IOException ie = new IOException();
                        ie.initCause(e);
                        throw ie;
                    }
                }
            } else {
                nettyRequest.headers().set(HttpHeaders.Names.PROXY_AUTHORIZATION,
                        AuthenticatorUtils.computeBasicAuthentication(proxyServer));
            }
        }
    }

    // Add default accept headers.
    if (request.getHeaders().getFirstValue("Accept") == null) {
        nettyRequest.headers().set(HttpHeaders.Names.ACCEPT, "*/*");
    }

    if (request.getHeaders().getFirstValue("User-Agent") != null) {
        nettyRequest.headers().set("User-Agent", request.getHeaders().getFirstValue("User-Agent"));
    } else if (config.getUserAgent() != null) {
        nettyRequest.headers().set("User-Agent", config.getUserAgent());
    } else {
        nettyRequest.headers().set("User-Agent",
                AsyncHttpProviderUtils.constructUserAgent(NettyAsyncHttpProvider.class, config));
    }

    if (!m.equals(HttpMethod.CONNECT)) {
        if (isNonEmpty(request.getCookies())) {
            CookieEncoder httpCookieEncoder = new CookieEncoder(false);
            Iterator<Cookie> ic = request.getCookies().iterator();
            Cookie c;
            org.jboss.netty.handler.codec.http.Cookie cookie;
            while (ic.hasNext()) {
                c = ic.next();
                cookie = new DefaultCookie(c.getName(), c.getValue());
                cookie.setPath(c.getPath());
                cookie.setMaxAge(c.getMaxAge());
                cookie.setDomain(c.getDomain());
                httpCookieEncoder.addCookie(cookie);
            }
            nettyRequest.headers().set(HttpHeaders.Names.COOKIE, httpCookieEncoder.encode());
        }

        String reqType = request.getMethod();
        if (!"HEAD".equals(reqType) && !"OPTION".equals(reqType) && !"TRACE".equals(reqType)) {

            String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET
                    : request.getBodyEncoding();

            // We already have processed the body.
            if (buffer != null && buffer.writerIndex() != 0) {
                nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, buffer.writerIndex());
                nettyRequest.setContent(buffer);
            } else if (request.getByteData() != null) {
                nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH,
                        String.valueOf(request.getByteData().length));
                nettyRequest.setContent(Unpooled.wrappedBuffer(request.getByteData()));
            } else if (request.getStringData() != null) {
                nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH,
                        String.valueOf(request.getStringData().getBytes(bodyCharset).length));
                nettyRequest.setContent(Unpooled.wrappedBuffer(request.getStringData().getBytes(bodyCharset)));
            } else if (request.getStreamData() != null) {
                int[] lengthWrapper = new int[1];
                byte[] bytes = AsyncHttpProviderUtils.readFully(request.getStreamData(), lengthWrapper);
                int length = lengthWrapper[0];
                nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(length));
                nettyRequest.setContent(Unpooled.wrappedBuffer(bytes, 0, length));
            } else if (isNonEmpty(request.getParams())) {
                StringBuilder sb = new StringBuilder();
                for (final Entry<String, List<String>> paramEntry : request.getParams()) {
                    final String key = paramEntry.getKey();
                    for (final String value : paramEntry.getValue()) {
                        if (sb.length() > 0) {
                            sb.append("&");
                        }
                        UTF8UrlEncoder.appendEncoded(sb, key);
                        sb.append("=");
                        UTF8UrlEncoder.appendEncoded(sb, value);
                    }
                }
                nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sb.length()));
                nettyRequest.setContent(Unpooled.wrappedBuffer(sb.toString().getBytes(bodyCharset)));

                if (!request.getHeaders().containsKey(HttpHeaders.Names.CONTENT_TYPE)) {
                    nettyRequest.headers().set(HttpHeaders.Names.CONTENT_TYPE,
                            "application/x-www-form-urlencoded");
                }

            } else if (request.getParts() != null) {
                int lenght = computeAndSetContentLength(request, nettyRequest);

                if (lenght == -1) {
                    lenght = MAX_BUFFERED_BYTES;
                }

                MultipartRequestEntity mre = AsyncHttpProviderUtils
                        .createMultipartRequestEntity(request.getParts(), request.getParams());

                nettyRequest.headers().set(HttpHeaders.Names.CONTENT_TYPE, mre.getContentType());
                nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH,
                        String.valueOf(mre.getContentLength()));

                /**
                 * TODO: AHC-78: SSL + zero copy isn't supported by the MultiPart class and pretty complex to implements.
                 */

                if (isSecure(uri)) {
                    ByteBuf b = Unpooled.buffer(lenght);
                    mre.writeRequest(new ByteBufOutputStream(b));
                    nettyRequest.setContent(b);
                }
            } else if (request.getEntityWriter() != null) {
                int lenght = computeAndSetContentLength(request, nettyRequest);

                if (lenght == -1) {
                    lenght = MAX_BUFFERED_BYTES;
                }

                ByteBuf b = Unpooled.buffer(lenght);
                request.getEntityWriter().writeEntity(new ByteBufOutputStream(b));
                nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, b.writerIndex());
                nettyRequest.setContent(b);
            } else if (request.getFile() != null) {
                File file = request.getFile();
                if (!file.isFile()) {
                    throw new IOException(
                            String.format("File %s is not a file or doesn't exist", file.getAbsolutePath()));
                }
                nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, file.length());
            }
        }
    }
    return nettyRequest;
}

From source file:com.openddal.server.ProtocolTransport.java

License:Apache License

public ProtocolTransport(Channel channel, ByteBuf in) {
    this.channel = channel;
    this.in = in;
    out = channel.alloc().buffer(DEFAULT_BUFFER_SIZE);
    input = new ByteBufInputStream(in);
    output = new ByteBufOutputStream(out);
}

From source file:com.soho.framework.server.servlet.impl.ServletOutputStreamImpl.java

License:Apache License

public ServletOutputStreamImpl(FullHttpResponse response) {
    this.response = response;
    this.out = new ByteBufOutputStream(response.content());
}

From source file:com.spotify.ffwd.riemann.RiemannResponder.java

License:Apache License

private ByteBuf ack(boolean ok) throws IOException {
    final Proto.Msg m = Proto.Msg.newBuilder().setOk(ok).build();

    final ByteBuf b = Unpooled.buffer();

    try (final ByteBufOutputStream output = new ByteBufOutputStream(b)) {
        m.writeTo(output);/*  w  ww .j a  v  a  2s  .com*/

        final ByteBuf frame = output.buffer();
        final ByteBuf buffer = Unpooled.buffer(4 + frame.readableBytes());

        buffer.writeInt(frame.readableBytes());
        buffer.writeBytes(frame);

        return buffer;
    } finally {
        b.release();
    }
}

From source file:com.spotify.ffwd.riemann.RiemannSerialization.java

License:Apache License

public ByteBuf encodeAll0(Collection<Object> messages) throws IOException {
    final Proto.Msg.Builder builder = Proto.Msg.newBuilder();

    for (final Object d : messages) {
        if (d instanceof Metric) {
            builder.addEvents(encodeMetric0((Metric) d));
        } else if (d instanceof Event) {
            builder.addEvents(encodeEvent0((Event) d));
        }/*from w ww  .  j a  v a 2s . c o m*/
    }

    final Proto.Msg m = builder.build();

    final ByteBuf work = Unpooled.buffer();

    try (final ByteBufOutputStream output = new ByteBufOutputStream(work)) {
        m.writeTo(output);

        final ByteBuf result = Unpooled.buffer();

        result.writeInt(work.writerIndex());
        result.writeBytes(work);

        return result;
    } finally {
        work.release();
    }
}

From source file:com.spotify.heroic.rpc.nativerpc.NativeRpcEncoder.java

License:Apache License

@Override
protected void encode(final ChannelHandlerContext ctx, final Object in, final ByteBuf out) throws Exception {
    try (final ByteBufOutputStream stream = new ByteBufOutputStream(out)) {
        try (final Packer packer = messagePack.createPacker(stream)) {
            if (in instanceof NativeRpcHeartBeat) {
                packer.write(NativeRpc.HEARTBEAT);
                NativeRpcHeartBeat.pack((NativeRpcHeartBeat) in, packer);
                return;
            }/*w w w .  ja v  a 2s  .co  m*/

            if (in instanceof NativeRpcRequest) {
                packer.write(NativeRpc.REQUEST);
                NativeRpcRequest.pack((NativeRpcRequest) in, packer);
                return;
            }

            if (in instanceof NativeRpcResponse) {
                packer.write(NativeRpc.RESPONSE);
                NativeRpcResponse.pack((NativeRpcResponse) in, packer);
                return;
            }

            if (in instanceof NativeRpcError) {
                packer.write(NativeRpc.ERR_RESPONSE);
                NativeRpcError.pack((NativeRpcError) in, packer);
                return;
            }
        }
    }

    throw new IllegalArgumentException("Unable to encode object: " + in);
}

From source file:com.twitter.http2.HttpHeaderBlockEncoder.java

License:Apache License

/**
 * Encode the header block frame./*w  w w. j av  a 2  s.  c o m*/
 */
public ByteBuf encode(ChannelHandlerContext ctx, HttpHeaderBlockFrame frame) throws IOException {
    ByteBuf buf = Unpooled.buffer();
    ByteBufOutputStream out = new ByteBufOutputStream(buf);

    // The current allowable max header table size is the
    // minimum of the encoder and decoder allowable sizes
    int allowableHeaderTableSize = Math.min(encoderMaxHeaderTableSize, decoderMaxHeaderTableSize);

    // maxHeaderTableSize will hold the smallest size seen the
    // last call to encode. This might be smaller than the
    // current allowable max header table size
    if (maxHeaderTableSize < allowableHeaderTableSize) {
        encoder.setMaxHeaderTableSize(out, maxHeaderTableSize);
    }

    // Check if the current allowable size is equal to the encoder's
    // capacity and set the new size if necessary
    if (allowableHeaderTableSize != encoder.getMaxHeaderTableSize()) {
        encoder.setMaxHeaderTableSize(out, allowableHeaderTableSize);
    }

    // Store the current allowable size for the next call
    maxHeaderTableSize = allowableHeaderTableSize;

    // Now we can encode headers
    for (String name : frame.headers().names()) {
        if ("cookie".equalsIgnoreCase(name)) {
            // Sec. 8.1.3.4. Cookie Header Field
            for (String value : frame.headers().getAll(name)) {
                for (String crumb : value.split(";")) {
                    byte[] valueBytes = crumb.trim().getBytes(StandardCharsets.UTF_8);
                    encoder.encodeHeader(out, COOKIE, valueBytes, true);
                }
            }
        } else {
            byte[] nameBytes = name.toLowerCase(Locale.ENGLISH).getBytes(StandardCharsets.UTF_8);
            // Sec. 8.1.3.3. Header Field Ordering
            List<String> values = frame.headers().getAll(name);
            if (values.size() == 0) {
                encoder.encodeHeader(out, nameBytes, EMPTY, false);
            } else {
                for (String value : values) {
                    byte[] valueBytes = value.getBytes(StandardCharsets.UTF_8);
                    encoder.encodeHeader(out, nameBytes, valueBytes, false);
                }
            }
        }
    }

    return buf;
}

From source file:com.zaradai.distributor.messaging.netty.handler.MessageEncoder.java

License:Apache License

private void writeEvent(Message msg, ByteBuf out) throws EncodingException {
    try {//  ww  w  .ja  va 2s .  c om
        ByteBufOutputStream outputStream = new ByteBufOutputStream(out);
        serializer.serialize(outputStream, msg.getEvent());
        outputStream.flush();
        outputStream.close();
    } catch (Exception e) {
        throw new EncodingException("Unable to encode event", e);
    }
}