List of usage examples for io.netty.buffer ByteBuf readableBytes
public abstract int readableBytes();
From source file:com.codeabovelab.dm.platform.http.async.ByteBufHolderAdapter.java
License:Apache License
@Override public int readByte(ByteBufHolder chunk) { ByteBuf buf = chunk.content(); if (buf.readableBytes() == 0) { return ChunkedInputStream.EOF; }//w w w .ja v a2 s . c o m return buf.readByte(); }
From source file:com.codeabovelab.dm.platform.http.async.ByteBufHolderAdapter.java
License:Apache License
@Override public int readBytes(ByteBufHolder chunk, byte[] arr, int off, int len) { ByteBuf buf = chunk.content(); int avail = buf.readableBytes(); if (avail == 0) { return ChunkedInputStream.EOF; }/*w w w .j a v a2 s . com*/ int readed = Math.min(len, avail); buf.readBytes(arr, off, readed); return readed; }
From source file:com.codebullets.external.party.simulator.connections.websocket.inbound.NettyWebSocketServerHandler.java
License:Apache License
private void handleHttpRequest(final ChannelHandlerContext ctx, final FullHttpRequest req) { if (!req.getDecoderResult().isSuccess()) { // Handle a bad request. sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); } else if (req.getMethod() != GET) { // Allow only GET methods. sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); } else if ("/".equals(req.getUri())) { ByteBuf content = WebSocketServerIndexPage.getContent(endpoint.toString()); FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content); res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8"); setContentLength(res, content.readableBytes()); sendHttpResponse(ctx, req, res); } else if ("/favicon.ico".equals(req.getUri())) { // Send the demo page and favicon.ico FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND); sendHttpResponse(ctx, req, res); } else {/*from w ww . j a v a 2 s . c om*/ // Handshake WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(endpoint.toString(), null, false); handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel()); } else { handshaker.handshake(ctx.channel(), req).addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (future.isSuccess()) { connectedChannels.add(ctx.channel()); connectionMonitor.connectionEstablished(getContext(ctx)); } } }); } } }
From source file:com.codnos.dbgp.internal.handlers.DBGpResponseDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> objects) throws Exception { final int length = in.readableBytes(); LOGGER.fine("got something from engine (" + length + " bytes)"); int nullPosition = in.forEachByte(ByteProcessor.FIND_NUL); int readerIndex = in.readerIndex(); int numberOfBytes = nullPosition - readerIndex; LOGGER.fine("found nullposition on " + nullPosition + " and readerIndex is " + readerIndex + " calculated number of bytes " + numberOfBytes); if (numberOfBytes <= 0) { LOGGER.fine("not enough to read, finishing"); in.resetReaderIndex();//from w ww . j a v a2s . c o m return; } if (nullPosition > length) { LOGGER.fine("have null position further than length, finishing"); in.resetReaderIndex(); return; } ByteBuf sizeBuf = in.readBytes(numberOfBytes); in.readByte(); String sizeBufAsString = sizeBuf.toString(UTF_8); int size = Integer.parseInt(sizeBufAsString); int expectedSize = sizeBuf.readableBytes() + NULL_BYTE_SIZE + size + NULL_BYTE_SIZE; if (length < expectedSize) { LOGGER.fine("don't have the whole message yet (expected " + expectedSize + "), finishing"); in.resetReaderIndex(); sizeBuf.release(); return; } ByteBuf messageBuf = in.readBytes(size); in.readByte(); objects.add(messageBuf.toString(UTF_8)); sizeBuf.release(); messageBuf.release(); }
From source file:com.comphenix.protocol.compat.netty.independent.NettyChannelInjector.java
License:Open Source License
/** * Retrieve every byte in the given byte buffer. * @param buffer - the buffer./*from w w w . j a v a2 s . com*/ * @return The bytes. */ private byte[] getBytes(ByteBuf buffer) { byte[] data = new byte[buffer.readableBytes()]; buffer.readBytes(data); return data; }
From source file:com.comphenix.protocol.events.PacketContainer.java
License:Open Source License
private void writeObject(ObjectOutputStream output) throws IOException { // Default serialization output.defaultWriteObject();//from w w w . jav a2 s. c o m // We'll take care of NULL packets as well output.writeBoolean(handle != null); try { if (MinecraftReflection.isUsingNetty()) { ByteBuf buffer = createPacketBuffer(); MinecraftMethods.getPacketWriteByteBufMethod().invoke(handle, buffer); output.writeInt(buffer.readableBytes()); buffer.readBytes(output, buffer.readableBytes()); } else { // Call the write-method output.writeInt(-1); getMethodLazily(writeMethods, handle.getClass(), "write", DataOutput.class).invoke(handle, new DataOutputStream(output)); } } catch (IllegalArgumentException e) { throw new IOException("Minecraft packet doesn't support DataOutputStream", e); } catch (IllegalAccessException e) { throw new RuntimeException("Insufficient security privileges.", e); } catch (InvocationTargetException e) { throw new IOException("Could not serialize Minecraft packet.", e); } }
From source file:com.comphenix.protocol.injector.netty.WirePacket.java
License:Open Source License
private static byte[] getBytes(ByteBuf buffer) { byte[] array = new byte[buffer.readableBytes()]; buffer.readBytes(array);/* ww w. ja v a 2 s. com*/ return array; }
From source file:com.corundumstudio.socketio.handler.EncoderHandler.java
License:Apache License
private void sendMessage(HttpMessage msg, Channel channel, ByteBuf out, String type) { HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK); res.headers().add(CONTENT_TYPE, type).add("Set-Cookie", "io=" + msg.getSessionId()).add(CONNECTION, KEEP_ALIVE);//from ww w . jav a 2 s . c o m addOriginHeaders(channel, res); HttpHeaders.setContentLength(res, out.readableBytes()); // prevent XSS warnings on IE // https://github.com/LearnBoost/socket.io/pull/1333 String userAgent = channel.attr(EncoderHandler.USER_AGENT).get(); if (userAgent != null && (userAgent.contains(";MSIE") || userAgent.contains("Trident/"))) { res.headers().add("X-XSS-Protection", "0"); } sendMessage(msg, channel, out, res); }
From source file:com.corundumstudio.socketio.parser.Decoder.java
License:Apache License
private long parseLong(ByteBuf chars) { return parseLong(chars, chars.readerIndex() + chars.readableBytes()); }
From source file:com.corundumstudio.socketio.parser.Decoder.java
License:Apache License
private Packet decodePacket(ByteBuf buffer, UUID uuid) throws IOException { if (buffer.readableBytes() < 3) { throw new DecoderException("Can't parse " + buffer.toString(CharsetUtil.UTF_8)); }/*from ww w. j a va 2 s .co m*/ PacketType type = getType(buffer); int readerIndex = buffer.readerIndex() + 1; // 'null' to avoid unnecessary StringBuilder creation boolean hasData = false; StringBuilder messageId = null; for (readerIndex += 1; readerIndex < buffer.readableBytes(); readerIndex++) { if (messageId == null) { messageId = new StringBuilder(4); } byte msg = buffer.getByte(readerIndex); if (msg == Packet.SEPARATOR) { break; } if (msg != (byte) '+') { messageId.append((char) msg); } else { hasData = true; } } Long id = null; if (messageId != null && messageId.length() > 0) { id = Long.valueOf(messageId.toString()); } // 'null' to avoid unnecessary StringBuilder creation StringBuilder endpointBuffer = null; for (readerIndex += 1; readerIndex < buffer.readableBytes(); readerIndex++) { if (endpointBuffer == null) { endpointBuffer = new StringBuilder(); } byte msg = buffer.getByte(readerIndex); if (msg == Packet.SEPARATOR) { break; } endpointBuffer.append((char) msg); } String endpoint = Namespace.DEFAULT_NAME; if (endpointBuffer != null && endpointBuffer.length() > 0) { endpoint = endpointBuffer.toString(); } if (buffer.readableBytes() == readerIndex) { buffer.readerIndex(buffer.readableBytes()); } else { readerIndex += 1; buffer.readerIndex(readerIndex); } Packet packet = new Packet(type); packet.setEndpoint(endpoint); if (id != null) { packet.setId(id); if (hasData) { packet.setAck(Packet.ACK_DATA); } else { packet.setAck(true); } } switch (type) { case ERROR: { if (!buffer.isReadable()) { break; } String[] pieces = buffer.toString(CharsetUtil.UTF_8).split("\\+"); if (pieces.length > 0 && pieces[0].trim().length() > 0) { ErrorReason reason = ErrorReason.valueOf(Integer.valueOf(pieces[0])); packet.setReason(reason); if (pieces.length > 1) { ErrorAdvice advice = ErrorAdvice.valueOf(Integer.valueOf(pieces[1])); packet.setAdvice(advice); } } break; } case MESSAGE: { if (buffer.isReadable()) { packet.setData(buffer.toString(CharsetUtil.UTF_8)); } else { packet.setData(""); } break; } case EVENT: { ByteBufInputStream in = new ByteBufInputStream(buffer); Event event = jsonSupport.readValue(in, Event.class); packet.setName(event.getName()); if (event.getArgs() != null) { packet.setArgs(event.getArgs()); } break; } case JSON: { ByteBufInputStream in = new ByteBufInputStream(buffer); JsonObject obj = jsonSupport.readValue(in, JsonObject.class); if (obj != null) { packet.setData(obj.getObject()); } else { in.reset(); Object object = jsonSupport.readValue(in, Object.class); packet.setData(object); } break; } case CONNECT: { if (buffer.isReadable()) { packet.setQs(buffer.toString(CharsetUtil.UTF_8)); } break; } case ACK: { if (!buffer.isReadable()) { break; } boolean validFormat = true; int plusIndex = -1; for (int i = buffer.readerIndex(); i < buffer.readerIndex() + buffer.readableBytes(); i++) { byte dataChar = buffer.getByte(i); if (!Character.isDigit(dataChar)) { if (dataChar == '+') { plusIndex = i; break; } else { validFormat = false; break; } } } if (!validFormat) { break; } if (plusIndex == -1) { packet.setAckId(parseLong(buffer)); break; } else { packet.setAckId(parseLong(buffer, plusIndex)); buffer.readerIndex(plusIndex + 1); ByteBufInputStream in = new ByteBufInputStream(buffer); AckCallback<?> callback = ackManager.getCallback(uuid, packet.getAckId()); AckArgs args = jsonSupport.readAckArgs(in, callback); packet.setArgs(args.getArgs()); } break; } case DISCONNECT: case HEARTBEAT: case NOOP: break; } buffer.readerIndex(buffer.readerIndex() + buffer.readableBytes()); return packet; }