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.apache.tez.runtime.library.common.writers.TestUnorderedPartitionedKVWriter.java

private OutputContext createMockOutputContext(TezCounters counters, ApplicationId appId, String uniqueId) {
    OutputContext outputContext = mock(OutputContext.class);
    doReturn(counters).when(outputContext).getCounters();
    doReturn(appId).when(outputContext).getApplicationId();
    doReturn(1).when(outputContext).getDAGAttemptNumber();
    doReturn("dagName").when(outputContext).getDAGName();
    doReturn("destinationVertexName").when(outputContext).getDestinationVertexName();
    doReturn(1).when(outputContext).getOutputIndex();
    doReturn(1).when(outputContext).getTaskAttemptNumber();
    doReturn(1).when(outputContext).getTaskIndex();
    doReturn(1).when(outputContext).getTaskVertexIndex();
    doReturn("vertexName").when(outputContext).getTaskVertexName();
    doReturn(uniqueId).when(outputContext).getUniqueIdentifier();
    ByteBuffer portBuffer = ByteBuffer.allocate(4);
    portBuffer.mark();
    portBuffer.putInt(SHUFFLE_PORT);//from www  .  j av  a2 s.  c  o m
    portBuffer.reset();
    doReturn(portBuffer).when(outputContext)
            .getServiceProviderMetaData(eq(ShuffleUtils.SHUFFLE_HANDLER_SERVICE_ID));
    Path outDirBase = new Path(TEST_ROOT_DIR, "outDir_" + uniqueId);
    String[] outDirs = new String[] { outDirBase.toString() };
    doReturn(outDirs).when(outputContext).getWorkDirs();
    return outputContext;
}

From source file:com.esri.geoevent.solutions.adapter.cot.CoTAdapter.java

@Override
public void receive(ByteBuffer buf, String channelId) {
    buf.mark();
    int size = buf.remaining();
    if (size < 1)
        return;//from  ww w.j  a va2  s. c o  m
    byte[] data = new byte[size];
    buf.get(data, 0, size);
    //System.out.println(" \n");
    //System.out.println("Read " + size + " bytes");

    String xml = new String(data);
    parseUsingDocument(xml, channelId);
    //parseUsingStream(buf);
}

From source file:org.jmangos.sniffer.network.model.impl.WOWNetworkChannel.java

@Override
synchronized public void onResiveServerData(final long frameNumber, final byte[] buffer) {
    final ByteBuffer bytebuf = ByteBuffer.wrap(buffer);
    bytebuf.order(ByteOrder.LITTLE_ENDIAN);
    long opcode = 0;
    long size = 0;
    byte[] data = null;
    if (getChannelState().contains(State.AUTHED)) {
        final long header = bytebuf.getInt() & 0xFFFFFFFF;
        size = header >> 13;/*w ww.  ja  v  a 2 s . c om*/
        opcode = header & 0x1FFF;
        data = new byte[(int) size];
        bytebuf.get(data);
    } else {
        size = bytebuf.getShort();
        opcode = bytebuf.getInt();
        bytebuf.mark();
        data = new byte[(int) size - 4];
        bytebuf.get(data);
        bytebuf.reset();
        // old 0xc0b
        if ((opcode == 0x221) & !getChannelState().contains(State.NOT_ACCEPT_SEED)) {
            this.log.debug("Get new Seed");
            final byte[] serverSeed = new byte[16];
            final byte[] clientSeed = new byte[16];
            for (int i = 0; i < 16; i++) {
                serverSeed[i] = bytebuf.get();
            }
            for (int i = 0; i < 16; i++) {
                clientSeed[i] = bytebuf.get();
            }
            bytebuf.get();
            this.csPacketBuffer.getCrypt().setEncryptionSeed(clientSeed);
            this.scPacketBuffer.getCrypt().setEncryptionSeed(serverSeed);
        }

    }
    this.log.debug(String.format("Frame: %d; Resive packet %s Opcode: 0x%x OpcodeSize: %d", frameNumber, "SMSG",
            opcode, size));
    for (final PacketLogHandler logger : this.packetLoggers) {
        logger.onDecodePacket(this, Direction.SERVER, (int) size, (int) opcode, data, (int) frameNumber);
    }
}

From source file:org.cloudata.core.common.io.CText.java

