Example usage for io.netty.buffer ByteBuf getBytes

List of usage examples for io.netty.buffer ByteBuf getBytes

Introduction

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

Prototype

public abstract ByteBuf getBytes(int index, ByteBuffer dst);

Source Link

Document

Transfers this buffer's data to the specified destination starting at the specified absolute index until the destination's position reaches its limit.

Usage

From source file:org.dcache.xrootd.security.RawBucket.java

License:Open Source License

public static RawBucket deserialize(BucketType type, ByteBuf buffer) {

    byte[] tmp = new byte[buffer.readableBytes()];
    buffer.getBytes(0, tmp);
    return new RawBucket(type, tmp);
}

From source file:org.dcache.xrootd.tpc.protocol.messages.InboundAttnResponse.java

License:Open Source License

private void parseParameters(ByteBuf buffer, int len) {
    switch (actnum) {
    case kXR_asyncab:
    case kXR_asyncms:
        message = buffer.toString(12, len, US_ASCII);
        break;//from  ww w  .  j  a  v  a 2s .  c  o m
    case kXR_asyncdi:
        wsec = buffer.getInt(12);
        msec = buffer.getInt(16);
        break;
    case kXR_asyncrd:
        port = buffer.getInt(12);
        redirectData = buffer.toString(16, len - 4, US_ASCII);
        break;
    case kXR_asynresp:
        rStreamId = buffer.getUnsignedShort(16);
        rStat = buffer.getUnsignedShort(18);
        int dlen = buffer.getInt(20);
        if (dlen > 0) {
            rData = new byte[dlen];
            buffer.getBytes(24, rData);
        }
        break;
    case kXR_asyncwt:
        wsec = buffer.getInt(12);
        break;
    default:
        break;
    }
}

From source file:org.dcache.xrootd.tpc.protocol.messages.InboundLoginResponse.java

License:Open Source License

public InboundLoginResponse(ByteBuf buffer) throws XrootdException {
    super(buffer);

    if (buffer.readableBytes() > 8) {
        int slen = buffer.getInt(4) - SESSION_ID_SIZE;
        byte[] session = new byte[SESSION_ID_SIZE];
        buffer.getBytes(8, session);
        sessionId = new XrootdSessionIdentifier(session);
        if (slen > 0) {
            protocols = new ArrayList<>();

            String sec = buffer.toString(24, slen, US_ASCII);
            for (String description : Splitter.on('&').trimResults().omitEmptyStrings().split(sec)) {
                if (!description.startsWith(PROTOCOL_PREFIX)) {
                    throw new XrootdException(kXR_error, "Malformed 'sec': " + sec);
                }/*from   ww w.java2  s  .co  m*/
                protocols.add(new SecurityInfo(description.substring(PROTOCOL_PREFIX.length())));
            }
        } else {
            protocols = Collections.EMPTY_LIST;
        }
    } else {
        sessionId = null;
        protocols = Collections.EMPTY_LIST;
    }

    protocolMap = protocols.stream().collect(Collectors.toMap((p) -> p.getProtocol(), (p) -> p));
}

From source file:org.dcache.xrootd.tpc.protocol.messages.InboundReadResponse.java

License:Open Source License

public InboundReadResponse(ByteBuf buffer) {
    super(buffer);
    dlen = buffer.getInt(4);
    data = buffer.alloc().ioBuffer(dlen);
    buffer.getBytes(8, data);
}

From source file:org.dcache.xrootd.tpc.protocol.messages.OutboundSigverRequest.java

License:Open Source License

/**
 *  A signature consists of a SHA-256 hash of
 *    1. an unsigned 64-bit sequence number,
 *    2. the request header, and/*from w ww .j a va 2s. com*/
 *    3. the request payload,
 *  in that exact order.
 */
private byte[] getSignature(AbstractXrootdOutboundRequest request, ChannelHandlerContext ctx)
        throws NoSuchAlgorithmException {
    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    ByteBuf buffer = ctx.alloc().buffer(12 + request.getParamsLen());
    try {
        buffer.writeLong(seqno);
        request.writeToBuffer(buffer);
        byte[] contents = new byte[buffer.readableBytes()];
        buffer.getBytes(0, contents);
        return digest.digest(contents);
    } finally {
        buffer.release();
    }
}

From source file:org.ebayopensource.scc.cache.BaseResponseSerializer.java

License:Apache License

protected void copyBody(CacheResponse cacheResp, ByteBuf... chunks) {
    int totalSize = 0;
    for (ByteBuf c : chunks) {
        if (c.isReadable()) {
            totalSize += c.readableBytes();
        }/*from w w w.j a va2 s .  c  om*/
    }

    ByteBuffer nioBuffer = ByteBuffer.allocate(totalSize);
    for (ByteBuf c : chunks) {
        if (c.isReadable()) {
            c.getBytes(c.readerIndex(), nioBuffer);
        }
    }

    if (nioBuffer.hasArray()) {
        cacheResp.setContent(nioBuffer.array());
    }

    // reset Content-Length
    List<CacheEntry<String, String>> headers = cacheResp.getHeaders();
    for (Iterator<CacheEntry<String, String>> it = headers.iterator(); it.hasNext();) {
        CacheEntry<String, String> header = it.next();
        if (HttpHeaders.Names.CONTENT_LENGTH.equals(header.getKey())) {
            it.remove();
        }
    }
    headers.add(new CacheEntry<String, String>(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(totalSize)));
}

From source file:org.eclipse.californium.elements.tcp.DatagramFramer.java

