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.woodcomputing.bobbin.format.PESFormat.java

@Override
public Design load(File file) {

    byte[] bytes = null;
    try (InputStream is = new FileInputStream(file)) {
        bytes = IOUtils.toByteArray(is);
    } catch (IOException ex) {
        log.catching(ex);/*  w w w  .  j  a v  a2s . c  o  m*/
    }
    ByteBuffer bb = ByteBuffer.wrap(bytes);
    bb.order(ByteOrder.LITTLE_ENDIAN);
    Design design = new Design();
    log.debug("Magic: {}{}{}{}", (char) bb.get(), (char) bb.get(), (char) bb.get(), (char) bb.get());
    int pecStart = bb.getInt(8);
    log.debug("PEC Start: {}", pecStart);
    byte colorCount = bb.get(pecStart + 48);
    log.debug("Color Count: {}", colorCount);
    int colors[] = new int[colorCount];
    for (int i = 0; i < colorCount; i++) {
        colors[i] = bb.get() & 0xFF;
        log.debug("Color[{}] = {}", i, colors[i]);
    }

    bb.position(pecStart + 532);
    int x;
    int y;
    int colorChanges = 0;
    PESColor color = pesColorMap.get(colors[colorChanges++]);
    StitchGroup stitchGroup = new StitchGroup();
    stitchGroup.setColor(color.getColor());

    while (true) {
        x = bb.get() & 0xFF;
        y = bb.get() & 0xFF;
        if (x == 0xFF && y == 0x00) {
            log.debug("End of stitches");
            break;
        }
        if (x == 0xFE && y == 0xB0) {
            int colorIndex = bb.get() & 0xFF;
            log.debug("Color change: {}", colorIndex);
            color = pesColorMap.get(colors[colorChanges++]);
            stitchGroup = new StitchGroup();
            stitchGroup.setColor(color.getColor());
            continue;
        }
        if ((x & 0x80) > 0) {
            log.debug("Testing X: {} -  X & 0x80: {}", x, x & 0x80);
            if ((x & 0x20) > 0) {
                log.debug("Stich type TRIM");
            }
            if ((x & 0x10) > 0) {
                log.debug("Stich type JUMP");
            }
            x = ((x & 0x0F) << 8) + y;

            if ((x & 0x800) > 0) {
                x -= 0x1000;
            }
            y = bb.get() & 0xFF;

        } else if (x >= 0x40) {
            x -= 0x80;
        }
        if ((y & 0x80) > 0) {
            log.debug("Testing Y: {} -  Y & 0x80: {}", y, y & 0x80);
            if ((y & 0x20) > 0) {
                log.debug("Stich type TRIM");
            }
            if ((y & 0x10) > 0) {
                log.debug("Stich type JUMP");
            }
            y = ((y & 0x0F) << 8) + bb.get() & 0xFF;

            if ((y & 0x800) > 0) {
                y -= 0x1000;
            }
        } else if (y >= 0x40) {
            y -= 0x80;
        }
        //            Stitch designStitch = new Stitch(cx, -cy, nx, -ny);
        //            stitchGroup.getStitches().add(designStitch);
        log.debug("X: {} Y: {}", x, y);
    }
    log.debug("Color Changes: {}", colorChanges);
    return design;
}

From source file:com.sm.store.utils.FileStore.java

private void reset() throws IOException {
    ByteBuffer buf = ByteBuffer.allocate(RECORD_SIZE);
    long pos = OFFSET + (long) (totalRecord - 1) * RECORD_SIZE;
    indexChannel.read(buf, pos);/* www.j a  va 2  s. c om*/
    buf.rewind();
    byte status = buf.get();
    long keyLen = buf.getLong();
    byte[] keys = readChannel(keyLen, keyChannel);
    long data = buf.getLong();
    long block2version = buf.getLong();
    CacheBlock block = new CacheBlock(totalRecord, data, block2version, status);
    byte[] datas = readChannel(block.getDataOffset2Len(), dataChannel);

}

From source file:fr.cls.atoll.motu.processor.wps.StringList.java

public static void print(ByteBuffer bb) {
    while (bb.hasRemaining()) {
        System.out.print(bb.get() + " ");
    }//  ww  w  .  j ava2  s . co  m
    System.out.println();
    bb.rewind();
}

From source file:com.saasovation.common.port.adapter.messaging.slothmq.SlothWorker.java

