Example usage for java.nio ByteBuffer put

List of usage examples for java.nio ByteBuffer put

Introduction

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

Prototype

public ByteBuffer put(ByteBuffer src) 

Source Link

Document

Writes all the remaining bytes of the src byte buffer to this buffer's current position, and increases both buffers' position by the number of bytes copied.

Usage

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

public SmartcardStatusCode addUProveIssuerParametersWithAttendanceCheck(RSAKeyPair rootKey, URI parametersUri,
        int keyIDForCounter, UProveParams uProveParams, RSAVerificationKey courseKey, int minimumAttendance) {
    byte issuerID = this.getNewIssuerID(parametersUri);
    byte groupID = issuerID;
    byte genID1 = 1;
    byte genID2 = 0; //Not used in UProve, thus set to 0.
    byte numPres = 0; //unlimited presentations - limit not used in the pilot
    byte counterID = issuerID;
    ByteBuffer buf = ByteBuffer.allocate(11);
    //SET ISSUER(BYTE issuerID, groupID, genID1, genID2, numpres, counterID)
    byte[] data = new byte[] { issuerID, groupID, genID1, genID2, numPres, counterID };
    buf.put(new byte[] { (byte) this.ABC4TRUSTCMD, this.setIssuer, 0, 0, 6 });
    buf.put(data);/* w ww. j ava  2  s  .  c om*/
    buf.position(0);

    try {
        //Before setting the issuer, we must create a group, generators as well as a counter
        int mode = this.getMode();
        this.setGroupComponent(mode, uProveParams.p.toByteArray(), groupID, 0, rootKey);
        this.setGroupComponent(mode, uProveParams.q.toByteArray(), groupID, 1, rootKey);
        this.setGroupComponent(mode, uProveParams.f.toByteArray(), groupID, 2, rootKey);
        System.out.println("p: " + uProveParams.p);
        System.out.println("q: " + uProveParams.q);
        System.out.println("g: " + uProveParams.g);
        System.out.println("f: " + uProveParams.f);
        this.setGenerator(mode, uProveParams.g.toByteArray(), groupID, genID1, rootKey);

        byte[] cursor = this.getNewCursor(0);

        //Create a new key with keyID that counter can use.
        this.setAuthenticationKey(courseKey.n, keyIDForCounter, rootKey);
        this.setCounter(counterID, keyIDForCounter, 0, minimumAttendance, cursor, rootKey);

        //prior to the actual command,if we are in working mode,
        //we have to authenticate the input data first.
        if (mode == 2) {
            System.out.println("Can only use addIssuerParameters in root mode");
            return SmartcardStatusCode.UNAUTHORIZED;
        }

        System.out.println("Input for setIssuer: " + Arrays.toString(buf.array()));
        ResponseAPDU response = this.transmitCommand(new CommandAPDU(buf));
        System.out.println("Response from setIssuer: " + response);
        if (evaluateStatus(response) == SmartcardStatusCode.OK) {
            //               SmartcardStatusCode code = this.storeIssuerUriAndID(pin, parametersUri, issuerID);
            //               if(code != SmartcardStatusCode.OK){
            //                  System.err.println("Could not store the issuerURI and ID on the card, but the issuer itself is still stored on the card. Returned code: " + code);
            //                  return code;
            //               }
        }
        return this.evaluateStatus(response);
    } catch (CardException e) {
        //TODO: Error handling. Remove stuff again if something fails.
        e.printStackTrace();
        return SmartcardStatusCode.NOT_FOUND;
    }
}

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

/**
 * Writes the index definitions into a table definition buffer.
 * @param buffer Buffer to write to/* w  w w. j  a v  a2  s. c  o  m*/
 * @param indexes List of IndexBuilders to write definitions for
 */
