List of usage examples for java.nio ByteBuffer hasRemaining
public final boolean hasRemaining()
From source file:io.github.dsheirer.sample.adapter.ChannelShortAdapter.java
@Override public float[] convert(byte[] samples) { float[] processed = new float[samples.length / 4]; int pointer = 0; /* Wrap byte array in a byte buffer so we can process them as shorts */ ByteBuffer buffer = ByteBuffer.wrap(samples); /* Set endian to correct byte ordering */ buffer.order(mByteOrder);// w ww . ja v a 2s . c om while (buffer.hasRemaining()) { if (mMixerChannel == MixerChannel.LEFT) { processed[pointer] = mMap.get(buffer.getShort()); /* Throw away the right channel */ buffer.getShort(); } else { /* Throw away the left channel */ buffer.getShort(); processed[pointer] = mMap.get(buffer.getShort()); } pointer++; } return processed; }
From source file:org.alfresco.repo.transfer.HttpClientTransmitterImpl.java
private static void channelCopy(final ReadableByteChannel src, final WritableByteChannel dest) throws IOException { final ByteBuffer buffer = ByteBuffer.allocateDirect(2 * 1024); while (src.read(buffer) != -1) { // prepare the buffer to be drained buffer.flip();/* ww w. ja va 2s .c om*/ // write to the channel, may block dest.write(buffer); // If partial transfer, shift remainder down // If buffer is empty, same as doing clear() buffer.compact(); } // EOF will leave buffer in fill state buffer.flip(); // make sure the buffer is fully drained. while (buffer.hasRemaining()) { dest.write(buffer); } }
From source file:com.alibaba.napoli.metamorphosis.client.consumer.storage.LocalOffsetStorage.java
@Override public void commitOffset(final String group, final Collection<TopicPartitionRegInfo> infoList) { if (infoList == null || infoList.isEmpty()) { return;//from www .j ava 2 s .com } this.groupInfoMap.put(group, (List<TopicPartitionRegInfo>) infoList); try { final String json = JSONUtils.serializeObject(this.groupInfoMap); this.channel.position(0); final ByteBuffer buf = ByteBuffer.wrap(json.getBytes()); while (buf.hasRemaining()) { this.channel.write(buf); } this.channel.truncate(this.channel.position()); } catch (final Exception e) { log.error("commitOffset failed ", e); } }
From source file:net.lightbody.bmp.proxy.jetty.http.nio.ByteBufferInputStream.java
public synchronized void write(ByteBuffer buffer) { if (buffer.hasRemaining()) { _buffers = LazyList.add(_buffers, buffer); this.notify(); } else//w w w . jav a2 s.co m recycle(buffer); }
From source file:com.byteatebit.nbserver.task.TestWriteMessageTask.java
@Test public void testWriteCompleteMessage() throws IOException { SocketChannel socket = mock(SocketChannel.class); ByteArrayOutputStream messageStream = new ByteArrayOutputStream(); String message = "hi\n"; when(socket.write(any(ByteBuffer.class))).then(new Answer<Integer>() { @Override//from www. j ava2 s . c om public Integer answer(InvocationOnMock invocationOnMock) throws Throwable { ByteBuffer buffer = (ByteBuffer) invocationOnMock.getArguments()[0]; while (buffer.hasRemaining()) messageStream.write(buffer.get()); return buffer.position(); } }); INbContext nbContext = mock(INbContext.class); SelectionKey selectionKey = mock(SelectionKey.class); when(selectionKey.channel()).thenReturn(socket); when(selectionKey.isValid()).thenReturn(true); when(selectionKey.readyOps()).thenReturn(SelectionKey.OP_WRITE); WriteMessageTask writeTask = WriteMessageTask.Builder.builder().withByteBuffer(ByteBuffer.allocate(100)) .build(); List<String> callbackInvoked = new ArrayList<>(); Runnable callback = () -> callbackInvoked.add(""); Consumer<Exception> exceptionHandler = e -> Assert.fail(e.getMessage()); writeTask.writeMessage(message.getBytes(StandardCharsets.UTF_8), nbContext, socket, callback, exceptionHandler); verify(nbContext, times(1)).register(any(SocketChannel.class), eq(SelectionKey.OP_WRITE), any(), any()); writeTask.write(selectionKey, callback, exceptionHandler); verify(selectionKey, times(1)).interestOps(0); Assert.assertEquals(message, messageStream.toString(StandardCharsets.UTF_8)); Assert.assertEquals(1, callbackInvoked.size()); }
From source file:com.flexive.core.stream.BinaryUploadProtocol.java
/** * {@inheritDoc}//www.j ava2 s. c o m */ @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:hudson.Util.java
/** * Encode a single path component for use in an HTTP URL. * Escapes all non-ASCII, general unsafe (space and "#%<>[\]^`{|}~) * and HTTP special characters (/;:?) as specified in RFC1738. * (so alphanumeric and !@$&*()-_=+',. are not encoded) * Note that slash(/) is encoded, so the given string should be a * single path component used in constructing a URL. * Method name inspired by PHP's rawurlencode. *//*from w ww.ja va 2 s . c o m*/ public static String rawEncode(String s) { boolean escaped = false; StringBuilder out = null; CharsetEncoder enc = null; CharBuffer buf = null; char c; for (int i = 0, m = s.length(); i < m; i++) { c = s.charAt(i); if (c > 122 || uriMap[c]) { if (!escaped) { out = new StringBuilder(i + (m - i) * 3); out.append(s.substring(0, i)); enc = Charset.forName("UTF-8").newEncoder(); buf = CharBuffer.allocate(1); escaped = true; } // 1 char -> UTF8 buf.put(0, c); buf.rewind(); try { ByteBuffer bytes = enc.encode(buf); while (bytes.hasRemaining()) { byte b = bytes.get(); out.append('%'); out.append(toDigit((b >> 4) & 0xF)); out.append(toDigit(b & 0xF)); } } catch (CharacterCodingException ex) { } } else if (escaped) { out.append(c); } } return escaped ? out.toString() : s; }
From source file:com.act.lcms.v2.fullindex.BuilderTest.java
@Test public void testExtractTriples() throws Exception { // Verify all TMzI triples are stored correctly. Map<Long, TMzI> deserializedTriples = new HashMap<>(); assertEquals("All triples should have entries in the DB", 9, fakeDB.getFakeDB().get(ColumnFamilies.ID_TO_TRIPLE).size()); for (Map.Entry<List<Byte>, byte[]> entry : fakeDB.getFakeDB().get(ColumnFamilies.ID_TO_TRIPLE).entrySet()) { Long id = ByteBuffer.wrap(fakeDB.byteListToArray(entry.getKey())).getLong(); TMzI triple = TMzI.readNextFromByteBuffer(ByteBuffer.wrap(entry.getValue())); Float expectedTime = Double.valueOf(TIMES[id.intValue() / 3]).floatValue(); Double expectedMZ = MZS[id.intValue() / 3][id.intValue() % 3]; Float expectedIntensity = Double.valueOf(INTENSITIES[id.intValue() / 3][id.intValue() % 3]) .floatValue();/*from w ww .j av a2s . c o m*/ assertEquals("Time matches expected", expectedTime, triple.getTime(), FP_TOLERANCE); // No error expected assertEquals("M/z matches expected", expectedMZ, triple.getMz(), FP_TOLERANCE); assertEquals("Intensity matches expected", expectedIntensity, triple.getIntensity(), FP_TOLERANCE); deserializedTriples.put(id, triple); } for (Map.Entry<List<Byte>, byte[]> entry : fakeDB.getFakeDB().get(ColumnFamilies.WINDOW_ID_TO_TRIPLES) .entrySet()) { int windowId = ByteBuffer.wrap(fakeDB.byteListToArray(entry.getKey())).getInt(); MZWindow window = windowIdsToWindows.get(windowId); List<Long> tmziIds = new ArrayList<>(entry.getValue().length / Long.BYTES); ByteBuffer valBuffer = ByteBuffer.wrap(entry.getValue()); while (valBuffer.hasRemaining()) { tmziIds.add(valBuffer.getLong()); } for (Long tripleId : tmziIds) { TMzI triple = deserializedTriples.get(tripleId); assertTrue("Triple m/z falls within range of containing window", triple.getMz() >= window.getMin() && triple.getMz() <= window.getMax()); } } for (Map.Entry<List<Byte>, byte[]> entry : fakeDB.getFakeDB().get(ColumnFamilies.TIMEPOINT_TO_TRIPLES) .entrySet()) { float time = ByteBuffer.wrap(fakeDB.byteListToArray(entry.getKey())).getFloat(); List<Long> tmziIds = new ArrayList<>(entry.getValue().length / Long.BYTES); ByteBuffer valBuffer = ByteBuffer.wrap(entry.getValue()); while (valBuffer.hasRemaining()) { tmziIds.add(valBuffer.getLong()); } for (Long tripleId : tmziIds) { TMzI triple = deserializedTriples.get(tripleId); assertEquals("Triple time matches key time", time, triple.getTime(), FP_TOLERANCE); } } }
From source file:org.gephi.desktop.importer.DesktopImportControllerUI.java
/** * Uncompress a GZIP file./*from ww w . j a v a2 s .c o m*/ */ private static File getGzFile(FileObject in, File out, boolean isTar) throws IOException { // Stream buffer final int BUFF_SIZE = 8192; final byte[] buffer = new byte[BUFF_SIZE]; GZIPInputStream inputStream = null; FileOutputStream outStream = null; try { inputStream = new GZIPInputStream(new FileInputStream(in.getPath())); outStream = new FileOutputStream(out); if (isTar) { // Read Tar header int remainingBytes = readTarHeader(inputStream); // Read content ByteBuffer bb = ByteBuffer.allocateDirect(4 * BUFF_SIZE); byte[] tmpCache = new byte[BUFF_SIZE]; int nRead, nGet; while ((nRead = inputStream.read(tmpCache)) != -1) { if (nRead == 0) { continue; } bb.put(tmpCache); bb.position(0); bb.limit(nRead); while (bb.hasRemaining() && remainingBytes > 0) { nGet = Math.min(bb.remaining(), BUFF_SIZE); nGet = Math.min(nGet, remainingBytes); bb.get(buffer, 0, nGet); outStream.write(buffer, 0, nGet); remainingBytes -= nGet; } bb.clear(); } } else { int len; while ((len = inputStream.read(buffer)) > 0) { outStream.write(buffer, 0, len); } } } catch (IOException ex) { Exceptions.printStackTrace(ex); } finally { if (inputStream != null) { inputStream.close(); } if (outStream != null) { outStream.close(); } } return out; }
From source file:org.gephi.desktop.importer.DesktopImportControllerUI.java
/** * Uncompress a Bzip2 file./*from ww w . j a v a 2 s .c o m*/ */ private static File getBzipFile(FileObject in, File out, boolean isTar) throws IOException { // Stream buffer final int BUFF_SIZE = 8192; final byte[] buffer = new byte[BUFF_SIZE]; BZip2CompressorInputStream inputStream = null; FileOutputStream outStream = null; try { FileInputStream is = new FileInputStream(in.getPath()); inputStream = new BZip2CompressorInputStream(is); outStream = new FileOutputStream(out.getAbsolutePath()); if (isTar) { // Read Tar header int remainingBytes = readTarHeader(inputStream); // Read content ByteBuffer bb = ByteBuffer.allocateDirect(4 * BUFF_SIZE); byte[] tmpCache = new byte[BUFF_SIZE]; int nRead, nGet; while ((nRead = inputStream.read(tmpCache)) != -1) { if (nRead == 0) { continue; } bb.put(tmpCache); bb.position(0); bb.limit(nRead); while (bb.hasRemaining() && remainingBytes > 0) { nGet = Math.min(bb.remaining(), BUFF_SIZE); nGet = Math.min(nGet, remainingBytes); bb.get(buffer, 0, nGet); outStream.write(buffer, 0, nGet); remainingBytes -= nGet; } bb.clear(); } } else { int len; while ((len = inputStream.read(buffer)) > 0) { outStream.write(buffer, 0, len); } } } catch (IOException ex) { Exceptions.printStackTrace(ex); } finally { if (inputStream != null) { inputStream.close(); } if (outStream != null) { outStream.close(); } } return out; }