Java Code Examples for java.nio.ByteBuffer#getLong()

The following examples show how to use java.nio.ByteBuffer#getLong() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UrlUtils.java    From EFRConnect-android with Apache License 2.0 6 votes vote down vote up
static String decodeUrnUuid(byte[] serviceData, int offset, StringBuilder urnBuilder) {
    ByteBuffer bb = ByteBuffer.wrap(serviceData);
    // UUIDs are ordered as byte array, which means most significant first
    bb.order(ByteOrder.BIG_ENDIAN);
    long mostSignificantBytes, leastSignificantBytes;
    try {
        bb.position(offset);
        mostSignificantBytes = bb.getLong();
        leastSignificantBytes = bb.getLong();
    } catch (BufferUnderflowException e) {
        Log.w(TAG, "decodeUrnUuid BufferUnderflowException!");
        return null;
    }
    UUID uuid = new UUID(mostSignificantBytes, leastSignificantBytes);
    urnBuilder.append(uuid.toString());
    return urnBuilder.toString();
}
 
Example 2
Source File: GroupUtil.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public static Long gidFromAddress(Address address) {
    try {
        ByteBuffer buffer = ByteBuffer.allocate(8);
        buffer.put(decodeTTGroupId(address.toGroupString()));
        buffer.flip();
        return buffer.getLong();
    } catch (AssertionError | IOException e) {
        Logger.e(e, "groupIdFromRecipient");
    }
    return 0L;
}
 
Example 3
Source File: ConnectResponse.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Connection response reply constructor
 *
 * @param inStream
 *            the data input stream
 * @throws IOException
 *             a network error
 */
public ConnectResponse(DataInputStream inStream) throws IOException {
    byte data[] = new byte[SIZE];
    inStream.readFully(data);
    ByteBuffer bb = ByteBuffer.wrap(data);
    bb.order(ByteOrder.BIG_ENDIAN);
    fViewerSessionId = bb.getLong();
    fMajor = bb.getInt();
    fMinor = bb.getInt();
    bb.getInt(); // Should not be used, see http://bugs.lttng.org/issues/728
    fType = ConnectionType.VIEWER_CLIENT_COMMAND;
}
 
Example 4
Source File: Serializer.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
public static long readSendTime(ByteBuffer byteBuffer) {
    ByteBuffer slice = byteBuffer.slice();
    slice.position(39);
    long sendTime = slice.getLong();

    return sendTime;
}
 
Example 5
Source File: QueryVersionTimeRequest.java    From bboxdb with Apache License 2.0 5 votes vote down vote up
/**
 * Decode the encoded package into a object
 * 
 * @param encodedPackage
 * @return
 * @throws PackageEncodeException 
 * @throws IOException 
 */
public static QueryVersionTimeRequest decodeTuple(final ByteBuffer encodedPackage) throws PackageEncodeException, IOException {
	final short sequenceNumber = NetworkPackageDecoder.getRequestIDFromRequestPackage(encodedPackage);
	
	final boolean decodeResult = NetworkPackageDecoder.validateRequestPackageHeader(encodedPackage, NetworkConst.REQUEST_TYPE_QUERY);
	
	if(decodeResult == false) {
		throw new PackageEncodeException("Unable to decode package");
	}
	
    final byte queryType = encodedPackage.get();
    
    if(queryType != NetworkConst.REQUEST_QUERY_VERSION_TIME) {
    	throw new PackageEncodeException("Wrong query type: " + queryType);
    }
	
    boolean pagingEnabled = false;
    if(encodedPackage.get() != 0) {
    	pagingEnabled = true;
    }
    
    final short tuplesPerPage = encodedPackage.getShort();
    
    final long timestamp = encodedPackage.getLong();
	final short tableLength = encodedPackage.getShort();
	
	final byte[] tableBytes = new byte[tableLength];
	encodedPackage.get(tableBytes, 0, tableBytes.length);
	final String table = new String(tableBytes);
	
	if(encodedPackage.remaining() != 0) {
		throw new PackageEncodeException("Some bytes are left after decoding: " + encodedPackage.remaining());
	}
	
	final RoutingHeader routingHeader = NetworkPackageDecoder.getRoutingHeaderFromRequestPackage(encodedPackage);

	return new QueryVersionTimeRequest(sequenceNumber, routingHeader, table, timestamp, pagingEnabled, 
			tuplesPerPage);
}
 
