List of usage examples for io.netty.buffer ByteBuf toString
public abstract String toString(int index, int length, Charset charset);
From source file:at.yawk.dbus.protocol.auth.CommandCodec.java
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { int crlfPos = in.forEachByte(new CRLFFinder()); if (crlfPos == -1) { return;//from w w w .ja va 2s . c o m } int start = in.readerIndex(); int end = crlfPos - 1; // remove trailing crlf String commandString = in.toString(start, end - start, CHARSET); log.trace("Received message {}", commandString); in.readerIndex(crlfPos + 1); int sep = commandString.indexOf(' '); String commandName = sep == -1 ? commandString : commandString.substring(0, sep); Function<List<String>, Command> factory = FACTORIES.get(commandName); if (factory != null) { List<String> args; if (sep == -1) { args = Collections.emptyList(); } else { args = Arrays.asList(commandString.substring(sep + 1).split(" ")); } out.add(factory.apply(args)); } }
From source file:cloudfoundry.norouter.f5.dropsonde.LineEventDecoder.java
License:Open Source License
private String nextString(ByteBuf buffer) { // Read space terminated string final int start = buffer.readerIndex(); int length = 0; while (buffer.readByte() != ' ') { length++;/*from ww w . j a v a 2 s.c o m*/ } return buffer.toString(start, length, StandardCharsets.UTF_8); }
From source file:com.antsdb.saltedfish.server.mysql.util.BufferUtils.java
License:Open Source License
public static String readString(ByteBuf buf) { String s;/*from w w w . j a va 2s . c o m*/ int bytes = buf.bytesBefore((byte) 0); if (bytes == -1) { // string might not be terminated by 0 bytes = buf.readableBytes(); s = buf.toString(buf.readerIndex(), bytes, Charset.defaultCharset()); buf.skipBytes(bytes); } else { s = buf.toString(buf.readerIndex(), bytes, Charset.defaultCharset()); buf.skipBytes(bytes + 1); } return s; }
From source file:com.chiorichan.http.ssl.SniNegotiator.java
License:Mozilla Public License
private String sniHostNameFromHandshakeInfo(ByteBuf in) { int readerIndex = in.readerIndex(); try {//from w w w.j a v a 2 s . c om 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; } }
From source file:com.datastax.driver.core.CBUtil.java
License:Apache License
private static String readString(ByteBuf cb, int length) { try {//from ww w.ja v a 2 s .co m String str = cb.toString(cb.readerIndex(), length, CharsetUtil.UTF_8); cb.readerIndex(cb.readerIndex() + length); return str; } catch (IllegalStateException e) { // That's the way netty encapsulate a CCE if (e.getCause() instanceof CharacterCodingException) throw new DriverInternalError("Cannot decode string as UTF8"); else throw e; } }
From source file:com.dc.gameserver.ServerCore.Controller.AbstractController.AbstractController.java
License:Apache License
/** * fastjson??javaBean </br>/* w ww . ja v a2 s. c om*/ * ??javaBean </br> * * @param buffer buffer * @param clazz class sub-class * @return Object javaBean */ public static Object parseObject(ByteBuf buffer, Class clazz) { Object o = JSON.parseObject(buffer.toString(buffer.readerIndex(), buffer.writerIndex() - buffer.readerIndex(), Charset.defaultCharset()), clazz); buffer.release();//buf byteBuffer +buf? buffer = null; return o; }
From source file:com.streamsets.pipeline.lib.parser.net.DelimitedLengthFieldBasedFrameDecoder.java
License:Apache License
/** * Create a frame out of the {@link ByteBuf} and return it. * * @param ctx the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to * @param in the {@link ByteBuf} from which to read data * @return frame the {@link ByteBuf} which represent the frame or {@code null} if no frame could * be created./*w w w . j ava2 s.co m*/ */ protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception { if (discardingTooLongFrame) { long bytesToDiscard = this.bytesToDiscard; int localBytesToDiscard = (int) Math.min(bytesToDiscard, in.readableBytes()); in.skipBytes(localBytesToDiscard); bytesToDiscard -= localBytesToDiscard; this.bytesToDiscard = bytesToDiscard; failIfNecessary(false); return null; } if (consumingLength) { int delimIndex = indexOf(in, delimiter); if (delimIndex < 0) { return null; } final String lengthStr = in.toString(in.readerIndex(), delimIndex, lengthFieldCharset); try { frameLength = Long.parseLong(trimLengthString ? lengthStr.trim() : lengthStr); } catch (NumberFormatException e) { throw new CorruptedFrameException(String.format("Invalid length field decoded (in %s charset): %s", lengthFieldCharset.name(), lengthStr), e); } if (frameLength < 0) { throw new CorruptedFrameException("negative pre-adjustment length field: " + frameLength); } frameLength += lengthAdjustment; //consume length field and delimiter bytes in.skipBytes(delimIndex + delimiter.capacity()); //consume delimiter bytes consumingLength = false; } if (frameLength > maxFrameLength) { long discard = frameLength - in.readableBytes(); tooLongFrameLength = frameLength; if (discard < 0) { // buffer contains more bytes then the frameLength so we can discard all now in.skipBytes((int) frameLength); } else { // Enter the discard mode and discard everything received so far. discardingTooLongFrame = true; consumingLength = true; bytesToDiscard = discard; in.skipBytes(in.readableBytes()); } failIfNecessary(true); return null; } // never overflows because it's less than maxFrameLength int frameLengthInt = (int) frameLength; if (in.readableBytes() < frameLengthInt) { // need more bytes available to read actual frame return null; } // the frame is now entirely present, reset state vars consumingLength = true; frameLength = 0; // extract frame int readerIndex = in.readerIndex(); int actualFrameLength = frameLengthInt;// - initialBytesToStrip; ByteBuf frame = extractFrame(ctx, in, readerIndex, actualFrameLength); in.readerIndex(readerIndex + actualFrameLength); return frame; }
From source file:com.zextras.modules.chat.server.xmpp.netty.XmlSubTagTokenizer.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> objects) throws Exception { int idx = byteBuf.bytesBefore(sTokenEnd); if (idx == -1) { return;/*from w w w.j av a 2s. co m*/ } String token = byteBuf.toString(0, idx + 1, mCharset); byteBuf.readerIndex(byteBuf.readerIndex() + idx + 1); byteBuf.discardReadBytes(); objects.add(token); }
From source file:de.felix_klauke.pegasus.protocol.util.ByteBufUtils.java
License:Apache License
/** * * Read an UTF-8 String from a ByteBuf./*from w ww .j a v a2 s .co m*/ * * @param byteBuf the bytebuf to read from * @return the String */ public static String readUTF8String(ByteBuf byteBuf) { int length = byteBuf.readInt(); String string = byteBuf.toString(byteBuf.readerIndex(), length, Charsets.UTF_8); byteBuf.readerIndex(byteBuf.readerIndex() + length); return string; }
From source file:io.advantageous.conekt.dns.impl.netty.decoder.AddressDecoder.java
License:Open Source License
/** * Returns an {@link java.net.InetAddress} containing a decoded address from either an A * or AAAA resource record.// w w w . ja v a2s.co m * * @param response the {@link DnsResponse} received that contained the resource * record being decoded * @param resource the {@link DnsResource} being decoded */ @Override public InetAddress decode(DnsResponse response, DnsResource resource) { ByteBuf data = resource.content().copy().readerIndex(response.originalIndex()); int size = data.writerIndex() - data.readerIndex(); if (data.readerIndex() != 0 || size != octets) { throw new DecoderException("Invalid content length, or reader index when decoding address [index: " + data.readerIndex() + ", expected length: " + octets + ", actual: " + size + "]."); } byte[] address = new byte[octets]; data.getBytes(data.readerIndex(), address); try { return InetAddress.getByAddress(address); } catch (UnknownHostException e) { throw new DecoderException("Could not convert address " + data.toString(data.readerIndex(), size, CharsetUtil.UTF_8) + " to InetAddress."); } }