Java Code Examples for io.netty.buffer.Unpooled

The following are top voted examples for showing how to use io.netty.buffer.Unpooled. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Re-Collector   File: PatternChunkSplitterTest.java   Source Code and License 7 votes vote down vote up
@Test
public void testEncodings() throws Exception {
    final PatternChunkSplitter splitter = new PatternChunkSplitter("^(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)");

    // "Feb 20 17:05:18 Hällö Wörld\nFeb 20 17:05:18 Büe\n" in ISO-8859-1 encoding
    final byte[] bytes = new byte[]{
            0x46, 0x65, 0x62, 0x20, 0x32, 0x30, 0x20, 0x31, 0x37, 0x3a, 0x30, 0x35, 0x3a, 0x31, 0x38, 0x20,
            0x48, (byte) 0xe4, 0x6c, 0x6c, (byte) 0xf6, 0x20, 0x57, (byte) 0xf6, 0x72, 0x6c, 0x64, 0x0a,
            0x46, 0x65, 0x62, 0x20, 0x32, 0x30, 0x20, 0x31, 0x37, 0x3a, 0x30, 0x35, 0x3a, 0x31, 0x38, 0x20,
            0x42, (byte) 0xfc, 0x65, 0x0a
    };

    // With correct encoding
    final ByteBuf buffer = Unpooled.copiedBuffer(bytes);
    final Iterator<String> iterator = splitter.splitRemaining(buffer, ISO_8859_1).iterator();

    assertEquals("Feb 20 17:05:18 Hällö Wörld\n", iterator.next());
    assertEquals("Feb 20 17:05:18 Büe\n", iterator.next());

    // With wrong encoding
    final ByteBuf buffer2 = Unpooled.copiedBuffer(bytes);
    final Iterator<String> iterator2 = splitter.splitRemaining(buffer2, UTF_8).iterator();

    assertNotEquals("Feb 20 17:05:18 Hällö Wörld\n", iterator2.next());
    assertNotEquals("Feb 20 17:05:18 Büe\n", iterator2.next());
}
 
Example 2
Project: angel   File: ServerDenseIntRowTest.java   Source Code and License 7 votes vote down vote up
@Test
public void testDeserialize() throws Exception {
  ByteBuf buf = Unpooled.buffer(16);
  buf.writeInt(0);
  buf.writeInt(1);
  buf.writeLong(2);
  buf.writeLong(3);
  buf.writeInt(4);
  buf.writeInt(3);
  buf.writeInt(-1);
  buf.writeInt(-2);
  buf.writeInt(-3);
  serverDenseIntRow.deserialize(buf);
  assertEquals(serverDenseIntRow.getRowId(), 0);
  assertEquals(serverDenseIntRow.getClock(), 1);
  assertEquals(serverDenseIntRow.getStartCol(), 2);
  assertEquals(serverDenseIntRow.getEndCol(), 3);
  assertEquals(serverDenseIntRow.getRowVersion(), 4);
  assertEquals(serverDenseIntRow.getData().get(0), -1, 0.0);
  assertEquals(serverDenseIntRow.getData().get(1), -2, 0.0);
  assertEquals(serverDenseIntRow.getData().get(2), -3, 0.0);
}
 
Example 3
Project: jsf-sdk   File: HttpJsonHandler.java   Source Code and License 7 votes vote down vote up
public static int writeBack(Channel channel, boolean isSuccess, String resultStr, boolean isKeepAlive) {
    ByteBuf content = Unpooled.copiedBuffer(resultStr, Constants.DEFAULT_CHARSET);
    HttpResponseStatus status;
    if (isSuccess) {
        status = HttpResponseStatus.OK;
    } else {
        status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
    }
    FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, status, content);
    //logger.info("result str:{}", resultStr);
    res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
    HttpHeaders.setContentLength(res, content.readableBytes());
    try {
        ChannelFuture f = channel.writeAndFlush(res);
        if (isKeepAlive) {
            HttpHeaders.setKeepAlive(res, true);
        } else {
            HttpHeaders.setKeepAlive(res, false);//set keepalive closed
            f.addListener(ChannelFutureListener.CLOSE);
        }
    } catch (Exception e2) {
        logger.warn("Failed to send HTTP response to remote, cause by:", e2);
    }

    return content.readableBytes();
}
 
Example 4
Project: angel   File: ServerDenseFloatRowTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testReadFrom() throws Exception {
  ByteBuf buf = Unpooled.buffer(16);
  buf.writeFloat((float) 10.00);
  buf.writeFloat((float) 11.00);
  buf.writeFloat((float) 12.00);
  serverDenseFloatRow.update(RowType.T_FLOAT_DENSE, buf, 3);
  DataOutputStream out = new DataOutputStream(new FileOutputStream("data"));
  serverDenseFloatRow.writeTo(out);
  out.close();
  DataInputStream in = new DataInputStream(new FileInputStream("data"));
  ServerDenseFloatRow newServerDenseFloatRow = new ServerDenseFloatRow(rowId, startCol, endCol);
  newServerDenseFloatRow.readFrom(in);

  assertEquals(newServerDenseFloatRow.getData().get(0), serverDenseFloatRow.getData().get(0),
      0.00);
  assertEquals(newServerDenseFloatRow.getData().get(1), serverDenseFloatRow.getData().get(1),
      0.00);
  assertEquals(newServerDenseFloatRow.getData().get(2), serverDenseFloatRow.getData().get(2),
      0.00);
}
 