/**
 * Finds any occurence of <code>what</code> in the backing
 * buffer, starting as position <code>start</code>. The starting
 * position is measured in bytes and the return value is in
 * terms of byte position in the buffer. The backing buffer is
 * not converted to a string for this operation.
 * @return byte position of the first occurence of the search
 *         string in the UTF-8 buffer or -1 if not found
 *///from www. ja va 2  s.  co  m
public int find(String what, int start) {
    try {
        ByteBuffer src = ByteBuffer.wrap(this.bytes);
        ByteBuffer tgt = encode(what);
        byte b = tgt.get();
        src.position(start);

        while (src.hasRemaining()) {
            if (b == src.get()) { // matching first byte
                src.mark(); // save position in loop
                tgt.mark(); // save position in target
                boolean found = true;
                int pos = src.position() - 1;
                while (tgt.hasRemaining()) {
                    if (!src.hasRemaining()) { // src expired first
                        tgt.reset();
                        src.reset();
                        found = false;
                        break;
                    }
                    if (!(tgt.get() == src.get())) {
                        tgt.reset();
                        src.reset();
                        found = false;
                        break; // no match
                    }
                }
                if (found)
                    return pos;
            }
        }
        return -1; // not found
    } catch (CharacterCodingException e) {
        // can't get here
        e.printStackTrace();
        return -1;
    }
}

From source file:io.Text.java

/**
 * Finds any occurence of <code>what</code> in the backing
 * buffer, starting as position <code>start</code>. The starting
 * position is measured in bytes and the return value is in
 * terms of byte position in the buffer. The backing buffer is
 * not converted to a string for this operation.
 * @return byte position of the first occurence of the search
 *         string in the UTF-8 buffer or -1 if not found
 *//*  w  w w.jav  a2 s.c  om*/
public int find(String what, int start) {
    try {
        ByteBuffer src = ByteBuffer.wrap(this.bytes, 0, this.length);
        ByteBuffer tgt = encode(what);
        byte b = tgt.get();
        src.position(start);

        while (src.hasRemaining()) {
            if (b == src.get()) { // matching first byte
                src.mark(); // save position in loop
                tgt.mark(); // save position in target
                boolean found = true;
                int pos = src.position() - 1;
                while (tgt.hasRemaining()) {
                    if (!src.hasRemaining()) { // src expired first
                        tgt.reset();
                        src.reset();
                        found = false;
                        break;
                    }
                    if (!(tgt.get() == src.get())) {
                        tgt.reset();
                        src.reset();
                        found = false;
                        break; // no match
                    }
                }
                if (found)
                    return pos;
            }
        }
        return -1; // not found
    } catch (CharacterCodingException e) {
        // can't get here
        e.printStackTrace();
        return -1;
    }
}

From source file:org.apache.arrow.vector.util.Text.java

/**
 * Finds any occurence of <code>what</code> in the backing buffer, starting as position <code>start</code>. The
 * starting position is measured in bytes and the return value is in terms of byte position in the buffer. The backing
 * buffer is not converted to a string for this operation.
 *
 * @return byte position of the first occurence of the search string in the UTF-8 buffer or -1 if not found
 *///w  ww .  ja va 2  s .  com
public int find(String what, int start) {
    try {
        ByteBuffer src = ByteBuffer.wrap(this.bytes, 0, this.length);
        ByteBuffer tgt = encode(what);
        byte b = tgt.get();
        src.position(start);

        while (src.hasRemaining()) {
            if (b == src.get()) { // matching first byte
                src.mark(); // save position in loop
                tgt.mark(); // save position in target
                boolean found = true;
                int pos = src.position() - 1;
                while (tgt.hasRemaining()) {
                    if (!src.hasRemaining()) { // src expired first
                        tgt.reset();
                        src.reset();
                        found = false;
                        break;
                    }
                    if (!(tgt.get() == src.get())) {
                        tgt.reset();
                        src.reset();
                        found = false;
                        break; // no match
                    }
                }
                if (found) {
                    return pos;
                }
            }
        }
        return -1; // not found
    } catch (CharacterCodingException e) {
        // can't get here
        e.printStackTrace();
        return -1;
    }
}

From source file:com.offbynull.portmapper.natpmp.NatPmpController.java

