Example usage for io.netty.buffer ByteBufUtil writeAscii

List of usage examples for io.netty.buffer ByteBufUtil writeAscii

Introduction

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

Prototype

public static int writeAscii(ByteBuf buf, CharSequence seq) 

Source Link

Document

Encode a CharSequence in <a href="http://en.wikipedia.org/wiki/ASCII">ASCII</a> and write it to a ByteBuf .

Usage

From source file:com.flysoloing.learning.network.netty.http2.helloworld.multiplex.server.HelloWorldHttp2Handler.java

License:Apache License

/**
 * If receive a frame with end-of-stream set, send a pre-canned response.
 *//*from ww w  . ja  v a2s . c  o  m*/
public void onHeadersRead(ChannelHandlerContext ctx, Http2HeadersFrame headers) throws Exception {
    if (headers.isEndStream()) {
        ByteBuf content = ctx.alloc().buffer();
        content.writeBytes(RESPONSE_BYTES.duplicate());
        ByteBufUtil.writeAscii(content, " - via HTTP/2");
        sendResponse(ctx, content);
    }
}

From source file:com.flysoloing.learning.network.netty.http2.helloworld.server.HelloWorldHttp1Handler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
    if (HttpUtil.is100ContinueExpected(req)) {
        ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
    }//w  w  w .j a va  2s  .  c o m
    boolean keepAlive = HttpUtil.isKeepAlive(req);

    ByteBuf content = ctx.alloc().buffer();
    content.writeBytes(HelloWorldHttp2Handler.RESPONSE_BYTES.duplicate());
    ByteBufUtil.writeAscii(content, " - via " + req.protocolVersion() + " (" + establishApproach + ")");

    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
    response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());

    if (!keepAlive) {
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    } else {
        response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        ctx.writeAndFlush(response);
    }
}

From source file:com.flysoloing.learning.network.netty.http2.helloworld.server.HelloWorldHttp2Handler.java

License:Apache License

public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding,
        boolean endOfStream) {
    if (endOfStream) {
        ByteBuf content = ctx.alloc().buffer();
        content.writeBytes(RESPONSE_BYTES.duplicate());
        ByteBufUtil.writeAscii(content, " - via HTTP/2");
        sendResponse(ctx, streamId, content);
    }/*w w  w  .j a  va2s  .c o  m*/
}

From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpDownloadHandlerTest.java

License:Open Source License

/**
 * Test that the handler correctly supports http error codes i.e. 404 (NOT FOUND) with a
 * Content-Length header./* ww w. j  a v a 2 s .  c om*/
 */
@Test
public void httpErrorsWithContentAreSupported() throws IOException {
    EmbeddedChannel ch = new EmbeddedChannel(new HttpDownloadHandler(null));
    ByteArrayOutputStream out = Mockito.spy(new ByteArrayOutputStream());
    DownloadCommand cmd = new DownloadCommand(CACHE_URI, true, "abcdef", out);
    ChannelPromise writePromise = ch.newPromise();
    ch.writeOneOutbound(cmd, writePromise);

    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
    ByteBuf errorMessage = ByteBufUtil.writeAscii(ch.alloc(), "Error message");
    response.headers().set(HttpHeaders.HOST, "localhost");
    response.headers().set(HttpHeaders.CONTENT_LENGTH, String.valueOf(errorMessage.readableBytes()));
    response.headers().set(HttpHeaders.CONNECTION, HttpHeaderValues.CLOSE);

    ch.writeInbound(response);
    // The promise must not be done because we haven't received the error message yet.
    assertThat(writePromise.isDone()).isFalse();

    ch.writeInbound(new DefaultHttpContent(errorMessage));
    ch.writeInbound(LastHttpContent.EMPTY_LAST_CONTENT);
    assertThat(writePromise.isDone()).isTrue();
    assertThat(writePromise.cause()).isInstanceOf(HttpException.class);
    assertThat(((HttpException) writePromise.cause()).response().status())
            .isEqualTo(HttpResponseStatus.NOT_FOUND);
    // No data should have been written to the OutputStream and it should have been closed.
    assertThat(out.size()).isEqualTo(0);
    // The caller is responsible for closing the stream.
    verify(out, never()).close();
    assertThat(ch.isOpen()).isFalse();
}

From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpUploadHandlerTest.java

License:Open Source License

