List of usage examples for java.nio ByteBuffer put
public ByteBuffer put(ByteBuffer src)
From source file:byps.BBufferJson.java
private final void ensureRemaining(int size) { if (buf.position() + size > buf.capacity()) { int cap = Math.max(buf.capacity() << 1, buf.position() + size); ByteBuffer nbuf = ByteBuffer.allocate(cap); nbuf.order(buf.order());/*from ww w.ja v a 2s . c o m*/ buf.flip(); nbuf.put(buf); buf = nbuf; } }
From source file:com.linkedin.databus.core.DbusEventV1.java
@Override public DbusEventInternalWritable createCopy() { ByteBuffer cloned = ByteBuffer.allocate(size()).order(_buf.order()); cloned.put(getRawBytes()); DbusEventV1 c = new DbusEventV1(cloned, 0); return c;// w ww .jav a2 s .c o m }
From source file:com.koda.integ.hbase.blockcache.OffHeapBlockCacheOld.java
/** * Store external.// www. j a v a 2 s. co m * * @param blockName the block name * @param buf the buf * @param inMemory the in memory * @throws IOException Signals that an I/O exception has occurred. */ @SuppressWarnings("unused") private void storeExternal(String blockName, Cacheable buf, boolean inMemory) throws IOException { // If external storage is disable - bail out if (overflowExtEnabled == false) return; // Check if we have already this block in external storage cache if (extStorageCache.contains(blockName)) return; ByteBuffer buffer = extStorageCache.getLocalBufferWithAddress().getBuffer(); deserializer.set(buf.getDeserializer()); buffer.clear(); buffer.position(4); buffer.put(inMemory ? (byte) 1 : (byte) 0); buf.serialize(buffer); buffer.putInt(0, buffer.position() - 4); StorageHandle handle = storage.storeData(buffer); try { extStorageCache.put(blockName, handle); } catch (Exception e) { throw new IOException(e); } }
From source file:edu.umass.cs.gigapaxos.paxospackets.PaxosPacket.java
protected ByteBuffer toBytes(ByteBuffer bbuf) throws UnsupportedEncodingException { // paxospacket stuff bbuf.putInt(PaxosPacket.PaxosPacketType.PAXOS_PACKET.getInt()); // type bbuf.putInt(this.packetType.getInt()); // paxos type bbuf.putInt(this.version); // paxosID length followed by paxosID byte[] paxosIDBytes = this.paxosID != null ? this.paxosID.getBytes(CHARSET) : new byte[0]; bbuf.put((byte) paxosIDBytes.length); bbuf.put(paxosIDBytes);//from ww w.j av a 2 s . c o m assert (bbuf.position() == SIZEOF_PAXOSPACKET_FIXED + paxosIDBytes.length) : bbuf.position() + " != " + SIZEOF_PAXOSPACKET_FIXED + paxosIDBytes.length; return bbuf; }
From source file:com.github.ambry.commons.BlobIdTest.java
/** * Build a string that resembles a bad blobId. * @param version The version number to be embedded in the blobId. * @param type The {@link BlobIdType} of the blobId. * @param datacenterId The datacenter id to be embedded in the blobId. * @param accountId The account id to be embedded in the blobId. * @param containerId The container id to be embedded in the blobId. * @param partitionId The partition id to be embedded in the blobId. * @param uuidLength The length of the uuid. * @param uuid The UUID to be embedded in the blobId. * @param extraChars Extra characters to put at the end of the ID. * @return a base-64 encoded {@link String} representing the blobId. */// w w w .java 2s . co m private String buildBadBlobId(short version, BlobIdType type, Byte datacenterId, Short accountId, Short containerId, PartitionId partitionId, int uuidLength, String uuid, String extraChars) { int idLength; ByteBuffer idBuf; switch (version) { case BLOB_ID_V1: idLength = 2 + partitionId.getBytes().length + 4 + uuid.length() + extraChars.length(); idBuf = ByteBuffer.allocate(idLength); idBuf.putShort(version); break; case BLOB_ID_V2: idLength = 2 + 1 + 1 + 2 + 2 + partitionId.getBytes().length + 4 + uuid.length() + extraChars.length(); idBuf = ByteBuffer.allocate(idLength); idBuf.putShort(version); idBuf.put((byte) 0); idBuf.put(datacenterId); idBuf.putShort(accountId); idBuf.putShort(containerId); break; case BLOB_ID_V3: case BLOB_ID_V4: case BLOB_ID_V5: case BLOB_ID_V6: idLength = 2 + 1 + 1 + 2 + 2 + partitionId.getBytes().length + 4 + uuid.length() + extraChars.length(); idBuf = ByteBuffer.allocate(idLength); idBuf.putShort(version); idBuf.put((byte) type.ordinal()); idBuf.put(datacenterId); idBuf.putShort(accountId); idBuf.putShort(containerId); break; default: idLength = 2 + partitionId.getBytes().length + 4 + uuid.length() + extraChars.length(); idBuf = ByteBuffer.allocate(idLength); idBuf.putShort(version); break; } idBuf.put(partitionId.getBytes()); switch (version) { case BLOB_ID_V6: UUID uuidObj = UUID.fromString(uuid); idBuf.putLong(uuidObj.getMostSignificantBits()); idBuf.putLong(uuidObj.getLeastSignificantBits()); break; default: idBuf.putInt(uuidLength); idBuf.put(uuid.getBytes()); } idBuf.put(extraChars.getBytes()); return Base64.encodeBase64URLSafeString(idBuf.array()); }
From source file:io.pcp.parfait.dxm.PcpMmvWriter.java
private void populateDataBuffer(ByteBuffer dataFileBuffer, Collection<PcpValueInfo> valueInfos) throws IOException { // Automatically cleanup the file if this is a mapping where we // mandate PID checking from the MMV PMDA (MMV_FLAG_PROCESS) and // we were able to stash a path name earlier if (file != null && flags.contains(MmvFlag.MMV_FLAG_PROCESS)) { file.deleteOnExit();//from www.j a v a2s.c o m } dataFileBuffer.position(0); dataFileBuffer.put(TAG); dataFileBuffer.putInt(mmvVersion.getVersion()); long generation = System.currentTimeMillis() / 1000; dataFileBuffer.putLong(generation); int gen2Offset = dataFileBuffer.position(); // Generation 2 will be filled in later, once the file's ready dataFileBuffer.putLong(0); // 2 TOC blocks, 3 if there are instances dataFileBuffer.putInt(tocCount()); dataFileBuffer.putInt(getFlagMask()); dataFileBuffer.putInt(getProcessIdentifier()); dataFileBuffer.putInt(clusterIdentifier); Collection<? extends MmvWritable> instanceDomains = getInstanceDomains(); Collection<? extends MmvWritable> instances = getInstances(); Collection<? extends MmvWritable> metrics = getMetricInfos(); Collection<? extends MmvWritable> strings = getStrings(); int tocBlockIndex = 0; if (!instanceDomains.isEmpty()) { dataFileBuffer.position(getTocOffset(tocBlockIndex++)); writeToc(dataFileBuffer, TocType.INSTANCE_DOMAINS, instanceDomains.size(), instanceDomains.iterator().next().getOffset()); } if (!instances.isEmpty()) { dataFileBuffer.position(getTocOffset(tocBlockIndex++)); writeToc(dataFileBuffer, TocType.INSTANCES, instances.size(), instances.iterator().next().getOffset()); } dataFileBuffer.position(getTocOffset(tocBlockIndex++)); int metricsFirstEntryOffset = metrics.isEmpty() ? 0 : metrics.iterator().next().getOffset(); int valuesFirstEntryOffset = valueInfos.isEmpty() ? 0 : valueInfos.iterator().next().getOffset(); writeToc(dataFileBuffer, TocType.METRICS, metrics.size(), metricsFirstEntryOffset); dataFileBuffer.position(getTocOffset(tocBlockIndex++)); writeToc(dataFileBuffer, TocType.VALUES, valueInfos.size(), valuesFirstEntryOffset); if (!getStrings().isEmpty()) { dataFileBuffer.position(getTocOffset(tocBlockIndex++)); writeToc(dataFileBuffer, TocType.STRINGS, strings.size(), strings.iterator().next().getOffset()); } for (MmvWritable instanceDomain : instanceDomains) { instanceDomain.writeToMmv(dataFileBuffer); } for (MmvWritable info : metrics) { info.writeToMmv(dataFileBuffer); } for (MmvWritable info : valueInfos) { info.writeToMmv(dataFileBuffer); } for (MmvWritable string : strings) { string.writeToMmv(dataFileBuffer); } // Once it's set up, let the agent know dataFileBuffer.position(gen2Offset); dataFileBuffer.putLong(generation); }
From source file:de.rwhq.btree.InnerNode.java
/** * @param serializedKey/* w w w .ja v a2 s .com*/ * @param pageId * @param posOfKeyForInsert */ private void insertKeyPointerPageIdAtPosition(final byte[] serializedKey, final Integer pageId, final int posOfKeyForInsert) { final KeyStruct thisKeyStruct = new KeyStruct(posOfKeyForInsert); final ByteBuffer buf = rawPage().bufferForWriting(thisKeyStruct.getOffset()); final int spaceNeededForInsert = getSizeOfPageId() + keySerializer.getSerializedLength(); System.arraycopy(buf.array(), buf.position(), buf.array(), buf.position() + spaceNeededForInsert, buf.limit() - buf.position() - spaceNeededForInsert); buf.put(serializedKey); buf.putInt(pageId); setNumberOfKeys(getNumberOfKeys() + 1); rawPage().sync(); }
From source file:edu.hawaii.soest.kilonalu.utilities.SerialChannel.java
/** * A method used to read bytes from the serial port * * @param readBuffer - the ByteBuffer used to store the bytes read * @return count - the number of bytes read as an integer */// w w w . ja v a2s. co m public int read(ByteBuffer readBuffer) throws IOException { //byte[] buffer = new byte[8192]; StringBuffer buffer = new StringBuffer(); int count = 0; String line = null; try { line = this.serialReader.readLine(); // only append the line read if it is not null, has a length // greater than zero, and isn't just a single null character. if (line != null && line.length() > 0 && !line.equals(new String(new byte[] { 0x00 }))) { buffer.append(line); buffer.append("\r\n"); //add termination bytes back into the line // filter null characters out of the string before putting the // bytes into the ByteBuffer. byte[] lineAsBytes = buffer.toString().getBytes(); for (int i = 0; i < lineAsBytes.length; i++) { if (lineAsBytes[i] != 0x00) { readBuffer.put(lineAsBytes[i]); count++; } } } else { count = 0; } } catch (BufferOverflowException bofe) { logger.info("There a problem reading from the serial port: " + bofe.getMessage()); this.serialPort.close(); throw new IOException(bofe.getMessage()); } catch (ReadOnlyBufferException robe) { logger.info("There a problem reading from the serial port: " + robe.getMessage()); this.serialPort.close(); throw new IOException(robe.getMessage()); } return count; }
From source file:org.openpilot_nonag.uavtalk.UAVTalk.java
/** * Send an object through the telemetry link. * @throws IOException// w w w . j a v a 2s. c om * @param[in] obj Object handle to send * @param[in] type Transaction type \return Success (true), Failure (false) */ private boolean transmitSingleObject(int type, long objId, long instId, UAVObject obj) throws IOException { int length = 0; assert (objMngr != null && outStream != null); // IMPORTANT : obj can be null (when type is NACK for example) // Determine data length if (type == TYPE_OBJ_REQ || type == TYPE_ACK || type == TYPE_NACK) { length = 0; } else { length = obj.getNumBytes(); } ByteBuffer bbuf = ByteBuffer.allocate(MAX_PACKET_LENGTH); bbuf.order(ByteOrder.LITTLE_ENDIAN); // Setup type and object id fields bbuf.put((byte) (SYNC_VAL & 0xff)); bbuf.put((byte) (type & 0xff)); bbuf.putShort((short) (length + HEADER_LENGTH)); bbuf.putInt((int) objId); bbuf.putShort((short) (instId & 0xffff)); // Check length if (length >= MAX_PAYLOAD_LENGTH) { ++stats.txErrors; return false; } // Copy data (if any) if (length > 0) try { if (obj.pack(bbuf) == 0) { ++stats.txErrors; return false; } } catch (Exception e) { ++stats.txErrors; // TODO Auto-generated catch block e.printStackTrace(); return false; } // Calculate checksum bbuf.put((byte) (updateCRC(0, bbuf.array(), bbuf.position()) & 0xff)); int packlen = bbuf.position(); bbuf.position(0); byte[] dst = new byte[packlen]; bbuf.get(dst, 0, packlen); outStream.write(dst); // Update stats ++stats.txObjects; stats.txBytes += bbuf.position(); stats.txObjectBytes += length; // Done return true; }
From source file:com.koda.integ.hbase.blockcache.OffHeapBlockCacheOld.java
/** * Store external with codec./* ww w. ja va 2 s . c o m*/ * Format: * 0..3 - total record size (-4) * 4..7 - size of a key in bytes (16 if use hash128) * 8 .. x - key data * x+1 ..x+1- IN_MEMORY flag ( 1- in memory, 0 - not) * x+2 ... block, serialized and compressed * * @param blockName the block name * @param buf the buf * @param inMemory the in memory * @throws IOException Signals that an I/O exception has occurred. */ private void storeExternalWithCodec(String blockName, Cacheable buf, boolean inMemory) throws IOException { // If external storage is disable - bail out if (overflowExtEnabled == false) { return; } byte[] hashed = Utils.hash128(blockName); // Check if we have already this block in external storage cache if (extStorageCache.contains(hashed)) { return; } ByteBuffer buffer = extStorageCache.getLocalBufferWithAddress().getBuffer(); deserializer.set(buf.getDeserializer()); SerDe serde = extStorageCache.getSerDe(); Codec codec = extStorageCache.getCompressionCodec(); buffer.clear(); buffer.position(4); // Save key buffer.putInt(hashed.length); buffer.put(hashed); buffer.put(inMemory ? (byte) 1 : (byte) 0); if (buf != null) { serde.writeCompressed(buffer, buf, codec); int pos = buffer.position(); buffer.putInt(0, pos - 4); } else { buffer.putInt(0, 0); } StorageHandle handle = storage.storeData(buffer); try { // WE USE byte array as a key extStorageCache.put(hashed, handle); } catch (Exception e) { throw new IOException(e); } }