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() 

Source Link

Document

Creates a new big-endian Java heap buffer with reasonably small initial capacity, which expands its capacity boundlessly on demand.

Usage

From source file:com.microsoft.Malmo.MissionHandlers.RewardForItemBase.java

License:Open Source License

protected static void sendItemStackToClient(EntityPlayerMP player, MalmoMessageType message, ItemStack is) {
    ByteBuf buf = Unpooled.buffer();
    ByteBufUtils.writeItemStack(buf, is);
    byte[] bytes = new byte[buf.readableBytes()];
    buf.getBytes(0, bytes);//from ww  w.  ja v  a2 s  .  c o  m
    String data = DatatypeConverter.printBase64Binary(bytes);
    MalmoMod.MalmoMessage msg = new MalmoMod.MalmoMessage(message, data);
    MalmoMod.network.sendTo(msg, player);
}

From source file:com.mobius.software.mqtt.parser.test.TestPublish.java

License:Open Source License

@Test
public void testSetData() {
    ByteBuf data = Unpooled.buffer()
            .writeBytes(new byte[] { 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64 });
    Publish actual = new Publish(expected.getPacketID(), expected.getTopic(), data, expected.isRetain(),
            expected.isDup());/*w w w .java 2 s . c  o  m*/
    assertEquals("setData results with invalid length", actual.getLength(), 24);
}

From source file:com.mobius.software.mqtt.parser.test.TestPublish.java

License:Open Source License

@Test
public void testTime() throws UnsupportedEncodingException, MalformedMessageException {
    Publish actual = new Publish(20,
            new Topic(new Text("root/first/second/third/fourth/fifth/andsomeadditionalsymbols"),
                    QoS.EXACTLY_ONCE),/*w  w  w . j a v a2 s . com*/
            Unpooled.buffer().writeBytes("1234567890-=qwertyuiop[]asdfghjkl".getBytes()), false, false);
    ByteBuf buf = MQParser.encode(actual);
    buf = MQParser.encode(actual);
    ByteBuf slice = MQParser.next(buf);
    buf.readBytes(slice);
    MQParser.decode(slice);
}

From source file:com.netflix.ribbon.RibbonTest.java

License:Apache License

@Test
public void testFallback() throws IOException {
    HttpResourceGroup group = Ribbon.createHttpResourceGroup("myclient", ClientOptions.create()
            .withConfigurationBasedServerList("localhost:12345").withMaxAutoRetriesNextServer(1));
    final String fallback = "fallback";
    HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("test", ByteBuf.class).withUriTemplate("/")
            .withMethod("GET").withFallbackProvider(new FallbackHandler<ByteBuf>() {
                @Override//from w  w w  .j av  a2s  .com
                public Observable<ByteBuf> getFallback(HystrixExecutableInfo<?> hystrixInfo,
                        Map<String, Object> requestProperties) {
                    try {
                        return Observable.just(Unpooled.buffer().writeBytes(fallback.getBytes("UTF-8")));
                    } catch (UnsupportedEncodingException e) {
                        return Observable.error(e);
                    }
                }
            }).build();
    RibbonRequest<ByteBuf> request = template.requestBuilder().build();
    final AtomicReference<HystrixExecutableInfo<?>> hystrixInfo = new AtomicReference<HystrixExecutableInfo<?>>();
    final AtomicBoolean failed = new AtomicBoolean(false);
    Observable<String> result = request.withMetadata().toObservable()
            .flatMap(new Func1<RibbonResponse<Observable<ByteBuf>>, Observable<String>>() {
                @Override
                public Observable<String> call(final RibbonResponse<Observable<ByteBuf>> response) {
                    hystrixInfo.set(response.getHystrixInfo());
                    failed.set(response.getHystrixInfo().isFailedExecution());
                    return response.content().map(new Func1<ByteBuf, String>() {
                        @Override
                        public String call(ByteBuf t1) {
                            return t1.toString(Charset.defaultCharset());
                        }
                    });
                }
            });
    String s = result.toBlocking().single();
    // this returns true only after the blocking call is done
    assertTrue(hystrixInfo.get().isResponseFromFallback());
    assertTrue(failed.get());
    assertEquals(fallback, s);
}

From source file:com.netflix.ribbon.RibbonTest.java

License:Apache License

@Test
public void testCacheHit() {
    HttpResourceGroup group = Ribbon.createHttpResourceGroup("myclient", ClientOptions.create()
            .withConfigurationBasedServerList("localhost:12345").withMaxAutoRetriesNextServer(1));
    final String content = "from cache";
    final String cacheKey = "somekey";
    HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("test")
            .withCacheProvider(cacheKey, new CacheProvider<ByteBuf>() {
                @Override//from  www .j  av  a 2  s  .  c  o m
                public Observable<ByteBuf> get(String key, Map<String, Object> vars) {
                    if (key.equals(cacheKey)) {
                        try {
                            return Observable.just(Unpooled.buffer().writeBytes(content.getBytes("UTF-8")));
                        } catch (UnsupportedEncodingException e) {
                            return Observable.error(e);
                        }
                    } else {
                        return Observable.error(new Exception("Cache miss"));
                    }
                }
            }).withUriTemplate("/").withMethod("GET").build();
    RibbonRequest<ByteBuf> request = template.requestBuilder().build();
    String result = request.execute().toString(Charset.defaultCharset());
    assertEquals(content, result);
}

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

