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

The following examples show how to use io.netty.buffer.ByteBuf#toString() . 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: SpotifyWebAPI.java    From The-5zig-Mod with GNU General Public License v3.0 6 votes vote down vote up
public boolean resolveTrackImage(final SpotifyNewTrack track) throws IOException {
    URL url = new URL(track.getImageUrl());
    BufferedImage image = ImageIO.read(url);
    BufferedImage image1 = new BufferedImage(128, 128, image.getType());
    Graphics graphics = image1.getGraphics();
    try {
        graphics.drawImage(image, 0, 0, image1.getWidth(), image1.getHeight(), null);
    } finally {
        graphics.dispose();
    }
    // Converting Image byte array into Base64 String
    ByteBuf localByteBuf1 = Unpooled.buffer();
    ImageIO.write(image1, "PNG", new ByteBufOutputStream(localByteBuf1));
    ByteBuf localByteBuf2 = Base64.encode(localByteBuf1);
    String imageDataString = localByteBuf2.toString(Charsets.UTF_8);

    track.setImage(imageDataString);
    TRACK_IMAGE_LOOKUP.put(track.getId(), imageDataString);

    return true;
}
 
Example 2
Source File: SmtpSessionTest.java    From NioSmtpClient with Apache License 2.0 6 votes vote down vote up
@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
Source File: HttpMatcher.java    From cute-proxy with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public int match(ByteBuf buf) {
    if (buf.readableBytes() < 8) {
        return PENDING;
    }

    int index = buf.indexOf(0, 8, (byte) ' ');
    if (index < 0) {
        return MISMATCH;
    }

    int firstURIIndex = index + 1;
    if (buf.readableBytes() < firstURIIndex + 1) {
        return PENDING;
    }

    String method = buf.toString(0, index, US_ASCII);
    char firstURI = (char) (buf.getByte(firstURIIndex + buf.readerIndex()) & 0xff);
    if (!methods.contains(method) || firstURI != '/') {
        return MISMATCH;
    }

    return MATCH;
}
 
Example 4
Source File: Base64Renderer.java    From The-5zig-Mod with MIT License 6 votes vote down vote up
public static Base64Renderer getRenderer(BufferedImage icon, String id) {
	Base64Renderer renderer = CACHE.getIfPresent(id);
	if (renderer != null) {
		return renderer;
	}
	final Base64Renderer finalRenderer = new Base64Renderer(null, icon.getWidth(), icon.getHeight());
	CACHE.put(id, finalRenderer);
	try {
		ByteBuf decodedBuffer = Unpooled.buffer();
		ImageIO.write(icon, "PNG", new ByteBufOutputStream(decodedBuffer));
		ByteBuf encodedBuffer = Base64.encode(decodedBuffer);
		String imageDataString = encodedBuffer.toString(Charsets.UTF_8);

		finalRenderer.setBase64String(imageDataString, id);
	} catch (Exception e) {
		The5zigMod.logger.error("Could not load icon " + id, e);
	}
	return finalRenderer;
}
 
Example 5
Source File: StringPasswordLineDecoder.java    From Summer with Apache License 2.0 6 votes vote down vote up
@Override
protected Object decode(ChannelHandlerContext ctx, ByteBuf buffer)  throws Exception {
	ByteBuf msg = (ByteBuf) super.decode(ctx, buffer);
	if (msg != null) {
		if (pass != null) {
			byte[] bytes = new byte[msg.readableBytes()];
			msg.readBytes(bytes);
			int index = bytes.length % 10;
			for (int i = 0; i < bytes.length; i++) {
				if (index >= pass.length)
					index = 0;
				int res = bytes[i] ^ pass[index];
				if (res != 10 && res != 13)
					bytes[i] = (byte)res;
				index++;
			}
			return new String(bytes, charset);
		} else {
			return msg.toString(Charset.forName(charset));
		}
	}
	return null;
}
 