/**
 * Test that the handler correctly supports http error codes i.e. 404 (NOT FOUND) with a
 * Content-Length header./*from  w w  w . j av a  2 s.  co m*/
 */
@Test
public void httpErrorsWithContentAreSupported() {
    EmbeddedChannel ch = new EmbeddedChannel(new HttpUploadHandler(null));
    ByteArrayInputStream data = new ByteArrayInputStream(new byte[] { 1, 2, 3, 4, 5 });
    ChannelPromise writePromise = ch.newPromise();
    ch.writeOneOutbound(new UploadCommand(CACHE_URI, true, "abcdef", data, 5), writePromise);

    HttpRequest request = ch.readOutbound();
    assertThat(request).isInstanceOf(HttpRequest.class);
    HttpChunkedInput content = ch.readOutbound();
    assertThat(content).isInstanceOf(HttpChunkedInput.class);

    ByteBuf errorMsg = ByteBufUtil.writeAscii(ch.alloc(), "error message");
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND,
            errorMsg);
    response.headers().set(HttpHeaders.CONNECTION, HttpHeaderValues.KEEP_ALIVE);

    ch.writeInbound(response);

    assertThat(writePromise.isDone()).isTrue();
    assertThat(writePromise.cause()).isInstanceOf(HttpException.class);
    assertThat(((HttpException) writePromise.cause()).response().status())
            .isEqualTo(HttpResponseStatus.NOT_FOUND);
    assertThat(ch.isOpen()).isTrue();
}

From source file:com.hop.hhxx.example.http2.helloworld.multiplex.server.HelloWorldHttp2Handler.java

License:Apache License

/**
 * If receive a frame with end-of-stream set, send a pre-canned response.
 *//*from   ww  w  .ja va  2s.c  om*/
public void onHeadersRead(ChannelHandlerContext ctx, Http2HeadersFrame headers) throws Exception {
    if (headers.isEndStream()) {
        ByteBuf content = ctx.alloc().buffer();
        content.writeBytes(RESPONSE_BYTES);
        ByteBufUtil.writeAscii(content, " - via HTTP/2");
        sendResponse(ctx, content);
    }
}

From source file:com.hop.hhxx.example.http2.helloworld.server.HelloWorldHttp2Handler.java

License:Apache License

@Override
public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding,
        boolean endOfStream) {
    if (endOfStream) {
        ByteBuf content = ctx.alloc().buffer();
        content.writeBytes(RESPONSE_BYTES.duplicate());
        ByteBufUtil.writeAscii(content, " - via HTTP/2");
        sendResponse(ctx, streamId, content);
    }/*from   w w w  . j av  a 2  s .  c om*/
}

From source file:com.lambdaworks.redis.codec.StringCodec.java

License:Apache License

public void encode(String str, ByteBuf target) {

    if (str == null) {
        return;//  w  w w  .  j  a  v  a2s. c om
    }

    if (utf8) {
        ByteBufUtil.writeUtf8(target, str);
        return;
    }

    if (ascii) {
        ByteBufUtil.writeAscii(target, str);
        return;
    }

    CharsetEncoder encoder = CharsetUtil.encoder(charset);
    int length = (int) ((double) str.length() * encoder.maxBytesPerChar());
    target.ensureWritable(length);
    try {
        final ByteBuffer dstBuf = target.nioBuffer(0, length);
        final int pos = dstBuf.position();
        CoderResult cr = encoder.encode(CharBuffer.wrap(str), dstBuf, true);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
        cr = encoder.flush(dstBuf);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
        target.writerIndex(target.writerIndex() + dstBuf.position() - pos);
    } catch (CharacterCodingException x) {
        throw new IllegalStateException(x);
    }
}

From source file:de.unipassau.isl.evs.ssh.core.sec.DeviceConnectInformation.java

License:Open Source License

/**
 * Read a DeviceConnectInformation from a Base64 encoded String, which was read from a QR Code.
 *//*  www.  ja  v a 2s.co m*/
