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:edu.tsinghua.lumaqq.qq.Util.java

/**
 * buf???buf?lenbyte??// w  ww  . j a va  2s  . c  o m
 * <p>
 * ?buf??buf????
 * ?buf???len???
 * </p>
 * <p>
 * QQ???GBK?
 * </p>
 * 
 * @param buf
 *          ByteBuffer          
 * @return 
 */
public static String getString(ByteBuffer buf, int len) {
    baos.reset();
    while (buf.hasRemaining() && len-- > 0) {
        baos.write(buf.get());
    }
    return getString(baos.toByteArray());
}

From source file:com.sm.connector.server.MRStore.java

@Override
public void setCurrent(int current) {
    if (current >= getTotalRecord())
        throw new RuntimeException("current " + current + " >= total " + getTotalRecord());
    else {/*from  w w  w  .  j  a  va  2 s  .co m*/
        curRecord = current;
        if (current == 0)
            return;
        //set 3 channel position
        long pos = OFFSET + (long) getCurRecord() * RECORD_SIZE;
        try {
            //read the first index record
            ByteBuffer buf = ByteBuffer.allocate(RECORD_SIZE);
            //re read the index buffer
            indexChannel.read(buf, pos);
            buf.rewind();
            long len = indexChannel.read(indexBuf, pos);
            indexBuf.rewind();
            indexPos = pos + len;
            // data and key pos, need to get from previous index record
            buf.get(); //get status byte
            long key = buf.getLong();
            long keyOff = getOffset(key);
            //long keyLen = getLen( key);
            len = keyChannel.read(keyBuf, keyOff);
            keyBuf.rewind();
            keyPos = keyOff + len;
            //read data channel
            long dataOffset2Len = buf.getLong();
            //long block2version = buf.getLong();
            long dataLen = getLen(dataOffset2Len);
            long offset = getOffset(dataOffset2Len);
            //long blockSize = getSize( block2version);
            len = dataChannel.read(dataBuf, offset);
            dataBuf.rewind();
            dataPos = offset + len;
        } catch (IOException ex) {
            throw new RuntimeException(ex.getMessage(), ex);
        }
    }
}

From source file:edu.tsinghua.lumaqq.qq.Util.java

/**
 * buf???delimit?maxLenbyte//ww w. ja  v a2s . c o m
 * ??
 * <p>
 * ?buf??buf????
 * ?buf???maxLen?
 * </p>
 * <p>
 * QQ???GBK?
 * </p>
 * 
 * @param buf
 *          ByteBuffer
 * @param delimit
 *          delimit
 * @param maxLen
 *          max len to read
 * @return String
 */
public static String getString(ByteBuffer buf, byte delimit, int maxLen) {
    baos.reset();
    while (buf.hasRemaining() && maxLen-- > 0) {
        byte b = buf.get();
        if (b == delimit)
            break;
        else
            baos.write(b);
    }
    while (buf.hasRemaining() && maxLen-- > 0)
        buf.get();
    return getString(baos.toByteArray());
}

From source file:com.healthmarketscience.jackcess.impl.IndexImpl.java

protected IndexImpl(ByteBuffer tableBuffer, List<IndexData> indexDatas, JetFormat format) throws IOException {

    ByteUtil.forward(tableBuffer, format.SKIP_BEFORE_INDEX_SLOT); //Forward past Unknown
    _indexNumber = tableBuffer.getInt();
    int indexDataNumber = tableBuffer.getInt();

    // read foreign key reference info
    byte relIndexType = tableBuffer.get();
    int relIndexNumber = tableBuffer.getInt();
    int relTablePageNumber = tableBuffer.getInt();
    byte cascadeUpdatesFlag = tableBuffer.get();
    byte cascadeDeletesFlag = tableBuffer.get();

    _indexType = tableBuffer.get();/*from w w  w  . j  a v  a  2  s.  c o m*/

    if ((_indexType == FOREIGN_KEY_INDEX_TYPE) && (relIndexNumber != INVALID_INDEX_NUMBER)) {
        _reference = new ForeignKeyReference(relIndexType, relIndexNumber, relTablePageNumber,
                (cascadeUpdatesFlag == CASCADE_UPDATES_FLAG), (cascadeDeletesFlag == CASCADE_DELETES_FLAG));
    } else {
        _reference = null;
    }

    ByteUtil.forward(tableBuffer, format.SKIP_AFTER_INDEX_SLOT); //Skip past Unknown

    _data = indexDatas.get(indexDataNumber);

    _data.addIndex(this);
}