Example 6
Source File: LiKafkaClientsUtils.java    From li-apache-kafka-clients with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static UUID randomUUID() {
  byte[] bytes = new byte[16];
  _secureRandom.nextBytes(bytes);
  // Set UUID version number 4
  bytes[6] &= 0x0f;
  bytes[6] |= 0x40;
  // Set IETF variant
  bytes[8] &= 0x3f;
  bytes[8] |= 0x80;
  ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
  return new UUID(byteBuffer.getLong(), byteBuffer.getLong());
}
 
Example 7
Source File: TcpStorageRequest.java    From incubator-crail with Apache License 2.0 5 votes vote down vote up
public void update(ByteBuffer buffer) throws IOException {
	key = buffer.getInt();
	address = buffer.getLong();
	length = buffer.getInt();
	int remaining = buffer.getInt();
	buffer.limit(buffer.position() + remaining);
	data.clear();
	data.put(buffer);
	data.flip();
}
 
Example 8
Source File: ServerInfoResponse.java    From Plumble with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates a ServerInfoResponse object with the bytes obtained from the server.
 * @param response The response to the UDP pings sent by the server.
 * @see http://mumble.sourceforge.net/Protocol
 */
public ServerInfoResponse(Server server, byte[] response, int latency) {
	ByteBuffer buffer = ByteBuffer.wrap(response);
	mVersion = buffer.getInt();
	mIdentifier = buffer.getLong();
	mCurrentUsers = buffer.getInt();
	mMaximumUsers = buffer.getInt();
	mAllowedBandwidth = buffer.getInt();
       mLatency = latency;
       mServer = server;
}
 
Example 9
Source File: MixAll.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
public static long createBrokerId(final String ip, final int port) {
    InetSocketAddress isa = new InetSocketAddress(ip, port);
    byte[] ipArray = isa.getAddress().getAddress();
    ByteBuffer bb = ByteBuffer.allocate(8);
    bb.put(ipArray);
    bb.putInt(port);
    long value = bb.getLong(0);
    return Math.abs(value);
}
 
Example 10
Source File: Capture.java    From outbackcdx with Apache License 2.0 4 votes vote down vote up
private void decodeKeyV0(byte[] key) {
    urlkey = new String(key, 0, key.length - 8, US_ASCII);
    ByteBuffer keyBuf = ByteBuffer.wrap(key);
    timestamp = keyBuf.getLong(key.length - 8);
}
 
Example 11
Source File: PartialSnapshot.java    From journalkeeper with Apache License 2.0 4 votes vote down vote up
/**
 * 安装快照。
 * 反复调用install复制序列化的状态数据。
 * 状态数据先被安装在{@link #partialSnapshotPath}中,当全部状态数据安装完成后,
 * 再复制到{@link #snapshotPath}中
 * 所有数据都复制完成后,将状态。
 * @param offset 快照偏移量
 * @param data 快照数据
 * @param snapshotPath 安装路径
 * @throws IOException 发生IO异常时抛出
 */
void installTrunk(long offset, byte[] data, Path snapshotPath) throws IOException {

    if (offset == 0) {
        begin(snapshotPath);
    } else {
        if (!isPartial()) {
            throw new InstallSnapshotException(
                    String.format("No partial snapshot exists! Install path: %s.", snapshotPath)
            );
        }

        if (!snapshotPath.equals(getSnapshotPath())) {
            throw new InstallSnapshotException(
                    String.format("Partial snapshot path not match! Partial snapshot: %s, install path: %s.", this, snapshotPath)
            );
        }

        if (offset != getOffset()) {
            throw new InstallSnapshotException(
                    String.format("Partial snapshot offset not match! Partial snapshot: %s, request offset: %d.", this, offset)
            );
        }

    }

    ByteBuffer buffer = ByteBuffer.wrap(data);
    int filenameLength = buffer.getInt();
    byte[] filenameBytes = new byte[filenameLength];
    buffer.get(filenameBytes);
    String filePathString = new String(filenameBytes, StandardCharsets.UTF_8);
    long offsetOfFile = buffer.getLong();

    Path filePath = this.partialSnapshotPath.resolve(filePathString);

    if (offsetOfFile == 0) {
        Files.createDirectories(filePath.getParent());
    }


    if (offsetOfFile == 0 && isDirectory(buffer)) {
        logger.info("Creating snapshot directory: {}...", filePath);
        Files.createDirectories(filePath);
    } else {
        logger.info("Installing snapshot file: {}...", filePath);
        if(offsetOfFile == 0 || Files.size(filePath) == offsetOfFile) {
            try (FileOutputStream output = new FileOutputStream(filePath.toFile(), true)) {
                output.write(data, buffer.position(), buffer.remaining());
            }
        } else {
            throw new InstallSnapshotException(
                    String.format(
                            "Current file size %d should equal trunk offset %d! File: %s",
                            Files.size(filePath), offsetOfFile, filePath.toString()
                    )
            );
        }
    }
    this.offset += data.length;
}
 
