Example usage for java.nio ByteBuffer mark

List of usage examples for java.nio ByteBuffer mark

Introduction

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

Prototype

public final Buffer mark() 

Source Link

Document

Marks the current position, so that the position may return to this point later by calling reset().

Usage

From source file:org.sglover.alfrescoextensions.common.HasherImpl.java

private String getHash(ByteBuffer bytes, int start, int end, MessageDigest digest)
        throws NoSuchAlgorithmException {
    int saveLimit = bytes.limit();
    bytes.limit(end + 1);/*from w  w w .j  ava  2s .c  om*/

    bytes.mark();
    bytes.position(start);

    digest.reset();
    digest.update(bytes);
    byte[] array = digest.digest();
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < array.length; ++i) {
        sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
    }

    bytes.limit(saveLimit);
    bytes.reset();

    return sb.toString();
}

From source file:com.github.jinahya.verbose.codec.BinaryCodecTest.java

protected final void encodeDecode(final ByteBuffer expectedBuffer) {

    expectedBuffer.mark();

    final ByteBuffer encodedBuffer = encoder.encode(expectedBuffer);

    final ByteBuffer actualBuffer = decoder.decode(encodedBuffer);

    expectedBuffer.reset();//from  ww w .j av  a 2 s . com

    assertEquals(actualBuffer, expectedBuffer);
}

From source file:org.apache.hadoop.util.Crc32PerformanceTest.java

private ByteBuffer newData() {
    final byte[] bytes = new byte[dataLengthMB << 20];
    new Random().nextBytes(bytes);
    final ByteBuffer dataBufs = allocateByteBuffer(bytes.length);
    dataBufs.mark();
    dataBufs.put(bytes);/*  w w w .  ja  va  2  s.c  om*/
    dataBufs.reset();
    return dataBufs;
}

From source file:com.homeadvisor.kafdrop.service.MessageInspector.java

private byte[] readBytes(ByteBuffer buffer, int offset, int size) {
    byte[] dest = new byte[size];
    if (buffer.hasArray()) {
        System.arraycopy(buffer.array(), buffer.arrayOffset() + offset, dest, 0, size);
    } else {//from   ww  w  . j  ava 2 s  .co  m
        buffer.mark();
        buffer.get(dest);
        buffer.reset();
    }
    return dest;
}

From source file:com.github.srgg.yads.impl.context.communication.AbstractTransport.java

protected final int onReceive(final String sender, final String recipient, final ByteBuffer bb)
        throws Exception {
    // -- decode// w  w  w  .  j  a v a  2s. co  m
    if (bb.remaining() < 4) {
        return 4;
    }

    bb.mark();
    final int length = bb.getInt();

    if (bb.remaining() < length) {
        bb.reset();
        return length;
    }

    final byte msgCode = bb.get();
    final byte[] p = new byte[length - 1];
    bb.get(p);

    final Class<? extends Message> c = getMessageClass(msgCode);
    final Message msg = payloadMapper.fromBytes(c, p);

    // -- fire
    final Messages.MessageTypes mt = Messages.MessageTypes.valueOf(msgCode);
    if (logger.isTraceEnabled()) {
        logger.trace(MessageUtils.dumpMessage(msg, "[MSG IN] '%s' -> '%s': %s@%s", msg.getSender(), recipient,
                mt, msg.getId()));
    } else {
        logger.debug("[MSG IN]  '{}' -> '{}': {}@{}", sender, recipient, mt, msg.getId());
    }

    boolean isHandled = true;
    if (recipient != null) {
        final CommunicationContext.MessageListener listener = handlerById(recipient);
        checkState(listener != null,
                "Can't process received message '%s' sended by '%s', recipient '%s' is not registered.",
                msgCode, sender, recipient);

        isHandled = listener.onMessage(recipient, mt, msg);
    } else {
        for (Map.Entry<String, CommunicationContext.MessageListener> e : handlers()) {
            if (!e.getValue().onMessage(null, mt, msg)) {
                isHandled = false;
            }
        }
    }

    if (!isHandled) {
        unhandledMessage(sender, recipient, mt, msg);
    }

    return -1;
}

From source file:nl.dobots.bluenet.ble.base.structs.CrownstoneServiceData.java

