List of usage examples for java.nio ByteBuffer remaining
public final int remaining()
From source file:com.offbynull.portmapper.pcp.PcpResponse.java
/** * Constructs a {@link PcpResponse} object by parsing a buffer. * @param buffer buffer containing PCP response data * @throws NullPointerException if any argument is {@code null} * @throws BufferUnderflowException if not enough data is available in {@code buffer} * @throws IllegalArgumentException if the version doesn't match the expected version (must always be {@code 2}), or if the r-flag isn't * set, or if there's an unsuccessful/unrecognized result code *//*from ww w . java 2 s . com*/ PcpResponse(ByteBuffer buffer) { Validate.notNull(buffer); if (buffer.remaining() < 4 || buffer.remaining() > 1100 || buffer.remaining() % 4 != 0) { throw new IllegalArgumentException("Bad packet size: " + buffer.remaining()); } int version = buffer.get() & 0xFF; Validate.isTrue(version == 2, "Unknown version: %d", version); int temp = buffer.get() & 0xFF; Validate.isTrue((temp & 128) == 128, "Bad R-flag: %d", temp); op = temp & 0x7F; // discard first bit, it was used for rflag buffer.get(); // skip reserved field int resultCodeNum = buffer.get() & 0xFF; PcpResultCode[] resultCodes = PcpResultCode.values(); Validate.isTrue(resultCodeNum < resultCodes.length, "Unknown result code encountered: %d", resultCodeNum); Validate.isTrue(resultCodeNum == PcpResultCode.SUCCESS.ordinal(), "Unsuccessful result code: %s [%s]", resultCodes[resultCodeNum].toString(), resultCodes[resultCodeNum].getMessage()); lifetime = buffer.getInt() & 0xFFFFFFFFL; epochTime = buffer.getInt() & 0xFFFFFFFFL; for (int i = 0; i < 12; i++) { buffer.get(); //Validate.isTrue(buffer.get() == 0, "Reserved space indicates unsuccessful response"); } options = Collections.emptyList(); }
From source file:org.apache.james.mailrepository.cassandra.CassandraMailRepositoryMailDAO.java
private Serializable fromByteBuffer(ByteBuffer byteBuffer) { try {// w w w . j ava2s . c om byte[] data = new byte[byteBuffer.remaining()]; byteBuffer.get(data); ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(data)); return (Serializable) objectInputStream.readObject(); } catch (IOException | ClassNotFoundException e) { throw new RuntimeException(e); } }
From source file:org.apache.nifi.processor.util.listen.handler.socket.StandardSocketChannelHandler.java
/** * Process the contents that have been read into the buffer. Allow sub-classes to override this behavior. * * @param socketChannel the channel the data was read from * @param socketBuffer the buffer the data was read into * @throws InterruptedException if interrupted when queuing events */// w ww . j a v a 2 s .c om protected void processBuffer(final SocketChannel socketChannel, final ByteBuffer socketBuffer) throws InterruptedException, IOException { // get total bytes in buffer final int total = socketBuffer.remaining(); final InetAddress sender = socketChannel.socket().getInetAddress(); // go through the buffer looking for the end of each message currBytes.reset(); for (int i = 0; i < total; i++) { // NOTE: For higher throughput, the looking for \n and copying into the byte stream could be improved // Pull data out of buffer and cram into byte array byte currByte = socketBuffer.get(); // check if at end of a message if (currByte == getDelimiter()) { if (currBytes.size() > 0) { final SocketChannelResponder response = new SocketChannelResponder(socketChannel); final Map<String, String> metadata = EventFactoryUtil.createMapWithSender(sender.toString()); final E event = eventFactory.create(currBytes.toByteArray(), metadata, response); events.offer(event); currBytes.reset(); // Mark this as the start of the next message socketBuffer.mark(); } } else { currBytes.write(currByte); } } }
From source file:com.esri.geoevent.solutions.adapter.geomessage.DefenseInboundAdapter.java
@Override public void receive(ByteBuffer buffer, String channelId) { try {/* w w w.j a va2 s .co m*/ int remaining = buffer.remaining(); if (remaining <= 0) return; if (bytes == null) { bytes = new byte[remaining]; buffer.get(bytes); } else { byte[] temp = new byte[bytes.length + remaining]; System.arraycopy(bytes, 0, temp, 0, bytes.length); buffer.get(temp, bytes.length, remaining); bytes = temp; } try { saxParser.parse(new ByteArrayInputStream(bytes), messageParser); bytes = null; commit(); } catch (SAXException e) { LOG.error("SAXException while trying to parse the incoming xml.", e); // TODO : figure out a way to recover the lost bytes. for now, just // throwing them away. if (tryingToRecoverPartialMessages) { queue.clear(); } else { bytes = null; commit(); } } } catch (IOException e) { LOG.error("IOException while trying to route data from the byte buffer to the pipe.", e); } }
From source file:gridool.communication.transport.tcp.GridNonBlockingClient.java
public void sendMessage(SocketAddress sockAddr, GridCommunicationMessage msg) throws GridException { final SocketChannel channel; try {// w ww . java 2 s . c o m channel = SocketChannel.open(); channel.configureBlocking(false); } catch (IOException e) { LOG.error(PrintUtils.prettyPrintStackTrace(e, -1)); throw new GridException(e); } final Socket socket = channel.socket(); try { socket.connect(sockAddr); // wait for connect succeeds while (!channel.finishConnect()) { try { Thread.sleep(1000L); } catch (InterruptedException e) { ; } } } catch (IOException e) { IOUtils.closeQuietly(channel); NetUtils.closeQuietly(socket); LOG.error(PrintUtils.prettyPrintStackTrace(e, -1)); throw new GridException(e); } final ByteBuffer buf = toBuffer(msg); if (LOG.isDebugEnabled()) { LOG.debug("Sending a GridCommunicationMessage [" + msg.getMessageId() + " (" + buf.remaining() + " bytes)] to a node [" + sockAddr + "] using a channel [" + channel + ']'); } final int written; try { written = NIOUtils.countingWriteFully(channel, buf); NetUtils.shutdownOutputQuietly(socket); // terminate socket output (send FIN) } catch (IOException ioe) { final String errmsg = "Failed to send a GridCommunicationMessage [" + msg + "] to host [" + sockAddr + ']'; LOG.error(errmsg, ioe); throw new GridException(errmsg, ioe); } catch (Throwable e) { LOG.fatal(e.getMessage(), e); throw new GridException("Unexpected exception was caused", e); } finally { NetUtils.closeQuietly(socket); } if (LOG.isDebugEnabled()) { LOG.debug("Succeeded to send a GridCommunicationMessage (" + written + " bytes) to host [" + sockAddr + "]"); } }
From source file:com.buaa.cfs.common.oncrpc.XDR.java
@VisibleForTesting public byte[] getBytes() { ByteBuffer d = asReadOnlyWrap().buffer(); byte[] b = new byte[d.remaining()]; d.get(b);/*from w w w . j av a 2 s . c o m*/ return b; }
From source file:com.linkedin.databus.core.DbusEventPart.java
@Override public String toString() { StringBuilder sb = new StringBuilder(64); sb.append("Length=").append(getDataLength()).append(";SchemaVersion=").append(getSchemaVersion()) .append(";SchemaId=").append("0x").append(Hex.encodeHexString(getSchemaDigest())); ByteBuffer dataBB = getData(); if (dataBB.remaining() > MAX_DATA_BYTES_PRINTED) { dataBB.limit(MAX_DATA_BYTES_PRINTED); }/*from ww w .j ava2 s . com*/ byte[] data = new byte[dataBB.remaining()]; dataBB.get(data); sb.append(";Value=").append("0x").append(Hex.encodeHexString(data)); return sb.toString(); }
From source file:org.apache.hadoop.util.Crc32PerformanceTest.java
private ByteBuffer computeCrc(ByteBuffer dataBufs, int bytePerCrc) { final int size = 4 * (dataBufs.remaining() - 1) / bytePerCrc + 1; final ByteBuffer crcBufs = allocateByteBuffer(size); final DataChecksum checksum = DataChecksum.newDataChecksum(DataChecksum.Type.CRC32, bytePerCrc); checksum.calculateChunkedSums(dataBufs, crcBufs); return crcBufs; }
From source file:com.github.srgg.yads.impl.context.communication.AbstractTransport.java
private ByteBuffer encode(final byte msgCode, final byte[] payload) throws Exception { final int length = payload.length + 1; final ByteBuffer b = ByteBuffer.allocateDirect(length + 4 /* sizeof(length header) */).putInt(length) .put(msgCode).put(payload);/*w w w.ja va2s . c o m*/ assert b.remaining() == 0; b.flip(); return b; }
From source file:com.smartitengineering.util.simple.io.BufferedInputStream.java
@Override public int read() throws IOException { ByteBuffer buffer = getCurrentBuffer(); if (available() > 0) { return buffer.get(); }/*from w w w. jav a 2 s. c o m*/ int remaining = buffer.remaining(); if (remaining <= 0) { if (hasNextBuffer()) { currentBuffer = nextBuffer(); return read(); } else if (eofReached) { return -1; } else { remaining = initializeNewBuffer(); buffer = getCurrentBuffer(); } } byte[] readBuffer = new byte[remaining]; int read = wrappedStream.read(readBuffer); if (read > 0) { int position = buffer.position(); buffer.put(readBuffer, 0, read); buffer.position(position); get(buffer).add(read); return buffer.get(); } else { eofReached = true; return -1; } }