Example 5
Project: proteus-java   File: RequestHandlingRSocket.java   Source Code and License 6 votes vote down vote up
@Override
public Mono<Void> fireAndForget(Payload payload) {
  try {
    ByteBuf metadata = Unpooled.wrappedBuffer(payload.getMetadata());
    int namespaceId = ProteusMetadata.namespaceId(metadata);
    int serviceId = ProteusMetadata.serviceId(metadata);

    ProteusService proteusService = getService(namespaceId, serviceId);

    if (proteusService == null) {
      return Mono.error(new ServiceNotFound(namespaceId, serviceId));
    }

    return proteusService.fireAndForget(payload);

  } catch (Throwable t) {
    return Mono.error(t);
  }
}
 
Example 6
Project: angel   File: ServerDenseFloatRowTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testDeserialize() throws Exception {
  ByteBuf buf = Unpooled.buffer(16);
  buf.writeInt(0);
  buf.writeInt(1);
  buf.writeLong(2);
  buf.writeLong(3);
  buf.writeInt(4);
  buf.writeInt(3);
  buf.writeFloat((float) -1.0);
  buf.writeFloat((float) -2.0);
  buf.writeFloat((float) -3.0);
  serverDenseFloatRow.deserialize(buf);
  assertEquals(serverDenseFloatRow.getRowId(), 0);
  assertEquals(serverDenseFloatRow.getClock(), 1);
  assertEquals(serverDenseFloatRow.getStartCol(), 2);
  assertEquals(serverDenseFloatRow.getEndCol(), 3);
  assertEquals(serverDenseFloatRow.getRowVersion(), 4);
  assertEquals(serverDenseFloatRow.getData().get(0), -1, 0.0);
  assertEquals(serverDenseFloatRow.getData().get(1), -2, 0.0);
  assertEquals(serverDenseFloatRow.getData().get(2), -3, 0.0);
}
 
Example 7
Project: message-broker   File: BasicCancelTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testEncodeDecode() throws Exception {
    BasicCancel testFrame = new BasicCancel(1,
                                            ShortString.parseString("1"),
                                            true);
    ByteBuf buf = Unpooled.buffer((int) testFrame.getMethodBodySize());
    testFrame.writeMethod(buf);
    BasicCancel decodedFrame = (BasicCancel) BasicCancel.getFactory()
                                                        .newInstance(buf, 1, testFrame.getMethodBodySize());

    Assert.assertEquals(decodedFrame.getChannel(), testFrame.getChannel(), "Decoded frame's channel should match"
            + " the original frame's channel");
    Assert.assertEquals(decodedFrame.getConsumerTag(), testFrame.getConsumerTag(), "Decoded frame's consumer-tag "
            + "should match the original frame's consumer-tag");
    Assert.assertEquals(decodedFrame.isNoWait(), testFrame.isNoWait(), "Decoded frame's no-wait bit "
            + "should match the original frame's no-wait bit");

}
 
Example 8
Project: message-broker   File: QueueBindTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testEncodeDecode() throws Exception {
    QueueBind testFrame = new QueueBind(1,
                                              ShortString.parseString("queue"),
                                              ShortString.parseString("amq.topic"),
                                              ShortString.parseString("a.b.c"),
                                              true,
                                              FieldTable.EMPTY_TABLE);
    ByteBuf buf = Unpooled.buffer((int) testFrame.getMethodBodySize());
    testFrame.writeMethod(buf);
    QueueBind decodedFrame = (QueueBind) QueueBind.getFactory()
                                                  .newInstance(buf, 1, testFrame.getMethodBodySize());

    Assert.assertEquals(decodedFrame.getChannel(), testFrame.getChannel(), "Decoded frame's channel should match"
            + " the original frame's channel");
    Assert.assertEquals(decodedFrame.getQueue(), testFrame.getQueue(), "Decoded frame's queue should match"
            + " the original frame's queue");
    Assert.assertEquals(decodedFrame.getExchange(), testFrame.getExchange(), "Decoded frame's exchange "
            + "should match the original frame's exchange");
    Assert.assertEquals(decodedFrame.getRoutingKey(), testFrame.getRoutingKey(), "Decoded frame's routing-key "
            + "should match the original frame's no-local bit");
    Assert.assertEquals(decodedFrame.isNoWait(), testFrame.isNoWait(), "Decoded frame's no-wait bit "
            + "should match the original frame's no-wait bit");
    Assert.assertEquals(decodedFrame.getArguments(), testFrame.getArguments(), "Decoded frame's arguments "
            + "should match the original frame's arguments");
}
 
Example 9
Project: teslog   File: HttpHelloWorldServerHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;

        boolean keepAlive = HttpUtil.isKeepAlive(req);
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT));
        response.headers().set(CONTENT_TYPE, "text/plain");
        response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());

        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, KEEP_ALIVE);
            ctx.write(response);
        }
    }
}
 