Example 6
Source File: RedisDecoder.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private long parseRedisNumber(ByteBuf byteBuf) {
    final int readableBytes = byteBuf.readableBytes();
    final boolean negative = readableBytes > 0 && byteBuf.getByte(byteBuf.readerIndex()) == '-';
    final int extraOneByteForNegative = negative ? 1 : 0;
    if (readableBytes <= extraOneByteForNegative) {
        throw new RedisCodecException("no number to parse: " + byteBuf.toString(CharsetUtil.US_ASCII));
    }
    if (readableBytes > RedisConstants.POSITIVE_LONG_MAX_LENGTH + extraOneByteForNegative) {
        throw new RedisCodecException("too many characters to be a valid RESP Integer: " +
                                      byteBuf.toString(CharsetUtil.US_ASCII));
    }
    if (negative) {
        return -parsePositiveNumber(byteBuf.skipBytes(extraOneByteForNegative));
    }
    return parsePositiveNumber(byteBuf);
}
 
Example 7
Source File: HttpRequestEncoderTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueryStringPath() throws Exception {
    HttpRequestEncoder encoder = new HttpRequestEncoder();
    ByteBuf buffer = Unpooled.buffer(64);
    encoder.encodeInitialLine(buffer, new DefaultHttpRequest(HttpVersion.HTTP_1_1,
            HttpMethod.GET, "/?url=http://example.com"));
    String req = buffer.toString(Charset.forName("US-ASCII"));
    assertEquals("GET /?url=http://example.com HTTP/1.1\r\n", req);
}
 
Example 8
Source File: BigDecimalCodec.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
@Override
public BigDecimal decode(ByteBuf value, FieldInformation info, Class<?> target, boolean binary, CodecContext context) {
    if (binary) {
        short type = info.getType();

        switch (type) {
            case DataTypes.FLOAT:
                return BigDecimal.valueOf(value.readFloatLE());
            case DataTypes.DOUBLE:
                return BigDecimal.valueOf(value.readDoubleLE());
        }
        // Not float or double, is text-encoded yet.
    }

    BigDecimal decimal = new BigDecimal(value.toString(StandardCharsets.US_ASCII));

    // Why Java has not BigDecimal.parseBigDecimal(String)?
    if (BigDecimal.ZERO.equals(decimal)) {
        return BigDecimal.ZERO;
    } else if (BigDecimal.ONE.equals(decimal)) {
        return BigDecimal.ONE;
    } else if (BigDecimal.TEN.equals(decimal)) {
        return BigDecimal.TEN;
    } else {
        return decimal;
    }
}
 
Example 9
Source File: Strings.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
public static String getPrefixedString(final ByteBuf buf, final int utf8StringLength) {
    checkNotNull(buf);
    final String string = buf.toString(buf.readerIndex(), utf8StringLength, UTF_8);
    //The ByteBuf.toString method, doesn't move the read index, therefor we have to do this manually.
    buf.skipBytes(utf8StringLength);
    return string;
}
 
Example 10
Source File: Packet.java    From Clither-Server with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
public static String readUTF16(ByteBuf in) {
       in = in.order(ByteOrder.BIG_ENDIAN);
       ByteBuf buffer = in.alloc().buffer();
       char chr;
       while (in.readableBytes() > 1 && (chr = in.readChar()) != 0) {
           buffer.writeChar(chr);
       }

       return buffer.toString(Charsets.UTF_16LE);
   }
 