public static DeviceConnectInformation fromDataString(String data) throws IOException {
    final ByteBuf base64 = UnpooledByteBufAllocator.DEFAULT.heapBuffer(data.length());
    ByteBufUtil.writeAscii(base64, data);
    final ByteBuf byteBuf = decode(base64);
    if (byteBuf.readableBytes() != DATA_LENGTH) {
        throw new IOException("too many bytes encoded");
    }

    final byte[] addressData = new byte[ADDRESS_LENGTH];
    byteBuf.readBytes(addressData);
    final InetAddress address = InetAddress.getByAddress(addressData);
    final int port = byteBuf.readUnsignedShort();
    final byte[] idData = new byte[DeviceID.ID_LENGTH];
    byteBuf.readBytes(idData);
    final DeviceID id = new DeviceID(idData);
    final byte[] encodedToken = new byte[TOKEN_BASE64_LENGTH];
    byteBuf.readBytes(encodedToken);
    final byte[] token = decodeToken(new String(encodedToken));

    return new DeviceConnectInformation(address, port, id, token);
}

From source file:eu.jangos.realm.network.packet.server.character.SMSG_CHAR_ENUM.java

License:Apache License

@Override
public void encode(ByteBuf buf) throws Exception {
    // Packet structure:
    // 2b - 2b - 1b
    // Size (Little Endian) - Opcode (Big Endian) - number of characters 
    // If any character:
    // 8b - ?b - 1b - 1b - 1b - 1b - 1b - 1b - 1b - 1b - 1b - 4b - 4b - 4b - 4b - 4b - 4b - 1b - 4b - 4b - 4b 
    // GUID (Little Endian) - Name - Race - Class - Gender - Skin - Face - HairStyle - HairColor - FacialHair - level - zone - map - x - y - z - guild
    // char flags - first login - Pet id - Pet level - Pet Family
    // Then equipment: (19 pieces)
    // 4b - 1b/* www  . ja va2s  .c o m*/
    // Item Display ID - Item Inventory Type
    // Then the bag
    // 4b - 1b
    // First bag display ID
    // First bag inventory type

    // TODO: 
    // - Guild membership
    // - Pet ID
    // - Pet Level
    // - Pet Family

    ItemService itemService = ItemServiceFactory.getInstance();
    ItemInstanceService iiService = new ItemInstanceService();

    buf.writeShort(this.size);
    buf.writeShort(this.code.getValue());
    buf.writeByte(this.numChars);

    for (Characters c : this.listChars) {
        buf = buf.order(ByteOrder.LITTLE_ENDIAN);
        buf.writeLong(c.getGuid());
        //buf = buf.order(ByteOrder.BIG_ENDIAN);
        ByteBufUtil.writeAscii(buf, c.getName());
        buf.writeByte((byte) 0); // End of string
        buf.writeByte(c.getRace());
        buf.writeByte(c.getFkDbcClass());
        buf.writeByte(c.getGender());
        buf.writeByte(c.getSkin());
        buf.writeByte(c.getFace());
        buf.writeByte(c.getHairstyle());
        buf.writeByte(c.getHaircolor());
        buf.writeByte(c.getFacialhair());
        buf.writeByte((byte) c.getLevel());
        buf.writeInt(c.getFkDbcZone());
        buf.writeInt(c.getFkDbcMap());
        buf.writeFloat((float) c.getPositionX()); // X
        buf.writeFloat((float) c.getPositionY()); // Y
        buf.writeFloat((float) c.getPositionZ()); // Z
        buf.writeInt(0); // Guild ID
        buf.writeInt(convertPlayersFlagsToInt(c)); // Char Flags            
        buf.writeByte(convertLoginFlagsToByte(c)); // First login
        buf.writeInt(0); // Pet ID
        buf.writeInt(0); // Pet Level
        buf.writeInt(0); // Pet family

        int count = 0;

        // We get the list of data for the equipment.
        for (Object data : iiService.getEquipmentCharEnum(c)) {
            Object[] itemInstance = (Object[]) data;
            int displayID = 0;
            byte inventoryType = 0;

            // We fill-in the data for the unoccupied slots.
            for (int i = count; i < Integer.parseInt(itemInstance[0].toString()); i++) {
                buf.writeInt(displayID);
                buf.writeByte(inventoryType);
                count++;
            }

            // We add the occupied slot.
            Object[] item = itemService.getItemByIDCharEnum(Integer.parseInt(itemInstance[1].toString()));

            displayID = Integer.parseInt(item[0].toString());
            inventoryType = Byte.parseByte(item[1].toString());

            buf.writeInt(displayID);
            buf.writeByte(inventoryType);

            count++;
        }

        // We fill in the data for the end of the equipment slot.
        for (int i = count; i <= EQUIPMENT_SLOT_END; i++) {
            buf.writeInt(0);
            buf.writeByte(0);
        }

    }

}