Example usage for java.nio ByteBuffer get

List of usage examples for java.nio ByteBuffer get

Introduction

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

Prototype

public abstract byte get();

Source Link

Document

Returns the byte at the current position and increases the position by 1.

Usage

From source file:com.dianping.puma.parser.mysql.event.BinlogHeader.java

public void parse(ByteBuffer buf, PumaContext context) {
    timestamp = PacketUtils.readLong(buf, 4);
    eventType = buf.get();
    serverId = PacketUtils.readLong(buf, 4);
    eventLength = PacketUtils.readLong(buf, 4);
    nextPosition = PacketUtils.readLong(buf, 4);
    flags = PacketUtils.readInt(buf, 2);
}

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

/**
 * Constructs a {@link FilterPcpOption} by parsing a buffer.
 * @param buffer buffer containing PCP option data
 * @throws NullPointerException if any argument is {@code null}
 * @throws BufferUnderflowException if not enough data is available in {@code buffer}
 * @throws IllegalArgumentException if option code is not {@code 3}, or if the field {@code prefixLength > 128}
 *//*from  w w w. j av a2s. c o m*/
public FilterPcpOption(ByteBuffer buffer) {
    super(buffer);

    Validate.isTrue(super.getCode() == 3);

    buffer.get(); // reserved
    prefixLength = buffer.get() & 0xFF;
    remotePeerPort = buffer.getShort() & 0xFFFF;

    Validate.inclusiveBetween(0, 128, prefixLength); // 0 indicates 'no filter'
    Validate.inclusiveBetween(0, 65535, remotePeerPort); // 0 indicates 'all ports', should never trigger

    byte[] addrArr = new byte[16];
    buffer.get(addrArr);
    try {
        remotePeerIpAddress = InetAddress.getByAddress(addrArr);
    } catch (UnknownHostException uhe) {
        throw new IllegalStateException(uhe); // should never happen
    }
}

From source file:com.codefollower.lealone.omid.tso.persistence.LoggerProtocol.java

/**
 * Execute a logged entry (several logged ops)
 * @param bb Serialized operations//w ww .j av  a  2s .co m
 */
void execute(ByteBuffer bb) {
    boolean done = !bb.hasRemaining();
    while (!done) {
        byte op = bb.get();
        long timestamp, startTimestamp, commitTimestamp;
        if (LOG.isTraceEnabled()) {
            LOG.trace("Operation: " + op);
        }
        switch (op) {
        case TIMESTAMP_ORACLE:
            timestamp = bb.getLong();
            this.getTimestampOracle().initialize(timestamp);
            this.initialize();
            oracle = true;
            break;
        case COMMIT:
            startTimestamp = bb.getLong();
            commitTimestamp = bb.getLong();
            processCommit(startTimestamp, commitTimestamp);
            if (commitTimestamp < largestDeletedTimestamp) {
                commits = true;
            }
            break;
        case LARGEST_DELETED_TIMESTAMP:
            timestamp = bb.getLong();
            processLargestDeletedTimestamp(timestamp);

            break;
        case ABORT:
            timestamp = bb.getLong();
            processHalfAbort(timestamp);

            break;
        case FULL_ABORT:
            timestamp = bb.getLong();
            processFullAbort(timestamp);

            break;
        case LOG_START:
            consumed = true;
            break;
        case SNAPSHOT:
            int snapshot = (int) bb.getLong();
            if (snapshot > this.snapshot) {
                this.snapshot = snapshot;
                this.hasSnapshot = true;
            }
            if (hasSnapshot && snapshot < this.snapshot) {
                this.aborts = true;
            }
            break;
        }
        if (bb.remaining() == 0)
            done = true;
    }
}

From source file:com.yahoo.omid.tso.persistence.LoggerProtocol.java

/**
 * Execute a logged entry (several logged ops)
 * @param bb Serialized operations// ww w.ja v a2 s.  c o m
 */