License:Open Source License

/**
 * Constructs a new object./*  w ww .  ja  v a2  s  .  co  m*/
 *
 * @param packet The packet.
 */
public PacketEncoder(PacketEncoderIdentifier packet) {
    this.packet = packet;
    this.builder = new GamePacketBuilder(Unpooled.buffer());
}

From source file:com.rs3e.network.protocol.codec.login.LoginDecoder.java

License:Open Source License

/**
 * Decodes the header of login./*from ww  w  .j a  va2s. c o  m*/
 * 
 * @param ctx
 *            The channel handler context.
 * @param buf
 *            The byte buf for writing data.
 * @return The login message, or {@code Null}.
 */
private Object decodeHeader(ChannelHandlerContext ctx, ByteBuf buf) {
    if (buf.readable()) {

        new SecureRandom().nextInt();

        ByteBuf unpooled = Unpooled.buffer();
        unpooled.writeByte(0);
        // unpooled.writeLong(secureKey);
        ctx.channel().write(unpooled);

        setState(LoginState.CONNECTION_TYPE);
    }
    return null;
}

From source file:com.rs3e.network.protocol.login.LoginDecoder.java

License:Open Source License

/**
 * Decodes the header of login.//  www .  j ava  2s. co  m
 * @param ctx The channel handler context.
 * @param buf The byte buf for writing data.
 * @return The login message, or {@code Null}.
 */
private Object decodeHeader(ChannelHandlerContext ctx, ByteBuf buf) {
    if (buf.readable()) {

        @SuppressWarnings("unused")
        //long clientHash = buf.readUnsignedByte();
        int secureKey = new SecureRandom().nextInt();

        ByteBuf unpooled = Unpooled.buffer();
        unpooled.writeByte(0);
        //unpooled.writeLong(secureKey);
        ctx.channel().write(unpooled);

        setState(LoginState.CONNECTION_TYPE);
    }
    return null;
}

From source file:com.rs3e.network.protocol.worldlist.WorldListEncoder.java

License:Open Source License

@Override
public void encode(ChannelHandlerContext ctx, WorldListMessage list, ByteBuf out) throws Exception {
    ByteBuf buf = Unpooled.buffer();
    buf.writeByte(1);// w  w  w . j a  va  2s . c  o  m
    buf.writeByte(1);

    Country[] countries = list.getCountries();
    ByteBufUtils.writeSmart(buf, countries.length);
    for (Country country : countries) {
        ByteBufUtils.writeSmart(buf, country.getFlag());
        ByteBufUtils.writeWorldListString(buf, country.getName());
    }

    World[] worlds = list.getWorlds();
    int minId = worlds[0].getId();
    int maxId = worlds[0].getId();
    for (int i = 1; i < worlds.length; i++) {
        World world = worlds[i];
        int id = world.getId();

        if (id > maxId)
            maxId = id;
        if (id < minId)
            minId = id;
    }

    ByteBufUtils.writeSmart(buf, minId);
    ByteBufUtils.writeSmart(buf, maxId);
    ByteBufUtils.writeSmart(buf, worlds.length);

    for (World world : worlds) {
        ByteBufUtils.writeSmart(buf, world.getId() - minId);
        buf.writeByte(world.getCountry());
        buf.writeInt(world.getFlags());
        ByteBufUtils.writeWorldListString(buf, world.getActivity());
        ByteBufUtils.writeWorldListString(buf, world.getIp());
    }

    buf.writeInt(list.getSessionId());
    for (int i = 0; i < worlds.length; i++) {
        World world = worlds[i];
        ByteBufUtils.writeSmart(buf, world.getId() - minId);
        buf.writeShort(0);
    }

    out.writeByte(0); // 0 = ok, 7/9 = world full
    out.writeShort(buf.readableBytes());
    out.writeBytes(buf);
}

From source file:com.savageboy74.savagetech.handler.packets.PacketPipeline.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext ctx, AbstractPacket msg, List<Object> out) throws Exception {
    ByteBuf buffer = Unpooled.buffer();
    Class<? extends AbstractPacket> apClass = msg.getClass();

    if (!this.packets.contains(apClass)) {
        throw new NullPointerException(Strings.Packets.NOT_REGISTERED + apClass.getCanonicalName());
    }// ww  w . ja v  a 2 s.co  m

    byte discriminator = (byte) this.packets.indexOf(apClass);
    buffer.writeByte(discriminator);
    msg.encodeInto(ctx, buffer);

    FMLProxyPacket packet = new FMLProxyPacket(buffer.copy(),
            ctx.channel().attr(NetworkRegistry.FML_CHANNEL).get());
    out.add(packet);

}