Example 12
Source File: Util.java    From beacons-android with Apache License 2.0 4 votes vote down vote up
public static UUID binToUUID(byte[] raw) {
    ByteBuffer byteBuffer = ByteBuffer.wrap(raw);
    return new UUID(byteBuffer.getLong(), byteBuffer.getLong());
}
 
Example 13
Source File: BinUtils.java    From BIMserver with GNU Affero General Public License v3.0 4 votes vote down vote up
public static long byteArrayToLong(byte[] bytes) {
	ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
	return byteBuffer.getLong();
}
 
Example 14
Source File: MurmurHashStrategy.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
@Override
public int hashCode(String key) {

    ByteBuffer buf = ByteBuffer.wrap(key.getBytes());
    int seed = 0x1234ABCD;

    ByteOrder byteOrder = buf.order();
    buf.order(ByteOrder.LITTLE_ENDIAN);

    long m = 0xc6a4a7935bd1e995L;
    int r = 47;

    long h = seed ^ (buf.remaining() * m);

    long k;
    while (buf.remaining() >= 8) {
        k = buf.getLong();

        k *= m;
        k ^= k >>> r;
        k *= m;

        h ^= k;
        h *= m;
    }

    if (buf.remaining() > 0) {
        ByteBuffer finish = ByteBuffer.allocate(8).order(
            ByteOrder.LITTLE_ENDIAN);
        // for big-endian version, do this first:
        // finish.position(8-buf.remaining());
        finish.put(buf).rewind();
        h ^= finish.getLong();
        h *= m;
    }
    h ^= h >>> r;
    h *= m;
    h ^= h >>> r;

    buf.order(byteOrder);
    return (int) (h & 0xffffffffL);
}
 
Example 15
Source File: ReceiveSendUdpPong.java    From aeron with Apache License 2.0 4 votes vote down vote up
public static void main(final String[] args) throws IOException
{
    int numChannels = 1;
    if (1 == args.length)
    {
        numChannels = Integer.parseInt(args[0]);
    }

    final ByteBuffer buffer = ByteBuffer.allocateDirect(Configuration.MTU_LENGTH_DEFAULT);

    final DatagramChannel[] receiveChannels = new DatagramChannel[numChannels];
    for (int i = 0; i < receiveChannels.length; i++)
    {
        receiveChannels[i] = DatagramChannel.open();
        init(receiveChannels[i]);
        receiveChannels[i].bind(new InetSocketAddress("localhost", Common.PING_PORT + i));
    }

    final InetSocketAddress sendAddress = new InetSocketAddress("localhost", Common.PONG_PORT);
    final DatagramChannel sendChannel = DatagramChannel.open();
    Common.init(sendChannel);

    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));

    while (true)
    {
        buffer.clear();

        boolean available = false;
        while (!available)
        {
            if (!running.get())
            {
                return;
            }

            for (int i = receiveChannels.length - 1; i >= 0; i--)
            {
                if (null != receiveChannels[i].receive(buffer))
                {
                    available = true;
                    break;
                }
            }
        }

        final long receivedSequenceNumber = buffer.getLong(0);
        final long receivedTimestamp = buffer.getLong(SIZE_OF_LONG);

        buffer.clear();
        buffer.putLong(receivedSequenceNumber);
        buffer.putLong(receivedTimestamp);
        buffer.flip();

        sendChannel.send(buffer, sendAddress);
    }
}
 