From source file:it.crs4.seal.recab.RecabTableMapper.java

protected void processMapping(AbstractTaggedMapping currentMapping, IMRContext<Text, ObservationCount> context)
        throws IOException, InterruptedException {
    context.increment(ReadCounters.Processed, 1);
    context.increment(BaseCounters.All, currentMapping.getLength());

    if (readFailsFilters(currentMapping))
        return;/*  ww w.  jav a 2s  . com*/

    final String contig = currentMapping.getContig();

    int left, right; // left and right "limits" within the current sequence
    if (currentMapping.isTemplateLengthAvailable()
            && currentMapping.getTemplateLength() < currentMapping.getLength()) {
        // Insert size is less than the read size, so we've sequenced part of the read adapter.
        // We need to trim it the last read_length - insert_size bases sequenced.
        if (currentMapping.isOnReverse()) {
            // trim from front
            left = currentMapping.getLength() - currentMapping.getTemplateLength();
            right = currentMapping.getLength();
        } else {
            // trim from the back
            left = 0;
            right = currentMapping.getTemplateLength();
        }

        context.increment(BaseCounters.AdaptorBasesTrimmed, currentMapping.getLength() - (right - left));
    } else {
        left = 0;
        right = currentMapping.getLength();
    }

    currentMapping.calculateReferenceCoordinates(referenceCoordinates);
    currentMapping.calculateReferenceMatches(referenceMatches);

    for (Covariate cov : covariateList)
        cov.applyToMapping(currentMapping);

    final ByteBuffer seq = currentMapping.getSequence();
    final ByteBuffer qual = currentMapping.getBaseQualities();

    if (left > 0) {
        // we're using a relative get() method in the loop below, so here we
        // advance the buffer position to our starting point.
        seq.position(seq.position() + left);
        qual.position(qual.position() + left);
    }

    for (int i = left; i < right; ++i) {
        byte base = seq.get();
        byte quality = qual.get();

        if (base == 'N' || quality <= SANGER_OFFSET)
            context.increment(BaseCounters.BadBases, 1);
        else {
            int pos = referenceCoordinates.get(i);
            if (pos > 0) // valid reference position
            {
                // is it a known variation site?
                if (skipKnownVariantPositions && snps.isVariantLocation(contig, pos)) {
                    context.increment(BaseCounters.VariantBases, 1);

                    if (!referenceMatches.get(i))
                        context.increment(BaseCounters.VariantMismatches, 1);
                } else {
                    // use this base
                    context.increment(BaseCounters.Used, 1);

                    key.clear();
                    for (Covariate cov : covariateList) {
                        String tmp = cov.getValue(i);
                        key.append(tmp.getBytes(RecabTable.ASCII), 0, tmp.length());
                        key.append(RecabTable.TableDelimBytes, 0, RecabTable.TableDelimBytes.length);
                    }

                    boolean match = referenceMatches.get(i);
                    if (match) {
                        value.set(1, 0); // (num observations, num mismatches)
                    } else { // mismatch
                        context.increment(BaseCounters.NonVariantMismatches, 1);
                        value.set(1, 1);
                    }

                    context.write(key, value);
                }
            }
        }
    }
}

From source file:net.sf.jinsim.response.ResponseFactory.java

