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:com.bittorrent.mpetazzoni.client.ConnectionHandler.java

/**
 * Validate an expected handshake on a connection.
 *
 * <p>//from  ww w. ja v a2  s  .  com
 * Reads an expected handshake message from the given connected socket,
 * parses it and validates that the torrent hash_info corresponds to the
 * torrent we're sharing, and that the peerId matches the peer ID we expect
 * to see coming from the remote peer.
 * </p>
 *
 * @param channel The connected socket channel to the remote peer.
 * @param peerId The peer ID we expect in the handshake. If <em>null</em>,
 * any peer ID is accepted (this is the case for incoming connections).
 * @return The validated handshake message object.
 */
private Handshake validateHandshake(SocketChannel channel, byte[] peerId) throws IOException, ParseException {
    ByteBuffer len = ByteBuffer.allocate(1);
    ByteBuffer data;

    // Read the handshake from the wire
    logger.trace("Reading handshake size (1 byte) from {}...", this.socketRepr(channel));
    if (channel.read(len) < len.capacity()) {
        throw new IOException("Handshake size read underrrun");
    }

    len.rewind();
    int pstrlen = len.get();

    data = ByteBuffer.allocate(Handshake.BASE_HANDSHAKE_LENGTH + pstrlen);
    data.put((byte) pstrlen);
    int expected = data.remaining();
    int read = channel.read(data);
    if (read < expected) {
        throw new IOException("Handshake data read underrun (" + read + " < " + expected + " bytes)");
    }

    // Parse and check the handshake
    data.rewind();
    Handshake hs = Handshake.parse(data);
    if (!Arrays.equals(hs.getInfoHash(), this.torrent.getInfoHash())) {
        throw new ParseException("Handshake for unknow torrent "
                + Torrent.byteArrayToHexString(hs.getInfoHash()) + " from " + this.socketRepr(channel) + ".",
                pstrlen + 9);
    }

    if (peerId != null && !Arrays.equals(hs.getPeerId(), peerId)) {
        throw new ParseException(
                "Announced peer ID " + Torrent.byteArrayToHexString(hs.getPeerId())
                        + " did not match expected peer ID " + Torrent.byteArrayToHexString(peerId) + ".",
                pstrlen + 29);
    }

    return hs;
}

From source file:de.rwhq.btree.InnerNode.java

private void setKey(final byte[] serializedKey, final int pos) {
    final ByteBuffer buf = rawPage().bufferForWriting(new KeyStruct(pos).getOffset());
    buf.put(serializedKey);
    rawPage().sync();//from   w w  w  .  ja  v a2 s  . com
}

From source file:com.warfrog.bitmapallthethings.BattEngine.java

private InputStream generateBitmapHeader(int width, int height, int fileSize, int fillerBytes) {
    ByteBuffer buffer = ByteBuffer.allocate(54);
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    buffer.put((byte) 0x42); //B
    buffer.put((byte) 0x4D); //M
    buffer.putInt(fileSize + 54); //total file size
    buffer.putInt(fileSize); //unofficial -- used to save the file size
    buffer.putInt(54); //pixel info offset
    buffer.putInt(40); //size of the bitmap info header
    buffer.putInt(width); //width
    buffer.putInt(height); //height
    buffer.putShort((short) 1); //number of color planes
    buffer.putShort((short) getBytesPerPixel()); //bytes per pixel
    buffer.putInt(0); //no compression
    buffer.putInt(fileSize); //size of the raw pixel array
    buffer.putInt(2835); //horizontal resolution
    buffer.putInt(2835); //vertical resolution
    buffer.putInt(0); //number of colors
    buffer.putInt(0); //important colors
    return new ByteArrayInputStream(buffer.array());
}

From source file:de.rwhq.btree.InnerNode.java

public void initRootState(final Integer pageId1, final byte[] serializedKey, final Integer pageId2) {
    ensureValid();/*w w w  . ja v  a 2 s . c o  m*/
    validateLengthOfSerializedKey(serializedKey);

    final ByteBuffer buf = rawPage().bufferForWriting(Header.size());

    buf.putInt(pageId1);
    buf.put(serializedKey);
    buf.putInt(pageId2);

    setNumberOfKeys(1);

    rawPage.sync();
}

