Example usage for io.netty.buffer Unpooled buffer

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

Introduction

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

Prototype

public static ByteBuf buffer(int initialCapacity) 

Source Link

Document

Creates a new big-endian Java heap buffer with the specified capacity , which expands its capacity boundlessly on demand.

Usage

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();
    }//from www .  ja v a  2 s  .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.phei.netty.chapter4.fault.TimeClientHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) {
    ByteBuf message;/*w  ww.ja  v a 2 s  .co m*/
    for (int i = 0; i < 100; i++) {
        message = Unpooled.buffer(req.length);
        message.writeBytes(req);
        ctx.writeAndFlush(message);
    }
}

From source file:com.pubkit.platform.messaging.protocol.mqtt.proto.parser.PublishDecoder.java

License:Open Source License

@Override
void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws Exception {
    LOG.info("decode invoked with buffer {}", in);
    in.resetReaderIndex();// w  ww  .  j  ava  2  s  .  c  o  m
    int startPos = in.readerIndex();

    //Common decoding part
    PublishMessage message = new PublishMessage();
    if (!decodeCommonHeader(message, in)) {
        LOG.info("decode ask for more data after {}", in);
        in.resetReaderIndex();
        return;
    }

    if (Utils.isMQTT3_1_1(ctx)) {
        if (message.getQos() == AbstractMessage.QOSType.MOST_ONE && message.isDupFlag()) {
            //bad protocol, if QoS=0 => DUP = 0
            throw new CorruptedFrameException("Received a PUBLISH with QoS=0 & DUP = 1, MQTT 3.1.1 violation");
        }

        if (message.getQos() == AbstractMessage.QOSType.RESERVED) {
            throw new CorruptedFrameException(
                    "Received a PUBLISH with QoS flags setted 10 b11, MQTT 3.1.1 violation");
        }
    }

    int remainingLength = message.getRemainingLength();

    //Topic name
    String topic = Utils.decodeString(in);
    if (topic == null) {
        in.resetReaderIndex();
        return;
    }
    if (topic.contains("+") || topic.contains("#")) {
        throw new CorruptedFrameException(
                "Received a PUBLISH with topic containting wild card chars, topic: " + topic);
    }

    message.setTopicName(topic);

    if (message.getQos() == AbstractMessage.QOSType.LEAST_ONE
            || message.getQos() == AbstractMessage.QOSType.EXACTLY_ONCE) {
        message.setMessageID(in.readUnsignedShort());
    }
    int stopPos = in.readerIndex();

    //read the payload
    int payloadSize = remainingLength - (stopPos - startPos - 2)
            + (Utils.numBytesToEncode(remainingLength) - 1);
    if (in.readableBytes() < payloadSize) {
        in.resetReaderIndex();
        return;
    }
    //        byte[] b = new byte[payloadSize];
    ByteBuf bb = Unpooled.buffer(payloadSize);
    in.readBytes(bb);
    message.setPayload(bb.nioBuffer());

    out.add(message);
}

From source file:com.pubkit.platform.messaging.protocol.mqtt.proto.parser.Utils.java

License:Open Source License

/**
 * Return the IoBuffer with string encoded as MSB, LSB and UTF-8 encoded
 * string content./*from w  w  w  . java  2 s .  c o  m*/
 */
public static ByteBuf encodeString(String str) {
    ByteBuf out = Unpooled.buffer(2);
    byte[] raw;
    try {
        raw = str.getBytes("UTF-8");
        //NB every Java platform has got UTF-8 encoding by default, so this 
        //exception are never raised.
    } catch (UnsupportedEncodingException ex) {
        LoggerFactory.getLogger(Utils.class).error(null, ex);
        return null;
    }
    //Utils.writeWord(out, raw.length);
    out.writeShort(raw.length);
    out.writeBytes(raw);
    return out;
}

From source file:com.quavo.osrs.network.protocol.packet.encode.PacketEncoder.java

License:Open Source License

/**
 * Constructs a new object./*from ww w .  j ava  2  s .  co  m*/
 * 
 * @param packet The packet.
 * @param size The packet size.
 */
public PacketEncoder(PacketEncoderIdentifier packet, int size) {
    this.packet = packet;
    this.builder = new GamePacketBuilder(Unpooled.buffer(size));
}

From source file:com.seagate.kinetic.client.io.provider.nio.udt.UdtTransportProvider.java

License:Open Source License