public InSimResponse getPacketData(ByteBuffer buffer) throws UnhandledPacketTypeException,
        BufferUnderflowException, InstantiationException, IllegalAccessException {
    InSimResponse insimResponse = null;/*from  w w  w  .  ja va2  s  .c  om*/
    /*
    if (buffer.limit() == 91) {
       // is OutGauge message
       insimResponse = new OutGaugeResponse();
    } else if (buffer.limit() == 63) {
       // is OutSim message
               
       log.debug("OutSim is not processed");
    } else 
     */
    if (buffer.limit() >= 3) {
        int packetId = buffer.get() & 0xFF;
        PacketType packetType = PacketType.getPacket(packetId);
        /*
        if (log.isDebugEnabled()) {
           log.debug("Packet is of type " + packetType);
        }
        */
        Class<? extends InSimResponse> insimResponseClass = (Class<? extends InSimResponse>) registeredTypes
                .get(packetType);
        if (insimResponseClass == null) {
            buffer.position(buffer.limit());
            throw new UnhandledPacketTypeException(packetId + ": is unkown");
        }
        insimResponse = (InSimResponse) insimResponseClass.newInstance();
    } else {
        if (log.isDebugEnabled()) {
            String bufferBytes = "";
            for (int i = 0; i < buffer.limit(); i++) {
                bufferBytes += buffer.get() + ", ";
            }
            log.debug("unknown packet: " + bufferBytes);
        } else {
            buffer.position(buffer.limit());
        }
    }

    if (insimResponse == null) {
        throw new UnhandledPacketTypeException("Can not identify response packet");
    }
    try {
        insimResponse.construct(buffer);
    } catch (BufferUnderflowException ex) {
        log.error(ex);
    }
    /*
     if (log.isDebugEnabled()) {
        log.debug("InSimResponse {packet size= " + (buffer.limit()+1) + "}: " + insimResponse);
     }
     */
    return insimResponse;
}

From source file:io.github.dsheirer.source.tuner.hackrf.HackRFTunerController.java

public int readByte(Request request, int value, int index, boolean signed) throws UsbException {
    ByteBuffer buffer = readArray(request, value, index, 1);

    if (signed) {
        return (int) (buffer.get());
    } else {/*w  w w . ja v  a2  s  . co  m*/
        return (int) (buffer.get() & 0xFF);
    }
}

From source file:com.healthmarketscience.jackcess.Index.java

protected Index(ByteBuffer tableBuffer, List<IndexData> indexDatas, JetFormat format) throws IOException {

    ByteUtil.forward(tableBuffer, format.SKIP_BEFORE_INDEX_SLOT); //Forward past Unknown
    _indexNumber = tableBuffer.getInt();
    int indexDataNumber = tableBuffer.getInt();

    // read foreign key reference info
    byte relIndexType = tableBuffer.get();
    int relIndexNumber = tableBuffer.getInt();
    int relTablePageNumber = tableBuffer.getInt();
    byte cascadeUpdatesFlag = tableBuffer.get();
    byte cascadeDeletesFlag = tableBuffer.get();

    _indexType = tableBuffer.get();// www. ja  v  a2s.co m

    if ((_indexType == FOREIGN_KEY_INDEX_TYPE) && (relIndexNumber != INVALID_INDEX_NUMBER)) {
        _reference = new ForeignKeyReference(relIndexType, relIndexNumber, relTablePageNumber,
                (cascadeUpdatesFlag == CASCADE_UPDATES_FLAG), (cascadeDeletesFlag == CASCADE_DELETES_FLAG));
    } else {
        _reference = null;
    }

    ByteUtil.forward(tableBuffer, format.SKIP_AFTER_INDEX_SLOT); //Skip past Unknown

    _data = indexDatas.get(indexDataNumber);

    _data.addIndex(this);
}

From source file:ed.net.lb.LBCall.java