Example 11
Source File: LogHelper.java    From redisson with Apache License 2.0 5 votes vote down vote up
public static String toString(Object object) {
        if (object == null) {
            return "null";
        } else if (object instanceof String) {
            return toStringString((String) object);
        } else if (object.getClass().isArray()) {
            return toArrayString(object);
        } else if (object instanceof Collection) {
            return toCollectionString((Collection<?>) object);
        } else if (object instanceof CommandData) {
            CommandData<?, ?> cd = (CommandData<?, ?>) object;
            if (RedisCommands.AUTH.equals(cd.getCommand())) {
                return cd.getCommand() + ", params: (password masked)";
            }
            return cd.getCommand() + ", params: " + LogHelper.toString(cd.getParams());
        } else if (object instanceof ByteBuf) {
            final ByteBuf byteBuf = (ByteBuf) object;
            // can't be used due to Buffer Leak error is appeared in log
//            if (byteBuf.refCnt() > 0) {
//                if (byteBuf.writerIndex() > MAX_BYTEBUF_LOG_SIZE) {
//                    return new StringBuilder(byteBuf.toString(0, MAX_BYTEBUF_LOG_SIZE, CharsetUtil.UTF_8)).append("...").toString();
//                } else {
//                    return byteBuf.toString(0, byteBuf.writerIndex(), CharsetUtil.UTF_8);
//                }
//            }
            return byteBuf.toString();
        } else {
            return String.valueOf(object);
        }
    }
 
Example 12
Source File: NumberUtil.java    From tajo with Apache License 2.0 5 votes vote down vote up
/**
 * Parses the byte buffer argument as if it was an long value and returns the
 * result. Throws NumberFormatException if the string does not represent an
 * long quantity. The second argument specifies the radix to use when parsing
 * the value.
 *
 * @param bytes  the string byte buffer
 * @param start
 * @param length a UTF-8 encoded string representation of a long quantity.
 * @param radix  the base to use for conversion.
 * @return the value represented by the argument
 * @throws NumberFormatException if the argument could not be parsed as an long quantity.
 */
public static long parseLong(ByteBuf bytes, int start, int length, int radix) {
  if (bytes == null) {
    throw new NumberFormatException("String is null");
  }

  if (!bytes.hasMemoryAddress()) {
    return parseInt(bytes.array(), start, length);
  }

  if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
    throw new NumberFormatException("Invalid radix: " + radix);
  }
  if (length == 0 || bytes.writerIndex() < start + length) {
    throw new NumberFormatException("Empty string or Invalid buffer!");
  }

  long memoryAddress = bytes.memoryAddress();

  int offset = start;
  boolean negative = PlatformDependent.getByte(memoryAddress + start) == '-';
  if (negative || PlatformDependent.getByte(memoryAddress + start) == '+') {
    offset++;
    if (length == 1) {
      throw new NumberFormatException(bytes.toString(start, length, Charset.defaultCharset()));
    }
  }

  return parseLongInternal(bytes, memoryAddress, start, length, offset, radix, negative);
}
 
Example 13
Source File: WebSocketUtil.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * Performs base64 encoding on the specified data
 *
 * @param data The data to encode
 * @return An encoded string containing the data
 */
static String base64(byte[] data) {
    ByteBuf encodedData = Unpooled.wrappedBuffer(data);
    ByteBuf encoded = Base64.encode(encodedData);
    String encodedString = encoded.toString(CharsetUtil.UTF_8);
    encoded.release();
    return encodedString;
}
 
Example 14
Source File: SmtpResponseDecoder.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@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.US_ASCII) : 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 {
                if (detail == null) {
                    details = Collections.emptyList();
                } else {
                    details = Collections.singletonList(detail);
                }
            }
            return new DefaultSmtpResponse(code, details);
        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<CharSequence>(4);
                }
                details.add(detail);
            }
            break;
        default:
            throw newDecoderException(buffer, readerIndex, readable);
        }
    } finally {
        frame.release();
    }
    return null;
}
 
Example 15
Source File: HttpPostMultipartRequestDecoder.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
/**
 * Read one line up to the CRLF or LF
 *
 * @return the String from one line
 * @throws NotEnoughDataDecoderException
 *             Need more chunks and reset the readerInder to the previous
 *             value
 */