public CrownstoneServiceData(byte[] bytes) {
    super();//from w  w w  . jav  a 2 s  .  co  m

    ByteBuffer bb = ByteBuffer.wrap(bytes);
    bb.order(ByteOrder.LITTLE_ENDIAN);

    bb.getShort(); // skip first two bytes (service UUID)

    bb.mark();
    int val = bb.get();

    if (val == 1) {
        setCrownstoneId(bb.getShort());
        setCrownstoneStateId(bb.getShort());
        setSwitchState((bb.get() & 0xff));
        setEventBitmask(bb.get());
        setTemperature(bb.get());
        setPowerUsage(bb.getInt());
        setAccumulatedEnergy(bb.getInt());

        setRelayState(BleUtils.isBitSet(getSwitchState(), 7));
        setPwm(getSwitchState() & ~(1 << 7));
    } else {
        bb.reset();
        setCrownstoneId(bb.getShort());
        setCrownstoneStateId(bb.getShort());
        setSwitchState((bb.get() & 0xff));
        setEventBitmask(bb.get());
        setTemperature(bb.get());
        bb.get(); // skip reserved
        //         bb.getShort(); // skip reserved
        setPowerUsage(bb.getInt());
        setAccumulatedEnergy(bb.getInt());

        setRelayState(BleUtils.isBitSet(getSwitchState(), 7));
        setPwm(getSwitchState() & ~(1 << 7));
    }
}

From source file:org.apache.nifi.processor.util.listen.dispatcher.SocketChannelDispatcher.java

@Override
public void run() {
    while (!stopped) {
        try {//from   w  w w  .  jav a2 s . c om
            int selected = selector.select();
            // if stopped the selector could already be closed which would result in a ClosedSelectorException
            if (selected > 0 && !stopped) {
                Iterator<SelectionKey> selectorKeys = selector.selectedKeys().iterator();
                // if stopped we don't want to modify the keys because close() may still be in progress
                while (selectorKeys.hasNext() && !stopped) {
                    SelectionKey key = selectorKeys.next();
                    selectorKeys.remove();
                    if (!key.isValid()) {
                        continue;
                    }
                    if (key.isAcceptable()) {
                        // Handle new connections coming in
                        final ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                        final SocketChannel socketChannel = channel.accept();
                        // Check for available connections
                        if (currentConnections.incrementAndGet() > maxConnections) {
                            currentConnections.decrementAndGet();
                            logger.warn("Rejecting connection from {} because max connections has been met",
                                    new Object[] { socketChannel.getRemoteAddress().toString() });
                            IOUtils.closeQuietly(socketChannel);
                            continue;
                        }
                        logger.debug("Accepted incoming connection from {}",
                                new Object[] { socketChannel.getRemoteAddress().toString() });
                        // Set socket to non-blocking, and register with selector
                        socketChannel.configureBlocking(false);
                        SelectionKey readKey = socketChannel.register(selector, SelectionKey.OP_READ);

                        // Prepare the byte buffer for the reads, clear it out
                        ByteBuffer buffer = bufferPool.poll();
                        buffer.clear();
                        buffer.mark();

                        // If we have an SSLContext then create an SSLEngine for the channel
                        SSLSocketChannel sslSocketChannel = null;
                        if (sslContext != null) {
                            final SSLEngine sslEngine = sslContext.createSSLEngine();
                            sslEngine.setUseClientMode(false);

                            switch (clientAuth) {
                            case REQUIRED:
                                sslEngine.setNeedClientAuth(true);
                                break;
                            case WANT:
                                sslEngine.setWantClientAuth(true);
                                break;
                            case NONE:
                                sslEngine.setNeedClientAuth(false);
                                sslEngine.setWantClientAuth(false);
                                break;
                            }

                            sslSocketChannel = new SSLSocketChannel(sslEngine, socketChannel);
                        }

                        // Attach the buffer and SSLSocketChannel to the key
                        SocketChannelAttachment attachment = new SocketChannelAttachment(buffer,
                                sslSocketChannel);
                        readKey.attach(attachment);
                    } else if (key.isReadable()) {
                        // Clear out the operations the select is interested in until done reading
                        key.interestOps(0);
                        // Create a handler based on the protocol and whether an SSLEngine was provided or not
                        final Runnable handler;
                        if (sslContext != null) {
                            handler = handlerFactory.createSSLHandler(key, this, charset, eventFactory, events,
                                    logger);
                        } else {
                            handler = handlerFactory.createHandler(key, this, charset, eventFactory, events,
                                    logger);
                        }

                        // run the handler
                        executor.execute(handler);
                    }
                }
            }
            // Add back all idle sockets to the select
            SelectionKey key;
            while ((key = keyQueue.poll()) != null) {
                key.interestOps(SelectionKey.OP_READ);
            }
        } catch (IOException e) {
            logger.error("Error accepting connection from SocketChannel", e);
        }
    }
}

From source file:com.offbynull.portmapper.pcp.PcpResponse.java

/**
 * MUST be called by child class constructor so that PCP options can be parsed.
 * @param buffer buffer containing PCP response data, with the pointer at the point which PCP options begin
 * @throws NullPointerException if any argument is {@code null}
 * @throws BufferUnderflowException if not enough data is available in {@code buffer}
 *//*from w  ww. j a va 2  s .  c o  m*/
