io.netty.buffer.ByteBufUtil Java Examples

The following examples show how to use io.netty.buffer.ByteBufUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SchemaUtils.java    From pulsar with Apache License 2.0 6 votes vote down vote up
public static Object toAvroObject(Object value) {
    if (value != null) {
        if (value instanceof ByteBuffer) {
            ByteBuffer bb = (ByteBuffer) value;
            byte[] bytes = new byte[bb.remaining()];
            bb.duplicate().get(bytes);
            return bytes;
        } else if (value instanceof ByteBuf) {
            return ByteBufUtil.getBytes((ByteBuf) value);
        } else {
            return value;
        }
    } else {
        return null;
    }
}
 
Example #2
Source File: HttpObjectEncoder.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
private static void encodeHeader(CharSequence name, CharSequence value, ByteBuf byteBuf, Buffer buffer) {
    final int nameLen = name.length();
    final int valueLen = value.length();
    final int entryLen = nameLen + valueLen + 4;
    byteBuf.ensureWritable(entryLen);
    int offset = byteBuf.writerIndex();
    writeAscii(name, byteBuf, buffer, offset);
    offset += nameLen;
    ByteBufUtil.setShortBE(byteBuf, offset, COLON_AND_SPACE_SHORT);
    offset += 2;
    writeAscii(value, byteBuf, buffer, offset);
    offset += valueLen;
    ByteBufUtil.setShortBE(byteBuf, offset, CRLF_SHORT);
    offset += 2;
    byteBuf.writerIndex(offset);
}
 
Example #3
Source File: AbstractEpollChannel.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an off-heap copy of the specified {@link ByteBuf}, and releases the specified holder.
 * The caller must ensure that the holder releases the original {@link ByteBuf} when the holder is released by
 * this method.返回指定ByteBuf的堆外副本,并释放指定的holder。调用方必须确保持有者在通过此方法释放持有者时释放原始ByteBuf。
 */
protected final ByteBuf newDirectBuffer(Object holder, ByteBuf buf) {
    final int readableBytes = buf.readableBytes();
    if (readableBytes == 0) {
        ReferenceCountUtil.release(holder);
        return Unpooled.EMPTY_BUFFER;
    }

    final ByteBufAllocator alloc = alloc();
    if (alloc.isDirectBufferPooled()) {
        return newDirectBuffer0(holder, buf, alloc, readableBytes);
    }

    final ByteBuf directBuf = ByteBufUtil.threadLocalDirectBuffer();
    if (directBuf == null) {
        return newDirectBuffer0(holder, buf, alloc, readableBytes);
    }

    directBuf.writeBytes(buf, buf.readerIndex(), readableBytes);
    ReferenceCountUtil.safeRelease(holder);
    return directBuf;
}
 
Example #4
Source File: HttpClientMockWrapper.java    From azure-cosmosdb-java with MIT License 6 votes vote down vote up
public HttpClientResponse<ByteBuf> asHttpClientResponse() {
    if (this.networkFailure != null) {
        return null;
    }

    HttpClientResponse<ByteBuf> resp = Mockito.mock(HttpClientResponse.class);
    Mockito.doReturn(HttpResponseStatus.valueOf(status)).when(resp).getStatus();
    Mockito.doReturn(Observable.just(ByteBufUtil.writeUtf8(ByteBufAllocator.DEFAULT, content))).when(resp).getContent();

    DefaultHttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(status), httpHeaders);

    try {
        Constructor<HttpResponseHeaders> constructor = HttpResponseHeaders.class.getDeclaredConstructor(HttpResponse.class);
        constructor.setAccessible(true);
        HttpResponseHeaders httpResponseHeaders = constructor.newInstance(httpResponse);
        Mockito.doReturn(httpResponseHeaders).when(resp).getHeaders();

    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException | NoSuchMethodException | SecurityException e) {
        throw new IllegalStateException("Failed to instantiate class object.", e);
    }

    return resp;
}
 
