List of usage examples for io.netty.buffer ByteBuf isReadable
public abstract boolean isReadable();
From source file:com.quavo.osrs.network.protocol.codec.update.UpdateDecoder.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (!in.isReadable() || in.readableBytes() < 4) { return;// w w w. j a v a 2s .co m } Optional<UpdateType> request = UpdateType.getType(in.readUnsignedByte()); if (request.isPresent()) { UpdateType updateType = request.get(); switch (updateType) { case LOW_PRIORITY_UPDATE: case HIGH_PRIORITY_UPDATE: int uid = in.readUnsignedMedium(); int type = (uid >> 16); int id = (uid & 0xffff); out.add(new UpdateRequest(this, type, id, updateType == UpdateType.HIGH_PRIORITY_UPDATE)); break; case XOR_ENCRYPTION_UPDATE: int key = in.readUnsignedByte(); in.readUnsignedShort(); out.add(new XOREncryptionRequest(this, key)); break; } } else { in.readUnsignedMedium(); } }
From source file:com.quavo.util.buf.ByteBufUtils.java
License:Open Source License
/** * Converts data from a {@link ByteBuf} into a readable string. * * @param buffer The {@link ByteBuf}./* w w w.j av a 2 s . c o m*/ * @return The string. */ public static String readString(ByteBuf buffer) { StringBuilder bldr = new StringBuilder(); byte b; while (buffer.isReadable() && (b = buffer.readByte()) != STRING_TERMINATOR) { bldr.append((char) b); } return bldr.toString(); }
From source file:com.quavo.util.buf.ByteBufUtils.java
License:Open Source License
/** * Converts data from a {@link ByteBuf} into a readable jag string. * * @param buffer The {@link ByteBuf}.// w w w . ja va 2s . co m * @return The string. */ public static String readJagString(ByteBuf buffer) { StringBuilder bldr = new StringBuilder(); byte b; buffer.readByte(); while (buffer.isReadable() && (b = buffer.readByte()) != STRING_TERMINATOR) { bldr.append((char) b); } return bldr.toString(); }
From source file:com.ReceiveFileHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf in = (ByteBuf) msg; try {/*www . j av a 2s . co m*/ while (in.isReadable()) { in.readBytes(bos, in.readableBytes()); } bos.flush(); } finally { in.release(); } }
From source file:com.sample.netty.socket.utils.MessageDecoder.java
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) { if (in.readableBytes() < 4) { return;//from w ww . j a v a 2s . com } StringBuilder sb = new StringBuilder(); while (in.isReadable()) { sb.append((char) in.readByte()); } out.add(sb.toString()); }
From source file:com.seagate.kinetic.simulator.io.provider.nio.http.HttpMessageServiceHandler.java
License:Open Source License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { int contentLength = 0; if (msg instanceof HttpRequest) { HttpRequest request = (HttpRequest) msg; logger.finest("protocol version: " + request.getProtocolVersion()); logger.finest("host: " + getHost(request, "unknown")); logger.finest("REQUEST_URI: " + request.getUri()); List<Map.Entry<String, String>> headers = request.headers().entries(); String lenstr = request.headers().get(HttpHeaders.Names.CONTENT_LENGTH); contentLength = Integer.parseInt(lenstr); logger.finest("content length=" + contentLength); if (!headers.isEmpty()) { for (Map.Entry<String, String> h : request.headers().entries()) { String key = h.getKey(); String value = h.getValue(); logger.finest("HEADER: " + key + " = " + value); }//from ww w . j a v a2s . com } QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri()); Map<String, List<String>> params = queryStringDecoder.parameters(); if (!params.isEmpty()) { for (Entry<String, List<String>> p : params.entrySet()) { String key = p.getKey(); List<String> vals = p.getValue(); for (String val : vals) { logger.finest("PARAM: " + key + " = " + val); } } } } // create extended builder ExtendedMessage.Builder extendedMessage = ExtendedMessage.newBuilder(); if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); if (content.isReadable()) { byte[] body = new byte[contentLength]; content.getBytes(0, body); // read from serialized bytes extendedMessage.mergeFrom(body); } // build message ExtendedMessage extended = extendedMessage.build(); if (logger.isLoggable(Level.FINEST)) { logger.finest("received request: " + extended); } // create kinetic message for processing KineticMessage km = new KineticMessage(); // set interface message km.setMessage(extended.getInterfaceMessage()); // get command bytes ByteString commandBytes = extendedMessage.getInterfaceMessage().getCommandBytes(); // build command Command.Builder commandBuilder = Command.newBuilder(); try { commandBuilder.mergeFrom(commandBytes); km.setCommand(commandBuilder.build()); } catch (InvalidProtocolBufferException e) { logger.log(Level.WARNING, e.getMessage(), e); } // set value if (extended.hasValue()) { km.setValue(extended.getValue().toByteArray()); } // process request KineticMessage kmresp = this.lcservice.processRequest(km); // construct response message ExtendedMessage.Builder extendedResponse = ExtendedMessage.newBuilder(); // set interface message extendedResponse.setInterfaceMessage((Message.Builder) kmresp.getMessage()); // set value if (kmresp.getValue() != null) { extendedResponse.setValue(ByteString.copyFrom(kmresp.getValue())); } // get serialized value ByteBuf data = Unpooled.copiedBuffer(extendedResponse.build().toByteArray()); FullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, data); httpResponse.headers().set(CONTENT_TYPE, "application/octet-stream"); httpResponse.headers().set(HttpHeaders.Names.CONTENT_ENCODING, HttpHeaders.Values.BINARY); httpResponse.headers().set(CONTENT_LENGTH, httpResponse.content().readableBytes()); httpResponse.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); // send response message ctx.writeAndFlush(httpResponse); if (logger.isLoggable(Level.FINEST)) { logger.finest("wrote and flushed response: " + kmresp); } } }
From source file:com.seventh_root.ld33.client.network.LD33ClientBoundPacketDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { byte[] output = new byte[in.readableBytes()]; in.readBytes(output);/*from www . j a v a 2 s . c o m*/ System.out.println(Arrays.toString(output)); in.resetReaderIndex(); while (in.isReadable()) { int id = in.readInt(); switch (id) { case 0: byte[] encodedPublicKey = new byte[in.readInt()]; in.readBytes(encodedPublicKey); out.add(new PublicKeyClientBoundPacket(encodedPublicKey)); break; case 1: out.add(new PlayerLoginClientBoundPacket()); break; case 2: String joiningPlayerUUID = readString(in); String joiningPlayerName = readString(in); int joiningPlayerResources = in.readInt(); out.add(new PlayerJoinClientBoundPacket(UUID.fromString(joiningPlayerUUID), joiningPlayerName, joiningPlayerResources)); break; case 3: String quittingPlayerUUID = readString(in); String quittingPlayerName = readString(in); out.add(new PlayerQuitClientBoundPacket(UUID.fromString(quittingPlayerUUID), quittingPlayerName)); break; case 4: String loginResponseMessage = readString(in); boolean loginSuccess = in.readBoolean(); out.add(new PlayerLoginResponseClientBoundPacket(loginResponseMessage, loginSuccess)); break; case 5: String spawningUnitUUID = readString(in); String spawningUnitPlayerUUID = readString(in); int spawningUnitX = in.readInt(); int spawningUnitY = in.readInt(); String type = readString(in); long spawningUnitCompletionTime = in.readLong(); Unit unit; switch (type) { case "wall": unit = new Wall(UUID.fromString(spawningUnitUUID), Player.getByUUID(null, UUID.fromString(spawningUnitPlayerUUID)), client.getWorldPanel().getWorld().getTileAt(spawningUnitX, spawningUnitY), spawningUnitCompletionTime); break; case "dragon": unit = new Dragon(UUID.fromString(spawningUnitUUID), Player.getByUUID(null, UUID.fromString(spawningUnitPlayerUUID)), client.getWorldPanel().getWorld().getTileAt(spawningUnitX, spawningUnitY), spawningUnitCompletionTime); break; case "flag": unit = new Flag(UUID.fromString(spawningUnitUUID), Player.getByUUID(null, UUID.fromString(spawningUnitPlayerUUID)), client.getWorldPanel().getWorld().getTileAt(spawningUnitX, spawningUnitY), spawningUnitCompletionTime); break; default: unit = null; break; } out.add(new UnitSpawnClientBoundPacket(unit)); break; case 6: String movingUnitUUID = readString(in); int movingUnitX = in.readInt(); int movingUnitY = in.readInt(); int movingUnitTargetX = in.readInt(); int movingUnitTargetY = in.readInt(); out.add(new UnitMoveClientBoundPacket( Unit.getByUUID(null, client.getWorldPanel().getWorld(), UUID.fromString(movingUnitUUID)), movingUnitX, movingUnitY, movingUnitTargetX, movingUnitTargetY)); break; case 7: String chatMessage = readString(in); out.add(new ChatMessageClientBoundPacket(chatMessage)); break; case 8: String purchasingPlayerUUID = readString(in); int purchasedUnitX = in.readInt(); int purchasedUnitY = in.readInt(); String purchasedUnitType = readString(in); out.add(new UnitPurchaseClientBoundPacket(UUID.fromString(purchasingPlayerUUID), purchasedUnitX, purchasedUnitY, purchasedUnitType)); break; } } }
From source file:com.seventh_root.ld33.server.network.LD33ServerBoundPacketDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { while (in.isReadable()) { int id = in.readInt(); switch (id) { case 0://from w w w . jav a2s . c o m byte[] encodedPublicKey = new byte[in.readInt()]; in.readBytes(encodedPublicKey); out.add(new PublicKeyServerBoundPacket(encodedPublicKey)); break; case 1: String loggingInPlayerName = readString(in); byte[] encryptedPassword = new byte[in.readInt()]; in.readBytes(encryptedPassword); boolean signUp = in.readBoolean(); out.add(new PlayerLoginServerBoundPacket(loggingInPlayerName, encryptedPassword, signUp)); break; case 2: out.add(new PlayerJoinServerBoundPacket()); break; case 3: out.add(new PlayerQuitServerBoundPacket()); break; case 4: String loginResponseMessage = readString(in); boolean loginSuccess = in.readBoolean(); out.add(new PlayerLoginResponseServerBoundPacket(loginResponseMessage, loginSuccess)); break; case 5: String spawningUnitUUID = readString(in); String spawningUnitPlayerUUID = readString(in); int spawningUnitX = in.readInt(); int spawningUnitY = in.readInt(); String spawningUnitType = readString(in); long spawningUnitCompletionTime = in.readLong(); Unit spawningUnit; switch (spawningUnitType) { case "wall": spawningUnit = new Wall(UUID.fromString(spawningUnitUUID), Player.getByUUID(null, UUID.fromString(spawningUnitPlayerUUID)), server.getWorld().getTileAt(spawningUnitX, spawningUnitY), spawningUnitCompletionTime); break; case "dragon": spawningUnit = new Dragon(UUID.fromString(spawningUnitUUID), Player.getByUUID(null, UUID.fromString(spawningUnitPlayerUUID)), server.getWorld().getTileAt(spawningUnitX, spawningUnitY), spawningUnitCompletionTime); break; case "flag": spawningUnit = new Flag(UUID.fromString(spawningUnitUUID), Player.getByUUID(null, UUID.fromString(spawningUnitPlayerUUID)), server.getWorld().getTileAt(spawningUnitX, spawningUnitY), spawningUnitCompletionTime); break; default: spawningUnit = null; break; } out.add(new UnitSpawnServerBoundPacket(spawningUnit)); break; case 6: String movingUnitUUID = readString(in); int movingUnitTargetX = in.readInt(); int movingUnitTargetY = in.readInt(); out.add(new UnitMoveServerBoundPacket(Unit.getByUUID(server.getDatabaseConnection(), server.getWorld(), UUID.fromString(movingUnitUUID)), movingUnitTargetX, movingUnitTargetY)); break; case 7: String chatMessage = readString(in); out.add(new ChatMessageServerBoundPacket(chatMessage)); break; case 8: int purchasedUnitX = in.readInt(); int purchasedUnitY = in.readInt(); String purchasedUnitType = readString(in); out.add(new UnitPurchaseServerBoundPacket(purchasedUnitX, purchasedUnitY, purchasedUnitType)); break; } } }
From source file:com.sohu.jafka.http.HttpServerHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx);//from ww w. ja v a 2 s.co m } body = new ByteArrayOutputStream(64); args = new HashMap<String, String>(4); // if (request.getMethod() != HttpMethod.POST) { sendStatusMessage(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED, "POST METHOD REQUIRED"); return; } HttpHeaders headers = request.headers(); String contentType = headers.get("Content-Type"); // ? text or octstream args.put("request_key", headers.get("request_key")); args.put("topic", headers.get("topic")); args.put("partition", headers.get("partition")); } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); if (content.isReadable()) { //body.write(content.array()); content.readBytes(body, content.readableBytes()); //body.append(content.toString(CharsetUtil.UTF_8)); } if (msg instanceof LastHttpContent) { //process request if (server.handler != null) { server.handler.handle(args, body.toByteArray()); } if (!writeResponse(ctx)) { // If keep-alive is off, close the connection once the content is fully written. ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } body = null; args = null; } } }
From source file:com.spotify.ffwd.json.JsonObjectMapperDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (!in.isReadable()) { return;//from w w w . j a va 2 s .c om } final Object frame; try { frame = decode0(in, out); } catch (Exception e) { log.error("Discarding invalid frame", e); return; } out.add(frame); }