void execute(ByteBuffer bb) {
    boolean done = !bb.hasRemaining();
    while (!done) {
        byte op = bb.get();
        long timestamp, startTimestamp, commitTimestamp;
        if (LOG.isTraceEnabled()) {
            LOG.trace("Operation: " + op);
        }
        switch (op) {
        case TIMESTAMPORACLE:
            timestamp = bb.getLong();
            this.getSO().initialize(timestamp);
            this.initialize();
            oracle = true;
            break;
        case COMMIT:
            startTimestamp = bb.getLong();
            commitTimestamp = bb.getLong();
            processCommit(startTimestamp, commitTimestamp);
            if (commitTimestamp < largestDeletedTimestamp) {
                commits = true;
            }
            break;
        case LARGESTDELETEDTIMESTAMP:
            timestamp = bb.getLong();
            processLargestDeletedTimestamp(timestamp);

            break;
        case ABORT:
            timestamp = bb.getLong();
            processAbort(timestamp);

            break;
        case FULLABORT:
            timestamp = bb.getLong();
            processFullAbort(timestamp);

            break;
        case LOGSTART:
            consumed = true;
            break;
        case SNAPSHOT:
            int snapshot = (int) bb.getLong();
            if (snapshot > this.snapshot) {
                this.snapshot = snapshot;
                this.hasSnapshot = true;
            }
            if (hasSnapshot && snapshot < this.snapshot) {
                this.aborts = true;
            }
            break;
        }
        if (bb.remaining() == 0)
            done = true;
    }
}

From source file:com.smartitengineering.util.simple.io.BufferedInputStream.java

@Override
public int read() throws IOException {
    ByteBuffer buffer = getCurrentBuffer();
    if (available() > 0) {
        return buffer.get();
    }/*from w  w w  . jav a2  s.c o m*/
    int remaining = buffer.remaining();
    if (remaining <= 0) {
        if (hasNextBuffer()) {
            currentBuffer = nextBuffer();
            return read();
        } else if (eofReached) {
            return -1;
        } else {
            remaining = initializeNewBuffer();
            buffer = getCurrentBuffer();
        }
    }
    byte[] readBuffer = new byte[remaining];
    int read = wrappedStream.read(readBuffer);
    if (read > 0) {
        int position = buffer.position();
        buffer.put(readBuffer, 0, read);
        buffer.position(position);
        get(buffer).add(read);
        return buffer.get();
    } else {
        eofReached = true;
        return -1;
    }
}

From source file:net.jenet.Packet.java

/**
 * Copies the given buffer into this packet's data.
 * @ param buffer//from  w  ww  . j a  v a  2  s  .  c  om
 *              Buffer to copy from
 */
public void fromBuffer(ByteBuffer buffer) {
    data.clear();
    for (int i = 0; i < dataLength; i++) {
        data.put(buffer.get());
    }
}

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

/**
 * Constructs a {@link NatPmpResponse} object by parsing a buffer.
 * @param buffer buffer containing NAT-PMP response data
 * @throws NullPointerException if any argument is {@code null}
 * @throws BufferUnderflowException if not enough data is available in {@code buffer}
 * @throws IllegalArgumentException if the version doesn't match the expected version (must always be {@code 0}), or if the op is
 * {@code < 128}, or if there's an unsuccessful/unrecognized result code
 *//*from  ww  w . ja v a2 s. c o m*/
NatPmpResponse(ByteBuffer buffer) {
    Validate.notNull(buffer);

    if (buffer.remaining() < 2) {
        throw new IllegalArgumentException("Bad packet size: " + buffer.remaining());
    }

    int version = buffer.get() & 0xFF;
    Validate.isTrue(version == 0, "Unknown version: %d", version);

    op = buffer.get() & 0xFF;
    Validate.isTrue(op >= 128, "Op must be >= 128: %d", op);

    int resultCodeNum = buffer.getShort() & 0xFFFF;
    NatPmpResultCode[] resultCodes = NatPmpResultCode.values();

    Validate.isTrue(resultCodeNum < resultCodes.length, "Unknown result code encountered: %d", resultCodeNum);
    Validate.isTrue(resultCodeNum == NatPmpResultCode.SUCCESS.ordinal(), "Unsuccessful result code: %s [%s]",
            resultCodes[resultCodeNum].toString(), resultCodes[resultCodeNum].getMessage());

    secondsSinceStartOfEpoch = buffer.getInt() & 0xFFFFFFFFL;
}

From source file:com.byteatebit.nbserver.task.TestWriteMessageTask.java