Example #5
Source File: NettyServerHandler.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
private void respondWithHttpError(
    ChannelHandlerContext ctx, int streamId, int code, Status.Code statusCode, String msg) {
  Metadata metadata = new Metadata();
  metadata.put(InternalStatus.CODE_KEY, statusCode.toStatus());
  metadata.put(InternalStatus.MESSAGE_KEY, msg);
  byte[][] serialized = InternalMetadata.serialize(metadata);

  Http2Headers headers = new DefaultHttp2Headers(true, serialized.length / 2)
      .status("" + code)
      .set(CONTENT_TYPE_HEADER, "text/plain; encoding=utf-8");
  for (int i = 0; i < serialized.length; i += 2) {
    headers.add(new AsciiString(serialized[i], false), new AsciiString(serialized[i + 1], false));
  }
  encoder().writeHeaders(ctx, streamId, headers, 0, false, ctx.newPromise());
  ByteBuf msgBuf = ByteBufUtil.writeUtf8(ctx.alloc(), msg);
  encoder().writeData(ctx, streamId, msgBuf, 0, true, ctx.newPromise());
}
 
Example #6
Source File: NettyServerHandlerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private void inboundDataShouldForwardToStreamListener(boolean endStream) throws Exception {
  createStream();
  stream.request(1);

  // Create a data frame and then trigger the handler to read it.
  ByteBuf frame = grpcDataFrame(STREAM_ID, endStream, contentAsArray());
  channelRead(frame);
  verify(streamListener, atLeastOnce())
      .messagesAvailable(any(StreamListener.MessageProducer.class));
  InputStream message = streamListenerMessageQueue.poll();
  assertArrayEquals(ByteBufUtil.getBytes(content()), ByteStreams.toByteArray(message));
  message.close();
  assertNull("no additional message expected", streamListenerMessageQueue.poll());

  if (endStream) {
    verify(streamListener).halfClosed();
  }
  verify(streamListener, atLeastOnce()).onReady();
  verifyNoMoreInteractions(streamListener);
}
 
Example #7
Source File: Base64Test.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private static void testEncodeDecode(int size, ByteOrder order) {
    byte[] bytes = new byte[size];
    PlatformDependent.threadLocalRandom().nextBytes(bytes);

    ByteBuf src = Unpooled.wrappedBuffer(bytes).order(order);
    ByteBuf encoded = Base64.encode(src);
    ByteBuf decoded = Base64.decode(encoded);
    ByteBuf expectedBuf = Unpooled.wrappedBuffer(bytes);
    try {
        assertEquals(StringUtil.NEWLINE + "expected: " + ByteBufUtil.hexDump(expectedBuf) +
                     StringUtil.NEWLINE + "actual--: " + ByteBufUtil.hexDump(decoded), expectedBuf, decoded);
    } finally {
        src.release();
        encoded.release();
        decoded.release();
        expectedBuf.release();
    }
}
 