protected final void parseOptions(ByteBuffer buffer) {
    Validate.notNull(buffer);

    List<PcpOption> pcpOptionsList = new ArrayList<>();
    while (buffer.hasRemaining()) {
        PcpOption option;

        try {
            buffer.mark();
            option = new FilterPcpOption(buffer);
            pcpOptionsList.add(option);
            continue;
        } catch (BufferUnderflowException | IllegalArgumentException e) {
            buffer.reset();
        }

        try {
            buffer.mark();
            option = new PreferFailurePcpOption(buffer);
            pcpOptionsList.add(option);
            continue;
        } catch (BufferUnderflowException | IllegalArgumentException e) {
            buffer.reset();
        }

        try {
            buffer.mark();
            option = new ThirdPartyPcpOption(buffer);
            pcpOptionsList.add(option);
            continue;
        } catch (BufferUnderflowException | IllegalArgumentException e) {
            buffer.reset();
        }

        option = new UnknownPcpOption(buffer);
        pcpOptionsList.add(option);
    }

    options = Collections.unmodifiableList(pcpOptionsList);
}

From source file:org.zuinnote.hadoop.bitcoin.format.BitcoinBlockReader.java

/**
* This function is used to read from a raw Bitcoin block some identifier. Note: Does not change ByteBuffer position
*
* @param rawByteBuffer ByteBuffer as read by readRawBlock
* @return byte array containing hashMerkleRoot and prevHashBlock
*
*///from   w  w  w  . j a  va 2  s. co  m
public byte[] getKeyFromRawBlock(ByteBuffer rawByteBuffer) {
    rawByteBuffer.mark();
    byte[] magicNo = new byte[4];
    byte[] hashMerkleRoot = new byte[32];
    byte[] hashPrevBlock = new byte[32];
    // magic no (skip)
    rawByteBuffer.get(magicNo, 0, 4);
    // blocksize (skip)
    int currentBlockSize = rawByteBuffer.getInt();
    // version (skip)
    int currentVersion = rawByteBuffer.getInt();
    // hashPrevBlock
    rawByteBuffer.get(hashPrevBlock, 0, 32);
    // hashMerkleRoot
    rawByteBuffer.get(hashMerkleRoot, 0, 32);
    byte[] result = new byte[hashMerkleRoot.length + hashPrevBlock.length];
    for (int i = 0; i < hashMerkleRoot.length; i++) {
        result[i] = hashMerkleRoot[i];
    }
    for (int j = 0; j < hashPrevBlock.length; j++) {
        result[j + hashMerkleRoot.length] = hashPrevBlock[j];
    }
    rawByteBuffer.reset();
    return result;
}

From source file:org.apache.nifi.processor.util.listen.handler.socket.StandardSocketChannelHandler.java

@Override
public void run() {
    boolean eof = false;
    SocketChannel socketChannel = null;

    try {/*from   www. j  ava2  s. com*/
        int bytesRead;
        socketChannel = (SocketChannel) key.channel();

        final SocketChannelAttachment attachment = (SocketChannelAttachment) key.attachment();
        final ByteBuffer socketBuffer = attachment.getByteBuffer();

        // read until the buffer is full
        while ((bytesRead = socketChannel.read(socketBuffer)) > 0) {
            // prepare byte buffer for reading
            socketBuffer.flip();
            // mark the current position as start, in case of partial message read
            socketBuffer.mark();
            // process the contents that have been read into the buffer
            processBuffer(socketChannel, socketBuffer);

            // Preserve bytes in buffer for next call to run
            // NOTE: This code could benefit from the  two ByteBuffer read calls to avoid
            // this compact for higher throughput
            socketBuffer.reset();
            socketBuffer.compact();
            logger.debug("bytes read {}", new Object[] { bytesRead });
        }

        // Check for closed socket
        if (bytesRead < 0) {
            eof = true;
            logger.debug("Reached EOF, closing connection");
        } else {
            logger.debug("No more data available, returning for selection");
        }
    } catch (ClosedByInterruptException | InterruptedException e) {
        logger.debug("read loop interrupted, closing connection");
        // Treat same as closed socket
        eof = true;
    } catch (ClosedChannelException e) {
        // ClosedChannelException doesn't have a message so handle it separately from IOException
        logger.error("Error reading from channel due to channel being closed", e);
        // Treat same as closed socket
        eof = true;
    } catch (IOException e) {
        logger.error("Error reading from channel due to {}", new Object[] { e.getMessage() }, e);
        // Treat same as closed socket
        eof = true;
    } finally {
        if (eof == true) {
            IOUtils.closeQuietly(socketChannel);
            dispatcher.completeConnection(key);
        } else {
            dispatcher.addBackForSelection(key);
        }
    }
}