From source file:com.arpnetworking.tsdcore.sinks.KairosDbSink.java

/**
 * {@inheritDoc}//  w w  w.  j av  a  2s. c o  m
 */
@Override
protected Collection<byte[]> serialize(final PeriodicData periodicData) {
    // Initialize serialization structures
    final List<byte[]> completeChunks = Lists.newArrayList();
    final ByteBuffer currentChunk = ByteBuffer.allocate(_maxRequestSize);
    final ByteArrayOutputStream chunkStream = new ByteArrayOutputStream();

    // Extract and transform shared data
    final long timestamp = periodicData.getStart().plus(periodicData.getPeriod()).getMillis();
    final String serializedPeriod = periodicData.getPeriod().toString(ISOPeriodFormat.standard());
    final ImmutableMap<String, String> dimensions = periodicData.getDimensions();
    final Serializer serializer = new Serializer(timestamp, serializedPeriod, dimensions);

    // Initialize the chunk buffer
    currentChunk.put(HEADER);

    // Add aggregated data
    for (final AggregatedData datum : periodicData.getData()) {
        if (!datum.isSpecified()) {
            LOGGER.trace().setMessage("Skipping unspecified datum").addData("datum", datum).log();
            continue;
        }

        serializer.serializeDatum(completeChunks, currentChunk, chunkStream, datum);
    }

    // Add conditions
    for (final Condition condition : periodicData.getConditions()) {
        serializer.serializeCondition(completeChunks, currentChunk, chunkStream, condition);
    }

    // Add the current chunk (if any) to the completed chunks
    if (currentChunk.position() > HEADER_BYTE_LENGTH) {
        currentChunk.put(currentChunk.position() - 1, FOOTER);
        completeChunks.add(Arrays.copyOf(currentChunk.array(), currentChunk.position()));
    }

    return completeChunks;
}

From source file:edu.hawaii.soest.kilonalu.ctd.SBE37Source.java

/**
 * A method that queries the instrument to obtain its ID
 *//*  ww w .  j  a va2s .com*/
public boolean queryInstrument(String command) {

    // the result of the query
    boolean result = false;

    // only send the command if the socket is connected
    if (this.socketChannel.isConnected()) {
        ByteBuffer commandBuffer = ByteBuffer.allocate(command.length() * 10);
        commandBuffer.put(command.getBytes());
        commandBuffer.flip();

        try {
            this.socketChannel.write(commandBuffer);
            logger.debug("Wrote " + command + " to the socket channel.");
            result = true;

        } catch (IOException ioe) {
            ioe.printStackTrace();
            result = false;
        }
    }
    return result;
}

From source file:dk.statsbiblioteket.util.LineReaderTest.java

public void testNIO() throws Exception {
    byte[] INITIAL = new byte[] { 1, 2, 3, 4 };
    byte[] EXTRA = new byte[] { 5, 6, 7, 8 };
    byte[] FULL = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
    byte[] FIFTH = new byte[] { 87 };
    byte[] FULL_WITH_FIFTH = new byte[] { 1, 2, 3, 4, 87, 6, 7, 8 };

    // Create temp-file with content
    File temp = createTempFile();
    FileOutputStream fileOut = new FileOutputStream(temp, true);
    fileOut.write(INITIAL);/*  www  .j a va  2s .c  o m*/
    fileOut.close();

    checkContent("The plain test-file should be correct", temp, INITIAL);
    {
        // Read the 4 bytes
        RandomAccessFile input = new RandomAccessFile(temp, "r");
        FileChannel channelIn = input.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(4096);
        channelIn.position(0);
        assertEquals("Buffer read should read full length", INITIAL.length, channelIn.read(buffer));
        buffer.position(0);

        checkContent("Using buffer should produce the right bytes", INITIAL, buffer);
        channelIn.close();
        input.close();
    }
    {
        // Fill new buffer
        ByteBuffer outBuffer = ByteBuffer.allocate(4096);
        outBuffer.put(EXTRA);
        outBuffer.flip();
        assertEquals("The limit of the outBuffer should be correct", EXTRA.length, outBuffer.limit());

        // Append new buffer to end
        RandomAccessFile output = new RandomAccessFile(temp, "rw");
        FileChannel channelOut = output.getChannel();
        channelOut.position(INITIAL.length);
        assertEquals("All bytes should be written", EXTRA.length, channelOut.write(outBuffer));
        channelOut.close();
        output.close();
        checkContent("The resulting file should have the full output", temp, FULL);
    }

    {
        // Fill single byte buffer
        ByteBuffer outBuffer2 = ByteBuffer.allocate(4096);
        outBuffer2.put(FIFTH);
        outBuffer2.flip();
        assertEquals("The limit of the second outBuffer should be correct", FIFTH.length, outBuffer2.limit());

        // Insert byte in the middle
        RandomAccessFile output2 = new RandomAccessFile(temp, "rw");
        FileChannel channelOut2 = output2.getChannel();
        channelOut2.position(4);
        assertEquals("The FIFTH should be written", FIFTH.length, channelOut2.write(outBuffer2));
        channelOut2.close();
        output2.close();
        checkContent("The resulting file with fifth should be complete", temp, FULL_WITH_FIFTH);
    }
}