Example #8
Source File: NettyHttpServerHandler.java    From datax-web with MIT License 6 votes vote down vote up
@Override
protected void channelRead0(final ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {

    // request parse
    final byte[] requestBytes = ByteBufUtil.getBytes(msg.content());    // byteBuf.toString(io.netty.util.CharsetUtil.UTF_8);
    final String uri = msg.uri();
    final boolean keepAlive = HttpUtil.isKeepAlive(msg);

    // do invoke
    serverHandlerPool.execute(new Runnable() {
        @Override
        public void run() {
            process(ctx, uri, requestBytes, keepAlive);
        }
    });
}
 
Example #9
Source File: AbstractRROWithSubobjectsParser.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
protected List<Subobject> parseSubobjects(final ByteBuf buffer) throws PCEPDeserializerException {
    Preconditions.checkArgument(buffer != null && buffer.isReadable(),
            "Array of bytes is mandatory. Can't be null or empty.");
    final List<Subobject> subs = new ArrayList<>();
    while (buffer.isReadable()) {
        final int type = buffer.readUnsignedByte();
        final int length = buffer.readUnsignedByte() - HEADER_LENGTH;
        if (length > buffer.readableBytes()) {
            throw new PCEPDeserializerException(
                    "Wrong length specified. Passed: " + length + "; Expected: <= " + buffer.readableBytes());
        }
        LOG.debug("Attempt to parse subobject from bytes: {}", ByteBufUtil.hexDump(buffer));
        final Subobject sub = this.subobjReg.parseSubobject(type, buffer.readSlice(length));
        if (sub == null) {
            LOG.warn("Parsing failed for subobject type: {}. Ignoring subobject.", type);
        } else {
            LOG.debug("Subobject was parsed. {}", sub);
            subs.add(sub);
        }
    }
    return subs;
}
 
Example #10
Source File: AbstractBmpMessageWithTlvParser.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
protected final void parseTlvs(final T builder, final ByteBuf bytes) throws BmpDeserializationException {
    Preconditions.checkArgument(bytes != null, "Array of bytes is mandatory. Can't be null.");
    if (!bytes.isReadable()) {
        return;
    }
    while (bytes.isReadable()) {
        final int type = bytes.readUnsignedShort();
        final int length = bytes.readUnsignedShort();
        if (length > bytes.readableBytes()) {
            throw new BmpDeserializationException("Wrong length specified. Passed: " + length
                    + "; Expected: <= " + bytes.readableBytes() + ".");
        }
        final ByteBuf tlvBytes = bytes.readSlice(length);
        LOG.trace("Parsing BMP TLV : {}", ByteBufUtil.hexDump(tlvBytes));

        final Tlv tlv = this.tlvRegistry.parseTlv(type, tlvBytes);
        if (tlv != null) {
            LOG.trace("Parsed BMP TLV {}.", tlv);
            addTlv(builder, tlv);
        }
    }
}
 
Example #11
Source File: AbstractEROWithSubobjectsParser.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
protected List<Subobject> parseSubobjects(final ByteBuf buffer) throws PCEPDeserializerException {
    // Explicit approval of empty ERO
    Preconditions.checkArgument(buffer != null, "Array of bytes is mandatory. Can't be null.");
    final List<Subobject> subs = new ArrayList<>();
    while (buffer.isReadable()) {
        final boolean loose = ((buffer.getUnsignedByte(buffer.readerIndex()) & (1 << Values.FIRST_BIT_OFFSET)) != 0)
                ? true
                : false;
        final int type = (buffer.readUnsignedByte() & Values.BYTE_MAX_VALUE_BYTES)
                & ~(1 << Values.FIRST_BIT_OFFSET);
        final int length = buffer.readUnsignedByte() - HEADER_LENGTH;
        if (length > buffer.readableBytes()) {
            throw new PCEPDeserializerException(
                    "Wrong length specified. Passed: " + length + "; Expected: <= " + buffer.readableBytes());
        }
        LOG.debug("Attempt to parse subobject from bytes: {}", ByteBufUtil.hexDump(buffer));
        final Subobject sub = this.subobjReg.parseSubobject(type, buffer.readSlice(length), loose);
        if (sub == null) {
            LOG.warn("Parsing failed for subobject type: {}. Ignoring subobject.", type);
        } else {
            LOG.debug("Subobject was parsed. {}", sub);
            subs.add(sub);
        }
    }
    return subs;
}
 
Example #12
Source File: Metadata.java    From rsocket-rpc-java with Apache License 2.0 6 votes vote down vote up
public static ByteBuf encode(
    ByteBufAllocator allocator,
    String service,
    String method,
    ByteBuf tracing,
    ByteBuf metadata) {
  ByteBuf byteBuf = allocator.buffer().writeShort(VERSION);

  int serviceLength = NumberUtils.requireUnsignedShort(ByteBufUtil.utf8Bytes(service));
  byteBuf.writeShort(serviceLength);
  ByteBufUtil.reserveAndWriteUtf8(byteBuf, service, serviceLength);

  int methodLength = NumberUtils.requireUnsignedShort(ByteBufUtil.utf8Bytes(method));
  byteBuf.writeShort(methodLength);
  ByteBufUtil.reserveAndWriteUtf8(byteBuf, method, methodLength);

  byteBuf.writeShort(tracing.readableBytes());
  byteBuf.writeBytes(tracing, tracing.readerIndex(), tracing.readableBytes());

  byteBuf.writeBytes(metadata, metadata.readerIndex(), metadata.readableBytes());

  return byteBuf;
}
 
Example #13
Source File: ProtocolMessageDecoder.java    From herddb with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf in = (ByteBuf) msg;

    if (LOGGER.isLoggable(Level.FINEST)) {
        StringBuilder dumper = new StringBuilder();
        ByteBufUtil.appendPrettyHexDump(dumper, in);
        LOGGER.log(Level.FINEST, "Received from {}: {}", new Object[]{ctx.channel(), dumper});
    }

    try {
        Pdu pdu = PduCodec.decodePdu(in);
        ctx.fireChannelRead(pdu);
    } catch (Throwable err) {
        LOGGER.log(Level.SEVERE, "Error decoding PDU", err);
        ReferenceCountUtil.safeRelease(msg);
    }

}
 
