Java Code Examples for java.nio.ByteBuffer.getInt()

The following are Jave code examples for showing how to use getInt() of the java.nio.ByteBuffer class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: FApkSigner   File: V2SchemeVerifier.java   View Source Code Vote up 6 votes
private static ByteBuffer getLengthPrefixedSlice(ByteBuffer source) throws ApkFormatException {
    if (source.remaining() < 4) {
        throw new ApkFormatException(
                "Remaining buffer too short to contain length of length-prefixed field"
                        + ". Remaining: " + source.remaining());
    }
    int len = source.getInt();
    if (len < 0) {
        throw new IllegalArgumentException("Negative length");
    } else if (len > source.remaining()) {
        throw new ApkFormatException(
                "Length-prefixed field longer than remaining buffer"
                        + ". Field length: " + len + ", remaining: " + source.remaining());
    }
    return getByteBuffer(source, len);
}
 
Example 2
Project: fitnotifications   File: ICUBinary.java   View Source Code Vote up 6 votes
/**
 * Checks that the ByteBuffer contains a valid, usable ICU .dat package.
 * Moves the buffer position from 0 to after the data header.
 */
static boolean validate(ByteBuffer bytes) {
    try {
        readHeader(bytes, DATA_FORMAT, IS_ACCEPTABLE);
    } catch (IOException ignored) {
        return false;
    }
    int count = bytes.getInt(bytes.position());  // Do not move the position.
    if (count <= 0) {
        return false;
    }
    // For each item, there is one ToC entry (8 bytes) and a name string
    // and a data item of at least 16 bytes.
    // (We assume no data item duplicate elimination for now.)
    if (bytes.position() + 4 + count * (8 + 16) > bytes.capacity()) {
        return false;
    }
    if (!startsWithPackageName(bytes, getNameOffset(bytes, 0)) ||
            !startsWithPackageName(bytes, getNameOffset(bytes, count - 1))) {
        return false;
    }
    return true;
}
 
Example 3
Project: kafka-0.11.0.0-src-with-comment   File: KafkaLZ4Test.java   View Source Code Vote up 6 votes
@Test
public void testBadBlockSize() throws Exception {
    if (!close || (useBrokenFlagDescriptorChecksum && !ignoreFlagDescriptorChecksum)) return;

    thrown.expect(IOException.class);
    thrown.expectMessage(CoreMatchers.containsString("exceeded max"));

    byte[] compressed = compressedBytes();
    final ByteBuffer buffer = ByteBuffer.wrap(compressed).order(ByteOrder.LITTLE_ENDIAN);

    int blockSize = buffer.getInt(7);
    blockSize = (blockSize & LZ4_FRAME_INCOMPRESSIBLE_MASK) | (1 << 24 & ~LZ4_FRAME_INCOMPRESSIBLE_MASK);
    buffer.putInt(7, blockSize);

    testDecompression(buffer);
}
 
Example 4
Project: openjdk-jdk10   File: ByteBufferViews.java   View Source Code Vote up 6 votes
@Test(dataProvider = "intViewProvider")
public void testIntGet(String desc, IntFunction<ByteBuffer> fbb,
                       Function<ByteBuffer, IntBuffer> fbi) {
    ByteBuffer bb = allocate(fbb);
    IntBuffer vb = fbi.apply(bb);
    int o = bb.position();

    for (int i = 0; i < vb.limit(); i++) {
        int fromBytes = getIntFromBytes(bb, o + i * 4);
        int fromMethodView = bb.getInt(o + i * 4);
        assertValues(i, fromBytes, fromMethodView, bb);

        int fromBufferView = vb.get(i);
        assertValues(i, fromMethodView, fromBufferView, bb, vb);
    }

    for (int i = 0; i < vb.limit(); i++) {
        int v = getIntFromBytes(bb, o + i * 4);
        int a = bb.getInt();
        assertValues(i, v, a, bb);

        int b = vb.get();
        assertValues(i, a, b, bb, vb);
    }

}
 
Example 5
Project: sstore-soft   File: SnapshotUtil.java   View Source Code Vote up 6 votes
/**
 * Check if the CRC of the snapshot file matches the digest.
 * @param f The snapshot file object
 * @return The table list as a string
 * @throws IOException If CRC does not match
 */