protected static void writeDefinitions(TableCreator creator, ByteBuffer buffer) throws IOException {
    ByteBuffer rootPageBuffer = creator.getPageChannel().createPageBuffer();
    writeDataPage(rootPageBuffer, NEW_ROOT_DATA_PAGE, creator.getTdefPageNumber(), creator.getFormat());

    for (IndexBuilder idx : creator.getIndexes()) {
        buffer.putInt(MAGIC_INDEX_NUMBER); // seemingly constant magic value

        // write column information (always MAX_COLUMNS entries)
        List<IndexBuilder.Column> idxColumns = idx.getColumns();
        for (int i = 0; i < MAX_COLUMNS; ++i) {

            short columnNumber = COLUMN_UNUSED;
            byte flags = 0;

            if (i < idxColumns.size()) {

                // determine column info
                IndexBuilder.Column idxCol = idxColumns.get(i);
                flags = idxCol.getFlags();

                // find actual table column number
                for (ColumnBuilder col : creator.getColumns()) {
                    if (col.getName().equalsIgnoreCase(idxCol.getName())) {
                        columnNumber = col.getColumnNumber();
                        break;
                    }
                }
                if (columnNumber == COLUMN_UNUSED) {
                    // should never happen as this is validated before
                    throw new IllegalArgumentException("Column with name " + idxCol.getName() + " not found");
                }
            }

            buffer.putShort(columnNumber); // table column number
            buffer.put(flags); // column flags (e.g. ordering)
        }

        TableCreator.IndexState idxState = creator.getIndexState(idx);

        buffer.put(idxState.getUmapRowNumber()); // umap row
        ByteUtil.put3ByteInt(buffer, creator.getUmapPageNumber()); // umap page

        // write empty root index page
        creator.getPageChannel().writePage(rootPageBuffer, idxState.getRootPageNumber());

        buffer.putInt(idxState.getRootPageNumber());
        buffer.putInt(0); // unknown
        buffer.put(idx.getFlags()); // index flags (unique, etc.)
        ByteUtil.forward(buffer, 5); // unknown
    }
}

From source file:edu.hawaii.soest.pacioos.text.SocketTextSource.java