Example #14
Source File: WriteBufferingAndExceptionHandler.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
  try {
    if (logger.isLoggable(Level.FINE)) {
      Object loggedMsg = msg instanceof ByteBuf ? ByteBufUtil.hexDump((ByteBuf) msg) : msg;
      logger.log(
          Level.FINE,
          "Unexpected channelRead()->{0} reached end of pipeline {1}",
          new Object[] {loggedMsg, ctx.pipeline().names()});
    }
    exceptionCaught(
        ctx,
        Status.INTERNAL.withDescription(
            "channelRead() missed by ProtocolNegotiator handler: " + msg)
            .asRuntimeException());
  } finally {
    ReferenceCountUtil.safeRelease(msg);
  }
}
 
Example #15
Source File: NettyHttpClientHandler.java    From xxl-rpc with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {

    // valid status
    if (!HttpResponseStatus.OK.equals(msg.status())) {
        throw new XxlRpcException("xxl-rpc response status invalid.");
    }

    // response parse
    byte[] responseBytes = ByteBufUtil.getBytes(msg.content());

    // valid length
    if (responseBytes.length == 0) {
        throw new XxlRpcException("xxl-rpc response data empty.");
    }

    // response deserialize
    XxlRpcResponse xxlRpcResponse = (XxlRpcResponse) serializer.deserialize(responseBytes, XxlRpcResponse.class);

    // notify response
    xxlRpcInvokerFactory.notifyInvokerFuture(xxlRpcResponse.getRequestId(), xxlRpcResponse);

}
 
Example #16
Source File: Socks4ClientEncoder.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected void encode(ChannelHandlerContext ctx, Socks4CommandRequest msg, ByteBuf out) throws Exception {
    out.writeByte(msg.version().byteValue());
    out.writeByte(msg.type().byteValue());
    out.writeShort(msg.dstPort());
    if (NetUtil.isValidIpV4Address(msg.dstAddr())) {
        out.writeBytes(NetUtil.createByteArrayFromIpAddressString(msg.dstAddr()));
        ByteBufUtil.writeAscii(out, msg.userId());
        out.writeByte(0);
    } else {
        out.writeBytes(IPv4_DOMAIN_MARKER);
        ByteBufUtil.writeAscii(out, msg.userId());
        out.writeByte(0);
        ByteBufUtil.writeAscii(out, msg.dstAddr());
        out.writeByte(0);
    }
}
 
Example #17
Source File: FingerprintTrustManagerFactory.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new instance.
 *
 * @param fingerprints a list of SHA1 fingerprints
 */