public static String CRCCheck(File f) throws IOException {
    final FileInputStream fis = new FileInputStream(f);
    try {
        final BufferedInputStream bis = new BufferedInputStream(fis);
        ByteBuffer crcBuffer = ByteBuffer.allocate(4);
        if (4 != bis.read(crcBuffer.array())) {
            throw new EOFException("EOF while attempting to read CRC from snapshot digest");
        }
        final int crc = crcBuffer.getInt();
        final InputStreamReader isr = new InputStreamReader(bis, "UTF-8");
        CharArrayWriter caw = new CharArrayWriter();
        while (true) {
            int nextChar = isr.read();
            if (nextChar == -1) {
                throw new EOFException("EOF while reading snapshot digest");
            }
            if (nextChar == '\n') {
                break;
            }
            caw.write(nextChar);
        }
        String tableList = caw.toString();
        byte tableListBytes[] = tableList.getBytes("UTF-8");
        CRC32 tableListCRC = new CRC32();
        tableListCRC.update(tableListBytes);
        tableListCRC.update("\n".getBytes("UTF-8"));
        final int calculatedValue = (int)tableListCRC.getValue();
        if (crc != calculatedValue) {
            throw new IOException("CRC of snapshot digest did not match digest contents");
        }

        return tableList;
    } finally {
        try {
            if (fis != null)
                fis.close();
        } catch (IOException e) {}
    }
}
 
Example 6
Project: kettle_support_kettle8.0   File: DefaultSessionIdGenerator.java   View Source Code Vote up 6 votes
public DefaultSessionIdGenerator(String s, boolean babble) {

		if (!isValid(s))
			throw new IllegalArgumentException("invalid ObjectId [" + s + "]");

		if (babble)
			s = babbleToMongod(s);

		byte b[] = new byte[12];
		for (int i = 0; i < b.length; i++) {
			b[i] = (byte) Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16);
		}
		ByteBuffer bb = ByteBuffer.wrap(b);
		_time = bb.getInt();
		_machine = bb.getInt();
		_inc = bb.getInt();
		_new = false;
	}
 
Example 7
Project: KernelHive   File: DataPublisher.java   View Source Code Vote up 6 votes
private void putData(ByteBuffer input, ByteBuffer output) {
	int id = input.getInt();
	int size = input.getInt();
	byte[] entity = new byte[size];

	try {
		input.get(entity);
	} catch (BufferUnderflowException bue) {
	}
	publish(id, entity);

	System.out.println("Bytes sent into the data server: ");
	/*ByteBuffer buf = ByteBuffer.wrap(entity);
	 while (true) {
	 try {
	 System.out.println("" + buf.get() + " " + buf.get() + " " + buf.get() + " " + buf.get());
	 } catch (BufferUnderflowException bue) {
	 break;
	 }
	 }*/
}
 
Example 8
Project: athena   File: NeighborSolicitation.java   View Source Code Vote up 6 votes
/**
 * Deserializer function for neighbor solicitation packets.
 *
 * @return deserializer function
 */
public static Deserializer<NeighborSolicitation> deserializer() {
    return (data, offset, length) -> {
        checkInput(data, offset, length, HEADER_LENGTH);

        NeighborSolicitation neighborSolicitation = new NeighborSolicitation();

        ByteBuffer bb = ByteBuffer.wrap(data, offset, length);

        bb.getInt();
        bb.get(neighborSolicitation.targetAddress, 0, Ip6Address.BYTE_LENGTH);

        if (bb.limit() - bb.position() > 0) {
            NeighborDiscoveryOptions options = NeighborDiscoveryOptions.deserializer()
                    .deserialize(data, bb.position(), bb.limit() - bb.position());

            for (NeighborDiscoveryOptions.Option option : options.options()) {
                neighborSolicitation.addOption(option.type(), option.data());
            }
        }

        return neighborSolicitation;
    };
}
 
Example 9
Project: directory-mavibot   File: ByteArraySerializer.java   View Source Code Vote up 6 votes
/**
 * {@inheritDoc}
 */
public byte[] deserialize( ByteBuffer buffer ) throws IOException
{
    int len = buffer.getInt();

    switch ( len )
    {
        case 0:
            return new byte[]
                {};

        case -1:
            return null;

        default:
            byte[] bytes = new byte[len];

            buffer.get( bytes );

            return bytes;
    }
}
 
Example 10
Project: openjdk-jdk10   File: DirectByteBufferTest.java   View Source Code Vote up 5 votes
Ret alignedReadSnippet(byte[] arg) {
    ByteBuffer buffer = makeDirect(arg, byteOrder);

    Ret ret = new Ret();
    ret.byteValue = buffer.get();
    ret.byteValue += buffer.get();
    ret.shortValue = buffer.getShort();
    ret.intValue = buffer.getInt();
    ret.longValue = buffer.getLong();
    ret.doubleValue = buffer.getDouble();
    ret.floatValue = buffer.getFloat();

    return ret;
}
 