private String readLine() {
    SeekAheadOptimize sao;
    try {
        sao = new SeekAheadOptimize(undecodedChunk);
    } catch (SeekAheadNoBackArrayException ignored) {
        return readLineStandard();
    }
    int readerIndex = undecodedChunk.readerIndex();
    try {
        ByteBuf line = buffer(64);

        while (sao.pos < sao.limit) {
            byte nextByte = sao.bytes[sao.pos++];
            if (nextByte == HttpConstants.CR) {
                if (sao.pos < sao.limit) {
                    nextByte = sao.bytes[sao.pos++];
                    if (nextByte == HttpConstants.LF) {
                        sao.setReadPosition(0);
                        return line.toString(charset);
                    } else {
                        // Write CR (not followed by LF)
                        sao.pos--;
                        line.writeByte(HttpConstants.CR);
                    }
                } else {
                    line.writeByte(nextByte);
                }
            } else if (nextByte == HttpConstants.LF) {
                sao.setReadPosition(0);
                return line.toString(charset);
            } else {
                line.writeByte(nextByte);
            }
        }
    } catch (IndexOutOfBoundsException e) {
        undecodedChunk.readerIndex(readerIndex);
        throw new NotEnoughDataDecoderException(e);
    }
    undecodedChunk.readerIndex(readerIndex);
    throw new NotEnoughDataDecoderException();
}
 
Example 16
Source File: StringSerializer.java    From ProtocolSupport with GNU Affero General Public License v3.0 4 votes vote down vote up
protected static String readString(ByteBuf from, int length, Charset charset) {
	String string = from.toString(from.readerIndex(), length, charset);
	from.skipBytes(length);
	return string;
}
 
Example 17
Source File: MqttProtocol.java    From joyqueue with Apache License 2.0 4 votes vote down vote up
private boolean decodeProtocol(ByteBuf buffer) {
    // from netty protocol implement

    // FixedHeader
    short b1 = buffer.readUnsignedByte();

    int messageType = b1 >> 4;
    boolean dupFlag = (b1 & 0x08) == 0x08;
    int qosLevel = (b1 & 0x06) >> 1;
    boolean retain = (b1 & 0x01) != 0;

    int remainingLength = 0;
    int multiplier = 1;
    short digit;
    int loops = 0;
    do {
        digit = buffer.readUnsignedByte();
        remainingLength += (digit & 127) * multiplier;
        multiplier *= 128;
        loops++;
    } while ((digit & 128) != 0 && loops < 4);

    // MQTT protocol limits Remaining Length to 4 bytes
    if (loops == 4 && (digit & 128) != 0) {
        return false;
    }

    if (buffer.readerIndex() >= buffer.writerIndex()) {
        return false;
    }

    // VariableHeader
    short msbSize = buffer.readUnsignedByte();
    short lsbSize = buffer.readUnsignedByte();
    int result = msbSize << 8 | lsbSize;
    String protocolName = buffer.toString(buffer.readerIndex(), result, CharsetUtil.UTF_8);
    if (!protocolName.equals("MQTT")) {
        return false;
    }
    return true;
}
 