Example 16
Source File: BlockChatMessage.java    From Rumble with GNU General Public License v3.0 4 votes vote down vote up
@Override
public long readBlock(InputStream in) throws MalformedBlockPayload, IOException, InputOutputStreamException {
    sanityCheck();

    long timeToTransfer = System.nanoTime();

    /* read the block */
    long readleft = header.getBlockLength();
    byte[] blockBuffer = new byte[(int)header.getBlockLength()];
    int count = in.read(blockBuffer, 0, (int)header.getBlockLength());
    if (count < 0)
        throw new IOException("end of stream reached");
    if (count < (int)header.getBlockLength())
        throw new MalformedBlockPayload("read less bytes than expected", count);

    BlockDebug.d(TAG, "BlockChatMessage received ("+count+" bytes): "+ Arrays.toString(blockBuffer));

    /* process the read buffer */
    try {
        ByteBuffer byteBuffer = ByteBuffer.wrap(blockBuffer);

        byte[] author_id = new byte[FIELD_UID_SIZE];
        byteBuffer.get(author_id, 0, FIELD_UID_SIZE);
        readleft -= FIELD_UID_SIZE;

        short authorLength = byteBuffer.get();
        readleft -= FIELD_AUTHOR_LENGTH_SIZE;
        if ((authorLength <= 0) || (authorLength > readleft) || (authorLength > Contact.CONTACT_NAME_MAX_SIZE))
            throw new MalformedBlockPayload("wrong author.length parameter: " + authorLength, header.getBlockLength()-readleft);
        byte[] author_name = new byte[authorLength];
        byteBuffer.get(author_name, 0, authorLength);
        readleft -= authorLength;

        short messageLength = byteBuffer.getShort();
        readleft -= FIELD_STATUS_LENGTH_SIZE;
        if ((messageLength <= 0) || (messageLength > readleft) || (messageLength > ChatMessage.MSG_MAX_SIZE))
            throw new MalformedBlockPayload("wrong message.length parameter: " + messageLength, header.getBlockLength()-readleft);
        byte[] message = new byte[messageLength];
        byteBuffer.get(message, 0, messageLength);
        readleft -= messageLength;

        long toc = byteBuffer.getLong();
        readleft -= FIELD_TOC_SIZE;

        if(readleft > 0)
            throw new MalformedBlockPayload("wrong header.length parameter, no more data to read: " + (header.getBlockLength()-readleft), header.getBlockLength()-readleft);

        /* assemble the status */
        String author_id_base64 = Base64.encodeToString(author_id, 0, FIELD_UID_SIZE, Base64.NO_WRAP);
        Contact contact_tmp  = new Contact(new String(author_name),author_id_base64,false);
        long receivedAt = (System.currentTimeMillis());
        chatMessage = new ChatMessage(contact_tmp, new String(message), toc, receivedAt, RumbleProtocol.protocolID);

        return header.getBlockLength();
    } catch (BufferUnderflowException exception) {
        throw new MalformedBlockPayload("buffer too small", header.getBlockLength() - readleft);
    }
}
 
Example 17
Source File: PEHeader.java    From davmail with GNU General Public License v2.0 4 votes vote down vote up
public void read() throws IOException {
  FileChannel ch = m_pe.getChannel();
  ByteBuffer head = ByteBuffer.allocate(350);
  head.order(ByteOrder.LITTLE_ENDIAN);
  ch.position(m_baseoffset);
  ch.read(head);
  head.position(0);

  PeMagic = head.getInt();
  // System.out.println("MAGIC::: " + pemagic);
  Machine = head.getShort(); // 4
  NumberOfSections = head.getShort(); // 6
  TimeDateStamp = head.getInt(); // 8
  PointerToSymbolTable = head.getInt(); // C
  NumberOfSymbols = head.getInt(); // 10
  SizeOfOptionalHeader = head.getShort(); // 14
  Characteristics = head.getShort(); // 16
  // Optional Header

  Magic = head.getShort(); // 18
  MajorLinkerVersion = head.get(); // 1a
  MinorLinkerVersion = head.get(); // 1b
  SizeOfCode = head.getInt(); // 1c
  SizeOfInitializedData = head.getInt(); // 20
  SizeOfUninitializedData = head.getInt(); // 24
  AddressOfEntryPoint = head.getInt(); // 28
  BaseOfCode = head.getInt(); // 2c
  if (isPe32Plus()) {
    ImageBase = head.getLong(); // 34
  } else {
    BaseOfData = head.getInt(); // // NT additional fields. // 30
    ImageBase = head.getInt(); // 34
  }
  SectionAlignment = head.getInt(); // 38
  FileAlignment = head.getInt(); // 3c
  MajorOperatingSystemVersion = head.getShort(); // 40
  MinorOperatingSystemVersion = head.getShort(); // 42
  MajorImageVersion = head.getShort(); // 44
  MinorImageVersion = head.getShort(); // 46
  MajorSubsystemVersion = head.getShort(); // 48
  MinorSubsystemVersion = head.getShort(); // 4a
  Reserved1 = head.getInt(); // 4c
  SizeOfImage = head.getInt(); // 50
  SizeOfHeaders = head.getInt(); // 54
  CheckSum = head.getInt(); // 58
  Subsystem = head.getShort(); // 5c
  DllCharacteristics = head.getShort(); // 5e
  if (isPe32Plus()) {
    SizeOfStackReserve = head.getLong(); // 60
    SizeOfStackCommit = head.getLong(); // 64
    SizeOfHeapReserve = head.getLong(); // 68
    SizeOfHeapCommit = head.getLong(); // 6c
  } else {
    SizeOfStackReserve = head.getInt(); // 60
    SizeOfStackCommit = head.getInt(); // 64
    SizeOfHeapReserve = head.getInt(); // 68
    SizeOfHeapCommit = head.getInt(); // 6c
  }
  LoaderFlags = head.getInt(); // 70
  NumberOfRvaAndSizes = head.getInt(); // 74

  ExportDirectory_VA = head.getInt(); // 78
  ExportDirectory_Size = head.getInt(); // 7c
  ImportDirectory_VA = head.getInt(); // 80
  ImportDirectory_Size = head.getInt(); // 84
  ResourceDirectory_VA = head.getInt(); // 88
  ResourceDirectory_Size = head.getInt(); // 8c
  ExceptionDirectory_VA = head.getInt(); // 90
  ExceptionDirectory_Size = head.getInt(); // 94
  SecurityDirectory_VA = head.getInt(); // 98
  SecurityDirectory_Size = head.getInt(); // 9c
  BaseRelocationTable_VA = head.getInt(); // a0
  BaseRelocationTable_Size = head.getInt(); // a4
  DebugDirectory_VA = head.getInt(); // a8
  DebugDirectory_Size = head.getInt(); // ac
  ArchitectureSpecificData_VA = head.getInt(); // b0
  ArchitectureSpecificData_Size = head.getInt(); // b4
  RVAofGP_VA = head.getInt(); // b8
  RVAofGP_Size = head.getInt(); // bc
  TLSDirectory_VA = head.getInt(); // c0
  TLSDirectory_Size = head.getInt(); // c4
  LoadConfigurationDirectory_VA = head.getInt(); // c8
  LoadConfigurationDirectory_Size = head.getInt(); // cc
  BoundImportDirectoryinheaders_VA = head.getInt(); // d0
  BoundImportDirectoryinheaders_Size = head.getInt(); // d4
  ImportAddressTable_VA = head.getInt(); // d8
  ImportAddressTable_Size = head.getInt(); // dc
  DelayLoadImportDescriptors_VA = head.getInt(); // e0
  DelayLoadImportDescriptors_Size = head.getInt(); // e4
  COMRuntimedescriptor_VA = head.getInt(); // e8
  COMRuntimedescriptor_Size = head.getInt(); // ec
}
 