@Override
protected boolean execute() {

    log.debug("SocketTextSource.execute() called.");
    // do not execute the stream if there is no connection
    if (!isConnected())
        return false;

    boolean failed = false;

    /* Get a connection to the instrument */
    SocketChannel socket = getSocketConnection();
    if (socket == null)
        return false;

    // while data are being sent, read them into the buffer
    try {// w  w  w .  ja  va 2  s. c o m
        // create four byte placeholders used to evaluate up to a four-byte 
        // window.  The FIFO layout looks like:
        //           -------------------------
        //   in ---> | One | Two |Three|Four |  ---> out
        //           -------------------------
        byte byteOne = 0x00, // set initial placeholder values
                byteTwo = 0x00, byteThree = 0x00, byteFour = 0x00;

        // Create a buffer that will store the sample bytes as they are read
        ByteBuffer sampleBuffer = ByteBuffer.allocate(getBufferSize());

        // create a byte buffer to store bytes from the TCP stream
        ByteBuffer buffer = ByteBuffer.allocateDirect(getBufferSize());

        // while there are bytes to read from the socket ...
        while (socket.read(buffer) != -1 || buffer.position() > 0) {

            // prepare the buffer for reading
            buffer.flip();

            // while there are unread bytes in the ByteBuffer
            while (buffer.hasRemaining()) {
                byteOne = buffer.get();

                // log the byte stream
                String character = new String(new byte[] { byteOne });
                if (log.isDebugEnabled()) {
                    List<Byte> whitespaceBytes = new ArrayList<Byte>();
                    whitespaceBytes.add(new Byte((byte) 0x0A));
                    whitespaceBytes.add(new Byte((byte) 0x0D));
                    if (whitespaceBytes.contains(new Byte(byteOne))) {
                        character = new String(Hex.encodeHex((new byte[] { byteOne })));

                    }
                }
                log.debug("char: " + character + "\t" + "b1: "
                        + new String(Hex.encodeHex((new byte[] { byteOne }))) + "\t" + "b2: "
                        + new String(Hex.encodeHex((new byte[] { byteTwo }))) + "\t" + "b3: "
                        + new String(Hex.encodeHex((new byte[] { byteThree }))) + "\t" + "b4: "
                        + new String(Hex.encodeHex((new byte[] { byteFour }))) + "\t" + "sample pos: "
                        + sampleBuffer.position() + "\t" + "sample rem: " + sampleBuffer.remaining() + "\t"
                        + "sample cnt: " + sampleByteCount + "\t" + "buffer pos: " + buffer.position() + "\t"
                        + "buffer rem: " + buffer.remaining() + "\t" + "state: " + state);

                // evaluate each byte to find the record delimiter(s), and when found, validate and
                // send the sample to the DataTurbine.
                int numberOfChannelsFlushed = 0;

                if (getRecordDelimiters().length == 2) {
                    // have we hit the delimiters in the stream yet?
                    if (byteTwo == getFirstDelimiterByte() && byteOne == getSecondDelimiterByte()) {
                        sampleBuffer.put(byteOne);
                        sampleByteCount++;
                        // extract just the length of the sample bytes out of the
                        // sample buffer, and place it in the channel map as a 
                        // byte array.  Then, send it to the DataTurbine.
                        log.debug("Sample byte count: " + sampleByteCount);
                        byte[] sampleArray = new byte[sampleByteCount];
                        sampleBuffer.flip();
                        sampleBuffer.get(sampleArray);
                        String sampleString = new String(sampleArray, "US-ASCII");

                        if (validateSample(sampleString)) {
                            numberOfChannelsFlushed = sendSample(sampleString);

                        }

                        sampleBuffer.clear();
                        sampleByteCount = 0;
                        byteOne = 0x00;
                        byteTwo = 0x00;
                        byteThree = 0x00;
                        byteFour = 0x00;
                        log.debug("Cleared b1,b2,b3,b4. Cleared sampleBuffer. Cleared rbnbChannelMap.");

                    } else {
                        // still in the middle of the sample, keep adding bytes
                        sampleByteCount++; // add each byte found

                        if (sampleBuffer.remaining() > 0) {
                            sampleBuffer.put(byteOne);

                        } else {
                            sampleBuffer.compact();
                            log.debug("Compacting sampleBuffer ...");
                            sampleBuffer.put(byteOne);

                        }

                    }

                } else if (getRecordDelimiters().length == 1) {
                    // have we hit the delimiter in the stream yet?
                    if (byteOne == getFirstDelimiterByte()) {
                        sampleBuffer.put(byteOne);
                        sampleByteCount++;
                        // extract just the length of the sample bytes out of the
                        // sample buffer, and place it in the channel map as a 
                        // byte array.  Then, send it to the DataTurbine.
                        byte[] sampleArray = new byte[sampleByteCount];
                        sampleBuffer.flip();
                        sampleBuffer.get(sampleArray);
                        String sampleString = new String(sampleArray, "US-ASCII");

                        if (validateSample(sampleString)) {
                            numberOfChannelsFlushed = sendSample(sampleString);

                        }

                        sampleBuffer.clear();
                        sampleByteCount = 0;
                        byteOne = 0x00;
                        byteTwo = 0x00;
                        byteThree = 0x00;
                        byteFour = 0x00;
                        log.debug("Cleared b1,b2,b3,b4. Cleared sampleBuffer. Cleared rbnbChannelMap.");

                    } else {
                        // still in the middle of the sample, keep adding bytes
                        sampleByteCount++; // add each byte found

                        if (sampleBuffer.remaining() > 0) {
                            sampleBuffer.put(byteOne);

                        } else {
                            sampleBuffer.compact();
                            log.debug("Compacting sampleBuffer ...");
                            sampleBuffer.put(byteOne);

                        }

                    }

                } // end getRecordDelimiters().length

                // shift the bytes in the FIFO window
                byteFour = byteThree;
                byteThree = byteTwo;
                byteTwo = byteOne;

            } //end while (more unread bytes)

            // prepare the buffer to read in more bytes from the stream
            buffer.compact();

        } // end while (more socket bytes to read)
        socket.close();

    } catch (IOException e) {
        // handle exceptions
        // In the event of an i/o exception, log the exception, and allow execute()
        // to return false, which will prompt a retry.
        failed = true;
        log.error("There was a communication error in sending the data sample. The message was: "
                + e.getMessage());
        if (log.isDebugEnabled()) {
            e.printStackTrace();
        }
        return !failed;

    } catch (SAPIException sapie) {
        // In the event of an RBNB communication  exception, log the exception, 
        // and allow execute() to return false, which will prompt a retry.
        failed = true;
        log.error("There was an RBNB error while sending the data sample. The message was: "
                + sapie.getMessage());
        if (log.isDebugEnabled()) {
            sapie.printStackTrace();
        }
        return !failed;
    }

    return !failed;

}

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

/**
 * CHECKED 2 Prepare key for Get op./* w  ww .  ja v a 2 s  .  co m*/
 * 
 * @param buf
 *          the buf
 * @param tableName
 *          the table name
 * @param row
 *          the row
 * @param offset
 *          the offset
 * @param size
 *          the size
 * @param columnFamily
 *          the column family
 * @param column
 *          the column
 */
private void prepareKeyForGet(ByteBuffer buf, byte[] tableName, byte[] row, int offset, int size,
        byte[] columnFamily, byte[] column) {

    buf.clear();
    int totalSize = 2 + tableName.length + // table
            2 + size + // row
            ((columnFamily != null) ? (2 + columnFamily.length) : 0) + // family
            ((column != null) ? (4 + column.length) : 0); // column
    buf.putInt(totalSize);
    // 4 bytes to keep key length;
    buf.putShort((short) tableName.length);
    buf.put(tableName);
    buf.putShort((short) size);
    buf.put(row, offset, size);
    if (columnFamily != null) {
        buf.putShort((short) columnFamily.length);
        buf.put(columnFamily);
    }
    if (column != null) {
        buf.putInt(column.length);
        buf.put(column);
    }
    // prepare for read
    // buf.flip();

}