public FingerprintTrustManagerFactory(byte[]... fingerprints) {
    if (fingerprints == null) {
        throw new NullPointerException("fingerprints");
    }

    List<byte[]> list = new ArrayList<byte[]>(fingerprints.length);
    for (byte[] f: fingerprints) {
        if (f == null) {
            break;
        }
        if (f.length != SHA1_BYTE_LEN) {
            throw new IllegalArgumentException("malformed fingerprint: " +
                    ByteBufUtil.hexDump(Unpooled.wrappedBuffer(f)) + " (expected: SHA1)");
        }
        list.add(f.clone());
    }

    this.fingerprints = list.toArray(new byte[list.size()][]);
}
 
Example #18
Source File: DefaultDnsRecordEncoder.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
protected void encodeName(String name, ByteBuf buf) throws Exception {
    if (ROOT.equals(name)) {
        // Root domain
        buf.writeByte(0);
        return;
    }

    final String[] labels = name.split("\\.");
    for (String label : labels) {
        final int labelLen = label.length();
        if (labelLen == 0) {
            // zero-length label means the end of the name.
            break;
        }

        buf.writeByte(labelLen);
        ByteBufUtil.writeAscii(buf, label);
    }

    buf.writeByte(0); // marks end of name field
}
 
Example #19
Source File: Http2ServerUpgradeHandler.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    int prefaceLength = CONNECTION_PREFACE.readableBytes();
    int bytesRead = Math.min(in.readableBytes(), prefaceLength);

    if (!ByteBufUtil.equals(CONNECTION_PREFACE, CONNECTION_PREFACE.readerIndex(),
        in, in.readerIndex(), bytesRead)) {
        ctx.pipeline().remove(this);
    } else if (bytesRead == prefaceLength) {
        // Full h2 preface match, removed source codec, using http2 codec to handle
        // following network traffic
        ctx.pipeline()
            .remove(httpServerCodec)
            .remove(httpServerUpgradeHandler);
        // 用业务线程池
        ctx.pipeline().addAfter(bizGroup, ctx.name(), null, http2ServerHandler);
        ctx.pipeline().remove(this);

        ctx.fireUserEventTriggered(Http2ServerUpgradeHandler.PriorKnowledgeUpgradeEvent.INSTANCE);
    }
}
 
Example #20
Source File: HttpContentCompressorTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * If the length of the content is unknown, {@link HttpContentEncoder} should not skip encoding the content
 * even if the actual length is turned out to be 0.
 */
@Test
public void testEmptySplitContent() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(new HttpContentCompressor());
    ch.writeInbound(newRequest());

    ch.writeOutbound(new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK));
    assertEncodedResponse(ch);

    ch.writeOutbound(LastHttpContent.EMPTY_LAST_CONTENT);
    HttpContent chunk = (HttpContent) ch.readOutbound();
    assertThat(ByteBufUtil.hexDump(chunk.content()), is("1f8b080000000000000003000000000000000000"));
    assertThat(chunk, is(instanceOf(HttpContent.class)));
    chunk.release();

    chunk = ch.readOutbound();
    assertThat(chunk.content().isReadable(), is(false));
    assertThat(chunk, is(instanceOf(LastHttpContent.class)));
    chunk.release();

    assertThat(ch.readOutbound(), is(nullValue()));
}
 
Example #21
Source File: SourceRconPacketBuilder.java    From async-gamequery-lib with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T extends SourceRconPacket> T construct(ByteBuf data) {
    try {
        if (data.readableBytes() < 14) {
            log.warn("Packet is less than 10 bytes. Unsupported packet.");
            if (log.isDebugEnabled())
                log.debug("Unrecognized Packet: \n{}", ByteBufUtil.prettyHexDump(data));
            return null;
        }

        //Remember the reader index
        data.markReaderIndex();

        //Read from the listen
        data.readerIndex(0);
        int size = data.readIntLE();
        int id = data.readIntLE();
        int type = data.readIntLE();

        String body = data.readCharSequence(data.readableBytes() - 2, StandardCharsets.UTF_8).toString();

        SourceRconResponsePacket packet = getResponsePacket(type);

        if (packet != null) {
            //Ok, we have a valid response packet. Lets keep reading.
            packet.setId(id);
            packet.setSize(size);
            packet.setType(type);
            packet.setBody(body);
            return (T) packet;
        }
    } finally {
        //Reset the index
        data.resetReaderIndex();
    }
    return null;
}
 