protected WhatToDo handleRead(ByteBuffer buf, Connection conn) {

    _logger.debug(3, "handleRead  _state:" + _state);

    if (_state == State.WAITING || _state == State.IN_HEADER) {
        // TODO: should i read this all in at once                
        if (_line == null)
            _line = new StringBuilder();
        while (buf.hasRemaining()) {
            char c = (char) buf.get();
            if (c == '\r')
                continue;
            if (c == '\n') {
                if (_line.length() == 0) {
                    _logger.debug(3, "end of header");
                    _state = State.READY_TO_STREAM;
                    break;
                }/* www  .  j a  v a  2s  . c  om*/

                String line = _line.toString();

                if (_state == State.WAITING) {
                    int idx = line.indexOf(" ");
                    if (idx < 0) {
                        backendError(ServerErrorType.INVALID, "invalid first line [" + line + "]");
                        return WhatToDo.ERROR;
                    }
                    line = line.substring(idx + 1).trim();
                    idx = line.indexOf(" ");
                    if (idx < 0)
                        _response.setResponseCode(Integer.parseInt(line));
                    else
                        _response.setStatus(Integer.parseInt(line.substring(0, idx)),
                                line.substring(idx + 1).trim());

                    _logger.debug(3, "got first line ", line);
                    _state = State.IN_HEADER;
                } else {
                    int idx = line.indexOf(":");
                    if (idx < 0) {
                        backendError(ServerErrorType.INVALID, "invalid line [ " + line + "]");
                        return WhatToDo.ERROR;
                    }
                    String name = line.substring(0, idx);
                    String value = line.substring(idx + 1).trim();
                    _logger.debug(3, "got header line ", line);

                    if (name.equalsIgnoreCase("Connection")) {
                        _keepalive = !value.toLowerCase().contains("close");
                    } else {
                        _response.addHeader(name, value);
                    }

                }
                _line.setLength(0);
                continue;
            }
            _line.append(c);
        }

        if (_state != State.READY_TO_STREAM)
            return WhatToDo.CONTINUE;

        _logger.debug(3, "starting to stream data");
    }

    if (_state == State.READY_TO_STREAM) {
        MyChunk chunk = new MyChunk(this, conn, _response.getContentLength(), buf);
        _response.sendFile(new MySender(chunk));
        _state = State.STREAMING;
    }

    try {
        _response.done();
    } catch (IOException ioe) {
        _logger.debug(1, "client error", ioe);
        return WhatToDo.CLIENT_ERROR;
    }

    if (isDone() && !_keepalive)
        return WhatToDo.DONE_AND_CLOSE;

    if (_request.isHeadRequest()) {
        assert (_response.isFullySent());
        _lbsuccess(conn);
        return WhatToDo.DONE_AND_CONTINUE;
    }

    return WhatToDo.PAUSE;
}

From source file:io.fabric8.maven.docker.access.log.LogRequestor.java

private boolean readStreamFrame(InputStream is) throws IOException, LogCallback.DoneException {
    // Read the header, which is composed of eight bytes. The first byte is an integer
    // indicating the stream type (0 = stdin, 1 = stdout, 2 = stderr), the next three are thrown
    // out, and the final four are the size of the remaining stream as an integer.
    ByteBuffer headerBuffer = ByteBuffer.allocate(8);
    headerBuffer.order(ByteOrder.BIG_ENDIAN);
    try {//from   w  w  w  .jav  a  2  s  . co  m
        this.readFully(is, headerBuffer.array());
    } catch (NoBytesReadException e) {
        // Not bytes read for stream. Return false to stop consuming stream.
        return false;
    } catch (EOFException e) {
        throw new IOException("Failed to read log header. Could not read all 8 bytes. " + e.getMessage(), e);
    }

    // Grab the stream type (stdout, stderr, stdin) from first byte and throw away other 3 bytes.
    int type = headerBuffer.get();

    // Skip three bytes, then read size from remaining four bytes.
    int size = headerBuffer.getInt(4);

    // Ignore empty messages and keep reading.
    if (size <= 0) {
        return true;
    }

    // Read the actual message
    ByteBuffer payload = ByteBuffer.allocate(size);
    try {
        ByteStreams.readFully(is, payload.array());
    } catch (EOFException e) {
        throw new IOException("Failed to read log message. Could not read all " + size + " bytes. "
                + e.getMessage() + " [ Header: " + Hex.encodeHexString(headerBuffer.array()) + "]", e);
    }

    String message = Charsets.UTF_8.newDecoder().decode(payload).toString();
    callLogCallback(type, message);
    return true;
}