Example usage for java.nio ByteBuffer position

List of usage examples for java.nio ByteBuffer position

Introduction

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

Prototype

public final Buffer position(int newPosition) 

Source Link

Document

Sets the position of this buffer.

Usage

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

/**
 * @return the current database password, or {@code null} if none set.
 * @usage _general_method_/*from w  w w.j  a v a  2  s .c o m*/
 */
public String getDatabasePassword() throws IOException {
    ByteBuffer buffer = takeSharedBuffer();
    try {
        _pageChannel.readPage(buffer, 0);

        byte[] pwdBytes = new byte[_format.SIZE_PASSWORD];
        buffer.position(_format.OFFSET_PASSWORD);
        buffer.get(pwdBytes);

        // de-mask password using extra password mask if necessary (the extra
        // password mask is generated from the database creation date stored in
        // the header)
        byte[] pwdMask = getPasswordMask(buffer, _format);
        if (pwdMask != null) {
            for (int i = 0; i < pwdBytes.length; ++i) {
                pwdBytes[i] ^= pwdMask[i % pwdMask.length];
            }
        }

        boolean hasPassword = false;
        for (int i = 0; i < pwdBytes.length; ++i) {
            if (pwdBytes[i] != 0) {
                hasPassword = true;
                break;
            }
        }

        if (!hasPassword) {
            return null;
        }

        String pwd = Column.decodeUncompressedText(pwdBytes, getCharset());

        // remove any trailing null chars
        int idx = pwd.indexOf('\0');
        if (idx >= 0) {
            pwd = pwd.substring(0, idx);
        }

        return pwd;
    } finally {
        releaseSharedBuffer(buffer);
    }
}

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

private void readColumnDefinitions(ByteBuffer tableBuffer, short columnCount) throws IOException {
    int colOffset = getFormat().OFFSET_INDEX_DEF_BLOCK + _indexCount * getFormat().SIZE_INDEX_DEFINITION;

    tableBuffer.position(colOffset + (columnCount * getFormat().SIZE_COLUMN_HEADER));
    List<String> colNames = new ArrayList<String>(columnCount);
    for (int i = 0; i < columnCount; i++) {
        colNames.add(readName(tableBuffer));
    }/*from  w  w w  .  j  av a2s. com*/

    int dispIndex = 0;
    for (int i = 0; i < columnCount; i++) {
        ColumnImpl column = ColumnImpl.create(this, tableBuffer,
                colOffset + (i * getFormat().SIZE_COLUMN_HEADER), colNames.get(i), dispIndex++);
        _columns.add(column);
        if (column.isVariableLength()) {
            // also shove it in the variable columns list, which is ordered
            // differently from the _columns list
            _varColumns.add(column);
        }
    }

    Collections.sort(_columns);
    getAutoNumberColumns();

    // setup the data index for the columns
    int colIdx = 0;
    for (ColumnImpl col : _columns) {
        col.setColumnIndex(colIdx++);
    }

    // sort variable length columns based on their index into the variable
    // length offset table, because we will write the columns in this order
    Collections.sort(_varColumns, VAR_LEN_COLUMN_COMPARATOR);
}

From source file:com.yobidrive.diskmap.needles.NeedleManager.java

/** Loads the needle pointed by the needlePointer and checks for validity (checksum, ...) and returns the next linked needle
 * @param needlePointer//w ww .ja  va  2  s. com
 * @param needle
 * @return a chained needle if the read is successful, otherwise null
 * @throws NeedleManagerException
 */