Example #22
Source File: EndpointedChannelHandler.java    From riiablo with Apache License 2.0 5 votes vote down vote up
protected Object writeMessage(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
  if (DEBUG_CALLS) {
    InetSocketAddress receiver = (InetSocketAddress) ctx.channel().remoteAddress();
    Gdx.app.log(TAG, "writeMessage sending packet to " + receiver.getHostName() + ":" + receiver.getPort());
  }
  ByteBuf out = msg;
  if (DEBUG_OUTBOUND) Gdx.app.debug(TAG, "  " + ByteBufUtil.hexDump(out));
  return msg;
}
 
Example #23
Source File: EncoderUnitTest.java    From xio with Apache License 2.0 5 votes vote down vote up
@Test
public void testWriteSucceeds() throws Exception {
  Integer payload = new Integer(1);
  Request request =
      new Request(
          UUID.fromString("f6fb3dbf-43fa-4ebf-8f45-b38e7444beae"), SettableFuture.create());
  Message message = new Message(request, payload);
  ByteBuf buf = Unpooled.buffer();
  buf.writeBytes(Ints.toByteArray(payload));

  channel.writeOutbound(buf);
  channel.writeOutbound(message);
  channel.runPendingTasks();

  ByteBuf encoded = (ByteBuf) channel.outboundMessages().poll();
  String expectedEncoded =
      new StringBuilder()
          .append("         +-------------------------------------------------+\n")
          .append("         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |\n")
          .append(
              "+--------+-------------------------------------------------+----------------+\n")
          .append(
              "|00000000| 66 36 66 62 33 64 62 66 2d 34 33 66 61 2d 34 65 |f6fb3dbf-43fa-4e|\n")
          .append(
              "|00000010| 62 66 2d 38 66 34 35 2d 62 33 38 65 37 34 34 34 |bf-8f45-b38e7444|\n")
          .append(
              "|00000020| 62 65 61 65 00 00 00 00 00 00 00 04 00 00 00 01 |beae............|\n")
          .append("+--------+-------------------------------------------------+----------------+")
          .toString();

  assertEquals(
      "Expected:\n" + expectedEncoded, expectedEncoded, ByteBufUtil.prettyHexDump(encoded));
}
 
Example #24
Source File: DarkRepulsor.java    From jt808-server with Apache License 2.0 5 votes vote down vote up
@Override
public void write(ByteBuf buf, Property prop, Object value) {
    int before = buf.writerIndex();
    super.write(buf, prop, value);
    int after = buf.writerIndex();

    String hex = ByteBufUtil.hexDump(buf, before, after - before);
    System.out.println(prop.index() + "\t" + hex + "\t" + prop.desc() + "\t" + String.valueOf(value));
}
 
Example #25
Source File: BGPByteToMessageDecoder.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out)
        throws BGPDocumentedException, BGPParsingException {
    if (in.isReadable()) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Received to decode: {}", ByteBufUtil.hexDump(in));
        }
        out.add(this.registry.parseMessage(in, this.constraints));
    } else {
        LOG.trace("No more content in incoming buffer.");
    }
}
 
Example #26
Source File: Utf8SmtpRequestEncoder.java    From NioSmtpClient with Apache License 2.0 5 votes vote down vote up
private static void writeParameters(List<CharSequence> parameters, ByteBuf out) {
  if (parameters.isEmpty()) {
    return;
  }

  out.writeByte(SP);

  if (parameters instanceof RandomAccess) {
    int sizeMinusOne = parameters.size() - 1;
    for (int i = 0; i < sizeMinusOne; i++) {
      ByteBufUtil.writeUtf8(out, parameters.get(i));
      out.writeByte(SP);
    }

    ByteBufUtil.writeUtf8(out, parameters.get(sizeMinusOne));

  } else {
    Iterator<CharSequence> params = parameters.iterator();
    while (true) {
      ByteBufUtil.writeUtf8(out, params.next());
      if (params.hasNext()) {
        out.writeByte(SP);
      } else {
        break;
      }
    }
  }
}
 
