Example usage for java.nio ByteBuffer reset

List of usage examples for java.nio ByteBuffer reset

Introduction

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

Prototype

public final Buffer reset() 

Source Link

Document

Resets the position of this buffer to the mark.

Usage

From source file:Main.java

public static List<ByteBuffer> mergeAdjacentBuffers(List<ByteBuffer> paramList) {
    ArrayList localArrayList = new ArrayList(paramList.size());
    Iterator localIterator = paramList.iterator();
    while (localIterator.hasNext()) {
        ByteBuffer localByteBuffer1 = (ByteBuffer) localIterator.next();
        int i = -1 + localArrayList.size();
        if ((i >= 0) && (localByteBuffer1.hasArray()) && (((ByteBuffer) localArrayList.get(i)).hasArray())
                && (localByteBuffer1.array() == ((ByteBuffer) localArrayList.get(i)).array())
                && (((ByteBuffer) localArrayList.get(i)).arrayOffset()
                        + ((ByteBuffer) localArrayList.get(i)).limit() == localByteBuffer1.arrayOffset())) {
            ByteBuffer localByteBuffer3 = (ByteBuffer) localArrayList.remove(i);
            localArrayList.add(ByteBuffer.wrap(localByteBuffer1.array(), localByteBuffer3.arrayOffset(),
                    localByteBuffer3.limit() + localByteBuffer1.limit()).slice());
        } else if ((i >= 0) && ((localByteBuffer1 instanceof MappedByteBuffer))
                && ((localArrayList.get(i) instanceof MappedByteBuffer))
                && (((ByteBuffer) localArrayList.get(i))
                        .limit() == ((ByteBuffer) localArrayList.get(i)).capacity()
                                - localByteBuffer1.capacity())) {
            ByteBuffer localByteBuffer2 = (ByteBuffer) localArrayList.get(i);
            localByteBuffer2.limit(localByteBuffer1.limit() + localByteBuffer2.limit());
        } else {//from w  w w  .  j a  va2  s .c  om
            localByteBuffer1.reset();
            localArrayList.add(localByteBuffer1);
        }
    }
    return localArrayList;
}

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

protected final void encodeDecode(final ByteBuffer expectedBuffer) {

    expectedBuffer.mark();/*from   w ww.jav a  2  s.  com*/

    final ByteBuffer encodedBuffer = encoder.encode(expectedBuffer);

    final ByteBuffer actualBuffer = decoder.decode(encodedBuffer);

    expectedBuffer.reset();

    assertEquals(actualBuffer, expectedBuffer);
}

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//from  ww w .  j a v  a  2  s  .c  om
    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: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  ww w  . ja  va 2  s.co  m

    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.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}
 *///ww w  .j a  v a  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:com.spidertracks.datanucleus.convert.ByteConverterContext.java

/**
 * Get the row key for the given id//from ww w. ja va  2 s.  com
 * 
 * @param ec
 * @param id
 * @return
 */
public Bytes getRowKeyForId(Object id) {
    ByteBuffer buffer = getRowKeyForId(id, null);
    buffer.limit(buffer.position());
    buffer.reset();
    return Bytes.fromByteBuffer(buffer);
}

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();//from  www .ja  v  a 2s.c  om
    portBuffer.putInt(SHUFFLE_PORT);
    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.spidertracks.datanucleus.convert.ByteConverterContext.java

/**
 * Allocate a byte buffer and convert the bytes with the given converter.
 * Performs a mark and a reset on the internal buffer before invoking the
 * write//  ww  w . j  ava  2s. c o  m
 * 
 * @param converter
 * @param value
 * @return
 */
private ByteBuffer convertToBytes(ByteConverter converter, Object value) {
    ByteBuffer buff = converter.writeBytes(value, null, this);

    if (buff != null) {
        buff.limit();
        buff.reset();
    }

    //        System.out.println(String.format("Conversion Object -> Bytes >> value: %s ; hex: %s", value, new String(org.apache.commons.codec.binary.Hex.encodeHex(buff.array()))));

    return buff;
}

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;/*from   ww  w  .j  a v a2 s.c o m*/
        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:nl.dobots.bluenet.ble.base.structs.CrownstoneServiceData.java

public CrownstoneServiceData(byte[] bytes) {
    super();//from www .  j  a  v  a2 s. c  o  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));
    }
}