Example 10
Project: cornerstone   File: HttpHelloWorldServerHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if(msg instanceof  HttpContent){
        System.out.println(msg);
    }
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;
        String path = URI.create(req.getUri()).getPath();

        boolean keepAlive = HttpHeaders.isKeepAlive(req);
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT));
        response.headers().set(CONTENT_TYPE, "text/plain");
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, Values.KEEP_ALIVE);
            ctx.write(response);
        }
    }
}
 
Example 11
Project: angel   File: ServerDenseIntRowTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testUpdate() throws Exception {
  serverDenseIntRow = new ServerDenseIntRow(rowId, startCol, endCol);
  ByteBuf buf = Unpooled.buffer(16);
  buf.writeInt(0);
  buf.writeInt(1);
  buf.writeInt(-1);
  int newValue0 = buf.getInt(0) + serverDenseIntRow.getData().get(0);
  int newValue1 = buf.getInt(4) + serverDenseIntRow.getData().get(1);
  serverDenseIntRow.update(RowType.T_INT_DENSE, buf, 3);
  assertEquals(serverDenseIntRow.getData().get(0), newValue0, 0.000);
  assertEquals(serverDenseIntRow.getData().get(1), newValue1, 0.000);
  assertEquals(serverDenseIntRow.getData().get(2), -1, 0.000);

  serverDenseIntRow = new ServerDenseIntRow(rowId, startCol, endCol);
  buf = Unpooled.buffer(0);
  buf.writeInt(0);
  buf.writeInt(1);
  buf.writeInt(2);
  buf.writeInt(-2);
  serverDenseIntRow.update(RowType.T_INT_SPARSE, buf, 2);
  assertEquals(serverDenseIntRow.getData().get(0), 1, 0.000);
  assertEquals(serverDenseIntRow.getData().get(1), 0, 0.000);
  assertEquals(serverDenseIntRow.getData().get(2), -2, 0.000);
}
 
Example 12
Project: incubator-plc4x   File: IsoTPProtocolTest.java   Source Code and License 6 votes vote down vote up
@Test
@Tag("fast")
public void decodeDisconnectionConfirm() throws Exception {
    ChannelHandlerContext ctx = new MockChannelHandlerContext();
    ByteBuf buf = Unpooled.buffer();
    ArrayList<Object> out = new ArrayList<>();

    buf.writeByte(0x5); // header length
    buf.writeByte(TpduCode.DISCONNECT_CONFIRM.getCode());
    buf.writeShort(0x01); // destination reference
    buf.writeShort(0x02); // source reference
    buf.writeByte(DisconnectReason.NORMAL.getCode());
    IsoOnTcpMessage in = new IsoOnTcpMessage(buf);

    isoTPProtocol.decode(ctx, in, out);

    assertTrue(out.size() == 1, "Message not decoded");

    DisconnectConfirmTpdu requestTpdu = (DisconnectConfirmTpdu) ((IsoTPMessage)out.get(0)).getTpdu();

    assertTrue(requestTpdu.getTpduCode() == TpduCode.DISCONNECT_CONFIRM, "Message code not correct");
    assertTrue(requestTpdu.getDestinationReference() == (short) 0x1, "Message destination reference not correct");
    assertTrue(requestTpdu.getSourceReference() == (short) 0x2, "Message source reference not correct");
    assertTrue(requestTpdu.getParameters().isEmpty(), "Message contains paramaters");
}
 
Example 13
Project: qonduit   File: NonSslRedirectHandler.java   Source Code and License 6 votes vote down vote up
@Override
protected ChannelHandler newNonSslHandler(ChannelHandlerContext context) {
    return new ChannelInboundHandlerAdapter() {

        private HttpResponseEncoder encoder = new HttpResponseEncoder();

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            LOG.trace("Received non-SSL request, returning redirect");
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.MOVED_PERMANENTLY, Unpooled.EMPTY_BUFFER);
            response.headers().set(Names.LOCATION, redirectAddress);
            LOG.trace(Constants.LOG_RETURNING_RESPONSE, response);
            encoder.write(ctx, response, ctx.voidPromise());
            ctx.flush();
        }
    };
}
 
Example 14
Project: spark_deep   File: SaslEncryption.java   Source Code and License 6 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out)
  throws Exception {

  byte[] data;
  int offset;
  int length = msg.readableBytes();
  if (msg.hasArray()) {
    data = msg.array();
    offset = msg.arrayOffset();
    msg.skipBytes(length);
  } else {
    data = new byte[length];
    msg.readBytes(data);
    offset = 0;
  }

  out.add(Unpooled.wrappedBuffer(backend.unwrap(data, offset, length)));
}
 
Example 15
Project: upgradeToy   File: SimpleClient.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {
    Bootstrap b = new Bootstrap();
    b.group(new NioEventLoopGroup())
            .channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel ch) throws Exception {
                }
            });
    b.connect("localhost", 8090).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                future.channel().write(Unpooled.buffer().writeBytes("123".getBytes()));
                future.channel().flush();
                future.channel().close();
            }
        }
    });
}
 
Example 16
Project: AlphaLibary   File: EchoServerHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf in = (ByteBuf) msg;
    String sentData = in.toString(CharsetUtil.UTF_8);
    String returnee = sentData + "-::=::-" + "{}";

    RequestProcessor reprocessor = EchoServer.process(sentData);

    if (reprocessor != null)
        returnee = sentData + "-::=::-" + reprocessor.getProcessedData();

    ChannelFuture f = ctx.writeAndFlush(Unpooled.copiedBuffer(returnee, CharsetUtil.UTF_8)).sync();

    if (!f.isSuccess())
        try {
            throw f.cause();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
}
 