Example 18
Source File: SniHandler.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
private String sniHostNameFromHandshakeInfo(ByteBuf in) {
    int readerIndex = in.readerIndex();
    try {
        int command = in.getUnsignedByte(readerIndex);

        // tls, but not handshake command
        switch (command) {
            case SslConstants.SSL_CONTENT_TYPE_CHANGE_CIPHER_SPEC:
            case SslConstants.SSL_CONTENT_TYPE_ALERT:
            case SslConstants.SSL_CONTENT_TYPE_APPLICATION_DATA:
                return null;
            case SslConstants.SSL_CONTENT_TYPE_HANDSHAKE:
                break;
            default:
                //not tls or sslv3, do not try sni
                handshaken = true;
                return null;
        }

        int majorVersion = in.getUnsignedByte(readerIndex + 1);

        // SSLv3 or TLS
        if (majorVersion == 3) {

            int packetLength = in.getUnsignedShort(readerIndex + 3) + 5;

            if (in.readableBytes() >= packetLength) {
                // decode the ssl client hello packet
                // we have to skip some var-length fields
                int offset = readerIndex + 43;

                int sessionIdLength = in.getUnsignedByte(offset);
                offset += sessionIdLength + 1;

                int cipherSuitesLength = in.getUnsignedShort(offset);
                offset += cipherSuitesLength + 2;

                int compressionMethodLength = in.getUnsignedByte(offset);
                offset += compressionMethodLength + 1;

                int extensionsLength = in.getUnsignedShort(offset);
                offset += 2;
                int extensionsLimit = offset + extensionsLength;

                while (offset < extensionsLimit) {
                    int extensionType = in.getUnsignedShort(offset);
                    offset += 2;

                    int extensionLength = in.getUnsignedShort(offset);
                    offset += 2;

                    // SNI
                    if (extensionType == 0) {
                        handshaken = true;
                        int serverNameType = in.getUnsignedByte(offset + 2);
                        if (serverNameType == 0) {
                            int serverNameLength = in.getUnsignedShort(offset + 3);
                            return in.toString(offset + 5, serverNameLength,
                                    CharsetUtil.UTF_8);
                        } else {
                            // invalid enum value
                            return null;
                        }
                    }

                    offset += extensionLength;
                }

                handshaken = true;
                return null;
            } else {
                // client hello incomplete
                return null;
            }
        } else {
            handshaken = true;
            return null;
        }
    } catch (Throwable e) {
        // unexpected encoding, ignore sni and use default
        if (logger.isDebugEnabled()) {
            logger.debug("Unexpected client hello packet: " + ByteBufUtil.hexDump(in), e);
        }
        handshaken = true;
        return null;
    }
}
 
Example 19
Source File: ViewHandlerTest.java    From couchbase-jvm-core with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldParseRowWithBracketInIdKeysAndValue() throws Exception {
    String response = Resources.read("query_brackets.json", this.getClass());
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "OK"));
    HttpContent responseChunk = new DefaultLastHttpContent(Unpooled.copiedBuffer(response, CharsetUtil.UTF_8));

    ViewQueryRequest requestMock = mock(ViewQueryRequest.class);
    queue.add(requestMock);
    channel.writeInbound(responseHeader, responseChunk);
    latch.await(1, TimeUnit.SECONDS);
    assertEquals(1, firedEvents.size());
    ViewQueryResponse inbound = (ViewQueryResponse) firedEvents.get(0);

    assertTrue(inbound.status().isSuccess());
    assertEquals(200, inbound.responseCode());
    assertEquals("OK", inbound.responsePhrase());

    ByteBuf singleRow = inbound.rows().toBlocking().single(); //single will blow up if not exactly one
    String singleRowData = singleRow.toString(CharsetUtil.UTF_8);
    ReferenceCountUtil.releaseLater(singleRow);
    Map<String, Object> found = null;
    try {
        found = DefaultObjectMapper.readValueAsMap(singleRowData);
    } catch (IOException e) {
        e.printStackTrace();
        fail("Failed parsing JSON on data " + singleRowData);
    }

    assertEquals(3, found.size());
    assertTrue(found.containsKey("id"));
    assertTrue(found.containsKey("key"));
    assertTrue(found.containsKey("value"));
    assertEquals("IdClosing}BracketId", found.get("id"));
    assertEquals(Arrays.asList("KeyClosing}BracketKey", "KeySquareClosing]SquareBracketKey"), found.get("key"));
    assertEquals("ValueClosing}BracketValue", found.get("value"));

    final AtomicInteger called = new AtomicInteger();
    inbound.info().toBlocking().forEach(new Action1<ByteBuf>() {
        @Override
        public void call(ByteBuf byteBuf) {
            called.incrementAndGet();
            assertEquals("{\"total_rows\":1}", byteBuf.toString(CharsetUtil.UTF_8));
            ReferenceCountUtil.releaseLater(byteBuf);
        }
    });
    assertEquals(1, called.get());
}
 
Example 20
Source File: DataTypeCodec.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
private static LocalDate textDecodeDate(int collationId, ByteBuf buffer, int index, int length) {
  Charset charset = MySQLCollation.getJavaCharsetByCollationId(collationId);
  CharSequence cs = buffer.toString(index, length, charset);
  return LocalDate.parse(cs);
}