Example usage for io.netty.buffer ByteBuf writeBytes

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

Introduction

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

Prototype

public abstract int writeBytes(FileChannel in, long position, int length) throws IOException;

Source Link

Document

Transfers the content of the specified channel starting at the given file position to this buffer starting at the current writerIndex and increases the writerIndex by the number of the transferred bytes.

Usage

From source file:com.heliosapm.utils.buffer.BufferManager.java

License:Apache License

/**
 * Writes a UTF string to the passed ByteBuff
 * @param str The string to write// w  w w .ja v a2s . c  o  m
 * @param out The ByteBuf to write to
 * @return the number of bytes written
 */
public static int writeUTF(final String str, final ByteBuf out) {
    try {
        int strlen = str.length();
        int utflen = 0;
        int c, count = 0;

        /* use charAt instead of copying String to char array */
        for (int i = 0; i < strlen; i++) {
            c = str.charAt(i);
            if ((c >= 0x0001) && (c <= 0x007F)) {
                utflen++;
            } else if (c > 0x07FF) {
                utflen += 3;
            } else {
                utflen += 2;
            }
        }

        if (utflen > 65535)
            throw new UTFDataFormatException("encoded string too long: " + utflen + " bytes");

        byte[] bytearr = new byte[utflen + 2];

        bytearr[count++] = (byte) ((utflen >>> 8) & 0xFF);
        bytearr[count++] = (byte) ((utflen >>> 0) & 0xFF);

        int i = 0;
        for (i = 0; i < strlen; i++) {
            c = str.charAt(i);
            if (!((c >= 0x0001) && (c <= 0x007F)))
                break;
            bytearr[count++] = (byte) c;
        }

        for (; i < strlen; i++) {
            c = str.charAt(i);
            if ((c >= 0x0001) && (c <= 0x007F)) {
                bytearr[count++] = (byte) c;

            } else if (c > 0x07FF) {
                bytearr[count++] = (byte) (0xE0 | ((c >> 12) & 0x0F));
                bytearr[count++] = (byte) (0x80 | ((c >> 6) & 0x3F));
                bytearr[count++] = (byte) (0x80 | ((c >> 0) & 0x3F));
            } else {
                bytearr[count++] = (byte) (0xC0 | ((c >> 6) & 0x1F));
                bytearr[count++] = (byte) (0x80 | ((c >> 0) & 0x3F));
            }
        }

        out.writeBytes(bytearr, 0, utflen + 2);
        return utflen + 2;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.kael.surf.net.codec.LengthFieldBasedFrameDecoder.java

License:Apache License

/**
 * Extract the sub-region of the specified buffer.
 * <p>//  www . j  a  v  a 2 s  . co  m
 * If you are sure that the frame and its content are not accessed after
 * the current {@link #decode(ChannelHandlerContext, ByteBuf)}
 * call returns, you can even avoid memory copy by returning the sliced
 * sub-region (i.e. <tt>return buffer.slice(index, length)</tt>).
 * It's often useful when you convert the extracted frame into an object.
 * Refer to the source code of {@link ObjectDecoder} to see how this method
 * is overridden to avoid memory copy.
 */
protected ByteBuf extractFrame(ChannelHandlerContext ctx, ByteBuf buffer, int index, int length) {
    ByteBuf frame = ctx.alloc().buffer(length);
    frame.writeBytes(buffer, index, length);
    return frame;
}

From source file:com.larskroll.common.ByteArrayRef.java

License:Open Source License

@Override
public void copyTo(ByteBuf buffer) {
    buffer.writeBytes(backingArray, begin, length);
}

From source file:com.linecorp.armeria.internal.grpc.ArmeriaMessageDeframer.java

License:Apache License

/**
 * Adds the given data to this deframer and attempts delivery to the listener.
 *
 * @param data the raw data read from the remote endpoint. Must be non-null.
 * @param endOfStream if {@code true}, indicates that {@code data} is the end of the stream from
 *        the remote endpoint.  End of stream should not be used in the event of a transport
 *        error, such as a stream reset.
 * @throws IllegalStateException if {@link #close()} has been called previously or if
 *         this method has previously been called with {@code endOfStream=true}.
 *//*  www.  j  a  v  a 2 s.  com*/
public void deframe(HttpData data, boolean endOfStream) {
    requireNonNull(data, "data");
    checkNotClosed();
    checkState(!this.endOfStream, "Past end of stream");

    startedDeframing = true;

    if (!data.isEmpty()) {
        final ByteBuf buf;
        if (data instanceof ByteBufHolder) {
            buf = ((ByteBufHolder) data).content();
        } else {
            buf = alloc.buffer(data.length());
            buf.writeBytes(data.array(), data.offset(), data.length());
        }
        if (unprocessed != null) {
            unprocessed.addComponent(true, buf);
        } else if (firstFrame == null) {
            firstFrame = buf;
        } else {
            unprocessed = alloc.compositeBuffer();
            unprocessed.addComponent(true, firstFrame);
            unprocessed.addComponent(true, buf);
            firstFrame = null;
        }
    }

    // Indicate that all of the data for this stream has been received.
    this.endOfStream = endOfStream;
    deliver();
}

From source file:com.linecorp.armeria.internal.http.HttpObjectEncoder.java

License:Apache License

protected static ByteBuf toByteBuf(ChannelHandlerContext ctx, HttpData data) {
    final ByteBuf buf = ctx.alloc().directBuffer(data.length(), data.length());
    buf.writeBytes(data.array(), data.offset(), data.length());
    return buf;//www  .j  av  a 2 s . c  o  m
}

From source file:com.linecorp.armeria.internal.HttpObjectEncoder.java

License:Apache License

protected static ByteBuf toByteBuf(ChannelHandlerContext ctx, HttpData data) {
    if (data instanceof ByteBufHolder) {
        return ((ByteBufHolder) data).content();
    }/*from  w  ww .j  ava 2  s  .c  o  m*/
    final ByteBuf buf = ctx.alloc().directBuffer(data.length(), data.length());
    buf.writeBytes(data.array(), data.offset(), data.length());
    return buf;
}

From source file:com.linecorp.armeria.server.grpc.UnframedGrpcService.java

License:Apache License

private void frameAndServe(ServiceRequestContext ctx, HttpHeaders grpcHeaders,
        AggregatedHttpMessage clientRequest, CompletableFuture<HttpResponse> res) {
    final HttpRequest grpcRequest;
    try (ArmeriaMessageFramer framer = new ArmeriaMessageFramer(ctx.alloc(),
            ArmeriaMessageFramer.NO_MAX_OUTBOUND_MESSAGE_SIZE)) {
        final HttpData content = clientRequest.content();
        final ByteBuf message;
        if (content instanceof ByteBufHolder) {
            message = ((ByteBufHolder) content).content();
        } else {//from   w  w  w  . jav a  2s . c  om
            message = ctx.alloc().buffer(content.length());
            message.writeBytes(content.array(), content.offset(), content.length());
        }
        final HttpData frame;
        boolean success = false;
        try {
            frame = framer.writePayload(message);
            success = true;
        } finally {
            if (!success) {
                message.release();
            }
        }
        grpcRequest = HttpRequest.of(grpcHeaders, frame);
    }

    final HttpResponse grpcResponse;
    try {
        grpcResponse = delegate().serve(ctx, grpcRequest);
    } catch (Exception e) {
        res.completeExceptionally(e);
        return;
    }

    grpcResponse.aggregate().whenCompleteAsync((framedResponse, t) -> {
        if (t != null) {
            res.completeExceptionally(t);
        } else {
            deframeAndRespond(ctx, framedResponse, res);
        }
    }, ctx.eventLoop());
}

From source file:com.linecorp.armeria.server.thrift.THttpService.java

License:Apache License

private void decodeAndInvoke(ServiceRequestContext ctx, AggregatedHttpMessage req,
        SerializationFormat serializationFormat, CompletableFuture<HttpResponse> httpRes) {
    final HttpData content = req.content();
    final ByteBuf buf;
    if (content instanceof ByteBufHolder) {
        buf = ((ByteBufHolder) content).content();
    } else {/*from w w  w. j a  va2 s  .  c  o m*/
        buf = ctx.alloc().buffer(content.length());
        buf.writeBytes(content.array(), content.offset(), content.length());
    }

    final TByteBufTransport inTransport = new TByteBufTransport(buf);
    final TProtocol inProto = ThriftProtocolFactories.get(serializationFormat).getProtocol(inTransport);

    final int seqId;
    final ThriftFunction f;
    final RpcRequest decodedReq;

    try {
        final TMessage header;
        final TBase<?, ?> args;

        try {
            header = inProto.readMessageBegin();
        } catch (Exception e) {
            logger.debug("{} Failed to decode Thrift header:", ctx, e);
            httpRes.complete(HttpResponse.of(HttpStatus.BAD_REQUEST, MediaType.PLAIN_TEXT_UTF_8,
                    "Failed to decode Thrift header: " + Throwables.getStackTraceAsString(e)));
            return;
        }

        seqId = header.seqid;

        final byte typeValue = header.type;
        final int colonIdx = header.name.indexOf(':');
        final String serviceName;
        final String methodName;
        if (colonIdx < 0) {
            serviceName = "";
            methodName = header.name;
        } else {
            serviceName = header.name.substring(0, colonIdx);
            methodName = header.name.substring(colonIdx + 1);
        }

        // Basic sanity check. We usually should never fail here.
        if (typeValue != TMessageType.CALL && typeValue != TMessageType.ONEWAY) {
            final TApplicationException cause = new TApplicationException(
                    TApplicationException.INVALID_MESSAGE_TYPE,
                    "unexpected TMessageType: " + typeString(typeValue));

            handlePreDecodeException(ctx, httpRes, cause, serializationFormat, seqId, methodName);
            return;
        }

        // Ensure that such a method exists.
        final ThriftServiceEntry entry = entries().get(serviceName);
        f = entry != null ? entry.metadata.function(methodName) : null;
        if (f == null) {
            final TApplicationException cause = new TApplicationException(TApplicationException.UNKNOWN_METHOD,
                    "unknown method: " + header.name);

            handlePreDecodeException(ctx, httpRes, cause, serializationFormat, seqId, methodName);
            return;
        }

        // Decode the invocation parameters.
        try {
            args = f.newArgs();
            args.read(inProto);
            inProto.readMessageEnd();

            decodedReq = toRpcRequest(f.serviceType(), header.name, args);
            ctx.logBuilder().requestContent(decodedReq, new ThriftCall(header, args));
        } catch (Exception e) {
            // Failed to decode the invocation parameters.
            logger.debug("{} Failed to decode Thrift arguments:", ctx, e);

            final TApplicationException cause = new TApplicationException(TApplicationException.PROTOCOL_ERROR,
                    "failed to decode arguments: " + e);

            handlePreDecodeException(ctx, httpRes, cause, serializationFormat, seqId, methodName);
            return;
        }
    } finally {
        buf.release();
        ctx.logBuilder().requestContent(null, null);
    }

    invoke(ctx, serializationFormat, seqId, f, decodedReq, httpRes);
}

From source file:com.necla.simba.server.gateway.server.backend.BackendFrameDecoder.java

License:Apache License

private ByteBuf extractMessage(ChannelHandlerContext ctx, ByteBuf in, int index, int length) {
    ByteBuf frame = ctx.alloc().buffer(length);
    frame.writeBytes(in, index, length);
    return frame;
}

From source file:com.necla.simba.server.gateway.server.frontend.FrontendFrameEncoder.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
    LOG.debug("told to send out msg numBytes=" + msg.readableBytes() + " to " + ctx.channel());
    int length = msg.readableBytes();
    if (DOCOMPRESS) {
        compress(ctx, msg, out);//from w  w w .j  av  a  2s. co  m

    } else {
        length &= ~(1 << 30);
        out.writeInt(length);
        out.writeBytes(msg, msg.readerIndex(), msg.readableBytes());

        Stats.sent(length);
    }

}