public Needle getNeedleFromDisk(NeedlePointer needlePointer) throws NeedleManagerException {
    ByteBuffer needleBuffer = null;
    try {

        FileChannel fc = getChannel(needlePointer.getNeedleFileNumber());
        if (fc == null)
            return new Needle();
        // Position and read needle for check
        long position = needlePointer.getNeedleOffset();
        // Acquires a ByteBuffer
        if (threadBufferQ == null)
            return new Needle();
        Chrono chr = new Chrono();
        needleBuffer = threadBufferQ.take();
        chr.lap("Wait for thread buffer ", 20);
        // Finally we have a buffer
        needleBuffer.rewind();
        needleBuffer.limit(MAXKEYSIZE + MAXVERSIONSIZE + Needle.NEEDLEOVERHEAD);

        // First read header to know the data size
        int readBytes = 0, totalHeaderReadBytes = 0;
        while (readBytes >= 0 && totalHeaderReadBytes < needleBuffer.limit()) {
            readBytes = fc.read(needleBuffer, position + totalHeaderReadBytes);
            totalHeaderReadBytes += readBytes;
        }
        if (totalHeaderReadBytes <= 0)
            return new Needle();

        Needle needle = new Needle();
        if (!needle.getNeedleHeaderFromBuffer(needleBuffer)) {
            return new Needle(); // Incorrect header
        }
        // Needle Header is OK, read the rest until end of needle. Change limit to include data
        // needleBuffer.rewind() ;
        needleBuffer.position(totalHeaderReadBytes);
        // needleBuffer.limit(needle.getPostDataSize()) ;
        needleBuffer.limit(needle.getTotalSizeFromData());

        readBytes = 0;
        int totalContentReadBytes = 0;
        while (readBytes >= 0 && totalContentReadBytes < needleBuffer.limit() - totalHeaderReadBytes) {
            readBytes = fc.read(needleBuffer, position + totalHeaderReadBytes + totalContentReadBytes);
            totalContentReadBytes += readBytes;
        }
        // readBytes = fc.read(needleBuffer, position+needle.getHeaderSize()) ;
        // Parse data and verifies checksum
        // 
        needleBuffer.rewind();
        needleBuffer.position(needle.getHeaderSize());
        if (!needle.getNeedleDataFromBuffer(needleBuffer))
            return new Needle();
        // Now needle is parsed and OK
        chr.total("Read from disk ", 20);
        return needle;
    } catch (Throwable th) {
        logger.error("Error reading needle at " + needlePointer.getFormattedNeedleFileNumber() + "/"
                + needlePointer.getFormattedNeedleOffset(), th);
        throw new NeedleManagerException();
    } finally {
        if (needleBuffer != null) {
            try {
                threadBufferQ.put(needleBuffer);
            } catch (InterruptedException ie) {
                throw new BucketTableManagerException("Error giving back needle read thread", ie);
            }
        }
    }
}

From source file:com.inclouds.hbase.rowcache.RowCache.java

/**
 * CHECKED 2./*ww w.ja v  a2  s .  c o  m*/
 * 
 * @param buf
 *          the buf
 * @param skip
 *          the skip
 */
private final void skip(ByteBuffer buf, int skip) {
    buf.position(buf.position() + skip);
}

From source file:eu.abc4trust.smartcard.HardwareSmartcard.java

public SmartcardStatusCode setWorkingMode() {
    ByteBuffer buf = ByteBuffer.allocate(4);
    buf.put(new byte[] { (byte) this.ABC4TRUSTCMD, this.setWorkingMode, 0, 0 });
    buf.position(0);
    try {/*from   w  w  w .  ja v a  2 s.  co  m*/
        System.out.println("Input for setWorkingMode: " + Arrays.toString(buf.array()));
        ResponseAPDU response = this.transmitCommand(new CommandAPDU(buf));
        System.out.println("response from setWorkingMode: " + response);
        return this.evaluateStatus(response);
    } catch (CardException e) {
        return SmartcardStatusCode.NOT_FOUND;
    }
}

From source file:eu.abc4trust.smartcard.HardwareSmartcard.java

