List of usage examples for java.nio ByteBuffer asReadOnlyBuffer
public abstract ByteBuffer asReadOnlyBuffer();
From source file:Main.java
public static void main(String[] argv) throws Exception { ByteBuffer bbuf = ByteBuffer.allocate(10); int capacity = bbuf.capacity(); // 10 System.out.println(capacity); bbuf.putShort(2, (short) 123); ByteBuffer buf = bbuf.asReadOnlyBuffer(); System.out.println(buf.hashCode()); }
From source file:Main.java
/** * <p>//from w ww .j av a 2 s . c o m * Creates a new, read-only byte buffer that shares this buffer's content. * </p> * <p> * The content of the new buffer will be that of this buffer. Changes to this * buffer's content will be visible in the new buffer; the new buffer itself, * however, will be read-only and will not allow the shared content to be * modified. The two buffers' position, limit, and mark values will be * independent. Its byte order will be preserved. * </p> * <p> * The new buffer's capacity, limit, position, and mark values will be * identical to those of this buffer. * </p> * <p> * If this buffer is itself read-only then this method behaves in exactly the * same way as the duplicate method. * </p> * * @param buffer * source buffer * @return new buffer */ public static ByteBuffer asReadonly(ByteBuffer buffer) { final ByteOrder o = buffer.order(); final ByteBuffer r = buffer.asReadOnlyBuffer(); r.order(o); return r; }
From source file:Main.java
public static ByteBuffer cloneByteBuffer(final ByteBuffer original) { // Create clone with same capacity as original. final ByteBuffer clone = (original.isDirect()) ? ByteBuffer.allocateDirect(original.capacity()) : ByteBuffer.allocate(original.capacity()); // Create a read-only copy of the original. // This allows reading from the original without modifying it. final ByteBuffer readOnlyCopy = original.asReadOnlyBuffer(); // Flip and read from the original. readOnlyCopy.flip();/*w w w. ja va 2 s . c o m*/ clone.put(readOnlyCopy); clone.position(original.position()); clone.limit(original.limit()); clone.order(original.order()); return clone; }
From source file:com.offbynull.portmapper.natpmp.NatPmpDiscovery.java
private static Set<InetAddress> discoverGateways() throws InterruptedException, IOException { final Set<InetAddress> foundGateways = Collections.synchronizedSet(new HashSet<InetAddress>()); Set<InetAddress> potentialGateways = NetworkUtils.getPotentialGatewayAddresses(); // port 5351 DatagramChannel unicastChannel = null; try {//ww w. j av a 2 s.c o m unicastChannel = DatagramChannel.open(); unicastChannel.configureBlocking(false); unicastChannel.socket().bind(new InetSocketAddress(0)); } catch (IOException ioe) { IOUtils.closeQuietly(unicastChannel); throw ioe; } UdpCommunicator communicator = null; try { communicator = new UdpCommunicator(Collections.singletonList(unicastChannel)); communicator.startAsync().awaitRunning(); communicator.addListener(new UdpCommunicatorListener() { @Override public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel, ByteBuffer packet) { new ExternalAddressNatPmpResponse(packet); // should error out if not valid foundGateways.add(sourceAddress.getAddress()); } }); ByteBuffer outBuf = ByteBuffer.allocate(16); ExternalAddressNatPmpRequest eanpr = new ExternalAddressNatPmpRequest(); eanpr.dump(outBuf); outBuf.flip(); for (InetAddress potentialGateway : potentialGateways) { communicator.send(unicastChannel, new InetSocketAddress(potentialGateway, 5351), outBuf.asReadOnlyBuffer()); } Thread.sleep(5000L); } finally { if (communicator != null) { communicator.stopAsync().awaitTerminated(); } } return new HashSet<>(foundGateways); }
From source file:com.offbynull.portmapper.natpmp.NatPmpDiscovery.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 ww. ja va2s. c om*/ 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) { new ExternalAddressNatPmpResponse(packet); // should error out if not valid InetAddress localAddress = bindMap.get(channel); if (localAddress == null) { return; } localAddrToGatewayAddrMap.put(localAddress, sourceAddress.getAddress()); } }); ByteBuffer outBuf = ByteBuffer.allocate(16); ExternalAddressNatPmpRequest eanpr = new ExternalAddressNatPmpRequest(); eanpr.dump(outBuf); outBuf.flip(); for (DatagramChannel channel : bindMap.keySet()) { for (InetAddress gateway : gateways) { 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.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 {/*w w w.j a va2s. c om*/ 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.offbynull.portmapper.upnpigd.UpnpIgdDiscovery.java
private static Set<UpnpIgdDevice> scanForDevices(InetSocketAddress multicastSocketAddress, Set<InetAddress> localAddresses, String searchQuery) throws IOException, InterruptedException { final Set<UpnpIgdDevice> ret = Collections.synchronizedSet(new HashSet<UpnpIgdDevice>()); final Map<Channel, InetAddress> bindMap = Collections.synchronizedMap(new HashMap<Channel, InetAddress>()); UdpCommunicatorListener listener = new UdpCommunicatorListener() { @Override/*from ww w . jav a 2 s .c o m*/ public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel, ByteBuffer packet) { byte[] inPacket = ByteBufferUtils.copyContentsToArray(packet); String inStr; try { inStr = new String(inPacket, 0, inPacket.length, "US-ASCII"); } catch (UnsupportedEncodingException uee) { return; } Matcher matcher; URI url; if ((matcher = LOCATION_PATTERN.matcher(inStr)).find()) { String urlStr = matcher.group(1); try { url = new URI(urlStr); } catch (URISyntaxException urise) { return; } } else { return; } String name = null; if ((matcher = SERVER_PATTERN.matcher(inStr)).find()) { name = matcher.group(1); } InetAddress localAddress = bindMap.get(channel); UpnpIgdDevice device = new UpnpIgdDevice(localAddress, sourceAddress.getAddress(), name, url); ret.add(device); } }; UdpCommunicator comm = null; try { List<DatagramChannel> channels = new ArrayList<>(); for (InetAddress localAddr : localAddresses) { DatagramChannel channel = DatagramChannel.open(); channel.configureBlocking(false); channel.bind(new InetSocketAddress(localAddr, 0)); channels.add(channel); bindMap.put(channel, localAddr); } comm = new UdpCommunicator(channels); comm.startAsync().awaitRunning(); comm.addListener(listener); ByteBuffer searchQueryBuffer = ByteBuffer.wrap(searchQuery.getBytes("US-ASCII")).asReadOnlyBuffer(); for (int i = 0; i < 3; i++) { for (DatagramChannel channel : channels) { comm.send(channel, multicastSocketAddress, searchQueryBuffer.asReadOnlyBuffer()); } Thread.sleep(TimeUnit.SECONDS.toMillis(MAX_WAIT + 1)); } return new HashSet<>(ret); } finally { if (comm != null) { try { comm.stopAsync().awaitTerminated(); // this stop should handle closing all the datagram channels } catch (IllegalStateException ise) { // NOPMD // do nothing } } } }
From source file:com.linkedin.databus.core.DbusEventPart.java
/** * Decodes a bytebuffer and returns DbusEventPart. Preserves the ByteBuffer position. * @param buf//from ww w .j av a 2 s. co m * @return */ public static DbusEventPart decode(ByteBuffer buf) { int pos = buf.position(); int dataLen = buf.getInt(pos); if (dataLen < 0) { throw new UnsupportedOperationException("Data length " + dataLen + " not supported"); } short attributes = buf.getShort(pos + AttributesOffset); short schemaVersion = (short) (attributes >> VERSION_SHIFT); SchemaDigestType schemaDigestType = digestType(attributes); int digestLen = digestLen(schemaDigestType); byte[] digest = new byte[digestLen]; for (int i = 0; i < digestLen; i++) { digest[i] = buf.get(pos + AttributesOffset + AttributesLen + i); } // NOTE - this will create a new ByteBuffer object pointing to the // same memory. So the position of this new BB is beginning of the data // and limit is set to the end of the data. ByteBuffer dataBuf = buf.asReadOnlyBuffer(); dataBuf.position(pos + AttributesOffset + AttributesLen + digestLen); dataBuf.limit(dataBuf.position() + dataLen); return new DbusEventPart(schemaDigestType, digest, schemaVersion, dataBuf); }
From source file:org.onosproject.drivers.barefoot.TofinoPipelineProgrammable.java
@Override public ByteBuffer createDeviceDataBuffer(PiPipeconf pipeconf) { List<ByteBuffer> buffers = Lists.newLinkedList(); try {// www. ja v a 2 s .c o m buffers.add(nameBuffer(pipeconf)); buffers.add(extensionBuffer(pipeconf, TOFINO_BIN)); buffers.add(extensionBuffer(pipeconf, TOFINO_CONTEXT_JSON)); } catch (ExtensionException e) { return null; } // Concatenate buffers (flip so they can be read). int len = buffers.stream().mapToInt(Buffer::limit).sum(); ByteBuffer deviceData = ByteBuffer.allocate(len); buffers.forEach(b -> deviceData.put((ByteBuffer) b.flip())); deviceData.flip(); return deviceData.asReadOnlyBuffer(); }
From source file:org.apache.nifi.minifi.bootstrap.configuration.ingestors.FileChangeIngestor.java
@Override public void run() { logger.debug("Checking for a change"); if (targetChanged()) { logger.debug("Target changed, checking if it's different than current flow."); try (FileInputStream configFile = new FileInputStream(configFilePath.toFile()); ByteArrayOutputStream pipedOutputStream = new ByteArrayOutputStream(); TeeInputStream teeInputStream = new TeeInputStream(configFile, pipedOutputStream)) { if (differentiator.isNew(teeInputStream)) { logger.debug("New change, notifying listener"); // Fill the byteArrayOutputStream with the rest of the request data while (teeInputStream.available() != 0) { teeInputStream.read(); }/*from ww w . j av a 2 s .c o m*/ ByteBuffer newConfig = ByteBuffer.wrap(pipedOutputStream.toByteArray()); ByteBuffer readOnlyNewConfig = newConfig.asReadOnlyBuffer(); configurationChangeNotifier.notifyListeners(readOnlyNewConfig); logger.debug("Listeners notified"); } } catch (Exception e) { logger.error("Could not successfully notify listeners.", e); } } }