Java Code Examples for java.nio.ByteBuffer#putInt()
The following examples show how to use
java.nio.ByteBuffer#putInt() .
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: Tile.java From Game with GNU General Public License v3.0 | 6 votes |
/** * Writes the Tile raw data into a ByteBuffer */ ByteBuffer pack() throws IOException { ByteBuffer out = ByteBuffer.allocate(10); out.put(groundElevation); out.put(groundTexture); out.put(groundOverlay); out.put(roofTexture); out.put(horizontalWall); out.put(verticalWall); out.putInt(diagonalWalls); out.flip(); return out; }
Example 2
Source File: DataPageIO.java From ignite with Apache License 2.0 | 6 votes |
/** * @param buf Buffer. * @param cacheId Cache ID. * @param rowOff Row offset. * @param len Length. * @param prevLen Prev length. */ private void writeCacheIdFragment(ByteBuffer buf, int cacheId, int rowOff, int len, int prevLen) { if (cacheId == 0) return; int size = 4; if (size <= len) buf.putInt(cacheId); else { ByteBuffer cacheIdBuf = ByteBuffer.allocate(size); cacheIdBuf.order(buf.order()); cacheIdBuf.putInt(cacheId); buf.put(cacheIdBuf.array(), rowOff - prevLen, len); } }
Example 3
Source File: XmlAttribute.java From android-chunk-utils with Apache License 2.0 | 5 votes |
@Override public byte[] toByteArray(boolean shrink) { ByteBuffer buffer = ByteBuffer.allocate(SIZE).order(ByteOrder.LITTLE_ENDIAN); buffer.putInt(namespaceIndex()); buffer.putInt(nameIndex()); buffer.putInt(rawValueIndex()); buffer.put(typedValue().toByteArray(shrink)); return buffer.array(); }
Example 4
Source File: StringPool.java From buck with Apache License 2.0 | 5 votes |
public static StringPool create(Iterable<String> strings) { List<String> stringsList = ImmutableList.copyOf(strings); int stringCount = stringsList.size(); ByteBuffer stringOffsets = wrap(new byte[4 * stringCount]); ByteArrayOutputStream stringData = new ByteArrayOutputStream(); byte[] encodedLength = new byte[4]; ByteBuffer lengthBuf = wrap(encodedLength); for (int i = 0; i < stringsList.size(); i++) { lengthBuf.position(0); String value = stringsList.get(i); putEncodedLength(lengthBuf, value.length()); ByteBuffer encoded = Charsets.UTF_8.encode(value); putEncodedLength(lengthBuf, encoded.limit()); stringOffsets.putInt(i * 4, stringData.size()); stringData.write(encodedLength, 0, lengthBuf.position()); stringData.write(encoded.array(), encoded.arrayOffset(), encoded.limit()); stringData.write(0); } // Pad to 4-byte boundary. lengthBuf.putInt(0, 0); stringData.write(encodedLength, 0, (4 - (stringData.size() % 4)) % 4); return new StringPool( stringCount, 0, true, false, stringOffsets, wrap(new byte[0]), wrap(stringData.toByteArray()), wrap(new byte[0])); }
Example 5
Source File: DataView.java From HtmlUnit-Android with Apache License 2.0 | 5 votes |
/** * Sets the given signed 32-bit integer at the specified offset. * @param byteOffset the byte offset * @param value the value * @param littleEndian whether the value is stored in little- or big-endian format */ @JsxFunction public void setInt32(final int byteOffset, final int value, final boolean littleEndian) { final ByteBuffer buff = ByteBuffer.wrap(getBuffer().getBytes()); if (littleEndian) { buff.order(ByteOrder.LITTLE_ENDIAN); } buff.putInt(getByteOffset() + byteOffset, value); }
Example 6
Source File: AttributesFile.java From JMPQ3 with Apache License 2.0 | 5 votes |
public byte[] buildFile() { ByteBuffer buffer = ByteBuffer.wrap(file); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.position(8); for(int crc : crc32) { buffer.putInt(crc); } for(long timestamp : timestamps) { buffer.putLong(timestamp); } return buffer.array(); }
Example 7
Source File: DataChecksum.java From hadoop with Apache License 2.0 | 5 votes |
/** * Calculate checksums for the given data. * * The 'mark' of the ByteBuffer parameters may be modified by this function, * but the position is maintained. * * @param data the DirectByteBuffer pointing to the data to checksum. * @param checksums the DirectByteBuffer into which checksums will be * stored. Enough space must be available in this * buffer to put the checksums. */ public void calculateChunkedSums(ByteBuffer data, ByteBuffer checksums) { if (type.size == 0) return; if (data.hasArray() && checksums.hasArray()) { calculateChunkedSums(data.array(), data.arrayOffset() + data.position(), data.remaining(), checksums.array(), checksums.arrayOffset() + checksums.position()); return; } if (NativeCrc32.isAvailable()) { NativeCrc32.calculateChunkedSums(bytesPerChecksum, type.id, checksums, data); return; } data.mark(); checksums.mark(); try { byte[] buf = new byte[bytesPerChecksum]; while (data.remaining() > 0) { int n = Math.min(data.remaining(), bytesPerChecksum); data.get(buf, 0, n); summer.reset(); summer.update(buf, 0, n); checksums.putInt((int)summer.getValue()); } } finally { data.reset(); checksums.reset(); } }
Example 8
Source File: DataIndexOnlyIT.java From geowave with Apache License 2.0 | 5 votes |
public byte[] toBinary() { // ID can be set from the adapter so no need to persist final ByteBuffer buf = ByteBuffer.allocate(12); buf.putInt((int) time); buf.putFloat(lat); buf.putFloat(lon); return buf.array(); }
Example 9
Source File: DoubleClickCrypto.java From openrtb-doubleclick with Apache License 2.0 | 5 votes |
/** * Decrypts data. * * @param cipherData {@code initVector || E(payload) || I(signature)} * @return {@code initVector || payload || I'(signature)} * Where I'(signature) == I(signature) for success, different for failure */ public byte[] decrypt(byte[] cipherData) throws SignatureException { checkArgument(cipherData.length >= OVERHEAD_SIZE, "Invalid cipherData, %s bytes", cipherData.length); // workBytes := initVector || E(payload) || I(signature) byte[] workBytes = cipherData.clone(); ByteBuffer workBuffer = ByteBuffer.wrap(workBytes); boolean success = false; try { // workBytes := initVector || payload || I(signature) xorPayloadToHmacPad(workBytes); // workBytes := initVector || payload || I'(signature) int confirmationSignature = hmacSignature(workBytes); int integritySignature = workBuffer.getInt(workBytes.length - SIGNATURE_SIZE); workBuffer.putInt(workBytes.length - SIGNATURE_SIZE, confirmationSignature); if (confirmationSignature != integritySignature) { throw new SignatureException("Signature mismatch: " + Integer.toHexString(confirmationSignature) + " vs " + Integer.toHexString(integritySignature)); } if (logger.isDebugEnabled()) { logger.debug(dump("Decrypted", cipherData, workBytes)); } success = true; return workBytes; } finally { if (!success && logger.isDebugEnabled()) { logger.debug(dump("Decrypted (failed)", cipherData, workBytes)); } } }
Example 10
Source File: NTRUSignerPrng.java From ripple-lib-java with ISC License | 5 votes |
/** * Returns <code>n</code> random bytes * * @param n number of bytes to return * @return the next <code>n</code> random bytes */ byte[] nextBytes(int n) { ByteBuffer buf = ByteBuffer.allocate(n); while (buf.hasRemaining()) { ByteBuffer cbuf = ByteBuffer.allocate(seed.length + 4); cbuf.put(seed); cbuf.putInt(counter); byte[] array = cbuf.array(); byte[] hash = new byte[hashAlg.getDigestSize()]; hashAlg.update(array, 0, array.length); hashAlg.doFinal(hash, 0); if (buf.remaining() < hash.length) { buf.put(hash, 0, buf.remaining()); } else { buf.put(hash); } counter++; } return buf.array(); }
Example 11
Source File: SegmentFileHeader.java From waltz with Apache License 2.0 | 5 votes |
void writeTo(ByteBuffer byteBuffer) throws IOException { byteBuffer.putInt(VERSION); byteBuffer.putLong(System.currentTimeMillis()); byteBuffer.putLong(key.getMostSignificantBits()); byteBuffer.putLong(key.getLeastSignificantBits()); byteBuffer.putInt(partitionId); byteBuffer.putLong(firstTransactionId); }
Example 12
Source File: Command.java From remoteyourcam-usb with Apache License 2.0 | 5 votes |
protected void encodeCommand(ByteBuffer b, int code) { b.putInt(12); b.putShort((short) Type.Command); b.putShort((short) code); b.putInt(camera.nextTransactionId()); if (AppConfig.LOG_PACKETS) { Log.i(TAG, "command packet for " + getClass().getSimpleName()); PacketUtil.logHexdump(TAG, b.array(), 12); } }
Example 13
Source File: PubkeyIPObject.java From thundernetwork with GNU Affero General Public License v3.0 | 5 votes |
@Override public byte[] getData () { //TODO: Have some proper summary here.. ByteBuffer byteBuffer = ByteBuffer.allocate(IP.length() + 4 + 4 + pubkey.length + signature.length); try { byteBuffer.put(IP.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byteBuffer.putInt(port); byteBuffer.put(pubkey); byteBuffer.put(signature); byteBuffer.putInt(timestamp); return byteBuffer.array(); }
Example 14
Source File: UnsafeOptimizeDumpLongColumnBinaryMaker.java From yosegi with Apache License 2.0 | 4 votes |
@Override public ColumnBinary toBinary( final ColumnBinaryMakerConfig commonConfig , final ColumnBinaryMakerCustomConfigNode currentConfigNode , final CompressResultNode compressResultNode , final IColumn column ) throws IOException { ColumnBinaryMakerConfig currentConfig = commonConfig; if ( currentConfigNode != null ) { currentConfig = currentConfigNode.getCurrentConfig(); } long[] valueArray = new long[column.size()]; byte[] isNullArray = new byte[column.size()]; Long min = Long.MAX_VALUE; Long max = Long.MIN_VALUE; int rowCount = 0; boolean hasNull = false; for ( int i = 0 ; i < column.size() ; i++ ) { ICell cell = column.get(i); PrimitiveObject primitiveObj = null; if ( cell.getType() == ColumnType.NULL ) { hasNull = true; isNullArray[i] = 1; } else { PrimitiveCell stringCell = (PrimitiveCell) cell; primitiveObj = stringCell.getRow(); valueArray[rowCount] = primitiveObj.getLong(); if ( 0 < min.compareTo( valueArray[rowCount] ) ) { min = Long.valueOf( valueArray[rowCount] ); } if ( max.compareTo( valueArray[rowCount] ) < 0 ) { max = Long.valueOf( valueArray[rowCount] ); } rowCount++; } } if ( ! hasNull && min.equals( max ) ) { return ConstantColumnBinaryMaker.createColumnBinary( createConstObjectFromNum( column.getColumnType() , min ) , column.getColumnName() , column.size() ); } IBinaryMaker binaryMaker = chooseBinaryMaker( min.longValue() , max.longValue() ); ByteOrder order = ByteOrder.nativeOrder(); int nullBinaryLength = 0; if ( hasNull ) { nullBinaryLength = isNullArray.length; } int valueLength = binaryMaker.calcBinarySize( rowCount ); byte[] binaryRaw = new byte[ nullBinaryLength + valueLength ]; if ( hasNull ) { ByteBuffer compressBinaryBuffer = ByteBuffer.wrap( binaryRaw , 0 , nullBinaryLength ); compressBinaryBuffer.put( isNullArray ); } binaryMaker.create( valueArray , binaryRaw , nullBinaryLength , valueLength , order , rowCount ); CompressResult compressResult = compressResultNode.getCompressResult( this.getClass().getName() , "c0" , currentConfig.compressionPolicy , currentConfig.allowedRatio ); byte[] compressBinary = currentConfig.compressorClass.compress( binaryRaw , 0 , binaryRaw.length , compressResult ); byte[] binary = new byte[ Long.BYTES * 2 + Byte.BYTES * 2 + Integer.BYTES + compressBinary.length ]; byte byteOrderByte = order == ByteOrder.BIG_ENDIAN ? (byte)0 : (byte)1; ByteBuffer wrapBuffer = ByteBuffer.wrap( binary , 0 , binary.length ); wrapBuffer.putLong( min ); wrapBuffer.putLong( max ); wrapBuffer.put( hasNull ? (byte)1 : (byte)0 ); wrapBuffer.put( byteOrderByte ); wrapBuffer.putInt( rowCount ); wrapBuffer.put( compressBinary ); return new ColumnBinary( this.getClass().getName() , currentConfig.compressorClass.getClass().getName() , column.getColumnName() , column.getColumnType() , column.size() , binary.length , getLogicalSize( rowCount , column.getColumnType() ) , -1 , binary , 0 , binary.length , null ); }
Example 15
Source File: PartialKeyGrouping.java From jstorm with Apache License 2.0 | 4 votes |
@Override public List<Integer> chooseTasks(int taskId, List<Object> values) { List<Integer> boltIds = new ArrayList<>(1); if (values.size() > 0) { byte[] raw; if (fields != null) { List<Object> selectedFields = outFields.select(fields, values); ByteBuffer out = ByteBuffer.allocate(selectedFields.size() * 4); for (Object o : selectedFields) { if (o instanceof List) { out.putInt(Arrays.deepHashCode(((List) o).toArray())); } else if (o instanceof Object[]) { out.putInt(Arrays.deepHashCode((Object[]) o)); } else if (o instanceof byte[]) { out.putInt(Arrays.hashCode((byte[]) o)); } else if (o instanceof short[]) { out.putInt(Arrays.hashCode((short[]) o)); } else if (o instanceof int[]) { out.putInt(Arrays.hashCode((int[]) o)); } else if (o instanceof long[]) { out.putInt(Arrays.hashCode((long[]) o)); } else if (o instanceof char[]) { out.putInt(Arrays.hashCode((char[]) o)); } else if (o instanceof float[]) { out.putInt(Arrays.hashCode((float[]) o)); } else if (o instanceof double[]) { out.putInt(Arrays.hashCode((double[]) o)); } else if (o instanceof boolean[]) { out.putInt(Arrays.hashCode((boolean[]) o)); } else if (o != null) { out.putInt(o.hashCode()); } else { out.putInt(0); } } raw = out.array(); } else { raw = values.get(0).toString().getBytes(); // assume key is the first field } int firstChoice = (int) (Math.abs(h1.hashBytes(raw).asLong()) % this.targetTasks.size()); int secondChoice = (int) (Math.abs(h2.hashBytes(raw).asLong()) % this.targetTasks.size()); int selected = targetTaskStats[firstChoice] > targetTaskStats[secondChoice] ? secondChoice : firstChoice; boltIds.add(targetTasks.get(selected)); targetTaskStats[selected]++; } return boltIds; }
Example 16
Source File: LibraryChunk.java From apkfile with Apache License 2.0 | 4 votes |
@Override protected void writeHeader(ByteBuffer output) { super.writeHeader(output); output.putInt(entries.size()); }
Example 17
Source File: BitSet.java From akka-tutorial with Apache License 2.0 | 4 votes |
public void toBinary(ByteBuffer buffer) { buffer.putInt(this.words.length); for (int i = 0; i < this.words.length; i++) buffer.putLong(this.words[i]); }
Example 18
Source File: SlimUDTF.java From incubator-hivemall with Apache License 2.0 | 4 votes |
private void recordTrainingInput(final int itemI, @Nonnull final Int2ObjectMap<Int2FloatMap> knnItems, final int numKNNItems) throws HiveException { ByteBuffer buf = this._inputBuf; NioStatefulSegment dst = this._fileIO; if (buf == null) { // invoke only at task node (initialize is also invoked in compilation) final File file; try { file = File.createTempFile("hivemall_slim", ".sgmt"); // to save KNN data file.deleteOnExit(); if (!file.canWrite()) { throw new UDFArgumentException( "Cannot write a temporary file: " + file.getAbsolutePath()); } } catch (IOException ioe) { throw new UDFArgumentException(ioe); } this._inputBuf = buf = ByteBuffer.allocateDirect(8 * 1024 * 1024); // 8MB this._fileIO = dst = new NioStatefulSegment(file, false); } int recordBytes = SizeOf.INT + SizeOf.INT + SizeOf.INT * 2 * knnItems.size() + (SizeOf.INT + SizeOf.FLOAT) * numKNNItems; int requiredBytes = SizeOf.INT + recordBytes; // need to allocate space for "recordBytes" itself int remain = buf.remaining(); if (remain < requiredBytes) { writeBuffer(buf, dst); } buf.putInt(recordBytes); buf.putInt(itemI); buf.putInt(knnItems.size()); for (Int2ObjectMap.Entry<Int2FloatMap> e1 : Fastutil.fastIterable(knnItems)) { int user = e1.getIntKey(); buf.putInt(user); Int2FloatMap ru = e1.getValue(); buf.putInt(ru.size()); for (Int2FloatMap.Entry e2 : Fastutil.fastIterable(ru)) { buf.putInt(e2.getIntKey()); buf.putFloat(e2.getFloatValue()); } } }
Example 19
Source File: PatchModuleInvalidationUtils.java From wildfly-core with GNU Lesser General Public License v2.1 | 4 votes |
/** * Update the central directory signature of a .jar. * * @param file the file to process * @param searchPattern the search patter to use * @param badSkipBytes the bad bytes skip table * @param newSig the new signature * @param endSig the expected signature * @throws IOException */ private static void updateJar(final File file, final byte[] searchPattern, final int[] badSkipBytes, final int newSig, final int endSig) throws IOException { final RandomAccessFile raf = new RandomAccessFile(file, "rw"); try { final FileChannel channel = raf.getChannel(); try { long pos = channel.size() - ENDLEN; final ScanContext context; if (newSig == CRIPPLED_ENDSIG) { context = new ScanContext(GOOD_ENDSIG_PATTERN, CRIPPLED_ENDSIG_PATTERN); } else if (newSig == GOOD_ENDSIG) { context = new ScanContext(CRIPPLED_ENDSIG_PATTERN, GOOD_ENDSIG_PATTERN); } else { context = null; } if (!validateEndRecord(file, channel, pos, endSig)) { pos = scanForEndSig(file, channel, context); } if (pos == -1) { if (context.state == State.NOT_FOUND) { // Don't fail patching if we cannot validate a valid zip PatchLogger.ROOT_LOGGER.cannotInvalidateZip(file.getAbsolutePath()); } return; } // Update the central directory record channel.position(pos); final ByteBuffer buffer = ByteBuffer.allocate(4); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.putInt(newSig); buffer.flip(); while (buffer.hasRemaining()) { channel.write(buffer); } } finally { safeClose(channel); } } finally { safeClose(raf); } }
Example 20
Source File: TcpRestParserSelfTest.java From ignite with Apache License 2.0 | 4 votes |
/** * Assembles raw packet without any logical checks. * * @param magic Header for packet. * @param opCode Operation code. * @param opaque Opaque value. * @param key Key data. * @param val Value data. * @param extras Extras data. * @return Byte buffer containing assembled packet. */ private ByteBuffer rawPacket(byte magic, byte opCode, byte[] opaque, @Nullable byte[] key, @Nullable byte[] val, @Nullable byte[] extras) { // 1k should be enough. ByteBuffer res = ByteBuffer.allocate(1024); res.put(magic); res.put(opCode); int keyLen = key == null ? 0 : key.length; int extrasLen = extras == null ? 0 : extras.length; int valLen = val == null ? 0 : val.length; res.putShort((short)keyLen); res.put((byte)extrasLen); // Data type is always 0. res.put((byte)0); // Reserved. res.putShort((short)0); // Total body. res.putInt(keyLen + extrasLen + valLen); // Opaque. res.put(opaque); // CAS res.putLong(0); if (extrasLen > 0) res.put(extras); if (keyLen > 0) res.put(key); if (valLen > 0) res.put(val); res.flip(); return res; }