/**
 * Constructs a {@link NatPmpController} object.
 * @param gatewayAddress address of router/gateway
 * @param listener a listener to listen for all NAT-PMP packets from this router
 * @throws NullPointerException if any argument is {@code null}
 * @throws IOException if problems initializing UDP channels
 *///from  www .  ja  va 2s .com
public NatPmpController(InetAddress gatewayAddress, final NatPmpControllerListener listener)
        throws IOException {
    Validate.notNull(gatewayAddress);

    this.gateway = new InetSocketAddress(gatewayAddress, 5351);

    List<DatagramChannel> channels = new ArrayList<>(3);

    try {
        unicastChannel = DatagramChannel.open();
        unicastChannel.configureBlocking(false);
        unicastChannel.socket().bind(new InetSocketAddress(0));

        ipv4MulticastChannel = DatagramChannel.open(StandardProtocolFamily.INET);
        ipv4MulticastChannel.configureBlocking(false);
        ipv4MulticastChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        ipv4MulticastChannel.socket().bind(new InetSocketAddress(5350));
        NetworkUtils.multicastListenOnAllIpv4InterfaceAddresses(ipv4MulticastChannel);

        ipv6MulticastChannel = DatagramChannel.open(StandardProtocolFamily.INET6);
        ipv6MulticastChannel.configureBlocking(false);
        ipv6MulticastChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        ipv6MulticastChannel.socket().bind(new InetSocketAddress(5350));
        NetworkUtils.multicastListenOnAllIpv6InterfaceAddresses(ipv6MulticastChannel);
    } catch (IOException ioe) {
        IOUtils.closeQuietly(unicastChannel);
        IOUtils.closeQuietly(ipv4MulticastChannel);
        IOUtils.closeQuietly(ipv6MulticastChannel);
        throw ioe;
    }

    channels.add(unicastChannel);
    channels.add(ipv4MulticastChannel);
    channels.add(ipv6MulticastChannel);

    this.communicator = new UdpCommunicator(channels);
    this.communicator.startAsync().awaitRunning();

    if (listener != null) {
        this.communicator.addListener(new UdpCommunicatorListener() {

            @Override
            public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel,
                    ByteBuffer packet) {
                CommunicationType type;
                if (channel == unicastChannel) {
                    type = CommunicationType.UNICAST;
                } else if (channel == ipv4MulticastChannel || channel == ipv6MulticastChannel) {
                    type = CommunicationType.MULTICAST;
                } else {
                    return; // unknown, do nothing
                }

                try {
                    packet.mark();
                    listener.incomingResponse(type, new ExternalAddressNatPmpResponse(packet));
                } catch (BufferUnderflowException | IllegalArgumentException e) { // NOPMD
                    // ignore
                } finally {
                    packet.reset();
                }

                try {
                    packet.mark();
                    listener.incomingResponse(type, new UdpMappingNatPmpResponse(packet));
                } catch (BufferUnderflowException | IllegalArgumentException e) { // NOPMD
                    // ignore
                } finally {
                    packet.reset();
                }

                try {
                    packet.mark();
                    listener.incomingResponse(type, new TcpMappingNatPmpResponse(packet));
                } catch (BufferUnderflowException | IllegalArgumentException e) { // NOPMD
                    // ignore
                } finally {
                    packet.reset();
                }
            }
        });
    }
}

From source file:com.esri.geoevent.solutions.adapter.cot.CoTAdapterInbound.java

@Override
public void receive(ByteBuffer buf, String channelId) {
    try {/* w w  w. jav  a2s. co m*/
        buf.mark();
        int size = buf.remaining();
        if (size < 1)
            return;

        parseUsingStream(buf);
    } catch (Exception e) {
        log.error(e);
        log.error(e.getStackTrace());
    }
}

From source file:org.commoncrawl.util.TextBytes.java

/**
 * Finds any occurence of <code>what</code> in the backing buffer, starting as
 * position <code>start</code>. The starting position is measured in bytes and
 * the return value is in terms of byte position in the buffer. The backing
 * buffer is not converted to a string for this operation.
 * /*ww  w . j  av  a  2  s .  c o m*/
 * @return byte position of the first occurence of the search string in the
 *         UTF-8 buffer or -1 if not found
 */
