Java Code Examples for io.netty.buffer.ByteBuf.toString()

The following are Jave code examples for showing how to use toString() of the io.netty.buffer.ByteBuf class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: spark_deep   File: SparkSaslServer.java   Source Code and License Vote up 6 votes
/** Return a Base64-encoded string. */
private static String getBase64EncodedString(String str) {
  ByteBuf byteBuf = null;
  ByteBuf encodedByteBuf = null;
  try {
    byteBuf = Unpooled.wrappedBuffer(str.getBytes(StandardCharsets.UTF_8));
    encodedByteBuf = Base64.encode(byteBuf);
    return encodedByteBuf.toString(StandardCharsets.UTF_8);
  } finally {
    // The release is called to suppress the memory leak error messages raised by netty.
    if (byteBuf != null) {
      byteBuf.release();
      if (encodedByteBuf != null) {
        encodedByteBuf.release();
      }
    }
  }
}
 
Example 2
Project: NioSmtpClient   File: SmtpSessionTest.java   Source Code and License Vote up 6 votes
@Test
public void itCanAuthenticateWithAuthLogin() throws Exception {
  String username = "user";
  String password = "password";

  // do the initial request, which just includes the username
  session.authLogin("user", "password");

  verify(channel).writeAndFlush(new DefaultSmtpRequest("AUTH", "LOGIN", encodeBase64(username)));

  // now the second request, which sends the password
  responseFuture.complete(Lists.newArrayList(INTERMEDIATE_RESPONSE));

  // this is sent to the second invocation of writeAndFlush
  ArgumentCaptor<Object> bufCaptor = ArgumentCaptor.forClass(Object.class);
  verify(channel, times(2)).writeAndFlush(bufCaptor.capture());
  ByteBuf capturedBuffer = (ByteBuf) bufCaptor.getAllValues().get(1);

  String actualString = capturedBuffer.toString(0, capturedBuffer.readableBytes(), StandardCharsets.UTF_8);
  assertThat(actualString).isEqualTo(encodeBase64(password) + "\r\n");
}
 
Example 3
Project: simulacron   File: ByteBufCodec.java   Source Code and License Vote up 5 votes
@Override
public String readLongString(ByteBuf source) {
  int len = readInt(source);
  String str = source.toString(source.readerIndex(), len, CharsetUtil.UTF_8);
  source.readerIndex(source.readerIndex() + len);
  return str;
}
 
Example 4
Project: Re-Collector   File: NewlineChunkSplitter.java   Source Code and License Vote up 5 votes
@Override
public Iterable<String> split(final ByteBuf buffer, final Charset charset, final boolean includeRemainingData) {
    return () -> new AbstractIterator<String>() {
        @Override
        protected String computeNext() {
            ByteBuf fullLine = null;
            try {
                if (!buffer.isReadable()) {
                    return endOfData();
                }
                final int i = buffer.forEachByte(ByteBufProcessor.FIND_CRLF);
                if (i == -1) {
                    if (includeRemainingData) {
                        final ByteBuf remaining = buffer.readBytes(buffer.readableBytes());
                        return remaining.toString(charset);
                    } else {
                        return endOfData();
                    }
                }
                fullLine = buffer.readBytes(i);
                // Strip the \r/\n bytes from the buffer.
                final byte readByte = buffer.readByte(); // the \r or \n byte
                if (readByte == '\r') {
                    buffer.readByte(); // the \n byte if previous was \r
                }
                return fullLine.toString(charset);
            } finally {
                buffer.discardReadBytes();
                if (fullLine != null) {
                    fullLine.release();
                }

            }
        }
    };
}
 
Example 5
Project: CustomWorldGen   File: ByteBufUtils.java   Source Code and License Vote up 5 votes
/**
 * Read a UTF8 string from the byte buffer.
 * It is encoded as <varint length>[<UTF8 char bytes>]
 *
 * @param from The buffer to read from
 * @return The string
 */
public static String readUTF8String(ByteBuf from)
{
    int len = readVarInt(from,2);
    String str = from.toString(from.readerIndex(), len, Charsets.UTF_8);
    from.readerIndex(from.readerIndex() + len);
    return str;
}
 
Example 6
Project: SurvivalMMO   File: Packet.java   Source Code and License Vote up 5 votes
public static String readUTF8(ByteBuf in) {
    ByteBuf buffer = in.alloc().buffer();
    byte b;
    while (in.readableBytes() > 0 && (b = in.readByte()) != 0) {
        buffer.writeByte(b);
    }

    return buffer.toString(Charsets.UTF_8);
}
 