Example 17
Project: netty-socketio-demo   File: HttpCheckServer.java   Source Code and License 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

    if (msg instanceof HttpRequest) {
        HttpRequest request = (HttpRequest) msg;
        logger.info("check");
    }

    if (msg instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) msg;
        ByteBuf content = httpContent.content();
        content.release();

        ByteBuf byteBuf = Unpooled.wrappedBuffer("ok".getBytes("UTF-8"));
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, byteBuf);
        response.headers().set("Content-Type", "text/html; charset=UTF-8");
        response.headers().set("Content-Length", byteBuf.readableBytes());
        ctx.channel().write(response);
        ctx.channel().flush();
    }
}
 
Example 18
Project: CloudNet   File: WebsiteDocumentation.java   Source Code and License 6 votes vote down vote up
@Override
public FullHttpResponse get(ChannelHandlerContext channelHandlerContext, QueryDecoder queryDecoder, PathProvider path, HttpRequest httpRequest) throws Exception
{
    CloudNet.getLogger().debug("HTTP Request from " + channelHandlerContext.channel().remoteAddress());

    StringBuilder stringBuilder = new StringBuilder();

    try (InputStream inputStream = WebsiteDocumentation.class.getClassLoader().getResourceAsStream("files/api-doc.txt");
         BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)))
    {
        String input;
        while ((input = bufferedReader.readLine()) != null)
        {
            stringBuilder.append(input).append(System.lineSeparator());
        }
    }

    String output = stringBuilder.substring(0);
    ByteBuf byteBuf = Unpooled.wrappedBuffer(output.getBytes(StandardCharsets.UTF_8));
    FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(httpRequest.getProtocolVersion(), HttpResponseStatus.OK, byteBuf);
    fullHttpResponse.headers().set("Content-Type", "text/plain");
    return fullHttpResponse;
}
 
Example 19
Project: incubator-plc4x   File: S7ProtocolTest.java   Source Code and License 6 votes vote down vote up
@Test
@Tag("fast")
public void decode() throws Exception {
    //TODO: finish me
    LinkedList<Object> out = new LinkedList<>();
    ByteBuf buffer = Unpooled.buffer();
    // Magic Number
    buffer.writeByte(0x32);
    buffer.writeByte(MessageType.JOB.getCode());
    // Reserved magic value
    buffer.writeShort(0x0000);
    // tpduReference
    buffer.writeShort(0x0000);
    // headerParametersLength
    buffer.writeShort(0x0000);
    // userDataLength
    buffer.writeShort(0x0000);
    SUT.decode(null, new IsoTPMessage(mock(Tpdu.class), buffer), out);
    assertThat(out).hasSize(1);
}
 
Example 20
Project: DecompiledMinecraft   File: NetHandlerPlayClient.java   Source Code and License 6 votes vote down vote up
/**
 * Registers some server properties (gametype,hardcore-mode,terraintype,difficulty,player limit), creates a new
 * WorldClient and sets the player initial dimension
 */
public void handleJoinGame(S01PacketJoinGame packetIn)
{
    PacketThreadUtil.checkThreadAndEnqueue(packetIn, this, this.gameController);
    this.gameController.playerController = new PlayerControllerMP(this.gameController, this);
    this.clientWorldController = new WorldClient(this, new WorldSettings(0L, packetIn.getGameType(), false, packetIn.isHardcoreMode(), packetIn.getWorldType()), packetIn.getDimension(), packetIn.getDifficulty(), this.gameController.mcProfiler);
    this.gameController.gameSettings.difficulty = packetIn.getDifficulty();
    this.gameController.loadWorld(this.clientWorldController);
    this.gameController.thePlayer.dimension = packetIn.getDimension();
    this.gameController.displayGuiScreen(new GuiDownloadTerrain(this));
    this.gameController.thePlayer.setEntityId(packetIn.getEntityId());
    this.currentServerMaxPlayers = packetIn.getMaxPlayers();
    this.gameController.thePlayer.setReducedDebug(packetIn.isReducedDebugInfo());
    this.gameController.playerController.setGameType(packetIn.getGameType());
    this.gameController.gameSettings.sendSettingsToServer();
    this.netManager.sendPacket(new C17PacketCustomPayload("MC|Brand", (new PacketBuffer(Unpooled.buffer())).writeString(ClientBrandRetriever.getClientModName())));
}
 
Example 21
Project: incubator-servicecomb-java-chassis   File: TestTcpClientConnection.java   Source Code and License 6 votes vote down vote up
@Test
public void send_inWorkingStatus(@Mocked AbstractTcpClientPackage tcpClientPackage,
    @Mocked TcpOutputStream tcpOutputStream) {
  Deencapsulation.setField(tcpClientConnection, "status", Status.WORKING);

  long msgId = 1;
  ByteBuf byteBuf = Unpooled.buffer();
  new Expectations(tcpClientConnection) {
    {
      tcpClientPackage.getMsgId();
      result = msgId;
      tcpClientPackage.createStream();
      result = tcpOutputStream;
      tcpOutputStream.getByteBuf();
      result = byteBuf;
    }
  };
  tcpClientConnection.send(tcpClientPackage, ar -> {
  });

  Assert.assertSame(byteBuf, writeQueue.poll());
  Assert.assertNull(writeQueue.poll());
  Assert.assertEquals(Status.WORKING, Deencapsulation.getField(tcpClientConnection, "status"));
}
 