License:Open Source License

private int getBodyLength(ByteBuf in, int lengthNibble, int fieldSize) {
    byte data[] = new byte[fieldSize];
    in.getBytes(in.readerIndex() + 1, data);

    switch (fieldSize) {
    case 0://www  . j a  va2 s. com
        return lengthNibble;
    case 1:
        return new BigInteger(1, data).intValue() + 13;
    case 2:
        return new BigInteger(1, data).intValue() + 269;
    case 4:
        // Possible overflow here, but is anybody really sending 2GB
        // messages around?
        return new BigInteger(1, data).intValue() + 65805;
    default:
        throw new IllegalArgumentException("Invalid field size: " + fieldSize);
    }
}

From source file:org.fiware.kiara.transport.http.HttpHandler.java

License:Open Source License

@Override
protected void channelRead0(final ChannelHandlerContext ctx, Object msg) throws Exception {
    logger.debug("Handler: {} / Channel: {}", this, ctx.channel());
    if (mode == Mode.SERVER) {
        if (msg instanceof FullHttpRequest) {
            final FullHttpRequest request = (FullHttpRequest) msg;

            HttpRequestMessage transportMessage = new HttpRequestMessage(this, request);
            transportMessage.setPayload(request.content().copy().nioBuffer());

            if (logger.isDebugEnabled()) {
                logger.debug("RECEIVED CONTENT {}", HexDump.dumpHexString(transportMessage.getPayload()));
                //logger.debug("RECEIVED REQUEST WITH CONTENT {}", Util.bufferToString(transportMessage.getPayload()));
            }//from w w w.  j  a  v a2 s .  c  o  m

            notifyListeners(transportMessage);

            boolean keepAlive = HttpHeaders.isKeepAlive(request);
        }
    } else {
        // CLIENT
        if (msg instanceof HttpResponse) {
            HttpResponse response = (HttpResponse) msg;
            headers = response.headers();
            //if (!response.headers().isEmpty()) {
            //    contentType = response.headers().get("Content-Type");
            //}
        }
        if (msg instanceof HttpContent) {
            HttpContent content = (HttpContent) msg;
            ByteBuf buf = content.content();
            if (buf.isReadable()) {
                if (buf.hasArray()) {
                    bout.write(buf.array(), buf.readerIndex(), buf.readableBytes());
                } else {
                    byte[] bytes = new byte[buf.readableBytes()];
                    buf.getBytes(buf.readerIndex(), bytes);
                    bout.write(bytes);
                }
            }
            if (content instanceof LastHttpContent) {
                //ctx.close();
                bout.flush();
                HttpResponseMessage response = new HttpResponseMessage(this, headers);
                response.setPayload(ByteBuffer.wrap(bout.toByteArray(), 0, bout.size()));
                onResponse(response);
                bout.reset();
            }
        }
    }
}

From source file:org.glassfish.jersey.netty.connector.JerseyClientHandler.java

License:Open Source License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
    if (msg instanceof HttpResponse) {
        final HttpResponse response = (HttpResponse) msg;

        final ClientResponse jerseyResponse = new ClientResponse(new Response.StatusType() {
            @Override/*from ww  w  .j av  a 2s .c om*/
            public int getStatusCode() {
                return response.status().code();
            }

            @Override
            public Response.Status.Family getFamily() {
                return Response.Status.Family.familyOf(response.status().code());
            }

            @Override
            public String getReasonPhrase() {
                return response.status().reasonPhrase();
            }
        }, jerseyRequest);

        for (Map.Entry<String, String> entry : response.headers().entries()) {
            jerseyResponse.getHeaders().add(entry.getKey(), entry.getValue());
        }

        // request entity handling.
        if ((response.headers().contains(HttpHeaderNames.CONTENT_LENGTH)
                && HttpUtil.getContentLength(response) > 0) || HttpUtil.isTransferEncodingChunked(response)) {

            ctx.channel().closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() {
                @Override
                public void operationComplete(Future<? super Void> future) throws Exception {
                    isList.add(NettyInputStream.END_OF_INPUT_ERROR);
                }
            });

            jerseyResponse.setEntityStream(new NettyInputStream(isList));
        } else {
            jerseyResponse.setEntityStream(new InputStream() {
                @Override
                public int read() throws IOException {
                    return -1;
                }
            });
        }

        if (asyncConnectorCallback != null) {
            connector.executorService.execute(new Runnable() {
                @Override
                public void run() {
                    asyncConnectorCallback.response(jerseyResponse);
                    future.complete(jerseyResponse);
                }
            });
        }

    }
    if (msg instanceof HttpContent) {

        HttpContent httpContent = (HttpContent) msg;

        ByteBuf content = httpContent.content();

        if (content.isReadable()) {
            // copy bytes - when netty reads last chunk, it automatically closes the channel, which invalidates all
            // relates ByteBuffs.
            byte[] bytes = new byte[content.readableBytes()];
            content.getBytes(content.readerIndex(), bytes);
            isList.add(new ByteArrayInputStream(bytes));
        }

        if (msg instanceof LastHttpContent) {
            isList.add(NettyInputStream.END_OF_INPUT);
        }
    }
}

From source file:org.graylog2.gelfclient.encoder.GelfMessageJsonEncoderTest.java

License:Apache License

private byte[] readBytes() {
    ByteBuf buf = (ByteBuf) channel.readOutbound();
    byte[] bytes = new byte[buf.readableBytes()];

    buf.getBytes(0, bytes).release();

    return bytes;
}