@Test
public void testWriteCompleteMessage() throws IOException {
    SocketChannel socket = mock(SocketChannel.class);
    ByteArrayOutputStream messageStream = new ByteArrayOutputStream();
    String message = "hi\n";
    when(socket.write(any(ByteBuffer.class))).then(new Answer<Integer>() {
        @Override/*from w w w . jav a  2s .  c  o m*/
        public Integer answer(InvocationOnMock invocationOnMock) throws Throwable {
            ByteBuffer buffer = (ByteBuffer) invocationOnMock.getArguments()[0];
            while (buffer.hasRemaining())
                messageStream.write(buffer.get());
            return buffer.position();
        }
    });
    INbContext nbContext = mock(INbContext.class);
    SelectionKey selectionKey = mock(SelectionKey.class);
    when(selectionKey.channel()).thenReturn(socket);
    when(selectionKey.isValid()).thenReturn(true);
    when(selectionKey.readyOps()).thenReturn(SelectionKey.OP_WRITE);

    WriteMessageTask writeTask = WriteMessageTask.Builder.builder().withByteBuffer(ByteBuffer.allocate(100))
            .build();
    List<String> callbackInvoked = new ArrayList<>();
    Runnable callback = () -> callbackInvoked.add("");
    Consumer<Exception> exceptionHandler = e -> Assert.fail(e.getMessage());
    writeTask.writeMessage(message.getBytes(StandardCharsets.UTF_8), nbContext, socket, callback,
            exceptionHandler);
    verify(nbContext, times(1)).register(any(SocketChannel.class), eq(SelectionKey.OP_WRITE), any(), any());
    writeTask.write(selectionKey, callback, exceptionHandler);
    verify(selectionKey, times(1)).interestOps(0);

    Assert.assertEquals(message, messageStream.toString(StandardCharsets.UTF_8));
    Assert.assertEquals(1, callbackInvoked.size());
}

From source file:com.netflix.aegisthus.pig.AegisthusLoadCaster.java

private long getNumber(byte[] arg0) throws Exception {
    byte[] by = hex.decode(arg0);
    ByteBuffer bb = ByteBuffer.allocate(by.length);
    bb.put(by);//w  ww .ja  va  2 s  . c o m
    bb.position(0);
    switch (by.length) {
    case 1:
        return (long) bb.get();
    case 2:
        return (long) bb.getShort();
    case 4:
        return (long) bb.getInt();
    case 8:
        return (long) bb.getLong();
    }
    throw new UnexpectedException("couldn't determine datatype");
}

From source file:hudson.Util.java

/**
 * Encode a single path component for use in an HTTP URL.
 * Escapes all non-ASCII, general unsafe (space and "#%<>[\]^`{|}~)
 * and HTTP special characters (/;:?) as specified in RFC1738.
 * (so alphanumeric and !@$&*()-_=+',. are not encoded)
 * Note that slash(/) is encoded, so the given string should be a
 * single path component used in constructing a URL.
 * Method name inspired by PHP's rawurlencode.
 *//*  www.j  a v  a 2s  .  c  o  m*/
public static String rawEncode(String s) {
    boolean escaped = false;
    StringBuilder out = null;
    CharsetEncoder enc = null;
    CharBuffer buf = null;
    char c;
    for (int i = 0, m = s.length(); i < m; i++) {
        c = s.charAt(i);
        if (c > 122 || uriMap[c]) {
            if (!escaped) {
                out = new StringBuilder(i + (m - i) * 3);
                out.append(s.substring(0, i));
                enc = Charset.forName("UTF-8").newEncoder();
                buf = CharBuffer.allocate(1);
                escaped = true;
            }
            // 1 char -> UTF8
            buf.put(0, c);
            buf.rewind();
            try {
                ByteBuffer bytes = enc.encode(buf);
                while (bytes.hasRemaining()) {
                    byte b = bytes.get();
                    out.append('%');
                    out.append(toDigit((b >> 4) & 0xF));
                    out.append(toDigit(b & 0xF));
                }
            } catch (CharacterCodingException ex) {
            }
        } else if (escaped) {
            out.append(c);
        }
    }
    return escaped ? out.toString() : s;
}