List of usage examples for io.netty.buffer ByteBuf capacity
public abstract int capacity();
From source file:org.telegram.server.MTProtoDecoder.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) { if (currentPacketLength == 0) { if (in.readableBytes() < 1) { return; }//ww w. j a va2s . c o m fByte = in.readByte(); if ((byte) 0xef == fByte) { if (in.readableBytes() < 1) { return; } fByte = in.readByte(); } if (fByte != 0x7f && fByte != -1) { if (fByte < 0) { currentPacketLength = ((int) fByte + 128) * 4; } else { currentPacketLength = (int) fByte * 4; } } else { if (in.readableBytes() < 3) { return; } byte[] lenBytes = new byte[4]; lenBytes[3] = in.readByte(); lenBytes[2] = in.readByte(); lenBytes[1] = in.readByte(); ByteBuffer wrapped = ByteBuffer.wrap(lenBytes); int len = wrapped.getInt(); currentPacketLength = len * 4; } } if (in.readableBytes() < currentPacketLength) { if (in.capacity() < currentPacketLength) { in.capacity(in.capacity() + currentPacketLength); } return; } ProtocolBuffer received = new ProtocolBuffer(currentPacketLength); byte[] bytes = new byte[currentPacketLength]; in.readBytes(bytes, 0, currentPacketLength); received.write(bytes); out.add(received); currentPacketLength = 0; }
From source file:org.thingsplode.synapse.endpoint.handlers.HttpRequestIntrospector.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception { try {/*from www . j a v a2s. c o m*/ if (msg == null) { logger.warn("Message@Endpoint received: NULL"); } else if (logger.isDebugEnabled()) { final StringBuilder hb = new StringBuilder(); msg.headers().entries().forEach(e -> { hb.append(e.getKey()).append(" : ").append(e.getValue()).append("\n"); }); String payloadAsSring = null; if (msg instanceof FullHttpRequest) { ByteBuf content = ((FullHttpRequest) msg).content(); byte[] dst = new byte[content.capacity()]; content.copy().getBytes(0, dst); content.retain(); payloadAsSring = new String(dst, Charset.forName("UTF-8")); } logger.debug("Message@Endpoint received: \n\n" + "Uri: " + msg.uri() + "\n" + "Method: " + msg.method() + "\n" + hb.toString() + "\n" + "Payload -> " + (!Util.isEmpty(payloadAsSring) ? payloadAsSring + "\n" : "EMPTY\n")); } } catch (Throwable th) { logger.error(th.getClass().getSimpleName() + " caught while introspecting request, with message: " + th.getMessage(), th); } if (msg != null && msg instanceof FullHttpRequest) { ((FullHttpRequest) msg).content().retain(); } ctx.fireChannelRead(msg); }
From source file:org.thingsplode.synapse.endpoint.handlers.RequestHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Request request) throws Exception { Response response = null;//from w w w.ja v a 2 s.c om boolean fileDownload = filePattern.matcher(request.getHeader().getUri().getPath()).find(); if (!fileDownload) { try { if (request.getBody() != null && (request.getBody() instanceof ByteBuf)) { //the body is in unmarshalled //eg. http case ByteBuf content = (ByteBuf) request.getBody(); byte[] dst = new byte[content.capacity()]; content.getBytes(0, dst); String jsonBody = new String(dst, Charset.forName("UTF-8")); response = registry.invokeWithParsable(request.getHeader(), jsonBody); } else { //the complete body is unmarshalled already for an object //eg. websocket case response = registry.invokeWithObject(request.getHeader(), request.getBody()); } //else { // response = new Response(new Response.ResponseHeader(request.getHeader(), HttpResponseStatus.valueOf(HttpStatus.BAD_REQUEST.value()), new MediaType("text/plain; charset=UTF-8")), RequestHandler.class.getSimpleName() + ": Body type not supported."); //} } catch (MethodNotFoundException mex) { //simple listing, no stack trace (normal issue) logger.warn("Couldn't process request due to " + mex.getClass().getSimpleName() + " with message: " + mex.getMessage()); response = new Response( new Response.ResponseHeader(request.getHeader(), HttpResponseStatus.valueOf(mex.getResponseStatus().value()), MediaType.TEXT_PLAIN), mex.getClass().getSimpleName() + ": " + mex.getMessage()); } catch (SynapseException ex) { //it could be an internal issue logger.error("Error processing REST request: " + ex.getMessage(), ex); response = new Response( new Response.ResponseHeader(request.getHeader(), HttpResponseStatus.valueOf(ex.getResponseStatus().value()), MediaType.TEXT_PLAIN), ex.getClass().getSimpleName() + ": " + ex.getMessage()); } } if (fileDownload || response == null || isFileDownloadRetriable(response)) { FileRequest fr = new FileRequest(request.getHeader()); ctx.fireChannelRead(fr); } else { ctx.fireChannelRead(response); } }
From source file:org.thingsplode.synapse.proxy.handlers.HttpResponse2ResponseDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, HttpResponse httpResponse, List<Object> out) throws Exception { if (!httpResponse.decoderResult().isSuccess()) { logger.warn("HTTP Resonse decoding was not succesfull."); }//from www. j ava 2 s . co m //todo: convert to commands too Response rsp = new Response(new Response.ResponseHeader(httpResponse.status())); rsp.getHeader().addAllProperties(httpResponse.headers().entries()); rsp.getHeader().setMsgId(httpResponse.headers().get(AbstractMessage.PROP_MESSAGE_ID)); rsp.getHeader().setCorrelationId(httpResponse.headers().get(AbstractMessage.PROP_CORRELATION_ID)); rsp.getHeader().setProtocolVersion(httpResponse.headers().get(AbstractMessage.PROP_PROTOCOL_VERSION)); rsp.getHeader().setContentType(new MediaType(httpResponse.headers().get(HttpHeaderNames.CONTENT_TYPE))); rsp.getHeader().setRemoteAddress(ctx.channel().remoteAddress()); if (httpResponse instanceof FullHttpResponse && marshalledBodyExpected(httpResponse.status())) { ByteBuf contentBuffer = ((FullHttpResponse) httpResponse).content(); byte[] dst = new byte[contentBuffer.capacity()]; contentBuffer.getBytes(0, dst); String jsonResponse = new String(dst, Charset.forName("UTF-8")); String bodyType = httpResponse.headers().get(AbstractMessage.PROP_BODY_TYPE); if (Util.notEmpty(bodyType)) { try { Class clz = Class.forName(bodyType); Object payload = EndpointProxy.SERIALIZATION_SERVICE.getSerializer(getMediaType(httpResponse)) .unMarshall(clz, jsonResponse); rsp.setBody(payload); } catch (ClassNotFoundException cnfe) { logger.warn("There's a body of type [" + bodyType + "] on the response, but the corresponding class cannot be found. Skipping the deserialization of the body."); } } else if (logger.isDebugEnabled() && Util.isEmpty(bodyType) && Util.notEmpty(jsonResponse) && !"{ }".equals(jsonResponse)) { logger.warn("Body serialization will be skipped due to missing body type info on the header."); } } out.add(rsp); }
From source file:org.thingsplode.synapse.proxy.handlers.HttpResponseIntrospector.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, HttpResponse msg) throws Exception { if (msg != null) { final StringBuilder hb = new StringBuilder(); msg.headers().entries().forEach(e -> { hb.append(e.getKey()).append(" : ").append(e.getValue()).append("\n"); });//from www .j a va2 s . c om String payloadAsSring = null; if (msg instanceof FullHttpResponse) { ByteBuf content = ((FullHttpResponse) msg).content(); byte[] dst = new byte[content.capacity()]; content.copy().getBytes(0, dst); content.retain(); payloadAsSring = new String(dst, Charset.forName("UTF-8")); } logger.debug("Message@Proxy received [" + msg.getClass().getSimpleName() + "]: \n\n" + "Status: " + msg.status() + "\n" + hb.toString() + "\n" + "Payload -> [" + (!Util.isEmpty(payloadAsSring) ? payloadAsSring : "EMPTY") + "]\n"); } ctx.fireChannelRead(msg); }
From source file:org.tiger.netty.rpc.all.codec.NettyMessageDecoder.java
License:Apache License
private void print(ByteBuf sendBuf) { if (sendBuf == null) return;//from w w w.j a v a2s.c o m /*while(sendBuf.isReadable()){ System.out.print(sendBuf.readByte()+" "); //System.out.flush(); }*/ //System.out.println("ascii>>"+sendBuf.toString(CharsetUtil.US_ASCII)); if (sendBuf != null && sendBuf.capacity() > 0) { byte[] bt = new byte[sendBuf.capacity()]; sendBuf.getBytes(0, bt); System.out.println("bt>" + Arrays.toString(bt)); } else { System.out.println("***>>" + sendBuf); } }
From source file:org.tiger.netty.rpc.all.codec.NettyMessageEncoder.java
License:Apache License
private void print(ByteBuf sendBuf) { byte[] bt = new byte[sendBuf.capacity()]; sendBuf.getBytes(0, bt);/* w ww. ja v a 2 s . co m*/ System.out.println("bt>" + Arrays.toString(bt)); }
From source file:org.traccar.protocol.At2000ProtocolDecoder.java
License:Apache License
@Override protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg; if (buf.getUnsignedByte(buf.readerIndex()) == 0x01) { buf.readUnsignedByte(); // codec id }/*from www . j av a 2 s. c om*/ int type = buf.readUnsignedByte(); buf.readUnsignedMediumLE(); // length buf.skipBytes(BLOCK_LENGTH - 1 - 3); if (type == MSG_DEVICE_ID) { String imei = buf.readSlice(15).toString(StandardCharsets.US_ASCII); if (getDeviceSession(channel, remoteAddress, imei) != null) { byte[] iv = new byte[BLOCK_LENGTH]; buf.readBytes(iv); IvParameterSpec ivSpec = new IvParameterSpec(iv); SecretKeySpec keySpec = new SecretKeySpec( DataConverter.parseHex("000102030405060708090a0b0c0d0e0f"), "AES"); cipher = Cipher.getInstance("AES/CBC/NoPadding"); cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec); byte[] data = new byte[BLOCK_LENGTH]; buf.readBytes(data); cipher.update(data); } } else if (type == MSG_TRACK_RESPONSE) { DeviceSession deviceSession = getDeviceSession(channel, remoteAddress); if (deviceSession == null) { return null; } if (buf.capacity() <= BLOCK_LENGTH) { return null; // empty message } List<Position> positions = new LinkedList<>(); byte[] data = new byte[buf.capacity() - BLOCK_LENGTH]; buf.readBytes(data); buf = Unpooled.wrappedBuffer(cipher.update(data)); try { while (buf.readableBytes() >= 63) { Position position = new Position(getProtocolName()); position.setDeviceId(deviceSession.getDeviceId()); buf.readUnsignedShortLE(); // index buf.readUnsignedShortLE(); // reserved position.setValid(true); position.setTime(new Date(buf.readLongLE() * 1000)); position.setLatitude(buf.readFloatLE()); position.setLongitude(buf.readFloatLE()); position.setAltitude(buf.readFloatLE()); position.setSpeed(UnitsConverter.knotsFromKph(buf.readFloatLE())); position.setCourse(buf.readFloatLE()); buf.readUnsignedIntLE(); // geozone event buf.readUnsignedIntLE(); // io events buf.readUnsignedIntLE(); // geozone value buf.readUnsignedIntLE(); // io values buf.readUnsignedShortLE(); // operator position.set(Position.PREFIX_ADC + 1, buf.readUnsignedShortLE()); position.set(Position.PREFIX_ADC + 1, buf.readUnsignedShortLE()); position.set(Position.KEY_POWER, buf.readUnsignedShortLE() * 0.001); buf.readUnsignedShortLE(); // cid position.set(Position.KEY_RSSI, buf.readUnsignedByte()); buf.readUnsignedByte(); // current profile position.set(Position.KEY_BATTERY, buf.readUnsignedByte()); position.set(Position.PREFIX_TEMP + 1, buf.readUnsignedByte()); position.set(Position.KEY_SATELLITES, buf.readUnsignedByte()); positions.add(position); } } finally { buf.release(); } return positions; } if (type == MSG_DEVICE_ID) { sendRequest(channel); } return null; }
From source file:org.traccar.protocol.MeiligaoProtocolDecoder.java
License:Apache License
private static void sendResponse(Channel channel, SocketAddress remoteAddress, ByteBuf id, int type, ByteBuf msg) {/*from w w w .jav a 2 s.c om*/ if (channel != null) { ByteBuf buf = Unpooled.buffer(2 + 2 + id.readableBytes() + 2 + msg.readableBytes() + 2 + 2); buf.writeByte('@'); buf.writeByte('@'); buf.writeShort(buf.capacity()); buf.writeBytes(id); buf.writeShort(type); buf.writeBytes(msg); msg.release(); buf.writeShort(Checksum.crc16(Checksum.CRC16_CCITT_FALSE, buf.nioBuffer())); buf.writeByte('\r'); buf.writeByte('\n'); channel.writeAndFlush(new NetworkMessage(buf, remoteAddress)); } }
From source file:org.traccar.protocol.NavigilProtocolDecoder.java
License:Apache License
private void sendAcknowledgment(Channel channel, int sequenceNumber) { ByteBuf data = Unpooled.buffer(4);/*from w w w . j a va2 s .co m*/ data.writeShortLE(sequenceNumber); data.writeShortLE(0); // OK ByteBuf header = Unpooled.buffer(20); header.writeByte(1); header.writeByte(0); header.writeShortLE(senderSequenceNumber++); header.writeShortLE(MSG_ACKNOWLEDGEMENT); header.writeShortLE(header.capacity() + data.capacity()); header.writeShortLE(0); header.writeShortLE(Checksum.crc16(Checksum.CRC16_CCITT_FALSE, data.nioBuffer())); header.writeIntLE(0); header.writeIntLE((int) (System.currentTimeMillis() / 1000) + LEAP_SECONDS_DELTA); if (channel != null) { channel.writeAndFlush( new NetworkMessage(Unpooled.wrappedBuffer(header, data), channel.remoteAddress())); } }