From source file:edu.hawaii.soest.kilonalu.utilities.TextOutputPlugin.java

/**
 * Converts data for a time range.//from   w  ww.j a v  a  2s  . c o  m
 * 
 * @param map             the channel map
 * @param startTime       the start time for the data
 * @param endTime         the end time for the data
 * @param baseTime        the base elasped time for the conversion
 * @return                the number of data frames written to disk
 * @throws SAPIException  if there is an error getting the data from the
 *                        server
 * @throws IOException    if there is an error writing the file
 */
private int convertData(ChannelMap map, ChannelMap cmap, double startTime, double endTime, double duration,
        double baseTime) throws SAPIException, IOException {
    logger.debug("TextOutputPlugin.convertData() called.");

    sink.Subscribe(map, startTime, 0.0, "absolute");
    //sink.Subscribe(map, startTime, duration, "absolute");

    int frameCount = 0;
    int fetchRetryCount = 0;

    while (doTextConversion) {
        ChannelMap m = sink.Fetch(10000); // fetch with 10 sec timeout

        if (m.GetIfFetchTimedOut()) {
            if (++fetchRetryCount < 10) {
                logger.debug("Warning: Request for data timed out, retrying.");
                continue;
            } else {
                logger.debug("Error: Unable to get data from server.");
                break;
            }
        } else {
            fetchRetryCount = 0;
        }

        int index = m.GetIndex(channelPath);
        if (index < 0) {
            break;
        }

        byte[][] data = m.GetDataAsByteArray(index); // uses local byte order??
        for (int i = 0; i < data.length; i++) {
            ByteBuffer ensembleBuffer = ByteBuffer.allocate(data[i].length);
            // create an Ensemble
            ensembleBuffer.put(data[i]);
            Ensemble ensemble = new Ensemble(ensembleBuffer);
            logger.info("Ensemble is valid: " + ensemble.isValid());

            if (ensemble.isValid()) {
                int ensYear = (ensemble.getRealTimeY2KClockCentury() * 100)
                        + ensemble.getRealTimeY2KClockYear();
                int ensMonth = ensemble.getRealTimeY2KClockMonth() - 1; // 0 start
                int ensDay = ensemble.getRealTimeY2KClockDay();
                int ensHour = ensemble.getRealTimeY2KClockHour();
                int ensMinute = ensemble.getRealTimeY2KClockMinute();
                int ensSecond = ensemble.getRealTimeY2KClockSecond();
                int ensHundredths = ensemble.getRealTimeY2KClockHundredths();

                logger.debug("ensYear      : " + ensYear);
                logger.debug("ensMonth     : " + ensMonth);
                logger.debug("ensDay       : " + ensDay);
                logger.debug("ensHour      : " + ensHour);
                logger.debug("ensMinute    : " + ensMinute);
                logger.debug("ensSecond    : " + ensSecond);
                logger.debug("ensHundredths: " + ensHundredths);

                Calendar ensCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
                ensCalendar.set(ensYear, ensMonth, ensDay, ensHour, ensMinute, ensSecond);
                ensCalendar.add(Calendar.HOUR, 10); // set observation time to GMT
                ensCalendar.add(Calendar.MILLISECOND, ensHundredths * 10);

                // set the data frame timestamp to the observation timestamp
                double[] times = new double[1];
                times[0] = (double) (ensCalendar.getTime().getTime() / 1000);
                logger.debug("Observation time: = " + RBNBUtilities.secondsToISO8601(times[0]));
                cmap.PutTimes(times);

                String[] channelList = new String[cmap.NumberOfChannels()];
                for (int j = 0; j < channelList.length; j++) {
                    channelList[j] = cmap.GetName(j);
                    // add temperature data channel
                    if (channelList[j].equals("temperature")) {
                        //logger.debug("Temperature: " + ensemble.getTemperature());
                        cmap.PutDataAsFloat32(cmap.GetIndex(channelList[j]),
                                new float[] { ensemble.getTemperature() });
                    }
                    // add pressure data channel
                    if (channelList[j].equals("pressure")) {
                        //logger.debug("Pressure: " + ensemble.getPressure());
                        cmap.PutDataAsFloat32(cmap.GetIndex(channelList[j]),
                                new float[] { ensemble.getPressure() });
                    }
                    // add salinity data channel
                    if (channelList[j].equals("salinity")) {
                        //logger.debug("Salinity: " + ensemble.getSalinity());
                        cmap.PutDataAsInt32(cmap.GetIndex(channelList[j]),
                                new int[] { ensemble.getSalinity() });
                    }
                }
                // Flush the data frame to rbnb
                source.Flush(cmap);
                logger.debug("Flushed data to data turbine.");
            }

        }
        //doTextConversion = false;
    }

    return frameCount;
}