public int find(String what, int start) {
    try {
        ByteBuffer src = ByteBuffer.wrap(bytes.get(), bytes.getOffset(), bytes.getCount());
        ByteBuffer tgt = encode(what);
        byte b = tgt.get();
        src.position(start);

        while (src.hasRemaining()) {
            if (b == src.get()) { // matching first byte
                src.mark(); // save position in loop
                tgt.mark(); // save position in target
                boolean found = true;
                int pos = src.position() - 1;
                while (tgt.hasRemaining()) {
                    if (!src.hasRemaining()) { // src expired first
                        tgt.reset();
                        src.reset();
                        found = false;
                        break;
                    }
                    if (!(tgt.get() == src.get())) {
                        tgt.reset();
                        src.reset();
                        found = false;
                        break; // no match
                    }
                }
                if (found)
                    return pos;
            }
        }
        return -1; // not found
    } catch (CharacterCodingException e) {
        // can't get here
        e.printStackTrace();
        return -1;
    }
}

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

/**
 * Constructs a {@link PcpController} object.
 * @param random used to generate nonce values for requests
 * @param gatewayAddress address of router/gateway
 * @param selfAddress address of this machine on the interface that can talk to the router/gateway
 * @param listener a listener to listen for all PCP packets from this router
 * @throws NullPointerException if any argument is {@code null}
 * @throws IOException if problems initializing UDP channels
 *//*from   w w  w . j  a v a 2s.  c  o m*/
public PcpController(Random random, InetAddress gatewayAddress, InetAddress selfAddress,
        final PcpControllerListener listener) throws IOException {
    Validate.notNull(random);
    Validate.notNull(gatewayAddress);
    Validate.notNull(selfAddress);

    this.gateway = new InetSocketAddress(gatewayAddress, 5351);

    List<DatagramChannel> channels = new ArrayList<>(3);

    try {
        unicastChannel = DatagramChannel.open();
        unicastChannel.configureBlocking(false);
        unicastChannel.socket().bind(new InetSocketAddress(0));

        ipv4MulticastChannel = DatagramChannel.open(StandardProtocolFamily.INET);
        ipv4MulticastChannel.configureBlocking(false);
        ipv4MulticastChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        ipv4MulticastChannel.socket().bind(new InetSocketAddress(5350));
        NetworkUtils.multicastListenOnAllIpv4InterfaceAddresses(ipv4MulticastChannel);

        ipv6MulticastChannel = DatagramChannel.open(StandardProtocolFamily.INET6);
        ipv6MulticastChannel.configureBlocking(false);
        ipv6MulticastChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        ipv6MulticastChannel.socket().bind(new InetSocketAddress(5350));
        NetworkUtils.multicastListenOnAllIpv6InterfaceAddresses(ipv6MulticastChannel);
    } catch (IOException ioe) {
        IOUtils.closeQuietly(unicastChannel);
        IOUtils.closeQuietly(ipv4MulticastChannel);
        IOUtils.closeQuietly(ipv6MulticastChannel);
        throw ioe;
    }

    channels.add(unicastChannel);
    channels.add(ipv4MulticastChannel);
    channels.add(ipv6MulticastChannel);

    this.communicator = new UdpCommunicator(channels);
    this.selfAddress = selfAddress;
    this.random = random;

    this.communicator.startAsync().awaitRunning();

    if (listener != null) {
        this.communicator.addListener(new UdpCommunicatorListener() {

            @Override
            public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel,
                    ByteBuffer packet) {
                CommunicationType type;
                if (channel == unicastChannel) {
                    type = CommunicationType.UNICAST;
                } else if (channel == ipv4MulticastChannel || channel == ipv6MulticastChannel) {
                    type = CommunicationType.MULTICAST;
                } else {
                    return; // unknown, do nothing
                }

                try {
                    packet.mark();
                    listener.incomingResponse(type, new AnnouncePcpResponse(packet));
                } catch (BufferUnderflowException | IllegalArgumentException e) { // NOPMD
                    // ignore
                } finally {
                    packet.reset();
                }

                try {
                    packet.mark();
                    listener.incomingResponse(type, new MapPcpResponse(packet));
                } catch (BufferUnderflowException | IllegalArgumentException e) { // NOPMD
                    // ignore
                } finally {
                    packet.reset();
                }

                try {
                    packet.mark();
                    listener.incomingResponse(type, new PeerPcpResponse(packet));
                } catch (BufferUnderflowException | IllegalArgumentException e) { // NOPMD
                    // ignore
                } finally {
                    packet.reset();
                }
            }
        });
    }
}