Example 22
Project: incubator-plc4x   File: IsoTPProtocolTest.java   Source Code and License 6 votes vote down vote up
@Test
@Tag("fast")
public void decodeData() throws Exception {
  ChannelHandlerContext ctx = new MockChannelHandlerContext();
  ByteBuf buf = Unpooled.buffer();
  ArrayList<Object> out = new ArrayList<>();

  buf.writeByte(0x3); // header length
  buf.writeByte(TpduCode.DATA.getCode());
  buf.writeByte((byte) 0x1); // Tpdu code
  IsoOnTcpMessage in = new IsoOnTcpMessage(buf);

  isoTPProtocol.decode(ctx, in, out);

  assertTrue(out.size() == 1, "Message not decoded");

  DataTpdu requestTpdu = (DataTpdu) ((IsoTPMessage)out.get(0)).getTpdu();

  assertTrue(requestTpdu.getTpduCode() == TpduCode.DATA, "Message code not correct");
  assertTrue(requestTpdu.getTpduRef() == (short) 0x1, "Message Tpdu reference not correct");
  assertTrue(!requestTpdu.isEot(), "Message EOT not correct");
  assertTrue(requestTpdu.getParameters().isEmpty(), "Message contains paramaters");
}
 
Example 23
Project: Backmemed   File: EntityPlayerMP.java   Source Code and License 6 votes vote down vote up
public void displayVillagerTradeGui(IMerchant villager)
{
    this.getNextWindowId();
    this.openContainer = new ContainerMerchant(this.inventory, villager, this.world);
    this.openContainer.windowId = this.currentWindowId;
    this.openContainer.addListener(this);
    IInventory iinventory = ((ContainerMerchant)this.openContainer).getMerchantInventory();
    ITextComponent itextcomponent = villager.getDisplayName();
    this.connection.sendPacket(new SPacketOpenWindow(this.currentWindowId, "minecraft:villager", itextcomponent, iinventory.getSizeInventory()));
    MerchantRecipeList merchantrecipelist = villager.getRecipes(this);

    if (merchantrecipelist != null)
    {
        PacketBuffer packetbuffer = new PacketBuffer(Unpooled.buffer());
        packetbuffer.writeInt(this.currentWindowId);
        merchantrecipelist.writeToBuf(packetbuffer);
        this.connection.sendPacket(new SPacketCustomPayload("MC|TrList", packetbuffer));
    }
}
 
Example 24
Project: elasticsearch_my   File: Netty4Utils.java   Source Code and License 6 votes vote down vote up
/**
 * Turns the given BytesReference into a ByteBuf. Note: the returned ByteBuf will reference the internal
 * pages of the BytesReference. Don't free the bytes of reference before the ByteBuf goes out of scope.
 */
public static ByteBuf toByteBuf(final BytesReference reference) {
    if (reference.length() == 0) {
        return Unpooled.EMPTY_BUFFER;
    }
    if (reference instanceof ByteBufBytesReference) {
        return ((ByteBufBytesReference) reference).toByteBuf();
    } else {
        final BytesRefIterator iterator = reference.iterator();
        // usually we have one, two, or three components from the header, the message, and a buffer
        final List<ByteBuf> buffers = new ArrayList<>(3);
        try {
            BytesRef slice;
            while ((slice = iterator.next()) != null) {
                buffers.add(Unpooled.wrappedBuffer(slice.bytes, slice.offset, slice.length));
            }
            final CompositeByteBuf composite = Unpooled.compositeBuffer(buffers.size());
            composite.addComponents(true, buffers);
            return composite;
        } catch (IOException ex) {
            throw new AssertionError("no IO happens here", ex);
        }
    }
}
 
Example 25
Project: incubator-plc4x   File: IsoTPProtocolTest.java   Source Code and License 6 votes vote down vote up
@Test
@Tag("fast")
public void encodeSizeParameter() throws Exception {
    ChannelHandlerContext ctx = new MockChannelHandlerContext();
    ByteBuf buf = Unpooled.buffer();
    ArrayList<Parameter> parmameters = new ArrayList<>();
    TpduSizeParameter sizeParameter = new TpduSizeParameter(TpduSize.SIZE_512);
    parmameters.add(sizeParameter);
    ErrorTpdu tpdu = new ErrorTpdu((short)0x1, RejectCause.REASON_NOT_SPECIFIED, parmameters, buf);
    ArrayList<Object> out = new ArrayList<>();

    isoTPProtocol.encode(ctx, tpdu, out);

    assertTrue(out.size() == 1, "Message not decoded");

    ByteBuf userData = ((IsoOnTcpMessage)out.get(0)).getUserData();

    assertTrue(userData.writerIndex() == 8, "Incorrect message length");
    assertTrue(userData.readByte() == (byte)0x7, "Incorrect header length");
    assertTrue(userData.readByte() == TpduCode.TPDU_ERROR.getCode(), "Incorrect Tpdu code");
    assertTrue(userData.readShort() == (short)0x1, "Incorrect destination reference code");
    assertTrue(userData.readByte() == RejectCause.REASON_NOT_SPECIFIED.getCode(), "Incorrect reject cause code");
    assertTrue(userData.readByte() == ParameterCode.TPDU_SIZE.getCode(), "Incorrect parameter code");
    assertTrue(userData.readByte() == (byte)0x1, "Incorrect parameter length");
    assertTrue(userData.readByte() == TpduSize.SIZE_512.getCode(), "Incorrect tdpu size");
}
 