From source file:ar.com.qbe.siniestros.model.utils.MimeMagic.MagicMatcher.java

/**
 * internal test switch//from w ww  .  jav  a 2  s.c o  m
 * 
 * @param data DOCUMENT ME!
 * @return DOCUMENT ME!
 */
private boolean testInternal(byte[] data) {
    log.debug("testInternal(byte[])");

    if (data.length == 0) {
        return false;
    }

    String type = match.getType();
    String test = new String(match.getTest().array());
    String mimeType = match.getMimeType();
    String description = match.getDescription();

    ByteBuffer buffer = ByteBuffer.allocate(data.length);

    if ((type != null) && (test != null) && (test.length() > 0)) {
        if (type.equals("string")) {
            buffer = buffer.put(data);

            return testString(buffer);
        } else if (type.equals("byte")) {
            buffer = buffer.put(data);

            return testByte(buffer);
        } else if (type.equals("short")) {
            buffer = buffer.put(data);

            return testShort(buffer);
        } else if (type.equals("leshort")) {
            buffer = buffer.put(data);
            buffer.order(ByteOrder.LITTLE_ENDIAN);

            return testShort(buffer);
        } else if (type.equals("beshort")) {
            buffer = buffer.put(data);
            buffer.order(ByteOrder.BIG_ENDIAN);

            return testShort(buffer);
        } else if (type.equals("long")) {
            buffer = buffer.put(data);

            return testLong(buffer);
        } else if (type.equals("lelong")) {
            buffer = buffer.put(data);
            buffer.order(ByteOrder.LITTLE_ENDIAN);

            return testLong(buffer);
        } else if (type.equals("belong")) {
            buffer = buffer.put(data);
            buffer.order(ByteOrder.BIG_ENDIAN);

            return testLong(buffer);
        } else if (type.equals("regex")) {
            return testRegex(new String(data));
        } else if (type.equals("detector")) {
            buffer = buffer.put(data);

            return testDetector(buffer);

            //         } else if (type.equals("date")) {
            //            return testDate(data, BIG_ENDIAN);
            //         } else if (type.equals("ledate")) {
            //            return testDate(data, LITTLE_ENDIAN);
            //         } else if (type.equals("bedate")) {
            //            return testDate(data, BIG_ENDIAN);
        } else {
            log.error("testInternal(byte[]): invalid test type '" + type + "'");
        }
    } else {
        log.error("testInternal(byte[]): type or test is empty for '" + mimeType + " - " + description + "'");
    }

    return false;
}