public int getMode() {
    try {//from  w  w  w .  java2 s.  co m
        ByteBuffer buf = ByteBuffer.allocate(5);
        buf.put(new byte[] { (byte) this.ABC4TRUSTCMD, this.getMode, 0, 0, 1 });
        buf.position(0);
        System.out.println("Input to GetMode: " + Arrays.toString(buf.array()));
        ResponseAPDU response = this.transmitCommand(new CommandAPDU(buf));
        System.out.println("Reponse from getMode: " + response);
        if (this.evaluateStatus(response) == SmartcardStatusCode.OK) {
            return response.getData()[0];
        }
    } catch (CardException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return -1;
}

From source file:eu.abc4trust.smartcard.HardwareSmartcard.java

private SmartcardStatusCode setGenerator(int mode, byte[] g, int groupID, int genID, RSAKeyPair rootKey)
        throws CardException {
    g = this.removeSignBit(g);

    byte[] data = new byte[2];
    data[0] = (byte) groupID;
    data[1] = (byte) genID;
    if (mode == 1) {
        this.putData(g);
    } else {// w w  w . j  a v a2  s .  c  o  m
        System.out.println("Can only use setGenerator in root mode");
        return SmartcardStatusCode.UNAUTHORIZED;
    }
    ByteBuffer buf = ByteBuffer.allocate(7);
    buf.put(new byte[] { (byte) this.ABC4TRUSTCMD, this.setGenerator, 0, 0, 2, (byte) groupID, (byte) genID });
    buf.position(0);
    System.out.println("Input for set Generator: " + Arrays.toString(buf.array()));
    ResponseAPDU response = this.transmitCommand(new CommandAPDU(buf));
    System.out.println("Response from setGenerator: " + response);
    return this.evaluateStatus(response);
}

From source file:eu.abc4trust.smartcard.HardwareSmartcard.java

@Override
public SmartcardStatusCode changePin(int pin, int newPin) {
    byte[] data = new byte[8];
    System.arraycopy(this.pinToByteArr(pin), 0, data, 0, 4);
    System.arraycopy(this.pinToByteArr(newPin), 0, data, 4, 4);
    try {// w  w w  .  ja  va  2  s.  c o  m
        ByteBuffer buf = ByteBuffer.allocate(13);
        buf.put(new byte[] { (byte) this.ABC4TRUSTCMD, this.changePin, 0, 0, 8 });
        buf.put(data);
        buf.position(0);
        if (printInput)
            System.out.println("Input for changePin: " + Arrays.toString(buf.array()));
        ResponseAPDU response = this.transmitCommand(new CommandAPDU(buf));
        System.out.println("Response from changePin: " + response);
        return this.evaluateStatus(response);
    } catch (CardException e) {
        e.printStackTrace();
        return SmartcardStatusCode.NOT_FOUND;
    }
}

From source file:eu.abc4trust.smartcard.HardwareSmartcard.java

public SmartcardStatusCode setRootMode(byte[] accesscode) {
    try {/*w  ww. j a v  a  2s .  c  o  m*/
        ByteBuffer buf = ByteBuffer.allocate(13);
        buf.put(new byte[] { (byte) this.ABC4TRUSTCMD, this.setRootMode, 0, 0, 8 });
        buf.put(accesscode);
        buf.position(0);
        System.out.println("Input to setRootMode: " + Arrays.toString(buf.array()));
        ResponseAPDU response = this.transmitCommand(new CommandAPDU(buf));
        System.out.println("response from setRootMode: " + response);
        return this.evaluateStatus(response);
    } catch (CardException e) {
        return SmartcardStatusCode.NOT_FOUND;
    }
}

From source file:eu.abc4trust.smartcard.HardwareSmartcard.java

private SmartcardStatusCode setCounter(int counterID, int keyID, int index, int threshold, byte[] cursor,
        RSAKeyPair rootKey) {// www . j a  v a  2s .c  om
    if (cursor.length != 4) {
        throw new RuntimeException("Cursor should be of length 4");
    }
    byte[] data = new byte[8];
    data[0] = (byte) counterID;
    data[1] = (byte) keyID;
    data[2] = (byte) index;
    data[3] = (byte) threshold;
    System.arraycopy(cursor, 0, data, 4, 4);
    try {
        int mode = this.getMode();
        if (mode == 2) {
            System.out.println("Can only use setCounter in root mode");
            return SmartcardStatusCode.UNAUTHORIZED;
        }
        ByteBuffer buf = ByteBuffer.allocate(13);
        buf.put(new byte[] { (byte) this.ABC4TRUSTCMD, this.setCounter, 0, 0, 8 });
        buf.put(data);
        buf.position(0);
        System.out.println("Input for setCounter: " + Arrays.toString(buf.array()));
        ResponseAPDU response = this.transmitCommand(new CommandAPDU(buf));
        System.out.println("Response from setCounter: " + response);
        return this.evaluateStatus(response);
    } catch (CardException e) {
        return SmartcardStatusCode.NOT_FOUND;
    }
}