Example 7
Project: iotplatform   File: JsonMqttAdaptor.java   Source Code and License Vote up 5 votes
public static String validatePayload(SessionId sessionId, ByteBuf payloadData) throws AdaptorException {
  try {
    String payload = payloadData.toString(UTF8);
    if (payload == null) {
      log.warn("[{}] Payload is empty!", sessionId.toUidStr());
      throw new AdaptorException(new IllegalArgumentException("Payload is empty!"));
    }
    return payload;
  } finally {
    payloadData.release();
  }
}
 
Example 8
Project: ditb   File: SaslClientHandler.java   Source Code and License Vote up 5 votes
/**
 * Get the read status
 *
 * @param inStream to read
 * @throws org.apache.hadoop.ipc.RemoteException if status was not success
 */
private static void readStatus(ByteBuf inStream) throws RemoteException {
  int status = inStream.readInt(); // read status
  if (status != SaslStatus.SUCCESS.state) {
    throw new RemoteException(inStream.toString(Charset.forName("UTF-8")),
        inStream.toString(Charset.forName("UTF-8")));
  }
}
 
Example 9
Project: j1st-mqtt   File: MqttDecoder.java   Source Code and License Vote up 5 votes
private static Result<String> decodeString(ByteBuf buffer, int minBytes, int maxBytes) {
    final Result<Integer> decodedSize = decodeMsbLsb(buffer);
    int size = decodedSize.value;
    int numberOfBytesConsumed = decodedSize.numberOfBytesConsumed;
    if (size < minBytes || size > maxBytes) {
        buffer.skipBytes(size);
        numberOfBytesConsumed += size;
        return new Result<>(null, numberOfBytesConsumed);
    }
    ByteBuf buf = buffer.readBytes(size);
    numberOfBytesConsumed += size;
    return new Result<>(buf.toString(CharsetUtil.UTF_8), numberOfBytesConsumed);
}
 
Example 10
Project: netty_op   File: TimeServerHandler.java   Source Code and License Vote up 5 votes
/**
 *@description 接收客户端的请求数据
 *@time 创建时间:2017年7月24日下午2:30:30
 *@param ctx
 *@param msg
 *@throws Exception
 *@author dzn
 */
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if(msg instanceof ByteBuf){
        ByteBuf req = (ByteBuf)msg;
        String content = req.toString(Charset.defaultCharset());
        System.out.println("接收到ByteBuf类型的请求数据 : " + content);
        ctx.channel().writeAndFlush(msg);
    }else if(msg instanceof String){
        System.out.println("接收到String类型的请求数据 : " + msg.toString());
        ctx.channel().writeAndFlush(msg + "\r\n");
        System.out.println("向客户端返回响应数据 : " + msg);
    }
}
 
Example 11
Project: echidna   File: HTTPDecoder.java   Source Code and License Vote up 5 votes
@Override
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf,
	List<Object> list) throws Exception {
	String rawData = byteBuf.toString(CharsetUtil.UTF_8);
	
	HTTPRequest request = HTTPRequestParser.parseRequest(rawData);
	
	list.add(request);
	
	byteBuf.clear();
}
 