protected String receive() {
    SocketChannel socketChannel = null;

    try {//from www.j  av a  2s. co m
        socketChannel = this.socket.accept();

        if (socketChannel == null) {
            return null; // if non-blocking
        }

        ReadableByteChannel readByteChannel = Channels.newChannel(socketChannel.socket().getInputStream());

        ByteArrayOutputStream byteArray = new ByteArrayOutputStream();

        ByteBuffer readBuffer = ByteBuffer.allocate(8);

        while (readByteChannel.read(readBuffer) != -1) {
            readBuffer.flip();

            while (readBuffer.hasRemaining()) {
                byteArray.write(readBuffer.get());
            }

            readBuffer.clear();
        }

        return new String(byteArray.toByteArray());

    } catch (IOException e) {
        logger.error("Failed to receive because: {}: Continuing...", e.getMessage(), e);
        return null;

    } finally {
        if (socketChannel != null) {
            try {
                socketChannel.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}

From source file:adapter.davis.DavisSensor.java

/**
 * Expecting ACK message.//from   w  w w  .  j a v a  2 s . co m
 * @throws CommunicationException
 * @throws InterruptedException
 */
private void expectACK() throws CommunicationException, InterruptedException {
    logger.info("Expecting ACK");
    byte ans[] = this.expect(1);

    ByteBuffer wrapped = ByteBuffer.wrap(ans, 0, ans.length);
    wrapped.order(ByteOrder.LITTLE_ENDIAN);

    if (wrapped.get() != DavisReturnCodes.ACK)
        throw new CommunicationException("Didn't receive ACK");

    logger.info("Received ACK successful.");
}

From source file:de.unibayreuth.bayeos.goat.table.MassenTableModel.java

public boolean load(ObjektNode objekt, TimeFilter tFilter, StatusFilter sFilter) {
    try {/* w w w  .j a  v  a  2  s  .com*/

        Vector params = new Vector();
        params.add(objekt.getId());
        params.add(tFilter.getVector());
        params.add(sFilter.getVector());
        Vector vReturn = (Vector) xmlClient.execute("MassenTableHandler.getRows", params);
        // Rows als byte[]
        byte[] ba = (byte[]) vReturn.elementAt(1);

        statusList = new ArrayByteList(ba.length / rowLength);
        vonList = new ArrayIntList(ba.length / rowLength);
        wertList = new ArrayDoubleList(ba.length / rowLength);

        ByteBuffer b = ByteBuffer.wrap(ba);
        while (b.hasRemaining()) {
            vonList.add(b.getInt());
            wertList.add((double) b.getFloat());
            statusList.add(b.get());
        }
        vReturn = null;
        logger.debug("MassenTableModel filled with " + getRowCount() + " records.");
        return true;
    } catch (XmlRpcException e) {
        MsgBox.error(e.getMessage());
        return false;
    }
}

From source file:com.meidusa.venus.benchmark.FileLineRandomData.java

private void goNextNewLineHead(ByteBuffer buffer, int position) {
    if (closed)/*from  w  ww.j  ava 2s .  c  o m*/
        throw new IllegalStateException("file closed..");
    buffer.position(position);
    boolean eol = false;
    int c = -1; // NOPMD by structchen on 13-10-21 ?12:22
    while (!eol) {
        switch (c = buffer.get()) {
        case -1:
        case '\n':
            eol = true;
            break;
        case '\r':
            eol = true;
            int cur = buffer.position();
            if ((buffer.get()) != '\n') {
                buffer.position(cur);
            }
            break;
        }
        if (!eol) {
            if (position > 0) {
                buffer.position(--position);
            } else {
                eol = true;
            }
        }
    }
}

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

/**
 * Constructs a {@link PcpResponse} object by parsing a buffer.
 * @param buffer buffer containing PCP 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 2}), or if the r-flag isn't
 * set, or if there's an unsuccessful/unrecognized result code
 *//* w  ww  .ja  v a2  s. c  om*/
PcpResponse(ByteBuffer buffer) {
    Validate.notNull(buffer);

    if (buffer.remaining() < 4 || buffer.remaining() > 1100 || buffer.remaining() % 4 != 0) {
        throw new IllegalArgumentException("Bad packet size: " + buffer.remaining());
    }

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

    int temp = buffer.get() & 0xFF;
    Validate.isTrue((temp & 128) == 128, "Bad R-flag: %d", temp);
    op = temp & 0x7F; // discard first bit, it was used for rflag

    buffer.get(); // skip reserved field

    int resultCodeNum = buffer.get() & 0xFF;
    PcpResultCode[] resultCodes = PcpResultCode.values();

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

    lifetime = buffer.getInt() & 0xFFFFFFFFL;

    epochTime = buffer.getInt() & 0xFFFFFFFFL;

    for (int i = 0; i < 12; i++) {
        buffer.get();
        //Validate.isTrue(buffer.get() == 0, "Reserved space indicates unsuccessful response");
    }

    options = Collections.emptyList();
}

From source file:au.org.ala.delta.io.BinFile.java

public byte readByte() {
    ByteBuffer b = readByteBuffer(1);
    _stats.ReadByte++;
    return b.get();
}

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//www  . j  a  va  2s.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;
}