@Override
public void write(KineticMessage km) throws IOException {

    // get interface message
    Message.Builder message = (Builder) km.getMessage();

    // create extended message
    ExtendedMessage.Builder extendedMessage = ExtendedMessage.newBuilder();

    // set interface message
    extendedMessage.setInterfaceMessage(message);

    // set optional value
    if (km.getValue() != null) {
        extendedMessage.setValue(ByteString.copyFrom(km.getValue()));
    }//  ww  w.j ava2 s .co  m

    // get byte[] from extended message
    byte[] data = extendedMessage.build().toByteArray();

    final ByteBuf byteBuf = Unpooled.buffer(data.length);
    byteBuf.writeBytes(data);

    UdtMessage udt = new UdtMessage(byteBuf);

    logger.finest("writing udt message.size= " + byteBuf.readableBytes());

    this.channel.writeAndFlush(udt);
}

From source file:com.seagate.kinetic.simulator.io.provider.nio.udt.UdtRequestProcessRunner.java

License:Open Source License

@Override
public void run() {
    try {//from  w ww . j a v a  2 s.  c om

        // extended request builder
        ExtendedMessage.Builder extendedBuilder = ExtendedMessage.newBuilder().mergeFrom(request);

        // build extended message
        ExtendedMessage extendedMessage = extendedBuilder.build();

        // create kinetic message
        KineticMessage km = new KineticMessage();

        // set interface message
        km.setMessage(extendedMessage.getInterfaceMessage());

        // get command bytes
        ByteString commandBytes = extendedMessage.getInterfaceMessage().getCommandBytes();

        // build command
        Command.Builder commandBuilder = Command.newBuilder();

        try {
            commandBuilder.mergeFrom(commandBytes);
            km.setCommand(commandBuilder.build());
        } catch (InvalidProtocolBufferException e) {
            logger.log(Level.WARNING, e.getMessage(), e);
        }

        // set optiona value
        if (extendedMessage.hasValue()) {
            km.setValue(extendedMessage.getValue().toByteArray());
        }

        // process request
        KineticMessage kmresp = service.processRequest(km);

        // create response builder
        ExtendedMessage.Builder extendedResponse = ExtendedMessage.newBuilder();

        // set response interface message
        extendedResponse.setInterfaceMessage((Message.Builder) kmresp.getMessage());

        // set response value
        if (kmresp.getValue() != null) {
            extendedResponse.setValue(ByteString.copyFrom(kmresp.getValue()));
        }

        // get serialized bytes
        byte[] data = extendedResponse.build().toByteArray();

        ByteBuf byteBuf = Unpooled.buffer(data.length);
        byteBuf.writeBytes(data);

        UdtMessage udt = new UdtMessage(byteBuf);

        ctx.writeAndFlush(udt);
    } catch (Exception e) {
        logger.log(Level.WARNING, e.getMessage(), e);
    }
}

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

License:Apache License

public ServletInputStreamImpl(HttpRequest request) {
    this.request = request;

    this.in = new ByteBufInputStream(Unpooled.buffer(0));
}

From source file:com.spotify.folsom.client.binary.BinaryMemcacheDecoderTest.java

License:Apache License

@Test
public void test() throws Exception {
    GetRequest request = new GetRequest(KEY, OpCode.GET, 123, OPAQUE);
    BinaryMemcacheDecoder decoder = new BinaryMemcacheDecoder();

    ByteBuf cb = Unpooled.buffer(30);
    cb.writeByte(0x81);//w ww  .ja va  2s  . c  o  m
    cb.writeByte(OpCode.GET);
    cb.writeShort(3);
    cb.writeByte(0);
    cb.writeZero(1);
    cb.writeShort(0);
    cb.writeInt(6);
    cb.writeInt(request.getOpaque());
    cb.writeLong(258);
    cb.writeBytes(KEY.getBytes());
    cb.writeBytes(VALUE.getBytes());

    List<Object> out = Lists.newArrayList();
    decoder.decode(null, cb, out);
    @SuppressWarnings("unchecked")
    List<ResponsePacket> replies = (List<ResponsePacket>) out.get(0);
    request.handle(replies);

    GetResult<byte[]> getResult = request.get();
    assertEquals(258, getResult.getCas());
    assertEquals(VALUE, TRANSCODER.decode(getResult.getValue()));
}

From source file:com.spotify.netty.handler.codec.zmtp.ZMTPFramingEncoder.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, ZMTPMessage msg, List<Object> out) throws Exception {
    // TODO (dano): integrate with write batching to avoid buffer creation and reduce garbage

    final int size = ZMTPUtils.messageSize(msg, session.isEnveloped(), session.getActualVersion());
    final ByteBuf buffer = Unpooled.buffer(size);

    ZMTPUtils.writeMessage(msg, buffer, session.isEnveloped(), session.getActualVersion());

    out.add(buffer);//from w  w w .  j  av  a 2s.co m
}