Example #27
Source File: IrisUpnpServer.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private ChannelFuture respondBasicDevice(InetSocketAddress to, Channel ch, String date) {
   ByteBuf data = Unpooled.buffer();
   ByteBufUtil.writeUtf8(data, 
      "HTTP/1.1 200 OK\r\n" +
      "CACHE-CONTROL: max-age=1800\r\n" +
      "DATE: " + date + "\r\n" +
      "EXT:\r\n" +
      "LOCATION: http://" + addr + ":" + HttpServer.PORT + "/upnp/device.xml\r\n" +
      "ST: urn:schemas-upnp-org:device:Basic:1\r\n" +
      "USN: uuid:" + IrisUpnpService.uuid + "::urn:schemas-upnp-org:device:Basic:1\r\n" +
      "SERVER: Iris OS/2.0 UPnP/1.0 Iris/2.0\r\n\r\n"
   );

   return ch.writeAndFlush(new DatagramPacket(data,to));
}
 
Example #28
Source File: ReliableChannelHandler.java    From riiablo with Apache License 2.0 5 votes vote down vote up
protected void messageReceived(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
  InetSocketAddress sender = packet.sender();
  Gdx.app.log(TAG, "messageReceived received packet from " + sender.getHostName() + ":" + sender.getPort());
  ByteBuf in = packet.content();
  if (DEBUG_INBOUND) Gdx.app.debug(TAG, "  " + ByteBufUtil.hexDump(in));
  endpoint.messageReceived(ctx, packet.sender(), packet);
}
 
Example #29
Source File: IrisUpnpServer.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private ChannelFuture respondRootDevice(InetSocketAddress to, Channel ch, String date) {
   ByteBuf data = Unpooled.buffer();
   ByteBufUtil.writeUtf8(data, 
      "HTTP/1.1 200 OK\r\n" +
      "CACHE-CONTROL: max-age=1800\r\n" +
      "DATE: " + date + "\r\n" +
      "EXT:\r\n" +
      "LOCATION: http://" + addr + ":" + HttpServer.PORT + "/upnp/device.xml\r\n" +
      "ST: upnp:rootdevice\r\n" +
      "USN: uuid:" + IrisUpnpService.uuid + "::upnp:rootdevice\r\n" +
      "SERVER: Iris OS/2.0 UPnP/1.0 Iris/2.0\r\n\r\n"
   );

   return ch.writeAndFlush(new DatagramPacket(data,to));
}
 
Example #30
Source File: GatewayServiceConfigurationReaderTest.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
private HttpClientResponse<ByteBuf> getMockResponse(String databaseAccountJson) {
    HttpClientResponse<ByteBuf> resp = Mockito.mock(HttpClientResponse.class);
    Mockito.doReturn(HttpResponseStatus.valueOf(200)).when(resp).getStatus();
    ByteBuf byteBuffer = ByteBufUtil.writeUtf8(ByteBufAllocator.DEFAULT, databaseAccountJson);

    Mockito.doReturn(Observable.just(byteBuffer))
            .when(resp).getContent();

    HttpHeaders httpHeaders = new DefaultHttpHeaders();
    httpHeaders = httpHeaders.add(HttpConstants.HttpHeaders.CONTENT_LENGTH, byteBuffer.writerIndex());

    DefaultHttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            HttpResponseStatus.valueOf(200), httpHeaders);

    try {
        Constructor<HttpResponseHeaders> constructor = HttpResponseHeaders.class
                .getDeclaredConstructor(HttpResponse.class);
        constructor.setAccessible(true);
        HttpResponseHeaders httpResponseHeaders = constructor.newInstance(httpResponse);
        Mockito.doReturn(httpResponseHeaders).when(resp).getHeaders();

    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
            | NoSuchMethodException | SecurityException e) {
        throw new IllegalStateException("Failed to instantiate class object.", e);
    }
    return resp;
}