List of usage examples for io.netty.buffer ByteBuf readUnsignedInt
public abstract long readUnsignedInt();
From source file:mysql.client.Session_Old.java
public void doHandshake() throws Exception { ByteBuf buf = readPacket(); byte protocolVersion = buf.readByte(); String serverVersion = readString(buf, "ASCII"); System.out.println("protocolVersion = " + protocolVersion); System.out.println("serverVersion = " + serverVersion); long threadId = buf.readUnsignedInt(); System.out.println("threadId = " + threadId); String seed;/*from ww w.ja va 2 s. c o m*/ if (protocolVersion > 9) {//fuck ?mysql jdbc ?,,?mysql internal manualV10 // read auth-plugin-data-part-1 (string[8]) seed = readString(buf, "ASCII", 8);//????,ssl?? // read filler ([00]) buf.readByte(); System.out.println("seed=" + seed); } else { // read scramble (string[NUL]) seed = readString(buf, "ASCII");//v9 handshake?,? } //v10 ??? int serverCapabilities = 0; // read capability flags (lower 2 bytes) if (buf.readerIndex() < buf.capacity()) { serverCapabilities = buf.readShort(); } //??,???,??,????,?,? //?,???????,?? //???,?debug,?? int serverCharsetIndex = buf.readByte(); int serverStatus = buf.readShort(); serverCapabilities |= buf.readShort() << 16;//??,?? int clientParam = 3842703;//??serverCapabilitiesconnection? // clientParam |= 0x00200000; clientParam &= ~0x00100000; // ignore connection attributes // if capabilities & CLIENT_PLUGIN_AUTH { // 1 length of auth-plugin-data // } else { // 1 [00] // } int authPluginDataLength = buf.readByte();//length of auth-plugin-data // next 10 bytes are reserved (all [00]) // buf.setPosition(buf.getPosition() + 10); buf.readerIndex(buf.readerIndex() + 10);//10?? String seed2 = readString(buf, "ASCII", authPluginDataLength - 8); seed += seed2; System.out.println("seed =" + seed); // if ((this.serverCapabilities & CLIENT_PLUGIN_AUTH) != 0) { // proceedHandshakeWithPluggableAuthentication(user, password, database, buf); // return; // } //?????,filter-chain?? //?MysqlOldPasswordPlugin,MysqlNativePasswordPlugin,MysqlClearPasswordPlugin... boolean skipPassword = false; int passwordLength = 16; int userLength = (user != null) ? user.length() : 0; int databaseLength = (database != null) ? database.length() : 0; int packLength = ((userLength + passwordLength + databaseLength) * 3) + 7 + 4 + 33; String pluginName = readString(buf, "ASCII"); //initial handshake packet ?,??Handshake response packet ByteBuf fromServer = buf.alloc().buffer(seed.getBytes().length).writeBytes(seed.getBytes()); byte[] bytes = Security.scramble411(password, seed, "utf-8"); ByteBuf authBuf = buf.alloc().buffer(bytes.length).writeBytes(bytes); // write Auth Response Packet String enc = "utf-8"; ByteBuf sendBuf = createSendByteBuf(packLength); sendBuf = sendBuf.order(ByteOrder.LITTLE_ENDIAN); // last_sent.writeLong(this.clientParam); // last_sent.writeLong(this.maxThreeBytes); //0x00100000 // "_runtime_version" -> "1.8.0_65" // "_client_version" -> "5.1.38" // "_client_name" -> "MySQL Connector Java" // "_client_license" -> "GPL" // "_runtime_vendor" -> "Oracle Corporation" sendBuf.writeInt(clientParam); sendBuf.writeInt(16777215);//writeLong(this.maxThreeBytes); sendBuf.writeByte(33);//CharsetMapping.MYSQL_COLLATION_INDEX_utf8; sendBuf.writeBytes(new byte[23]); //user string<null> sendBuf.writeBytes(user.getBytes()); sendBuf.writeByte(0); //wite toserver length sendBuf.writeByte(0); //write database sendBuf.writeBytes(database.getBytes()); sendBuf.writeByte(0); sendBuf.writeBytes("mysql_native_password".getBytes()); sendBuf.writeByte(0); //propertie ByteBuf propertieBuf = allocator.heapBuffer(100); Properties properties = new Properties(); properties.setProperty("_runtime_version", "1.8.0_65"); properties.setProperty("_client_version", "5.1.38"); properties.setProperty("_client_name", "MySQL Connector Java"); properties.setProperty("_client_license", "GPL"); properties.setProperty("_runtime_vendor", "Oracle Corporation"); Buffer lb = new Buffer(100); for (Object p : properties.keySet()) { lb.writeLenString((String) p); lb.writeLenString(properties.getProperty((String) p)); //mysql buffer , ?int ,,?251,?65536 } // sendBuf.writeByte((byte) (lb.getPosition() - 4)); // sendBuf.writeBytes(lb.getByteBuffer(), 4, lb.getBufLength() - 4); send(sendBuf); // sendBuf.writeBytes(authBuf); //?,fromServertoServer //jdbc driver????,,sql }
From source file:nearenough.protocol.RtMessage.java
License:Open Source License
private Map<RtTag, byte[]> extractSingleMapping(ByteBuf msg) { long uintTag = msg.readUnsignedInt(); RtTag tag = RtTag.fromUnsignedInt((int) uintTag); byte[] value = new byte[msg.readableBytes()]; msg.readBytes(value);/* w w w .j av a2 s . c o m*/ return Collections.singletonMap(tag, value); }
From source file:nearenough.protocol.RtMessage.java
License:Open Source License
private Map<RtTag, byte[]> extractMultiMapping(ByteBuf msg) { // extractOffsets will leave the reader index positioned at the first tag int[] offsets = extractOffsets(msg); int startOfValues = msg.readerIndex() + (4 * numTags); Map<RtTag, byte[]> mapping = new LinkedHashMap<>(numTags); RtTag prevTag = null;/* w ww .j a va 2s . c o m*/ for (int i = 0; i < offsets.length; i++) { long uintCurrTag = msg.readUnsignedInt(); RtTag currTag = RtTag.fromUnsignedInt((int) uintCurrTag); if ((prevTag != null) && currTag.isLessThan(prevTag)) { String exMsg = String.format( "tags not strictly increasing: current '%s' (0x%08x), previous '%s' (0x%08x)", currTag, currTag.valueLE(), prevTag, prevTag.valueLE()); throw new TagsNotIncreasingException(exMsg); } int valueIdx = startOfValues + offsets[i]; int valueLen = ((i + 1) == offsets.length) ? msg.readableBytes() - offsets[i] : offsets[i + 1] - offsets[i]; byte[] valueBytes = new byte[valueLen]; msg.getBytes(valueIdx, valueBytes); mapping.put(currTag, valueBytes); prevTag = currTag; } return Collections.unmodifiableMap(mapping); }
From source file:org.apache.pulsar.broker.service.PersistentDispatcherFailoverConsumerTest.java
License:Apache License
@BeforeMethod public void setup() throws Exception { ServiceConfiguration svcConfig = spy(new ServiceConfiguration()); PulsarService pulsar = spy(new PulsarService(svcConfig)); doReturn(svcConfig).when(pulsar).getConfiguration(); mlFactoryMock = mock(ManagedLedgerFactory.class); doReturn(mlFactoryMock).when(pulsar).getManagedLedgerFactory(); ZooKeeper mockZk = createMockZooKeeper(); doReturn(mockZk).when(pulsar).getZkClient(); doReturn(createMockBookKeeper(mockZk, pulsar.getOrderedExecutor().chooseThread(0))).when(pulsar) .getBookKeeperClient();//from ww w.j ava 2 s. c om configCacheService = mock(ConfigurationCacheService.class); @SuppressWarnings("unchecked") ZooKeeperDataCache<Policies> zkDataCache = mock(ZooKeeperDataCache.class); LocalZooKeeperCacheService zkCache = mock(LocalZooKeeperCacheService.class); doReturn(CompletableFuture.completedFuture(Optional.empty())).when(zkDataCache).getAsync(any()); doReturn(zkDataCache).when(zkCache).policiesCache(); doReturn(zkDataCache).when(configCacheService).policiesCache(); doReturn(configCacheService).when(pulsar).getConfigurationCache(); doReturn(zkCache).when(pulsar).getLocalZkCacheService(); brokerService = spy(new BrokerService(pulsar)); doReturn(brokerService).when(pulsar).getBrokerService(); consumerChanges = new LinkedBlockingQueue<>(); this.channelCtx = mock(ChannelHandlerContext.class); doAnswer(invocationOnMock -> { ByteBuf buf = invocationOnMock.getArgumentAt(0, ByteBuf.class); ByteBuf cmdBuf = buf.retainedSlice(4, buf.writerIndex() - 4); try { int cmdSize = (int) cmdBuf.readUnsignedInt(); int writerIndex = cmdBuf.writerIndex(); cmdBuf.writerIndex(cmdBuf.readerIndex() + cmdSize); ByteBufCodedInputStream cmdInputStream = ByteBufCodedInputStream.get(cmdBuf); BaseCommand.Builder cmdBuilder = BaseCommand.newBuilder(); BaseCommand cmd = cmdBuilder.mergeFrom(cmdInputStream, null).build(); cmdBuilder.recycle(); cmdBuf.writerIndex(writerIndex); cmdInputStream.recycle(); if (cmd.hasActiveConsumerChange()) { consumerChanges.put(cmd.getActiveConsumerChange()); } cmd.recycle(); } finally { cmdBuf.release(); } return null; }).when(channelCtx).writeAndFlush(any(), any()); serverCnx = spy(new ServerCnx(pulsar)); doReturn(true).when(serverCnx).isActive(); doReturn(true).when(serverCnx).isWritable(); doReturn(new InetSocketAddress("localhost", 1234)).when(serverCnx).clientAddress(); when(serverCnx.getRemoteEndpointProtocolVersion()).thenReturn(ProtocolVersion.v12.getNumber()); when(serverCnx.ctx()).thenReturn(channelCtx); serverCnxWithOldVersion = spy(new ServerCnx(pulsar)); doReturn(true).when(serverCnxWithOldVersion).isActive(); doReturn(true).when(serverCnxWithOldVersion).isWritable(); doReturn(new InetSocketAddress("localhost", 1234)).when(serverCnxWithOldVersion).clientAddress(); when(serverCnxWithOldVersion.getRemoteEndpointProtocolVersion()) .thenReturn(ProtocolVersion.v11.getNumber()); when(serverCnxWithOldVersion.ctx()).thenReturn(channelCtx); NamespaceService nsSvc = mock(NamespaceService.class); doReturn(nsSvc).when(pulsar).getNamespaceService(); doReturn(true).when(nsSvc).isServiceUnitOwned(any(NamespaceBundle.class)); doReturn(true).when(nsSvc).isServiceUnitActive(any(TopicName.class)); setupMLAsyncCallbackMocks(); }
From source file:org.apache.pulsar.common.api.PulsarDecoder.java
License:Apache License
@Override final public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // Get a buffer that contains the full frame ByteBuf buffer = (ByteBuf) msg; BaseCommand cmd = null;/*from w ww . j av a 2s . co m*/ BaseCommand.Builder cmdBuilder = null; try { // De-serialize the command int cmdSize = (int) buffer.readUnsignedInt(); int writerIndex = buffer.writerIndex(); buffer.writerIndex(buffer.readerIndex() + cmdSize); ByteBufCodedInputStream cmdInputStream = ByteBufCodedInputStream.get(buffer); cmdBuilder = BaseCommand.newBuilder(); cmd = cmdBuilder.mergeFrom(cmdInputStream, null).build(); buffer.writerIndex(writerIndex); cmdInputStream.recycle(); if (log.isDebugEnabled()) { log.debug("[{}] Received cmd {}", ctx.channel().remoteAddress(), cmd.getType()); } messageReceived(); switch (cmd.getType()) { case PARTITIONED_METADATA: checkArgument(cmd.hasPartitionMetadata()); handlePartitionMetadataRequest(cmd.getPartitionMetadata()); cmd.getPartitionMetadata().recycle(); break; case PARTITIONED_METADATA_RESPONSE: checkArgument(cmd.hasPartitionMetadataResponse()); handlePartitionResponse(cmd.getPartitionMetadataResponse()); cmd.getPartitionMetadataResponse().recycle(); break; case LOOKUP: checkArgument(cmd.hasLookupTopic()); handleLookup(cmd.getLookupTopic()); cmd.getLookupTopic().recycle(); break; case LOOKUP_RESPONSE: checkArgument(cmd.hasLookupTopicResponse()); handleLookupResponse(cmd.getLookupTopicResponse()); cmd.getLookupTopicResponse().recycle(); break; case ACK: checkArgument(cmd.hasAck()); handleAck(cmd.getAck()); cmd.getAck().getMessageId().recycle(); cmd.getAck().recycle(); break; case CLOSE_CONSUMER: checkArgument(cmd.hasCloseConsumer()); handleCloseConsumer(cmd.getCloseConsumer()); cmd.getCloseConsumer().recycle(); break; case CLOSE_PRODUCER: checkArgument(cmd.hasCloseProducer()); handleCloseProducer(cmd.getCloseProducer()); cmd.getCloseProducer().recycle(); break; case CONNECT: checkArgument(cmd.hasConnect()); handleConnect(cmd.getConnect()); cmd.getConnect().recycle(); break; case CONNECTED: checkArgument(cmd.hasConnected()); handleConnected(cmd.getConnected()); cmd.getConnected().recycle(); break; case ERROR: checkArgument(cmd.hasError()); handleError(cmd.getError()); cmd.getError().recycle(); break; case FLOW: checkArgument(cmd.hasFlow()); handleFlow(cmd.getFlow()); cmd.getFlow().recycle(); break; case MESSAGE: { checkArgument(cmd.hasMessage()); handleMessage(cmd.getMessage(), buffer); cmd.getMessage().recycle(); break; } case PRODUCER: checkArgument(cmd.hasProducer()); handleProducer(cmd.getProducer()); cmd.getProducer().recycle(); break; case SEND: { checkArgument(cmd.hasSend()); // Store a buffer marking the content + headers ByteBuf headersAndPayload = buffer.markReaderIndex(); handleSend(cmd.getSend(), headersAndPayload); cmd.getSend().recycle(); break; } case SEND_ERROR: checkArgument(cmd.hasSendError()); handleSendError(cmd.getSendError()); cmd.getSendError().recycle(); break; case SEND_RECEIPT: checkArgument(cmd.hasSendReceipt()); handleSendReceipt(cmd.getSendReceipt()); cmd.getSendReceipt().recycle(); break; case SUBSCRIBE: checkArgument(cmd.hasSubscribe()); handleSubscribe(cmd.getSubscribe()); cmd.getSubscribe().recycle(); break; case SUCCESS: checkArgument(cmd.hasSuccess()); handleSuccess(cmd.getSuccess()); cmd.getSuccess().recycle(); break; case PRODUCER_SUCCESS: checkArgument(cmd.hasProducerSuccess()); handleProducerSuccess(cmd.getProducerSuccess()); cmd.getProducerSuccess().recycle(); break; case UNSUBSCRIBE: checkArgument(cmd.hasUnsubscribe()); handleUnsubscribe(cmd.getUnsubscribe()); cmd.getUnsubscribe().recycle(); break; case PING: checkArgument(cmd.hasPing()); handlePing(cmd.getPing()); cmd.getPing().recycle(); break; case PONG: checkArgument(cmd.hasPong()); handlePong(cmd.getPong()); cmd.getPong().recycle(); break; case REDELIVER_UNACKNOWLEDGED_MESSAGES: checkArgument(cmd.hasRedeliverUnacknowledgedMessages()); handleRedeliverUnacknowledged(cmd.getRedeliverUnacknowledgedMessages()); cmd.getRedeliverUnacknowledgedMessages().recycle(); break; case CONSUMER_STATS: checkArgument(cmd.hasConsumerStats()); handleConsumerStats(cmd.getConsumerStats()); cmd.getConsumerStats().recycle(); break; case CONSUMER_STATS_RESPONSE: checkArgument(cmd.hasConsumerStatsResponse()); handleConsumerStatsResponse(cmd.getConsumerStatsResponse()); cmd.getConsumerStatsResponse().recycle(); break; case REACHED_END_OF_TOPIC: checkArgument(cmd.hasReachedEndOfTopic()); handleReachedEndOfTopic(cmd.getReachedEndOfTopic()); cmd.getReachedEndOfTopic().recycle(); break; } } finally { if (cmdBuilder != null) { cmdBuilder.recycle(); } if (cmd != null) { cmd.recycle(); } buffer.release(); } }
From source file:org.bermuda.cartilage.core.ConnectionController.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object message) { ByteBuf buffer = (ByteBuf) message; try {/*from w w w .j a va2s .c om*/ logger.info("Incoming message : " + buffer.readUnsignedInt()); } finally { ReferenceCountUtil.release(message); } }
From source file:org.bgp4j.netty.protocol.BGPv4PacketDecoder.java
License:Apache License
/** * decode the NOTIFICATION network packet for error code "Cease". * /*from w w w . j a va2s . c o m*/ * @param buffer the buffer containing the data. * @return */ private NotificationPacket decodeCeaseNotificationPacket(ByteBuf buffer, int errorSubcode) { NotificationPacket packet = null; switch (errorSubcode) { default: log.info("cannot handle cease notification subcode {}", errorSubcode); case CeaseNotificationPacket.SUBCODE_UNSPECIFIC: packet = new UnspecifiedCeaseNotificationPacket(); break; case CeaseNotificationPacket.SUBCODE_MAXIMUM_NUMBER_OF_PREFIXES_REACHED: packet = new MaximumNumberOfPrefixesReachedNotificationPacket(); try { AddressFamily afi = AddressFamily.fromCode(buffer.readUnsignedShort()); SubsequentAddressFamily safi = SubsequentAddressFamily.fromCode(buffer.readUnsignedByte()); int prefixUpperBounds = (int) buffer.readUnsignedInt(); packet = new MaximumNumberOfPrefixesReachedNotificationPacket(afi, safi, prefixUpperBounds); } catch (RuntimeException e) { log.info("cannot decode specific reason for CEASE maximum number of prefixes reached notification", e); } break; case CeaseNotificationPacket.SUBCODE_ADMINSTRATIVE_SHUTDOWN: packet = new AdministrativeShutdownNotificationPacket(); break; case CeaseNotificationPacket.SUBCODE_PEER_DECONFIGURED: packet = new PeerDeconfiguredNotificationPacket(); break; case CeaseNotificationPacket.SUBCODE_ADMINSTRATIVE_RESET: packet = new AdministrativeResetNotificationPacket(); break; case CeaseNotificationPacket.SUBCODE_CONNECTION_REJECTED: packet = new ConnectionRejectedNotificationPacket(); break; case CeaseNotificationPacket.SUBCODE_OTHER_CONFIGURATION_CHANGE: packet = new OtherConfigurationChangeNotificationPacket(); break; case CeaseNotificationPacket.SUBCODE_CONNECTION_COLLISION_RESOLUTION: packet = new ConnectionCollisionResolutionNotificationPacket(); break; case CeaseNotificationPacket.SUBCODE_OUT_OF_RESOURCES: packet = new OutOfResourcesNotificationPacket(); break; } return packet; }
From source file:org.bgp4j.netty.protocol.open.CapabilityCodec.java
License:Apache License
private static Capability decodeAutonomousSystem4Capability(ByteBuf buffer) { AutonomousSystem4Capability cap = new AutonomousSystem4Capability(); assertFixedLength(buffer, BGPv4Constants.BGP_CAPABILITY_LENGTH_AS4_NUMBERS); cap.setAutonomousSystem((int) buffer.readUnsignedInt()); return cap;/*from w w w . ja v a 2 s. c o m*/ }
From source file:org.bgp4j.netty.protocol.open.OpenPacketDecoder.java
License:Apache License
/** * decode the OPEN network packet. The passed channel buffer MUST point to the first packet octet AFTER the packet type and the buffer * must be at least 9 octets large at this point. * // ww w . j a va 2s . c om * @param buffer the buffer containing the data. * @return */ public OpenPacket decodeOpenPacket(ByteBuf buffer) { OpenPacket packet = new OpenPacket(); ProtocolPacketUtils.verifyPacketSize(buffer, BGPv4Constants.BGP_PACKET_MIN_SIZE_OPEN, -1); packet.setProtocolVersion(buffer.readUnsignedByte()); if (packet.getProtocolVersion() != BGPv4Constants.BGP_VERSION) throw new UnsupportedVersionNumberException(BGPv4Constants.BGP_VERSION); packet.setAutonomousSystem(buffer.readUnsignedShort()); packet.setHoldTime(buffer.readUnsignedShort()); packet.setBgpIdentifier(buffer.readUnsignedInt()); if ((packet.getBgpIdentifier() & IPV4_MULTICAST_MASK) == IPV4_MULTICAST_MASK) throw new BadBgpIdentifierException(); int parameterLength = buffer.readUnsignedByte(); if (parameterLength > 0) { while (buffer.isReadable()) { int parameterType = buffer.readUnsignedByte(); int paramLength = buffer.readUnsignedByte(); ByteBuf valueBuffer = buffer.readBytes(paramLength); switch (parameterType) { case BGPv4Constants.BGP_OPEN_PARAMETER_TYPE_AUTH: break; case BGPv4Constants.BGP_OPEN_PARAMETER_TYPE_CAPABILITY: packet.getCapabilities().addAll(CapabilityCodec.decodeCapabilities(valueBuffer)); break; default: throw new UnsupportedOptionalParameterException(); } } } return packet; }
From source file:org.bgp4j.netty.protocol.refresh.RouteRefreshPacketDecoder.java
License:Apache License
private ORFEntry decodeAddressPrefixBasedORFEntry(ByteBuf buffer, ORFAction action, ORFMatch match) { AddressPrefixBasedORFEntry entry = new AddressPrefixBasedORFEntry(action, match); if (action != ORFAction.REMOVE_ALL) { entry.setSequence((int) buffer.readUnsignedInt()); entry.setMinLength(buffer.readUnsignedByte()); entry.setMaxLength(buffer.readUnsignedByte()); entry.setPrefix(NLRICodec.decodeNLRI(buffer)); }// w w w . ja v a2 s . co m return entry; }