Example usage for java.nio ByteBuffer asReadOnlyBuffer

List of usage examples for java.nio ByteBuffer asReadOnlyBuffer

Introduction

In this page you can find the example usage for java.nio ByteBuffer asReadOnlyBuffer.

Prototype

public abstract ByteBuffer asReadOnlyBuffer();

Source Link

Document

Returns a read-only buffer that shares its content with this buffer.

Usage

From source file:com.offbynull.portmapper.pcp.PcpDiscovery.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 {/*from   ww  w  .ja  v a2  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) {
                foundGateways.add(sourceAddress.getAddress());
            }
        });

        ByteBuffer outBuf = ByteBuffer.allocate(1100);
        MapPcpRequest mpr = new MapPcpRequest(ByteBuffer.allocate(12), 0, 0, 0, InetAddress.getByName("::"),
                0L);
        mpr.dump(outBuf, InetAddress.getByAddress(new byte[4])); // should get back an error for this, but this
                                                                 // should be fine because all we're looking for is a response, not
                                                                 // nessecarily a correct response -- self address being sent is
                                                                 // 0.0.0.0 (IPV4)
                                                                 //
                                                                 // also, we need to pass in MAP because Apple's garbage routers
                                                                 // give back NATPMP responses when you pass in ANNOUNCE

        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();
        }
    }

    foundGateways.retainAll(potentialGateways); // just incase we get back some unsolicited responses
    return new HashSet<>(foundGateways);
}

From source file:net.sf.cindy.impl.AbstractSession.java

/**
 * Recognize message from ByteBuffer.//from w  ww. java2s. c om
 * 
 * @param buffer
 *            The ByteBuffer contains data
 * @return Recognized message.
 */
protected Message recognizeMessage(ByteBuffer buffer) {
    try {
        if (log.isTraceEnabled())
            log.trace("session " + sessionId + " recognize message");

        Message message = messageRecognizer.recognize(this, buffer.asReadOnlyBuffer());
        if (message != null) {
            boolean completed = message.readFromBuffer(buffer);
            if (log.isTraceEnabled())
                log.trace("session " + sessionId + " recognized message " + message.getClass().getName()
                        + (completed ? " " : " not ") + "completed");
            if (completed)
                return message;
        }
    } catch (Exception e) { //Protection catch
        dispatchException(e);
    }
    return null;
}

From source file:io.druid.hll.HyperLogLogCollectorTest.java

private ByteBuffer makeCollectorBuffer(int offset, byte[] initialBytes, int remainingBytes) {
    short numNonZero = 0;
    for (byte initialByte : initialBytes) {
        numNonZero += computeNumNonZero(initialByte);
    }//from   ww w .j  ava 2 s. c  o m

    final short numNonZeroInRemaining = computeNumNonZero((byte) remainingBytes);
    numNonZero += (short) ((HyperLogLogCollector.NUM_BYTES_FOR_BUCKETS - initialBytes.length)
            * numNonZeroInRemaining);

    ByteBuffer biggerOffset = ByteBuffer.allocate(HyperLogLogCollector.getLatestNumBytesForDenseStorage());
    biggerOffset.put(HLLCV1.VERSION);
    biggerOffset.put((byte) offset);
    biggerOffset.putShort(numNonZero);
    biggerOffset.put((byte) 0);
    biggerOffset.putShort((short) 0);
    biggerOffset.put(initialBytes);
    while (biggerOffset.hasRemaining()) {
        biggerOffset.put((byte) remainingBytes);
    }
    biggerOffset.clear();
    return biggerOffset.asReadOnlyBuffer();
}

From source file:org.apache.druid.hll.HyperLogLogCollectorTest.java

private ByteBuffer makeCollectorBuffer(int offset, byte[] initialBytes, int remainingBytes) {
    short numNonZero = 0;
    for (byte initialByte : initialBytes) {
        numNonZero += computeNumNonZero(initialByte);
    }//from w w w.  ja v  a 2 s .  c  o  m

    final short numNonZeroInRemaining = computeNumNonZero((byte) remainingBytes);
    numNonZero += (short) ((HyperLogLogCollector.NUM_BYTES_FOR_BUCKETS - initialBytes.length)
            * numNonZeroInRemaining);

    ByteBuffer biggerOffset = ByteBuffer.allocate(HyperLogLogCollector.getLatestNumBytesForDenseStorage());
    biggerOffset.put(VersionOneHyperLogLogCollector.VERSION);
    biggerOffset.put((byte) offset);
    biggerOffset.putShort(numNonZero);
    biggerOffset.put((byte) 0);
    biggerOffset.putShort((short) 0);
    biggerOffset.put(initialBytes);
    while (biggerOffset.hasRemaining()) {
        biggerOffset.put((byte) remainingBytes);
    }
    biggerOffset.clear();
    return biggerOffset.asReadOnlyBuffer();
}

From source file:com.offbynull.portmapper.common.UdpCommunicator.java

@Override
protected void run() throws Exception {
    ByteBuffer recvBuffer = ByteBuffer.allocate(1100);

    while (true) {
        selector.select();//from www .j a v  a2s  .com
        if (stopFlag) {
            return;
        }

        for (DatagramChannel channel : sendQueue.keySet()) {
            if (!sendQueue.get(channel).isEmpty()) {
                channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
            } else {
                channel.register(selector, SelectionKey.OP_READ);
            }
        }

        for (SelectionKey key : selector.selectedKeys()) {
            if (!key.isValid()) {
                continue;
            }

            DatagramChannel channel = (DatagramChannel) key.channel();

            if (key.isReadable()) {
                recvBuffer.clear();
                InetSocketAddress incomingAddress = (InetSocketAddress) channel.receive(recvBuffer);
                recvBuffer.flip();
                for (UdpCommunicatorListener listener : listeners) {
                    try {
                        listener.incomingPacket(incomingAddress, channel, recvBuffer.asReadOnlyBuffer());
                    } catch (RuntimeException re) { // NOPMD
                        // do nothing
                    }
                }
            } else if (key.isWritable()) {
                LinkedBlockingQueue<ImmutablePair<InetSocketAddress, ByteBuffer>> queue = sendQueue
                        .get(channel);
                ImmutablePair<InetSocketAddress, ByteBuffer> next = queue.poll();

                if (next != null) {
                    try {
                        channel.send(next.getValue(), next.getKey());
                    } catch (RuntimeException re) { // NOPMD
                        // do nothing
                    }
                }
            }
        }
    }
}

From source file:com.zhengde163.netguard.ServiceSinkhole.java

/**
 * ByteBuffer ? String//from  w ww .jav a 2  s  .  c  o m
 *
 * @param buffer
 * @return
 */
public static String getString(ByteBuffer buffer) {
    Charset charset = null;
    CharsetDecoder decoder = null;
    CharBuffer charBuffer = null;
    try {
        charset = Charset.forName("UTF-8");
        decoder = charset.newDecoder();
        // charBuffer = decoder.decode(buffer);//???
        charBuffer = decoder.decode(buffer.asReadOnlyBuffer());
        return charBuffer.toString();
    } catch (Exception ex) {
        ex.printStackTrace();
        return "";
    }
}

From source file:org.apache.nifi.minifi.bootstrap.RunMiNiFi.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public void start() throws IOException, InterruptedException {

    final String confDir = getBootstrapProperties().getProperty(CONF_DIR_KEY);
    final File configFile = new File(getBootstrapProperties().getProperty(MINIFI_CONFIG_FILE_KEY));
    try (InputStream inputStream = new FileInputStream(configFile)) {
        ByteBuffer tempConfigFile = performTransformation(inputStream, confDir);
        currentConfigFileReference.set(tempConfigFile.asReadOnlyBuffer());
    } catch (ConfigurationChangeException e) {
        defaultLogger.error("The config file is malformed, unable to start.", e);
        return;/*  w  ww .j a  va 2s . c o  m*/
    }

    // Instantiate configuration listener and configured ingestors
    this.changeListener = new MiNiFiConfigurationChangeListener(this, defaultLogger);
    this.periodicStatusReporters = initializePeriodicNotifiers();
    startPeriodicNotifiers();
    try {
        this.changeCoordinator = initializeNotifier(this.changeListener);
    } catch (Exception e) {
        final String errorMsg = "Unable to start as {} is not properly configured due to: {}";
        cmdLogger.error(errorMsg, this.changeListener.getDescriptor(), e.getMessage());
        defaultLogger.error("Unable to initialize notifier.", e);
        // if we fail to initialize, exit without attempting to start
        System.exit(1);
    }

    Tuple<ProcessBuilder, Process> tuple = startMiNiFi();
    if (tuple == null) {
        cmdLogger.info("Start method returned null, ending start command.");
        return;
    }

    ProcessBuilder builder = tuple.getKey();
    Process process = tuple.getValue();

    try {
        while (true) {
            final boolean alive = isAlive(process);

            if (alive) {
                try {
                    Thread.sleep(1000L);

                    if (reloading.get() && getNifiStarted()) {
                        final File swapConfigFile = getSwapFile(defaultLogger);
                        if (swapConfigFile.exists()) {
                            defaultLogger.info(
                                    "MiNiFi has finished reloading successfully and swap file exists. Deleting old configuration.");

                            if (swapConfigFile.delete()) {
                                defaultLogger.info("Swap file was successfully deleted.");
                            } else {
                                defaultLogger
                                        .error("Swap file was not deleted. It should be deleted manually.");
                            }
                        }

                        reloading.set(false);
                    }

                } catch (final InterruptedException ie) {
                }
            } else {
                final Runtime runtime = Runtime.getRuntime();
                try {
                    runtime.removeShutdownHook(shutdownHook);
                } catch (final IllegalStateException ise) {
                    // happens when already shutting down
                }

                if (autoRestartNiFi) {
                    final File statusFile = getStatusFile(defaultLogger);
                    if (!statusFile.exists()) {
                        defaultLogger.info("Status File no longer exists. Will not restart MiNiFi");
                        return;
                    }

                    final File lockFile = getLockFile(defaultLogger);
                    if (lockFile.exists()) {
                        defaultLogger.info("A shutdown was initiated. Will not restart MiNiFi");
                        return;
                    }

                    final File reloadFile = getReloadFile(defaultLogger);
                    if (reloadFile.exists()) {
                        defaultLogger.info("Currently reloading configuration. Will wait to restart MiNiFi.");
                        Thread.sleep(5000L);
                        continue;
                    }

                    final boolean previouslyStarted = getNifiStarted();
                    if (!previouslyStarted) {
                        final File swapConfigFile = getSwapFile(defaultLogger);
                        if (swapConfigFile.exists()) {
                            defaultLogger.info(
                                    "Swap file exists, MiNiFi failed trying to change configuration. Reverting to old configuration.");

                            try {
                                ByteBuffer tempConfigFile = performTransformation(
                                        new FileInputStream(swapConfigFile), confDir);
                                currentConfigFileReference.set(tempConfigFile.asReadOnlyBuffer());
                            } catch (ConfigurationChangeException e) {
                                defaultLogger.error(
                                        "The swap file is malformed, unable to restart from prior state. Will not attempt to restart MiNiFi. Swap File should be cleaned up manually.");
                                return;
                            }

                            Files.copy(swapConfigFile.toPath(),
                                    Paths.get(getBootstrapProperties().getProperty(MINIFI_CONFIG_FILE_KEY)),
                                    REPLACE_EXISTING);

                            defaultLogger.info("Replacing config file with swap file and deleting swap file");
                            if (!swapConfigFile.delete()) {
                                defaultLogger.warn(
                                        "The swap file failed to delete after replacing using it to revert to the old configuration. It should be cleaned up manually.");
                            }
                            reloading.set(false);
                        } else {
                            defaultLogger.info(
                                    "MiNiFi either never started or failed to restart. Will not attempt to restart MiNiFi");
                            return;
                        }
                    } else {
                        setNiFiStarted(false);
                    }

                    process = builder.start();
                    handleLogging(process);

                    Long pid = getPid(process, defaultLogger);
                    if (pid != null) {
                        minifiPid = pid;
                        final Properties minifiProps = new Properties();
                        minifiProps.setProperty(PID_KEY, String.valueOf(minifiPid));
                        saveProperties(minifiProps, defaultLogger);
                    }

                    shutdownHook = new ShutdownHook(process, this, secretKey, gracefulShutdownSeconds,
                            loggingExecutor);
                    runtime.addShutdownHook(shutdownHook);

                    final boolean started = waitForStart();

                    if (started) {
                        defaultLogger.info("Successfully spawned the thread to start Apache MiNiFi{}",
                                (pid == null ? "" : " with PID " + pid));
                    } else {
                        defaultLogger.error("Apache MiNiFi does not appear to have started");
                    }
                } else {
                    return;
                }
            }
        }
    } finally {
        shutdownChangeNotifier();
        shutdownPeriodicStatusReporters();
    }
}

From source file:co.paralleluniverse.galaxy.core.Cache.java

private static ByteBuffer readOnly(ByteBuffer buffer) {
    return buffer != null ? buffer.asReadOnlyBuffer() : null;
}