Example 26
Project: Limitart   File: SendMessageUtil.java   Source Code and License 6 votes vote down vote up
public static void sendMessage(AbstractBinaryEncoder encoder, Channel channel, Message msg,
		Proc3<Boolean, Throwable, Channel> listener) throws MessageCodecException {
	if (channel == null) {
		Procs.invoke(listener, false, new NullPointerException("channel"), null);
		return;
	}
	if (!channel.isWritable()) {
		Procs.invoke(listener, false, new IOException(" channel " + channel.remoteAddress() + " is unwritable"),
				channel);
		return;
	}
	ByteBuf buffer = Unpooled.buffer();
	encoder.beforeWriteBody(buffer, msg.getMessageId());
	msg.buffer(buffer);
	try {
		msg.encode();
	} catch (Exception e) {
		throw new MessageCodecException(e);
	}
	msg.buffer(null);
	encoder.afterWriteBody(buffer);
	flow(msg.getClass(), buffer);
	channel.writeAndFlush(buffer).addListener((ChannelFutureListener) arg0 -> {
		Procs.invoke(listener, arg0.isSuccess(), arg0.cause(), arg0.channel());
	});
}
 
Example 27
Project: message-broker   File: BasicCancelTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testEncodeDecodeWithFalseFlags() throws Exception {
    BasicCancel testFrame = new BasicCancel(1,
                                            ShortString.parseString("1"),
                                            false);
    ByteBuf buf = Unpooled.buffer((int) testFrame.getMethodBodySize());
    testFrame.writeMethod(buf);
    BasicCancel decodedFrame = (BasicCancel) BasicCancel.getFactory()
                                                        .newInstance(buf, 1, testFrame.getMethodBodySize());

    Assert.assertEquals(decodedFrame.getChannel(), testFrame.getChannel(), "Decoded frame's channel should match"
            + " the original frame's channel");
    Assert.assertEquals(decodedFrame.getConsumerTag(), testFrame.getConsumerTag(), "Decoded frame's consumer-tag "
            + "should match the original frame's consumer-tag");
    Assert.assertEquals(decodedFrame.isNoWait(), testFrame.isNoWait(), "Decoded frame's no-wait bit "
            + "should match the original frame's no-wait bit");

}
 
Example 28
Project: incubator-plc4x   File: IsoTPProtocolTest.java   Source Code and License 6 votes vote down vote up
@Test
@Tag("fast")
public void encodeDisconnectionConfirm() throws Exception {
    ChannelHandlerContext ctx = new MockChannelHandlerContext();
    ByteBuf buf = Unpooled.buffer();
    DisconnectConfirmTpdu tpdu = new DisconnectConfirmTpdu((short)0x1, (short)(0x2), Collections.emptyList(), buf);
    ArrayList<Object> out = new ArrayList<>();

    isoTPProtocol.encode(ctx, tpdu, out);

    assertTrue(out.size() == 1, "Message not decoded");

    ByteBuf userData = ((IsoOnTcpMessage)out.get(0)).getUserData();

    assertTrue(userData.writerIndex() == 6, "Incorrect message length");
    assertTrue(userData.readByte() == (byte)0x5, "Incorrect header length");
    assertTrue(userData.readByte() == TpduCode.DISCONNECT_CONFIRM.getCode(), "Incorrect Tpdu code");
    assertTrue(userData.readShort() == (short)0x1, "Incorrect destination reference code");
    assertTrue(userData.readShort() == (short)0x2, "Incorrect source reference code");
}
 
Example 29
Project: incubator-plc4x   File: IsoTPProtocolTest.java   Source Code and License 5 votes vote down vote up
@Test
@Tag("fast")
public void decodeNull() throws Exception {
    ChannelHandlerContext ctx = new MockChannelHandlerContext();
    ByteBuf buf = Unpooled.buffer();
    ArrayList<Object> out = new ArrayList<>();
    IsoOnTcpMessage in = new IsoOnTcpMessage(buf);

    isoTPProtocol.decode(ctx, in, out);
    assertTrue(out.size() == 0, "Message decoded when blank message passed");

    isoTPProtocol.decode(ctx, null, out);
    assertTrue(out.size() == 0, "Message decoded when blank message passed");
}
 