Example 11
Project: apkfile   File: XmlStartElementChunk.java   View Source Code Vote up 5 votes
protected XmlStartElementChunk(ByteBuffer buffer, @Nullable Chunk parent) {
    super(buffer, parent);
    namespace = buffer.getInt();
    name = buffer.getInt();
    attributeStart = (buffer.getShort() & 0xFFFF);
    int attributeSize = (buffer.getShort() & 0xFFFF);
    Preconditions
            .checkState(attributeSize == XmlAttribute.SIZE, "attributeSize is wrong size. Got %s, want %s", attributeSize, XmlAttribute.SIZE);
    attributeCount = (buffer.getShort() & 0xFFFF);

    // The following indices are 1-based and need to be adjusted.
    idIndex = (buffer.getShort() & 0xFFFF) - 1;
    classIndex = (buffer.getShort() & 0xFFFF) - 1;
    styleIndex = (buffer.getShort() & 0xFFFF) - 1;
}
 
Example 12
Project: DAA_Converter   File: DAA_Header.java   View Source Code Vote up 5 votes
public void loadAllReferences() {
	try {
		RandomAccessFile raf = new RandomAccessFile(daaFile, "r");
		try {

			raf.seek(getLocationOfBlockInFile(refNamesBlockIndex));

			referenceNames = new byte[(int) dbSeqsUsed][];
			referenceLocations = new long[1 + ((int) dbSeqsUsed >>> referenceLocationChunkBits)];
			for (int i = 0; i < (int) dbSeqsUsed; i++) {
				if ((i & (referenceLocationChunkSize - 1)) == 0) {
					referenceLocations[i >>> referenceLocationChunkBits] = raf.getFilePointer();
				}
				int c = raf.read();
				while (c != 0)
					c = raf.read();
			}

			refLengths = new int[(int) dbSeqsUsed];
			for (int i = 0; i < dbSeqsUsed; i++) {
				ByteBuffer buffer = ByteBuffer.allocate(4);
				buffer.order(ByteOrder.LITTLE_ENDIAN);
				raf.read(buffer.array());
				refLengths[i] = buffer.getInt();
			}

		} finally {
			raf.close();
		}
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example 13
Project: alvisnlp   File: DocumentDecoder.java   View Source Code Vote up 5 votes
@Override
public Document decode1(ByteBuffer buffer) {
	String id = readString(buffer);
	Document result = Document.getDocument(this, corpus, id);
	sectionDecoder.setDoc(result);
	int nSec = buffer.getInt();
	for (int i = 0; i < nSec; ++i) {
		int secRef = buffer.getInt();
		sectionUnmarshaller.read(secRef);
	}
	return result;
}
 
Example 14
Project: mycat-src-1.6.1-RELEASE   File: BackendKeyData.java   View Source Code Vote up 5 votes
/***
 * 解析数据包
 * 
 * @param buffer
 * @param offset
 * @return
 * @throws IllegalArgumentException
 */
public static BackendKeyData parse(ByteBuffer buffer, int offset) {
	if (buffer.get(offset) != PacketMarker.B_BackendKey.getValue()) {
		throw new IllegalArgumentException("this packet not is BackendKeyData");
	}
	BackendKeyData pac = new BackendKeyData();
	pac.length = buffer.getInt(offset + 1);
	pac.pid = buffer.getInt(offset + 1 + 4);
	pac.secretKey = buffer.getInt(offset + 1 + 4 + 4);
	return pac;
}
 
Example 15
Project: sstore-soft   File: StoredProcedureInvocation.java   View Source Code Vote up 5 votes
public static void seekToParameterSet(ByteBuffer buffer) {
    // Skip to the procedure name
    //buffer.position(14);  // modified by hawk, 2014-3-7
    buffer.position(22);
    int procNameLen = buffer.getInt();
    buffer.position(buffer.position() + procNameLen);
}
 
Example 16
Project: Higher-Cloud-Computing-Project   File: MurmurHash.java   View Source Code Vote up 5 votes
/**
 * Hashes the bytes in a buffer from the current position to the limit.
 *
 * @param buf The bytes to hash.
 * @param seed The seed to start with.
 * @return The 32 bit murmur hash of the bytes in the buffer.
 */
public static int hash(ByteBuffer buf, int seed) {
    ByteOrder byteOrder = buf.order();
    buf.order(ByteOrder.LITTLE_ENDIAN);

    int m = 0x5bd1e995;
    int r = 24;

    int h = seed ^ buf.remaining();

    while (buf.remaining() >= 4) {
        int k = buf.getInt();

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

        h *= m;
        h ^= k;
    }

    if (buf.remaining() > 0) {
        ByteBuffer finish = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN);

        finish.put(buf).rewind();

        h ^= finish.getInt();
        h *= m;
    }

    h ^= h >>> 13;
    h *= m;
    h ^= h >>> 15;

    buf.order(byteOrder);

    return h;
}
 
Example 17
Project: twister2   File: MPIMultiMessageDeserializer.java   View Source Code Vote up 4 votes
@Override
  public Object build(Object partialObject, int edge) {
    MPIMessage currentMessage = (MPIMessage) partialObject;
    int readLength = 0;
    int bufferIndex = 0;
    List<MPIBuffer> buffers = currentMessage.getBuffers();
    List<Object> returnList = new ArrayList<>();
    MessageHeader header = currentMessage.getHeader();

    if (header == null) {
      throw new RuntimeException("Header must be built before the message");
    }
//    LOG.info(String.format("%d deserilizing message", executor));
    while (readLength < header.getLength()) {
      List<MPIBuffer> messageBuffers = new ArrayList<>();
      MPIBuffer mpiBuffer = buffers.get(bufferIndex);
      ByteBuffer byteBuffer = mpiBuffer.getByteBuffer();
      // now read the length
      int length = byteBuffer.getInt();
      int tempLength = 0;
      int tempBufferIndex = bufferIndex;
      while (tempLength < length) {
        mpiBuffer = buffers.get(tempBufferIndex);
        messageBuffers.add(mpiBuffer);
        tempLength += mpiBuffer.getByteBuffer().remaining();
        tempBufferIndex++;
//        LOG.info(String.format("%d temp %d length %d readLength %d header %d buf_pos %d",
//            executor, tempLength, length, readLength, header.getLength(),
//            mpiBuffer.getByteBuffer().position()));
      }

      Object object = buildMessage(currentMessage, messageBuffers, length);
      readLength += length + 4;
      byteBuffer = mpiBuffer.getByteBuffer();
      if (byteBuffer.remaining() > 0) {
        bufferIndex = tempBufferIndex - 1;
      } else {
        bufferIndex = tempBufferIndex;
      }

      returnList.add(object);
    }
    return returnList;
  }
 
Example 18
Project: openjdk-jdk10   File: NativeOrderOutputStreamTest.java   View Source Code Vote up 4 votes
private int getInt(int pos) {
    ByteBuffer buffer = ByteBuffer.wrap(target.array());
    buffer.order(ByteOrder.nativeOrder());
    return buffer.getInt(pos);
}
 
Example 19
Project: ApkMultiChannelPlugin   File: ZipUtils.java   View Source Code Vote up 4 votes
static long getUnsignedInt32(ByteBuffer buffer, int offset) {
    return buffer.getInt(offset) & 0xffffffffL;
}
 
Example 20
Project: jchmlib   File: ChmIndexSearcher.java   View Source Code Vote up 4 votes
private int getLeafNodeOffsetWithoutCatch(byte[] queryAsBytes) throws IOException {
    int lastNodeOffset = 0;
    int nodeOffset = ftsHeader.nodeOffset;
    int buffSize = ftsHeader.nodeLen;
    short treeDepth = ftsHeader.treeDepth;

    while ((--treeDepth) != 0) {
        if (nodeOffset == lastNodeOffset) {
            return 0;
        }

        lastNodeOffset = nodeOffset;

        ByteBuffer bufIndexNode = chmFile.retrieveObject(uiMain, nodeOffset, buffSize);
        if (bufIndexNode == null) {
            return 0;
        }

        // the length of free space at the end of the node.
        short freeSpace = bufIndexNode.getShort();
        bufIndexNode.limit(buffSize - freeSpace);

        WordBuilder wordBuilder = createWordBuilder();
        while (bufIndexNode.hasRemaining()) {
            wordBuilder.readWord(bufIndexNode);
            LOG.fine(" <=> word " + wordBuilder.getWord());

            int cmpResult = wordBuilder.compareWith(queryAsBytes);
            if (cmpResult >= 0) {
                LOG.fine("!found index node");
                // Offset of the leaf node whose last entry is this word
                nodeOffset = bufIndexNode.getInt();
                break;
            } else {
                ByteBufferHelper.skip(bufIndexNode, 6);
            }
        }
    }

    if (nodeOffset == lastNodeOffset) {
        return 0;
    }

    return nodeOffset;
}