List of usage examples for java.nio ByteBuffer remaining
public final int remaining()
From source file:org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.MappableBlock.java
/** * Reads bytes into a buffer until EOF or the buffer's limit is reached *//*ww w. j av a 2 s . com*/ private static int fillBuffer(FileChannel channel, ByteBuffer buf) throws IOException { int bytesRead = channel.read(buf); if (bytesRead < 0) { //EOF return bytesRead; } while (buf.remaining() > 0) { int n = channel.read(buf); if (n < 0) { //EOF return bytesRead; } bytesRead += n; } return bytesRead; }
From source file:com.openteach.diamond.network.waverider.slave.SlaveState.java
public static SlaveState fromByteBuffer(ByteBuffer buffer) { ByteArrayInputStream bin = null; ObjectInputStream oin = null; try {//from w ww . j av a 2s . c o m bin = new ByteArrayInputStream(buffer.array(), Packet.getHeaderSize() + Command.getHeaderSize(), buffer.remaining()); oin = new ObjectInputStream(bin); return (SlaveState) oin.readObject(); } catch (IOException e) { logger.error(e); throw new RuntimeException(e); } catch (ClassNotFoundException e) { logger.error(e); throw new RuntimeException(e); } finally { if (oin != null) { try { oin.close(); } catch (IOException e) { logger.error(e); } } } }
From source file:com.healthmarketscience.jackcess.impl.office.EncryptionHeader.java
private static String readCspName(ByteBuffer buffer) { // unicode string, must be multiple of 2 int rem = (buffer.remaining() / 2) * 2; String cspName = ""; if (rem > 0) { ByteBuffer cspNameBuf = ByteBuffer.wrap(ByteUtil.getBytes(buffer, rem)); CharBuffer tmpCspName = UNICODE_CHARSET.decode(cspNameBuf); // should be null terminated, strip that for (int i = 0; i < tmpCspName.limit(); ++i) { if (tmpCspName.charAt(i) == '\0') { tmpCspName.limit(i);/* w w w. jav a 2 s. c o m*/ break; } } cspName = tmpCspName.toString(); } return cspName; }
From source file:com.aerohive.nms.engine.admin.task.licensemgr.license.processor2.PacketUtil.java
public static byte[] split(ByteBuffer buf, Header header) { header.setPacketType(buf.get());//from ww w . j a v a 2 s . c om header.setLength(buf.getInt()); header.setProtocolVersion(buf.get()); header.setSecretFlag(buf.get() == CommConst.Secret_Flag_Yes ? true : false); byte[] content = new byte[buf.remaining()]; buf.get(content); if (header.isSecretFlag()) { byte[] outb = decryptData(content); return outb; } else { return content; } }
From source file:com.glaf.core.util.BinaryUtils.java
/** * Returns a copy of the bytes from the given <code>ByteBuffer</code>, * ranging from the the buffer's current position to the buffer's limit; or * null if the input is null./*from w w w.ja va 2 s. c o m*/ * <p> * The internal states of the given byte buffer will be restored when this * method completes execution. * <p> * When handling <code>ByteBuffer</code> from user's input, it's typical to * call the {@link #copyBytesFrom(ByteBuffer)} instead of * {@link #copyAllBytesFrom(ByteBuffer)} so as to account for the position * of the input <code>ByteBuffer</code>. The opposite is typically true, * however, when handling <code>ByteBuffer</code> from withint the * unmarshallers of the low-level clients. */ public static byte[] copyBytesFrom(ByteBuffer bb) { if (bb == null) return null; if (bb.hasArray()) return Arrays.copyOfRange(bb.array(), bb.position(), bb.limit()); bb.mark(); try { byte[] dst = new byte[bb.remaining()]; bb.get(dst); return dst; } finally { bb.reset(); } }
From source file:io.blobkeeper.file.util.FileUtils.java
@NotNull public static SortedMap<Long, Block> readBlob(@NotNull IndexService indexService, @NotNull File blob, @NotNull Partition partition) {// w w w .jav a2s. c o m List<IndexElt> elts = new ArrayList<>(indexService.getListByPartition(partition)); // sort it by offset, to read file consequentially sort(elts, new IndexEltOffsetComparator()); List<BlockElt> blockElts = new ArrayList<>(); for (IndexElt elt : elts) { try { ByteBuffer dataBuffer = readFile(blob, elt.getOffset(), elt.getLength()); byte[] dataBufferBytes = new byte[dataBuffer.remaining()]; dataBuffer.get(dataBufferBytes); long fileCrc = FileUtils.getCrc(dataBufferBytes); if (fileCrc == elt.getCrc()) { blockElts.add( new BlockElt(elt.getId(), elt.getType(), elt.getOffset(), elt.getLength(), fileCrc)); } } catch (Exception e) { log.error("Can't read file {} from blob", elt, e); } } return blockElts.stream().collect(groupingBy(BlockElt::getId)).values().stream() .map(groupedElts -> new Block(groupedElts.get(0).getId(), groupedElts.stream().sorted(new BlockEltComparator()).collect(toImmutableList()))) .collect( // TODO: replace with ImmutableSortedMap toMap(Block::getId, Function.identity(), Utils.throwingMerger(), TreeMap::new)); }
From source file:com.openteach.diamond.network.waverider.master.MasterState.java
public static MasterState fromByteBuffer(ByteBuffer buffer) { ByteArrayInputStream bin = null; ObjectInputStream oin = null; try {/* ww w . j a v a 2s. c o m*/ bin = new ByteArrayInputStream(buffer.array(), Packet.getHeaderSize() + Command.getHeaderSize(), buffer.remaining()); oin = new ObjectInputStream(bin); return (MasterState) oin.readObject(); } catch (IOException e) { logger.error(e); throw new RuntimeException(e); } catch (ClassNotFoundException e) { logger.error(e); throw new RuntimeException(e); } finally { try { if (oin != null) { oin.close(); } if (bin != null) { bin.close(); } } catch (IOException e) { logger.error(e); } } }
From source file:com.icloud.framework.core.util.FBUtilities.java
public static int byteBufferToInt(ByteBuffer bytes) { if (bytes.remaining() < 4) { throw new IllegalArgumentException("An integer must be 4 bytes in size."); }/*from ww w . j a v a 2 s.c om*/ int n = 0; for (int i = 0; i < 4; ++i) { n <<= 8; n |= bytes.array()[bytes.position() + bytes.arrayOffset() + i] & 0xFF; } return n; }
From source file:com.offbynull.portmapper.pcp.PcpDiscovery.java
private static Map<InetAddress, InetAddress> discoverLocalAddressesToGateways(Set<InetAddress> gateways) throws IOException, InterruptedException { Set<InetAddress> localAddresses = NetworkUtils.getAllLocalIpv4Addresses(); List<DatagramChannel> channels = new ArrayList<>(); final Map<DatagramChannel, InetAddress> bindMap = Collections .synchronizedMap(new HashMap<DatagramChannel, InetAddress>()); final Map<InetAddress, InetAddress> localAddrToGatewayAddrMap = Collections .synchronizedMap(new HashMap<InetAddress, InetAddress>()); try {//from w w w . j a va2s . c o m for (InetAddress localAddress : localAddresses) { DatagramChannel unicastChannel = null; try { unicastChannel = DatagramChannel.open(); unicastChannel.configureBlocking(false); unicastChannel.socket().bind(new InetSocketAddress(localAddress, 0)); } catch (IOException ioe) { IOUtils.closeQuietly(unicastChannel); throw ioe; } channels.add(unicastChannel); bindMap.put(unicastChannel, localAddress); } } catch (IOException ioe) { for (DatagramChannel channel : channels) { IOUtils.closeQuietly(channel); } throw ioe; } UdpCommunicator communicator = null; try { communicator = new UdpCommunicator(channels); communicator.startAsync().awaitRunning(); communicator.addListener(new UdpCommunicatorListener() { @Override public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel, ByteBuffer packet) { // make sure version is 2 and error isn't ADDRESS_MISMATCH and we're good to go if (packet.remaining() < 4 || packet.get(0) == 2 && packet.get(4) == PcpResultCode.ADDRESS_MISMATCH.ordinal()) { return; } InetAddress localAddress = bindMap.get(channel); if (localAddress == null) { return; } localAddrToGatewayAddrMap.put(localAddress, sourceAddress.getAddress()); } }); for (DatagramChannel channel : bindMap.keySet()) { for (InetAddress gateway : gateways) { ByteBuffer outBuf = ByteBuffer.allocate(1100); MapPcpRequest mpr = new MapPcpRequest(ByteBuffer.allocate(12), 0, 0, 0, InetAddress.getByName("::"), 0L); mpr.dump(outBuf, bindMap.get(channel)); outBuf.flip(); communicator.send(channel, new InetSocketAddress(gateway, 5351), outBuf.asReadOnlyBuffer()); } } Thread.sleep(5000L); } finally { if (communicator != null) { communicator.stopAsync().awaitTerminated(); } } return new HashMap<>(localAddrToGatewayAddrMap); }
From source file:com.buaa.cfs.utils.IOUtils.java
/** * Write a ByteBuffer to a WritableByteChannel, handling short writes. * * @param bc The WritableByteChannel to write to * @param buf The input buffer/*from w w w . j a v a2s . c o m*/ * * @throws IOException On I/O error */ public static void writeFully(WritableByteChannel bc, ByteBuffer buf) throws IOException { do { bc.write(buf); } while (buf.remaining() > 0); }