List of usage examples for java.nio ByteBuffer remaining
public final int remaining()
From source file:org.apache.hc.client5.http.impl.auth.CredSspScheme.java
private byte[] encodeUnicode(final CharBuffer charBuffer) { if (charBuffer == null) { return EMPTYBUFFER; }//ww w .jav a2s. c o m final ByteBuffer encoded = UNICODE_LITTLE_UNMARKED.encode(charBuffer); if (!encoded.hasRemaining()) { return EMPTYBUFFER; } final byte[] bytes = new byte[encoded.remaining()]; encoded.get(bytes); return bytes; }
From source file:org.apache.bookkeeper.bookie.BookieJournalTest.java
private JournalChannel writeV3Journal(File journalDir, int numEntries, byte[] masterKey) throws Exception { long logId = System.currentTimeMillis(); JournalChannel jc = new JournalChannel(journalDir, logId); moveToPosition(jc, JournalChannel.VERSION_HEADER_SIZE); BufferedChannel bc = jc.getBufferedChannel(); byte[] data = new byte[1024]; Arrays.fill(data, (byte) 'X'); long lastConfirmed = LedgerHandle.INVALID_ENTRY_ID; for (int i = 0; i <= numEntries; i++) { ByteBuffer packet; if (i == 0) { packet = generateMetaEntry(1, masterKey); } else {//from ww w . jav a 2 s . co m packet = ClientUtil.generatePacket(1, i, lastConfirmed, i * data.length, data).toByteBuffer(); } lastConfirmed = i; ByteBuffer lenBuff = ByteBuffer.allocate(4); lenBuff.putInt(packet.remaining()); lenBuff.flip(); bc.write(lenBuff); bc.write(packet); } bc.flush(true); updateJournalVersion(jc, JournalChannel.V3); return jc; }
From source file:org.apache.bookkeeper.bookie.BookieJournalTest.java
private JournalChannel writeV4Journal(File journalDir, int numEntries, byte[] masterKey) throws Exception { long logId = System.currentTimeMillis(); JournalChannel jc = new JournalChannel(journalDir, logId); moveToPosition(jc, JournalChannel.VERSION_HEADER_SIZE); BufferedChannel bc = jc.getBufferedChannel(); byte[] data = new byte[1024]; Arrays.fill(data, (byte) 'X'); long lastConfirmed = LedgerHandle.INVALID_ENTRY_ID; for (int i = 0; i <= numEntries; i++) { ByteBuffer packet; if (i == 0) { packet = generateMetaEntry(1, masterKey); } else {/* w ww . j ava 2s. c o m*/ packet = ClientUtil.generatePacket(1, i, lastConfirmed, i * data.length, data).toByteBuffer(); } lastConfirmed = i; ByteBuffer lenBuff = ByteBuffer.allocate(4); lenBuff.putInt(packet.remaining()); lenBuff.flip(); bc.write(lenBuff); bc.write(packet); } // write fence key ByteBuffer packet = generateFenceEntry(1); ByteBuffer lenBuf = ByteBuffer.allocate(4); lenBuf.putInt(packet.remaining()); lenBuf.flip(); bc.write(lenBuf); bc.write(packet); bc.flush(true); updateJournalVersion(jc, JournalChannel.V4); return jc; }
From source file:de.rwhq.btree.InnerNode.java
/** * @param rawKeys// w ww . j av a 2s .com * @param pageIds * @param fromId * @return */ public int bulkInitialize(final ArrayList<byte[]> rawKeys, final ArrayList<Integer> pageIds, final int fromId) { if (pageIds.size() < (fromId + 2) || rawKeys.size() != (pageIds.size() - 1)) throw new IllegalArgumentException( "for bulkinsert, you must have at least 2 page ids and keys.size() == (pageIds.size() - 1)\n" + "pageIds.size()=" + pageIds.size() + ";fromId=" + fromId + ";rawKeys.size()=" + rawKeys.size()); final int fromId2 = fromId; initialize(); final ByteBuffer buf = rawPage().bufferForWriting(Header.size()); buf.putInt(pageIds.get(fromId2)); final int requiredSpace = Integer.SIZE / 8 + rawKeys.get(0).length; final int spaceForEntries = buf.remaining() / requiredSpace; final int totalEntriesToInsert = (pageIds.size() - fromId - 1); int entriesToInsert = spaceForEntries < totalEntriesToInsert ? spaceForEntries : totalEntriesToInsert; // make sure that not exactly one pageId remains, because that can't be inserted alone in the next // InnerNode. == 2 because final int remaining = pageIds.size() - fromId - (entriesToInsert + 1); if (remaining == 1) entriesToInsert--; for (int i = 0; i < entriesToInsert; i++) { // System.out.println("fetching rawKey " + (fromId + i) + " from array length " + rawKeys.size() + " with i=" + i); buf.put(rawKeys.get(fromId + i)); // fromId + 1 - 1 +i //LOG.debug("insert key: " + keySerializer.deserialize(rawKeys.get(fromId + i))); buf.putInt(pageIds.get(fromId + 1 + i)); } setNumberOfKeys(entriesToInsert); rawPage.sync(); return entriesToInsert + 1; // page ids }
From source file:com.github.ambry.utils.UtilsTest.java
@Test public void testSerializeString() { String randomString = getRandomString(10); ByteBuffer outputBuffer = ByteBuffer.allocate(4 + randomString.getBytes().length); Utils.serializeString(outputBuffer, randomString, StandardCharsets.US_ASCII); outputBuffer.flip();/*from w w w . j a v a 2s .com*/ int length = outputBuffer.getInt(); assertEquals("Input and output string lengths don't match", randomString.getBytes().length, length); byte[] output = new byte[length]; outputBuffer.get(output); assertFalse("Output buffer shouldn't have any remaining, but has " + outputBuffer.remaining() + " bytes", outputBuffer.hasRemaining()); String outputString = new String(output); assertEquals("Input and output strings don't match", randomString, outputString); randomString = getRandomString(10) + ""; outputBuffer = ByteBuffer.allocate(4 + randomString.getBytes().length); Utils.serializeString(outputBuffer, randomString, StandardCharsets.US_ASCII); outputBuffer.flip(); length = outputBuffer.getInt(); assertEquals("Input and output string lengths don't match ", (randomString.getBytes().length - 1), length); output = new byte[length]; outputBuffer.get(output); assertFalse("Output buffer shouldn't have any remaining, but has " + outputBuffer.remaining() + " bytes", outputBuffer.hasRemaining()); outputString = new String(output); randomString = randomString.substring(0, randomString.length() - 1) + "?"; assertEquals("Input and output strings don't match", randomString, outputString); randomString = ""; outputBuffer = ByteBuffer.allocate(4); Utils.serializeString(outputBuffer, randomString, StandardCharsets.US_ASCII); outputBuffer.flip(); length = outputBuffer.getInt(); assertEquals("Input and output string lengths don't match", 0, length); output = new byte[length]; outputBuffer.get(output); assertFalse("Output buffer shouldn't have any remaining, but has " + outputBuffer.remaining() + " bytes", outputBuffer.hasRemaining()); outputString = new String(output); assertEquals("Output string \"" + outputString + "\" expected to be empty", outputString, ""); randomString = getRandomString(10); outputBuffer = ByteBuffer.allocate(4 + randomString.getBytes().length - 1); try { Utils.serializeString(outputBuffer, randomString, StandardCharsets.US_ASCII); Assert.fail("Serialization should have failed due to insufficient space"); } catch (RuntimeException e) { } }
From source file:org.apache.bookkeeper.bookie.BookieJournalTest.java
private JournalChannel writeV5Journal(File journalDir, int numEntries, byte[] masterKey) throws Exception { long logId = System.currentTimeMillis(); JournalChannel jc = new JournalChannel(journalDir, logId); BufferedChannel bc = jc.getBufferedChannel(); ByteBuffer paddingBuff = ByteBuffer.allocateDirect(2 * JournalChannel.SECTOR_SIZE); ZeroBuffer.put(paddingBuff);// w w w .j a v a 2 s . co m byte[] data = new byte[4 * 1024 * 1024]; Arrays.fill(data, (byte) 'X'); long lastConfirmed = LedgerHandle.INVALID_ENTRY_ID; long length = 0; for (int i = 0; i <= numEntries; i++) { ByteBuffer packet; if (i == 0) { packet = generateMetaEntry(1, masterKey); } else { packet = ClientUtil.generatePacket(1, i, lastConfirmed, length, data, 0, i).toByteBuffer(); } lastConfirmed = i; length += i; ByteBuffer lenBuff = ByteBuffer.allocate(4); lenBuff.putInt(packet.remaining()); lenBuff.flip(); bc.write(lenBuff); bc.write(packet); Journal.writePaddingBytes(jc, paddingBuff, JournalChannel.SECTOR_SIZE); } // write fence key ByteBuffer packet = generateFenceEntry(1); ByteBuffer lenBuf = ByteBuffer.allocate(4); lenBuf.putInt(packet.remaining()); lenBuf.flip(); bc.write(lenBuf); bc.write(packet); Journal.writePaddingBytes(jc, paddingBuff, JournalChannel.SECTOR_SIZE); bc.flush(true); updateJournalVersion(jc, JournalChannel.V5); return jc; }
From source file:Proxy.java
/** * Read all data from <code>from</code> and write it to <code>to</code>. * Returns false if channel was closed/*from w w w.ja v a2s.com*/ */ boolean relay(SocketChannel from, SocketChannel to, ByteBuffer buf) throws Exception { int num; StringBuilder sb; buf.clear(); while (true) { num = from.read(buf); if (num < 0) return false; else if (num == 0) return true; buf.flip(); if (verbose) { log(printRelayedData(toString(from), toString(to), buf.remaining())); } if (debug) { sb = new StringBuilder(); sb.append(new String(buf.array()).trim()); sb.append('\n'); log(sb.toString()); } to.write(buf); buf.flip(); } }
From source file:com.vest.album.fragment.CameraBasicFragment.java
private void sureSave() { ByteBuffer buffer = image.getPlanes()[0].getBuffer(); byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes);/*from w ww. j a v a2s . com*/ FileOutputStream output = null; try { output = new FileOutputStream(mFilePath); output.write(bytes); callback.onPhotoSuccess(mFilePath); } catch (IOException e) { e.printStackTrace(); callback.onPhotoError("??"); } finally { image.close(); if (null != output) { try { output.close(); } catch (IOException e) { e.printStackTrace(); } } } }
From source file:com.flexive.core.stream.BinaryUploadProtocol.java
/** * {@inheritDoc}//from w w w . j a va2s .com */ @Override public synchronized boolean receiveStream(ByteBuffer buffer) throws IOException { if (!buffer.hasRemaining()) { //this can only happen on remote clients if (LOG.isDebugEnabled()) LOG.debug("aborting (empty)"); return false; } if (!rcvStarted) { rcvStarted = true; if (LOG.isDebugEnabled()) LOG.debug("(internal serverside) receive start"); try { pout = getContentStorage().receiveTransitBinary(division, handle, mimeType, expectedLength, timeToLive); } catch (SQLException e) { LOG.error("SQL Error trying to receive binary stream: " + e.getMessage(), e); } catch (FxNotFoundException e) { LOG.error("Failed to lookup content storage for division #" + division + ": " + e.getLocalizedMessage()); } } if (LOG.isDebugEnabled() && count + buffer.remaining() > expectedLength) { LOG.debug("poss. overflow: pos=" + buffer.position() + " lim=" + buffer.limit() + " cap=" + buffer.capacity()); LOG.debug("Curr count: " + count + " count+rem=" + (count + buffer.remaining() + " delta:" + ((count + buffer.remaining()) - expectedLength))); } count += buffer.remaining(); pout.write(buffer.array(), buffer.position(), buffer.remaining()); buffer.clear(); if (expectedLength > 0 && count >= expectedLength) { if (LOG.isDebugEnabled()) LOG.debug("aborting"); return false; } return true; }
From source file:com.obviousengine.android.focus.ZslFocusCamera.java
/** * Given an image reader, extracts the JPEG image bytes and then closes the * reader.//from w w w.j av a 2 s . co m * * @param img the image from which to extract jpeg bytes or compress to * jpeg. * @return The bytes of the JPEG image. Newly allocated. */ private byte[] acquireJpegBytes(Image img) { ByteBuffer buffer; if (img.getFormat() == ImageFormat.JPEG) { Image.Plane plane0 = img.getPlanes()[0]; buffer = plane0.getBuffer(); byte[] imageBytes = new byte[buffer.remaining()]; buffer.get(imageBytes); buffer.rewind(); return imageBytes; } else { throw new RuntimeException("Unsupported image format."); } }