List of usage examples for io.netty.buffer ByteBuf readableBytes
public abstract int readableBytes();
From source file:com.dempe.chat.common.mqtt.codec.Utils.java
License:Open Source License
static boolean checkHeaderAvailability(ByteBuf in) { if (in.readableBytes() < 1) { return false; }// w ww . ja va2s . co m //byte h1 = in.get(); //byte messageType = (byte) ((h1 & 0x00F0) >> 4); in.skipBytes(1); //skip the messageType byte int remainingLength = Utils.decodeRemainingLenght(in); if (remainingLength == -1) { return false; } //check remaining length if (in.readableBytes() < remainingLength) { return false; } //return messageType == type ? MessageDecoderResult.OK : MessageDecoderResult.NOT_OK; return true; }
From source file:com.dempe.chat.common.mqtt.codec.Utils.java
License:Open Source License
/** * Decode the variable remaining length as defined in MQTT v3.1 specification * (section 2.1).// w w w . ja v a 2 s .c o m * * @return the decoded length or -1 if needed more data to decode the length field. */ static int decodeRemainingLenght(ByteBuf in) { int multiplier = 1; int value = 0; byte digit; do { if (in.readableBytes() < 1) { return -1; } digit = in.readByte(); value += (digit & 0x7F) * multiplier; multiplier *= 128; } while ((digit & 0x80) != 0); return value; }
From source file:com.dempe.chat.common.mqtt.codec.Utils.java
License:Open Source License
/** * Read a byte array from the buffer, use two bytes as length information followed by length bytes. *///w w w . ja v a2 s .c o m static byte[] readFixedLengthContent(ByteBuf in) throws UnsupportedEncodingException { if (in.readableBytes() < 2) { return null; } int strLen = in.readUnsignedShort(); if (in.readableBytes() < strLen) { return null; } byte[] strRaw = new byte[strLen]; in.readBytes(strRaw); return strRaw; }
From source file:com.dempe.chat.common.netty.PublishEncoder.java
License:Open Source License
@Override protected void encode(ChannelHandlerContext ctx, PublishMessage message, ByteBuf out) { if (message.getQos() == AbstractMessage.QOSType.RESERVED) { throw new IllegalArgumentException("Found a message with RESERVED Qos"); }/*w w w.j av a 2s . co m*/ if (message.getTopicName() == null || message.getTopicName().isEmpty()) { throw new IllegalArgumentException("Found a message with empty or null topic name"); } ByteBuf variableHeaderBuff = ctx.alloc().buffer(2); ByteBuf buff = null; try { variableHeaderBuff.writeBytes(Utils.encodeString(message.getTopicName())); if (message.getQos() == AbstractMessage.QOSType.LEAST_ONE || message.getQos() == AbstractMessage.QOSType.EXACTLY_ONCE) { if (message.getMessageID() == null) { throw new IllegalArgumentException("Found a message with QOS 1 or 2 and not MessageID setted"); } variableHeaderBuff.writeShort(message.getMessageID()); } variableHeaderBuff.writeBytes(message.getPayload()); int variableHeaderSize = variableHeaderBuff.readableBytes(); byte flags = Utils.encodeFlags(message); buff = ctx.alloc().buffer(2 + variableHeaderSize); buff.writeByte(AbstractMessage.PUBLISH << 4 | flags); buff.writeBytes(Utils.encodeRemainingLength(variableHeaderSize)); buff.writeBytes(variableHeaderBuff); out.writeBytes(buff); } finally { variableHeaderBuff.release(); if (buff != null) { buff.release(); } } }
From source file:com.dianping.cat.message.spi.codec.NativeMessageCodec.java
License:Open Source License
private Message decodeMessage(Context ctx, ByteBuf buf) { Message msg = null;/*from w w w.jav a2 s. c o m*/ while (buf.readableBytes() > 0) { char ch = ctx.readId(buf); switch (ch) { case 't': Codec.TRANSACTION_START.decode(ctx, buf); break; case 'T': msg = Codec.TRANSACTION_END.decode(ctx, buf); break; case 'E': Message e = Codec.EVENT.decode(ctx, buf); ctx.addChild(e); break; case 'M': Message m = Codec.METRIC.decode(ctx, buf); ctx.addChild(m); break; case 'H': Message h = Codec.HEARTBEAT.decode(ctx, buf); ctx.addChild(h); break; case 'L': Message l = Codec.TRACE.decode(ctx, buf); ctx.addChild(l); break; default: throw new RuntimeException(String.format("Unsupported message type(%s).", ch)); } } if (msg == null) { msg = ctx.getMessageTree().getMessage(); } return msg; }
From source file:com.dianping.cat.message.spi.codec.NativeMessageCodec.java
License:Open Source License
@Override public ByteBuf encode(MessageTree tree) { ByteBuf buf = PooledByteBufAllocator.DEFAULT.buffer(4 * 1024); try {/* w w w . j a v a 2 s.c om*/ Context ctx = new Context(tree); buf.writeInt(0); // place-holder Codec.HEADER.encode(ctx, buf, null); Message msg = tree.getMessage(); if (msg != null) { encodeMessage(ctx, buf, msg); } int readableBytes = buf.readableBytes(); buf.setInt(0, readableBytes - 4); // reset the message size return buf; } catch (RuntimeException e) { buf.release(); throw e; } }
From source file:com.difference.historybook.proxy.littleproxy.LittleProxyResponse.java
License:Apache License
@Override public byte[] getContent() { ByteBuf buf = response.content(); byte[] bytes; int length = buf.readableBytes(); if (buf.hasArray()) { bytes = buf.array();//from w w w .j a va 2s . co m } else { bytes = new byte[length]; buf.getBytes(buf.readerIndex(), bytes); } buf.release(); return bytes; }
From source file:com.digisky.outerproxy.server.OuterProxyHttpServerHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) { LogMgr.debug("channelRead0()", "channelRead0"); if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx);// w ww. j a v a2 s. com } } if (msg instanceof HttpContent) { String type = request.getUri().split("/")[1]; if (type.equals("email_activate") == true) { // GET? String[] tmp = request.getUri().split("="); String acode = tmp[tmp.length - 1]; LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "acode:" + acode); ProcessServerManager.getInstance().process(ctx.channel(), type, "{\"acode\":\"" + acode + "\"}"); return; } else if (type.equals("email_pwd_reset") == true) { //? String[] tmp = request.getUri().split("="); String vcode = tmp[tmp.length - 1]; LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "acode:" + vcode); ProcessServerManager.getInstance().process(ctx.channel(), type, "{\"vcode\":\"" + vcode + "\"}"); return; } //email_active email_pwd_reset, //??? HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(request); InterfaceHttpData postData = decoder.getBodyHttpData("val"); if (postData instanceof FileUpload == false) {//outerProxy???? ctx.close(); return; } FileUpload binData = (FileUpload) postData; ByteBuf content = null; try { content = binData.getByteBuf(); } catch (IOException e) { e.printStackTrace(); } //content??. , 0. ?(head)?id, json?, ?. ??, ???. //?content?head int index = content.bytesBefore((byte) 0); if (index < 0) { LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "ellegal request."); ctx.channel().close(); return; } byte[] head = new byte[index]; content.readBytes(head); String strHead = new String(head); LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "head:" + strHead); JSONObject jo = JSONObject.parseObject(strHead); LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "jo::app_id:" + jo.getString("app_id") + " jo::version:" + jo.getString("version")); content.readByte();//0 //?content?tail byte[] tail = new byte[content.readableBytes()]; content.readBytes(tail); String sjsonmsg = null; if (jo.getString("version").equals("0")) { //?0 byte[] bjsonmsg = XXTEA.decrypt(tail, key); int data_len = bjsonmsg.length; for (int i = bjsonmsg.length - 1; i != 0; --i) { if (bjsonmsg[i] == 0) { data_len--; continue; } else { break; } } try { sjsonmsg = new String(bjsonmsg, 0, data_len, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } else { //TODO?0, app_id. ??? LogMgr.error(OuterProxyHttpServerHandler.class.getName(), "?0, ??"); ctx.close(); return; } sjsonmsg = sjsonmsg.substring(sjsonmsg.indexOf('{'), sjsonmsg.indexOf('}') + 1);//? LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "sjson:" + sjsonmsg); //debug code //JSONObject jsonObj = JSONObject.parseObject(sjsonmsg); //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "tmp.get:" + jsonObj.getString("model")); /* debug code //b.getBytes(n+1, tail, 0, b.g-n-1); for(int i=0; i< tail.length; ++i) { System.out.print(String.format("%x ", tail[i])); } */ //debug code //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "uri:" + request.getUri()); //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(),"method:" + request.getMethod()); //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(),"type:" + type); LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "json:" + sjsonmsg); // ProcessServerManager.getInstance().process(ctx.channel(), type, sjsonmsg); } }
From source file:com.digitalpetri.modbus.codec.ModbusTcpCodec.java
License:Apache License
public void decode(ByteBuf buffer, List<Object> out) throws Exception { int startIndex = buffer.readerIndex(); while (buffer.readableBytes() >= HeaderLength && buffer.readableBytes() >= getLength(buffer, startIndex) + HeaderSize) { try {/*from w ww . ja v a 2 s.c o m*/ MbapHeader mbapHeader = MbapHeader.decode(buffer); ModbusPdu modbusPdu = decoder.decode(buffer); if (modbusPdu instanceof UnsupportedPdu) { // Advance past any bytes we should have read but didn't... int endIndex = startIndex + getLength(buffer, startIndex) + 6; buffer.readerIndex(endIndex); } out.add(new ModbusTcpPayload(mbapHeader.getTransactionId(), mbapHeader.getUnitId(), modbusPdu)); } catch (Throwable t) { throw new Exception("error decoding header/pdu", t); } startIndex = buffer.readerIndex(); } }
From source file:com.digitalpetri.opcua.sdk.client.api.identity.UsernameProvider.java
License:Open Source License
@Override public Tuple2<UserIdentityToken, SignatureData> getIdentityToken(EndpointDescription endpoint, ByteString serverNonce) throws Exception { UserTokenPolicy tokenPolicy = Arrays.stream(endpoint.getUserIdentityTokens()) .filter(t -> t.getTokenType() == UserTokenType.UserName).findFirst() .orElseThrow(() -> new Exception("no username token policy found")); String policyId = tokenPolicy.getPolicyId(); SecurityPolicy securityPolicy = SecurityPolicy.None; String securityPolicyUri = tokenPolicy.getSecurityPolicyUri(); try {//from www . ja v a2 s . c o m if (securityPolicyUri != null && !securityPolicyUri.isEmpty()) { securityPolicy = SecurityPolicy.fromUri(securityPolicyUri); } else { securityPolicyUri = endpoint.getSecurityPolicyUri(); securityPolicy = SecurityPolicy.fromUri(securityPolicyUri); } } catch (Throwable t) { logger.warn("Error parsing SecurityPolicy for uri={}, falling back to no security.", securityPolicyUri); } byte[] passwordBytes = password.getBytes("UTF-8"); byte[] nonceBytes = Optional.ofNullable(serverNonce.bytes()).orElse(new byte[0]); ByteBuf buffer = Unpooled.buffer().order(ByteOrder.LITTLE_ENDIAN); if (securityPolicy == SecurityPolicy.None) { buffer.writeBytes(passwordBytes); } else { buffer.writeInt(passwordBytes.length + nonceBytes.length); buffer.writeBytes(passwordBytes); buffer.writeBytes(nonceBytes); ByteString bs = endpoint.getServerCertificate(); X509Certificate certificate = CertificateUtil.decodeCertificate(bs.bytes()); int plainTextBlockSize = getPlainTextBlockSize(certificate, securityPolicy); int blockCount = (buffer.readableBytes() + plainTextBlockSize - 1) / plainTextBlockSize; Cipher cipher = getAndInitializeCipher(certificate, securityPolicy); ByteBuffer plainTextNioBuffer = buffer.nioBuffer(); ByteBuffer cipherTextNioBuffer = Unpooled.buffer().order(ByteOrder.LITTLE_ENDIAN).nioBuffer(); for (int blockNumber = 0; blockNumber < blockCount; blockNumber++) { int position = blockNumber * plainTextBlockSize; int limit = (blockNumber + 1) * plainTextBlockSize; plainTextNioBuffer.position(position).limit(limit); cipher.doFinal(plainTextNioBuffer, cipherTextNioBuffer); } cipherTextNioBuffer.flip(); buffer = Unpooled.wrappedBuffer(cipherTextNioBuffer); } byte[] bs = new byte[buffer.readableBytes()]; buffer.readBytes(bs); UserNameIdentityToken token = new UserNameIdentityToken(policyId, username, ByteString.of(bs), securityPolicy.getAsymmetricEncryptionAlgorithm().getUri()); return new Tuple2<>(token, new SignatureData()); }