Example 18
Source File: S3RecoverableSerializer.java    From flink with Apache License 2.0 4 votes vote down vote up
private static S3Recoverable deserializeV1(byte[] serialized) throws IOException {
	final ByteBuffer bb = ByteBuffer.wrap(serialized).order(ByteOrder.LITTLE_ENDIAN);

	if (bb.getInt() != MAGIC_NUMBER) {
		throw new IOException("Corrupt data: Unexpected magic number.");
	}

	final byte[] keyBytes = new byte[bb.getInt()];
	bb.get(keyBytes);

	final byte[] uploadIdBytes = new byte[bb.getInt()];
	bb.get(uploadIdBytes);

	final int numParts = bb.getInt();
	final ArrayList<PartETag> parts = new ArrayList<>(numParts);
	for (int i = 0; i < numParts; i++) {
		final int partNum = bb.getInt();
		final byte[] buffer = new byte[bb.getInt()];
		bb.get(buffer);
		parts.add(new PartETag(partNum, new String(buffer, CHARSET)));
	}

	final long numBytes = bb.getLong();

	final String lastPart;
	final int lastObjectArraySize = bb.getInt();
	if (lastObjectArraySize == 0) {
		lastPart = null;
	} else {
		byte[] lastPartBytes = new byte[lastObjectArraySize];
		bb.get(lastPartBytes);
		lastPart = new String(lastPartBytes, CHARSET);
	}

	final long lastPartLength = bb.getLong();

	return new S3Recoverable(
			new String(keyBytes, CHARSET),
			new String(uploadIdBytes, CHARSET),
			parts,
			numBytes,
			lastPart,
			lastPartLength);
}
 
Example 19
Source File: DeterministicUUIDGeneratorStrategy.java    From secure-data-service with Apache License 2.0 3 votes vote down vote up
protected static UUID generateUuid(byte[] data) {
    ByteBuffer byteBuffer = ByteBuffer.wrap(data);

    long msb = byteBuffer.getLong(0);
    long lsb = byteBuffer.getLong(8);

    UUID uuid = new UUID(msb, lsb);

    return uuid;
}
 
Example 20
Source File: BufferUtil.java    From talent-aio with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 * 8个字节
 * @param buffer
 * @return
 *
 * @author: tanyaowu
 * @创建时间: 2017年1月23日 下午3:07:31
 *
 */
public static long readLong(ByteBuffer buffer)
{
	return buffer.getLong();
}