Example 30
Project: DecompiledMinecraft   File: NettyCompressionDecoder.java   Source Code and License 5 votes vote down vote up
protected void decode(ChannelHandlerContext p_decode_1_, ByteBuf p_decode_2_, List<Object> p_decode_3_) throws DataFormatException, Exception
{
    if (p_decode_2_.readableBytes() != 0)
    {
        PacketBuffer packetbuffer = new PacketBuffer(p_decode_2_);
        int i = packetbuffer.readVarIntFromBuffer();

        if (i == 0)
        {
            p_decode_3_.add(packetbuffer.readBytes(packetbuffer.readableBytes()));
        }
        else
        {
            if (i < this.treshold)
            {
                throw new DecoderException("Badly compressed packet - size of " + i + " is below server threshold of " + this.treshold);
            }

            if (i > 2097152)
            {
                throw new DecoderException("Badly compressed packet - size of " + i + " is larger than protocol maximum of " + 2097152);
            }

            byte[] abyte = new byte[packetbuffer.readableBytes()];
            packetbuffer.readBytes(abyte);
            this.inflater.setInput(abyte);
            byte[] abyte1 = new byte[i];
            this.inflater.inflate(abyte1);
            p_decode_3_.add(Unpooled.wrappedBuffer(abyte1));
            this.inflater.reset();
        }
    }
}
 
Example 31
Project: BaseClient   File: GuiMerchant.java   Source Code and License 5 votes vote down vote up
/**
 * Called by the controls from the buttonList when activated. (Mouse pressed for buttons)
 */
protected void actionPerformed(GuiButton button) throws IOException
{
    boolean flag = false;

    if (button == this.nextButton)
    {
        ++this.selectedMerchantRecipe;
        MerchantRecipeList merchantrecipelist = this.merchant.getRecipes(this.mc.thePlayer);

        if (merchantrecipelist != null && this.selectedMerchantRecipe >= merchantrecipelist.size())
        {
            this.selectedMerchantRecipe = merchantrecipelist.size() - 1;
        }

        flag = true;
    }
    else if (button == this.previousButton)
    {
        --this.selectedMerchantRecipe;

        if (this.selectedMerchantRecipe < 0)
        {
            this.selectedMerchantRecipe = 0;
        }

        flag = true;
    }

    if (flag)
    {
        ((ContainerMerchant)this.inventorySlots).setCurrentRecipeIndex(this.selectedMerchantRecipe);
        PacketBuffer packetbuffer = new PacketBuffer(Unpooled.buffer());
        packetbuffer.writeInt(this.selectedMerchantRecipe);
        this.mc.getNetHandler().addToSendQueue(new C17PacketCustomPayload("MC|TrSel", packetbuffer));
    }
}
 
Example 32
Project: Lithium-Spigot   File: LithiumUtils.java   Source Code and License 5 votes vote down vote up
public static byte[] writeUTF8String(String string) {
	string = '\n' + string;
	val to = Unpooled.buffer();
	to.writeByte(0);
	byte[] utf8Bytes = string.getBytes(StandardCharsets.UTF_8);
	Validate.isTrue(varIntByteCount(utf8Bytes.length) < 3, "The string is too long for this encoding.");
	writeVarInt(to, utf8Bytes.length, 2);
	to.writeBytes(utf8Bytes);
	return to.array();
}
 
Example 33
Project: angel   File: ServerPartitionTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testDeserialize() throws Exception {
  ByteBuf buf = Unpooled.buffer(16);
  serverPartition.serialize(buf);
  PartitionKey partitionKeyNew = new PartitionKey(2, 1, 1, 2, 8, 10);
  ServerPartition serverPartitionNew =
      new ServerPartition(partitionKeyNew, RowType.T_DOUBLE_DENSE);
  assertNotEquals(serverPartition.getPartitionKey().getPartitionId(),
      serverPartitionNew.getPartitionKey().getPartitionId());
  serverPartitionNew.deserialize(buf);
  assertEquals(serverPartition.getPartitionKey().getPartitionId(),
      serverPartitionNew.getPartitionKey().getPartitionId());
}
 
Example 34
Project: qonduit   File: HttpHandler.java   Source Code and License 5 votes vote down vote up
default void sendHttpError(ChannelHandlerContext ctx, QonduitException e) throws JsonProcessingException {
    LOG.error("Error in pipeline, response code: {}, message: {}", e.getCode(), e.getMessage());
    byte[] buf = JsonUtil.getObjectMapper().writeValueAsBytes(
            "ResponseCode: " + e.getCode() + " Message: " + e.getMessage());
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(e
            .getCode()), Unpooled.copiedBuffer(buf));
    response.headers().set(Names.CONTENT_TYPE, Constants.JSON_TYPE);
    response.headers().set(Names.CONTENT_LENGTH, response.content().readableBytes());
    e.getResponseHeaders().entrySet().forEach(entry -> response.headers().set(entry.getKey(), entry.getValue()));
    // Send the error response
    sendResponse(ctx, response);
}
 
Example 35
Project: CustomWorldGen   File: MinecraftServer.java   Source Code and License 5 votes vote down vote up
public void applyServerIconToResponse(ServerStatusResponse response)
{
    File file1 = this.getFile("server-icon.png");

    if (!file1.exists())
    {
        file1 = this.getActiveAnvilConverter().getFile(this.getFolderName(), "icon.png");
    }

    if (file1.isFile())
    {
        ByteBuf bytebuf = Unpooled.buffer();

        try
        {
            BufferedImage bufferedimage = ImageIO.read(file1);
            Validate.validState(bufferedimage.getWidth() == 64, "Must be 64 pixels wide", new Object[0]);
            Validate.validState(bufferedimage.getHeight() == 64, "Must be 64 pixels high", new Object[0]);
            ImageIO.write(bufferedimage, "PNG", (OutputStream)(new ByteBufOutputStream(bytebuf)));
            ByteBuf bytebuf1 = Base64.encode(bytebuf);
            response.setFavicon("data:image/png;base64," + bytebuf1.toString(Charsets.UTF_8));
        }
        catch (Exception exception)
        {
            LOG.error((String)"Couldn\'t load server icon", (Throwable)exception);
        }
        finally
        {
            bytebuf.release();
        }
    }
}
 