Example 12
Project: Building_Effective_Microservices   File: RibbonMeetupClient.java   Source Code and License Vote up 5 votes
private <T> Observable<T> execute(Class<T> t,HttpRequestTemplate<ByteBuf> apiTemplate){
	
	RibbonResponse<ByteBuf> result = apiTemplate.requestBuilder().withHeader("client", "client-microservice").build()
			.withMetadata().execute();
	ByteBuf buf = result.content();
	String json = buf.toString(Charset.forName("UTF-8"));
	
	try {
		return Observable.just(mapper.readValue(json, t));
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 13
Project: Re-Collector   File: PatternChunkSplitter.java   Source Code and License Vote up 4 votes
@Override
public Iterable<String> split(final ByteBuf buffer, final Charset charset, final boolean includeRemainingData) {
    return () -> new AbstractIterator<String>() {
        // TODO Might throw an exception if multibyte charset is used and buffer is not complete.
        //      Use CharsetDecoder to create a CharBuffer and match on that!
        private final String inputAsString = buffer.toString(charset);
        final Matcher matcher = pattern.matcher(inputAsString);
        private int positionInString = 0;

        @Override
        protected String computeNext() {
            try {
                if (!buffer.isReadable()) {
                    return endOfData();
                }
                if (matcher.find()) {
                    int firstByte = matcher.start();
                    if (firstByte == 0) {
                        // advance further, the buffer begins with our pattern.
                        if (matcher.find()) {
                            firstByte = matcher.start();
                        } else {
                            if (!includeRemainingData) {
                                // couldn't find the end of the entry (i.e. there wasn't a next line yet)
                                return endOfData();
                            } else {
                                // couldn't find another line, but we are asked to finish up, include everything that remains
                                return getRemainingContent();
                            }
                        }
                    }
                    if (firstByte == 0) {
                        // still haven't found a non-zero length string, keep waiting for more data.
                        return endOfData();
                    }
                    final String substring = inputAsString.substring(positionInString, firstByte);
                    positionInString = firstByte;
                    buffer.skipBytes(substring.getBytes(charset).length); // TODO performance
                    return substring;
                } else {
                    if (includeRemainingData) {
                        return getRemainingContent();
                    }
                    return endOfData();
                }
            } catch (IllegalStateException e) {
                // the cause contains the CharacterCodingException from the ChannelBuffer.toString() methods
                // this usually means the buffer ended with an incomplete encoding of a unicode character.
                // WHY U SO SUCK CHARACTER ENCODINGS?
                // we need to wait until more data is available
                return endOfData();
            } finally {
                buffer.discardReadBytes();
            }
        }

        private String getRemainingContent() {
            final ByteBuf channelBuffer = buffer.readBytes(buffer.readableBytes());
            return channelBuffer.toString(charset);
        }
    };
}
 
Example 14
Project: JRediClients   File: KeyValueObjectDecoder.java   Source Code and License Vote up 4 votes
@Override
public Object decode(ByteBuf buf, State state) {
    String status = buf.toString(CharsetUtil.UTF_8);
    buf.skipBytes(1);
    return status;
}
 
Example 15
Project: JRediClients   File: SlotsDecoder.java   Source Code and License Vote up 4 votes
@Override
public Object decode(ByteBuf buf, State state) {
    return buf.toString(CharsetUtil.UTF_8);
}
 
Example 16
Project: JRediClients   File: StringListReplayDecoder.java   Source Code and License Vote up 4 votes
@Override
public Object decode(ByteBuf buf, State state) {
    return buf.toString(CharsetUtil.UTF_8);
}
 
Example 17
Project: JRediClients   File: ScoredSortedSetScanDecoder.java   Source Code and License Vote up 4 votes
@Override
public Object decode(ByteBuf buf, State state) {
    return new BigDecimal(buf.toString(CharsetUtil.UTF_8));
}
 
Example 18
Project: JRediClients   File: StringDataDecoder.java   Source Code and License Vote up 4 votes
@Override
public String decode(ByteBuf buf, State state) {
    return buf.toString(CharsetUtil.UTF_8);
}
 
Example 19
Project: NioSmtpClient   File: Utf8SmtpResponseDecoder.java   Source Code and License Vote up 4 votes
@Override
protected SmtpResponse decode(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
  ByteBuf frame = (ByteBuf) super.decode(ctx, buffer);
  if (frame == null) {
    // No full line received yet.
    return null;
  }
  try {
    final int readable = frame.readableBytes();
    final int readerIndex = frame.readerIndex();
    if (readable < 3) {
      throw newDecoderException(buffer, readerIndex, readable);
    }
    final int code = parseCode(frame);
    final int separator = frame.readByte();
    final CharSequence detail = frame.isReadable() ? frame.toString(CharsetUtil.UTF_8) : null;

    List<CharSequence> details = this.details;

    switch (separator) {
      case ' ':
        // Marks the end of a response.
        this.details = null;
        if (details != null) {
          if (detail != null) {
            details.add(detail);
          }
        } else {
          details = Collections.singletonList(detail);
        }
        return new DefaultSmtpResponse(code, details.toArray(new CharSequence[0]));
      case '-':
        // Multi-line response.
        if (detail != null) {
          if (details == null) {
            // Using initial capacity as it is very unlikely that we will receive a multi-line response
            // with more then 3 lines.
            this.details = details = new ArrayList<>(4);
          }
          details.add(detail);
        }
        break;
      default:
        throw newDecoderException(buffer, readerIndex, readable);
    }
  } finally {
    frame.release();
  }
  return null;
}
 
Example 20
Project: azeroth   File: FastdfsUtils.java   Source Code and License Vote up 2 votes
/**
 * 读取字符串(修剪掉补零的字节)
 *
 * @param in
 * @return
 */
public static String readString(ByteBuf in) {
    return in.toString(UTF_8);
}