Example 36
Project: angel   File: ServerDenseIntRowTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testSerialize() throws Exception {
  ByteBuf buf = Unpooled.buffer(16);
  serverDenseIntRow.setClock(8);
  serverDenseIntRow.serialize(buf);
  assertEquals(serverDenseIntRow.getRowId(), buf.readInt());
  assertEquals(serverDenseIntRow.getClock(), buf.readInt());
  assertEquals(serverDenseIntRow.getStartCol(), buf.readLong());
  assertEquals(serverDenseIntRow.getEndCol(), buf.readLong());
  assertEquals(serverDenseIntRow.getRowVersion(), buf.readInt());
  assertEquals(serverDenseIntRow.getEndCol() - serverDenseIntRow.getStartCol(), buf.readInt());
}
 
Example 37
Project: angel   File: DefaultRowUpdaterTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testUpdateIntDenseToIntDense() throws Exception {
  ServerDenseIntRow serverDenseIntRow = new ServerDenseIntRow(rowId, startCol, endCol);
  ByteBuf buf = Unpooled.buffer(16);
  buf.writeInt(0);
  buf.writeInt(1);
  buf.writeInt(-1);
  rowUpdater.updateIntDenseToIntDense(3, buf, serverDenseIntRow);
  assertEquals(serverDenseIntRow.getData().get(0), 0);
  assertEquals(serverDenseIntRow.getData().get(1), 1);
  assertEquals(serverDenseIntRow.getData().get(2), -1);
}
 
Example 38
Project: Backmemed   File: GuiEditCommandBlockMinecart.java   Source Code and License 5 votes vote down vote up
/**
 * Called by the controls from the buttonList when activated. (Mouse pressed for buttons)
 */
protected void actionPerformed(GuiButton button) throws IOException
{
    if (button.enabled)
    {
        if (button.id == 1)
        {
            this.commandBlockLogic.setTrackOutput(this.trackOutput);
            this.mc.displayGuiScreen((GuiScreen)null);
        }
        else if (button.id == 0)
        {
            PacketBuffer packetbuffer = new PacketBuffer(Unpooled.buffer());
            packetbuffer.writeByte(this.commandBlockLogic.getCommandBlockType());
            this.commandBlockLogic.fillInInfo(packetbuffer);
            packetbuffer.writeString(this.commandField.getText());
            packetbuffer.writeBoolean(this.commandBlockLogic.shouldTrackOutput());
            this.mc.getConnection().sendPacket(new CPacketCustomPayload("MC|AdvCmd", packetbuffer));

            if (!this.commandBlockLogic.shouldTrackOutput())
            {
                this.commandBlockLogic.setLastOutput((ITextComponent)null);
            }

            this.mc.displayGuiScreen((GuiScreen)null);
        }
        else if (button.id == 4)
        {
            this.commandBlockLogic.setTrackOutput(!this.commandBlockLogic.shouldTrackOutput());
            this.updateCommandOutput();
        }
    }
}
 
Example 39
Project: NSS   File: SocksServerConnectHandler.java   Source Code and License 5 votes vote down vote up
/**
 * 给remoteserver发送数据--需要进行加密处理
 * 
 * @param data
 * @param length
 * @param channel
 */
public void sendRemote(byte[] data, int length, Channel channel) {
	if(isProxy) {
		_crypt.encrypt(data, length, _remoteOutStream);
		data = _remoteOutStream.toByteArray();
	}
	channel.writeAndFlush(Unpooled.wrappedBuffer(data));
	logger.debug("sendRemote message:isProxy = " + isProxy +",length = " + length+",channel = " + channel);
}
 
Example 40
Project: JRediClients   File: RedissonTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testIteratorNotLooped2() {
    RedissonBaseIterator<Integer> iter = new RedissonBaseIterator<Integer>() {
        int i;
        @Override
        ListScanResult<ScanObjectEntry> iterator(InetSocketAddress client, long nextIterPos) {
            i++;
            if (i == 1) {
                return new ListScanResult<ScanObjectEntry>(14L, Arrays.asList(new ScanObjectEntry(Unpooled.wrappedBuffer(new byte[] {1}), 1)));
            }
            if (i == 2) {
                return new ListScanResult(7L, Collections.emptyList());
            }
            if (i == 3) {
                return new ListScanResult(0L, Collections.emptyList());
            }
            if (i == 4) {
                return new ListScanResult(14L, Collections.emptyList());
            }
            Assert.fail();
            return null;
        }

        @Override
        void remove(Integer value) {
        }
        
    };
    
    Assert.assertTrue(iter.hasNext());
    assertThat(iter.next()).isEqualTo(1);
    Assert.assertFalse(iter.hasNext());
}