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:edu.hawaii.soest.kilonalu.adcp.EnsembleFixedLeader.java

/**
 *  Constructor.  This method populates the Fixed Leader fields from 
 *  the given ByteBuffer of data passed in as an argument, based on metadata 
 *  found in the EnsembleHeader.//from   ww w  .j a va2 s.c  om
 *
 * @param ensembleBuffer the ByteBuffer that contains the binary ensemble data
 * @param ensemble  the parent ensemble for this fixed leader
 */
public EnsembleFixedLeader(ByteBuffer ensembleBuffer, Ensemble ensemble) {

    // prepare the ensemble buffer for reading
    ensembleBuffer.flip();
    ensembleBuffer.limit(ensembleBuffer.capacity());

    // position the cursor at the correct offset given the sequential location
    // of the fixed leader in the data stream.
    int typeNumber = ensemble.getDataTypeNumber(EnsembleDataType.FIXED_LEADER);
    int offset = ensemble.getDataTypeOffset(typeNumber);
    ensembleBuffer.position(offset);

    // define the temporary arrays for passing bytes
    byte[] oneByte = new byte[1];
    byte[] twoBytes = new byte[2];

    // set all of the FixedLeader fields in the order that they are read from 
    // the byte stream
    ensembleBuffer.get(twoBytes);
    setFixedLeaderID(twoBytes);
    ensemble.addToByteSum(twoBytes);
    ensembleBuffer.get(oneByte);
    setCpuFirmwareVersion(oneByte);
    ensemble.addToByteSum(oneByte);
    ensembleBuffer.get(oneByte);
    setCpuFirmwareRevision(oneByte);
    ensemble.addToByteSum(oneByte);
    ensembleBuffer.get(twoBytes);
    setSystemConfiguration(twoBytes);
    ensemble.addToByteSum(twoBytes);
    ensembleBuffer.get(oneByte);
    setPdRealOrSimulatedFlag(oneByte);
    ensemble.addToByteSum(oneByte);
    ensembleBuffer.get(oneByte);
    setLagLength(oneByte);
    ensemble.addToByteSum(oneByte);
    ensembleBuffer.get(oneByte);
    setNumberOfBeams(oneByte);
    ensemble.addToByteSum(oneByte);
    ensembleBuffer.get(oneByte);
    setNumberOfCells(oneByte);
    ensemble.addToByteSum(oneByte);
    ensembleBuffer.get(twoBytes);
    setPingsPerEnsemble(twoBytes);
    ensemble.addToByteSum(twoBytes);
    ensembleBuffer.get(twoBytes);
    setDepthCellLength(twoBytes);
    ensemble.addToByteSum(twoBytes);
    ensembleBuffer.get(twoBytes);
    setBlankAfterTransmit(twoBytes);
    ensemble.addToByteSum(twoBytes);
    ensembleBuffer.get(oneByte);
    setProfilingMode(oneByte);
    ensemble.addToByteSum(oneByte);
    ensembleBuffer.get(oneByte);
    setLowCorrelationThreshold(oneByte);
    ensemble.addToByteSum(oneByte);
    ensembleBuffer.get(oneByte);
    setNumberOfCodeRepetitions(oneByte);
    ensemble.addToByteSum(oneByte);
    ensembleBuffer.get(oneByte);
    setPercentGoodMinimum(oneByte);
    ensemble.addToByteSum(oneByte);
    ensembleBuffer.get(twoBytes);
    setErrorVelocityThreshold(twoBytes);
    ensemble.addToByteSum(twoBytes);
    ensembleBuffer.get(oneByte);
    setPingMinutes(oneByte);
    ensemble.addToByteSum(oneByte);
    ensembleBuffer.get(oneByte);
    setPingSeconds(oneByte);
    ensemble.addToByteSum(oneByte);
    ensembleBuffer.get(oneByte);
    setPingHundredths(oneByte);
    ensemble.addToByteSum(oneByte);
    ensembleBuffer.get(oneByte);
    setCoordinateTransformParams(oneByte);
    ensemble.addToByteSum(oneByte);
    ensembleBuffer.get(twoBytes);
    setHeadingAlignment(twoBytes);
    ensemble.addToByteSum(twoBytes);
    ensembleBuffer.get(twoBytes);
    setHeadingBias(twoBytes);
    ensemble.addToByteSum(twoBytes);
    ensembleBuffer.get(oneByte);
    setSensorSource(oneByte);
    ensemble.addToByteSum(oneByte);
    ensembleBuffer.get(oneByte);
    setSensorAvailability(oneByte);
    ensemble.addToByteSum(oneByte);
    ensembleBuffer.get(twoBytes);
    setBinOneDistance(twoBytes);
    ensemble.addToByteSum(twoBytes);
    ensembleBuffer.get(twoBytes);
    setTransmitPulseLength(twoBytes);
    ensemble.addToByteSum(twoBytes);
    ensembleBuffer.get(oneByte);
    setReferenceLayerStart(oneByte);
    ensemble.addToByteSum(oneByte);
    ensembleBuffer.get(oneByte);
    setReferenceLayerEnd(oneByte);
    ensemble.addToByteSum(oneByte);
    ensembleBuffer.get(oneByte);
    setFalseTargetThreshold(oneByte);
    ensemble.addToByteSum(oneByte);
    ensembleBuffer.get(oneByte);
    setFixedLeaderSpare(oneByte);
    ensemble.addToByteSum(oneByte);
    ensembleBuffer.get(twoBytes);
    setTransmitLagDistance(twoBytes);
    ensemble.addToByteSum(twoBytes);
    byte[] boardSerialNumber = new byte[8];
    ensembleBuffer.get(boardSerialNumber); // read 8 bytes
    setCpuBoardSerialNumber(boardSerialNumber);
    ensemble.addToByteSum(boardSerialNumber);
    ensembleBuffer.get(twoBytes);
    setSystemBandwidth(twoBytes);
    ensemble.addToByteSum(twoBytes);
    ensembleBuffer.get(oneByte);
    setSystemPower(oneByte);
    ensemble.addToByteSum(oneByte);

    // the following don't get called for Workhorse ADCPs
    // TODO: test for model and add fields if necessary

    //ensembleBuffer.get(oneByte);
    //setBaseFrequencyIndex(oneByte);
    //ensemble.addToByteSum(oneByte);
    //byte[] instrumentSerialNumber = new byte[4];
    //ensembleBuffer.get(instrumentSerialNumber);  // read 4 bytes
    //setSerialNumber(instrumentSerialNumber);
    //ensemble.addToByteSum(instrumentSerialNumber);
    //ensembleBuffer.get(oneByte);
    //setBeamAngle(oneByte);
    //ensemble.addToByteSum(oneByte);

}

From source file:com.robonobo.eon.SEONConnection.java

private void gotIncomingData(SEONPacket pkt) {
    ByteBuffer buf = pkt.getPayload();
    buf.position(0);
    // if (DEBUG_LOG_BUFS) {
    // StringBuffer sb = new StringBuffer(this.toString()).append(" receiving data: ");
    // ByteUtil.printBuf(buf, sb);
    // log.debug(sb);
    // }/*  w  w  w. ja  v  a2s  .  com*/
    receiveLock.lock();
    try {
        incomingDataBufs.add(buf);
        inFlowRate.notifyData(buf.limit());
        if (dataReceiver == null) {
            // Synchronous receives
            haveData.signalAll();
        } else {
            // Async receives
            if (dataReceiverRunning) {
                // The receiver will pick up this pkt when it's finished
                return;
            } else
                fireAsyncReceiver();
        }
    } finally {
        receiveLock.unlock();
    }
}

From source file:com.tomagoyaky.jdwp.IOUtils.java

/**
 * Skips bytes from a ReadableByteChannel.
 * This implementation guarantees that it will read as many bytes
 * as possible before giving up./*w  ww.  ja  v  a2 s  .co m*/
 *
 * @param input ReadableByteChannel to skip
 * @param toSkip number of bytes to skip.
 * @return number of bytes actually skipped.
 * @throws IOException              if there is a problem reading the ReadableByteChannel
 * @throws IllegalArgumentException if toSkip is negative
 * @since 2.2
 */
public static long skip(final ReadableByteChannel input, final long toSkip) throws IOException {
    if (toSkip < 0) {
        throw new IllegalArgumentException("Skip count must be non-negative, actual: " + toSkip);
    }
    final ByteBuffer skipByteBuffer = ByteBuffer.allocate((int) Math.min(toSkip, SKIP_BUFFER_SIZE));
    long remain = toSkip;
    while (remain > 0) {
        skipByteBuffer.position(0);
        skipByteBuffer.limit((int) Math.min(remain, SKIP_BUFFER_SIZE));
        final int n = input.read(skipByteBuffer);
        if (n == EOF) {
            break;
        }
        remain -= n;
    }
    return toSkip - remain;
}

From source file:com.mellanox.r4h.DFSInputStream.java

private synchronized ByteBuffer tryReadZeroCopy(int maxLength, EnumSet<ReadOption> opts) throws IOException {
    // Copy 'pos' and 'blockEnd' to local variables to make it easier for the
    // JVM to optimize this function.
    final long curPos = pos;
    final long curEnd = blockEnd;
    final long blockStartInFile = currentLocatedBlock.getStartOffset();
    final long blockPos = curPos - blockStartInFile;

    // Shorten this read if the end of the block is nearby.
    long length63;
    if ((curPos + maxLength) <= (curEnd + 1)) {
        length63 = maxLength;/*from  w  w  w. ja  v a 2s.c  o  m*/
    } else {
        length63 = 1 + curEnd - curPos;
        if (length63 <= 0) {
            if (DFSClient.LOG.isDebugEnabled()) {
                DFSClient.LOG.debug("Unable to perform a zero-copy read from offset " + curPos + " of " + src
                        + "; " + length63 + " bytes left in block.  " + "blockPos=" + blockPos + "; curPos="
                        + curPos + "; curEnd=" + curEnd);
            }
            return null;
        }
        if (DFSClient.LOG.isDebugEnabled()) {
            DFSClient.LOG.debug("Reducing read length from " + maxLength + " to " + length63
                    + " to avoid going more than one byte " + "past the end of the block.  blockPos=" + blockPos
                    + "; curPos=" + curPos + "; curEnd=" + curEnd);
        }
    }
    // Make sure that don't go beyond 31-bit offsets in the MappedByteBuffer.
    int length;
    if (blockPos + length63 <= Integer.MAX_VALUE) {
        length = (int) length63;
    } else {
        long length31 = Integer.MAX_VALUE - blockPos;
        if (length31 <= 0) {
            // Java ByteBuffers can't be longer than 2 GB, because they use
            // 4-byte signed integers to represent capacity, etc.
            // So we can't mmap the parts of the block higher than the 2 GB offset.
            // FIXME: we could work around this with multiple memory maps.
            // See HDFS-5101.
            if (DFSClient.LOG.isDebugEnabled()) {
                DFSClient.LOG.debug("Unable to perform a zero-copy read from offset " + curPos + " of " + src
                        + "; 31-bit MappedByteBuffer limit " + "exceeded.  blockPos=" + blockPos + ", curEnd="
                        + curEnd);
            }
            return null;
        }
        length = (int) length31;
        if (DFSClient.LOG.isDebugEnabled()) {
            DFSClient.LOG.debug(
                    "Reducing read length from " + maxLength + " to " + length + " to avoid 31-bit limit.  "
                            + "blockPos=" + blockPos + "; curPos=" + curPos + "; curEnd=" + curEnd);
        }
    }
    final ClientMmap clientMmap = blockReader.getClientMmap(opts);
    if (clientMmap == null) {
        if (DFSClient.LOG.isDebugEnabled()) {
            DFSClient.LOG.debug("unable to perform a zero-copy read from offset " + curPos + " of " + src
                    + "; BlockReader#getClientMmap returned " + "null.");
        }
        return null;
    }
    boolean success = false;
    ByteBuffer buffer;
    try {
        seek(curPos + length);
        buffer = clientMmap.getMappedByteBuffer().asReadOnlyBuffer();
        buffer.position((int) blockPos);
        buffer.limit((int) (blockPos + length));
        getExtendedReadBuffers().put(buffer, clientMmap);
        synchronized (infoLock) {
            readStatistics.addZeroCopyBytes(length);
        }
        if (DFSClient.LOG.isDebugEnabled()) {
            DFSClient.LOG.debug("readZeroCopy read " + length + " bytes from offset " + curPos
                    + " via the zero-copy read " + "path.  blockEnd = " + blockEnd);
        }
        success = true;
    } finally {
        if (!success) {
            IOUtils.closeQuietly(clientMmap);
        }
    }
    return buffer;
}

From source file:com.att.aro.core.packetanalysis.impl.VideoUsageAnalysisImpl.java

/**
 * Parse mp4 chunk/segment that contains one moof and one mdat.
 *
 * @param content//from w  ww . ja  v  a 2s. com
 * @return double[] mdat payload length, time sequence
 */
private Integer[] parsePayload(byte[] content) {
    byte[] buf = new byte[4];
    int mdatSize = 0;
    ByteBuffer bbc = ByteBuffer.wrap(content);
    // get moof size
    double moofSize = bbc.getInt();
    bbc.get(buf);
    String moofName = new String(buf);
    int timeSequence = 0;
    if (moofName.equals("moof")) {
        // skip past mfhd
        double mfhdSize = bbc.getInt();
        bbc.get(buf);
        String mfhdName = new String(buf);
        if (mfhdName.equals("mfhd")) {
            bbc.position((int) mfhdSize + bbc.position() - 8);
            // parse into traf
            // double trafSize =
            bbc.getInt(); // skip over
            bbc.get(buf);
            String trafName = new String(buf);
            if (trafName.equals("traf")) {
                // skip tfhd
                double tfhdSize = bbc.getInt();
                bbc.get(buf);
                String tfhdName = new String(buf);
                if (tfhdName.equals("tfhd")) {
                    // skip past this atom
                    bbc.position((int) tfhdSize + bbc.position() - 8);
                }
                // parse tfdt
                // double tfdtSize =
                bbc.getInt(); // skip over
                bbc.get(buf);
                String tfdtName = new String(buf);
                if (tfdtName.equals("tfdt")) {
                    bbc.getInt(); // skip over always 16k
                    bbc.getInt(); // skip over always 0
                    timeSequence = bbc.getInt();
                }
            }
        }
    } else {
        return new Integer[] { 0, 0 };
    }
    // parse mdat
    bbc.position((int) moofSize);
    mdatSize = bbc.getInt();
    bbc.get(buf, 0, 4);
    String mdatName = new String(buf);
    if (mdatName.equals("mdat")) {
        mdatSize -= 8;
    } else {
        mdatSize = 0;
    }
    return new Integer[] { mdatSize, timeSequence };
}

From source file:com.koda.integ.hbase.storage.FileExtStorage.java

/**
 * Tries to store batch of blocks into a current buffer.
 *
 * @param buf the buf/*from   w  ww  .ja  v a 2 s.c om*/
 * @return the list
 */
private List<StorageHandle> storeDataNoReleaseLock(ByteBuffer buf) {

    List<StorageHandle> handles = new ArrayList<StorageHandle>();
    writeLock.writeLock().lock();
    try {

        if (activeBuffer.get() == null) {
            return null;
        }
        int size = buf.getInt(0);
        long off = bufferOffset.get();
        if (off + size > bufferSize) {
            return null;
        }

        long currentFileLength = currentFileOffsetForWrites.get();
        if (bufferOffset.get() == 0 && currentFileLength + bufferSize > fileSizeLimit) {
            // previous buffer was flushed
            currentFileOffsetForWrites.set(0);
            maxIdForWrites.incrementAndGet();
        }

        buf.position(4);

        while (buf.position() < size + 4) {
            buf.limit(buf.capacity());
            int pos = buf.position();
            int blockSize = buf.getInt();
            buf.position(pos);
            buf.limit(pos + 4 + blockSize);
            activeBuffer.get().put(buf);
            FileStorageHandle fsh = new FileStorageHandle(maxIdForWrites.get(),
                    (int) (currentFileOffsetForWrites.get()), blockSize);
            handles.add(fsh);
            // Increase offset in current file for writes;
            currentFileOffsetForWrites.addAndGet(blockSize + 4);
            bufferOffset.getAndAdd(blockSize + 4);
        }
        return handles;
    } finally {
        WriteLock lock = writeLock.writeLock();
        if (lock.isHeldByCurrentThread()) {
            lock.unlock();
        }
    }
}

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

public String getDatabasePassword() throws IOException {
    ByteBuffer buffer = takeSharedBuffer();
    try {//from w  w w.jav a 2  s .c o m
        _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 = ColumnImpl.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:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.por.PORFileReader.java

private File decodeHeader(BufferedInputStream stream) throws IOException {
    File tempPORfile = null;/*from w  w w .ja v  a2 s.  c om*/

    if (stream == null) {
        throw new IllegalArgumentException("file == null!");
    }

    byte[] headerByes = new byte[POR_HEADER_SIZE];

    if (stream.markSupported()) {
        stream.mark(1000);
    }
    int nbytes = stream.read(headerByes, 0, POR_HEADER_SIZE);

    //printHexDump(headerByes, "hex dump of the byte-array");

    if (nbytes == 0) {
        throw new IOException("decodeHeader: reading failure");
    } else if (nbytes < 491) {
        // Size test: by defnition, it must have at least
        // 491-byte header, i.e., the file size less than this threshold
        // is not a POR file
        dbgLog.fine("this file is NOT spss-por type");
        throw new IllegalArgumentException("file is not spss-por type");
    }
    // rewind the current reading position back to the beginning
    if (stream.markSupported()) {
        stream.reset();
    }

    // line-terminating characters are usually one or two by defnition
    // however, a POR file saved by a genuine SPSS for Windows
    // had a three-character line terminator, i.e., failed to remove the
    // original file's one-character terminator when it was opened, and
    // saved it with the default two-character terminator without
    // removing original terminators. So we have to expect such a rare
    // case
    //
    // terminator
    // windows [0D0A]=>   [1310] = [CR/LF]
    // unix    [0A]  =>   [10]
    // mac     [0D]  =>   [13]
    // 3char  [0D0D0A]=> [131310] spss for windows rel 15
    //
    // terminating characters should be found at the following
    //                             column positions[counting from 0]:
    // unix    case: [0A]   : [80], [161], [242], [323], [404], [485]
    // windows case: [0D0A] : [81], [163], [245], [327], [409], [491]
    //           : [0D0D0A] : [82], [165], [248], [331], [414], [495]

    // convert b into a ByteBuffer

    ByteBuffer buff = ByteBuffer.wrap(headerByes);
    byte[] nlch = new byte[36];
    int pos1;
    int pos2;
    int pos3;
    int ucase = 0;
    int wcase = 0;
    int mcase = 0;
    int three = 0;
    int nolines = 6;
    int nocols = 80;
    for (int i = 0; i < nolines; ++i) {
        int baseBias = nocols * (i + 1);
        // 1-char case
        pos1 = baseBias + i;
        buff.position(pos1);
        dbgLog.finer("\tposition(1)=" + buff.position());
        int j = 6 * i;
        nlch[j] = buff.get();

        if (nlch[j] == 10) {
            ucase++;
        } else if (nlch[j] == 13) {
            mcase++;
        }

        // 2-char case
        pos2 = baseBias + 2 * i;
        buff.position(pos2);
        dbgLog.finer("\tposition(2)=" + buff.position());

        nlch[j + 1] = buff.get();
        nlch[j + 2] = buff.get();

        // 3-char case
        pos3 = baseBias + 3 * i;
        buff.position(pos3);
        dbgLog.finer("\tposition(3)=" + buff.position());

        nlch[j + 3] = buff.get();
        nlch[j + 4] = buff.get();
        nlch[j + 5] = buff.get();

        dbgLog.finer(i + "-th iteration position =" + nlch[j] + "\t" + nlch[j + 1] + "\t" + nlch[j + 2]);
        dbgLog.finer(i + "-th iteration position =" + nlch[j + 3] + "\t" + nlch[j + 4] + "\t" + nlch[j + 5]);

        if ((nlch[j + 3] == 13) && (nlch[j + 4] == 13) && (nlch[j + 5] == 10)) {
            three++;
        } else if ((nlch[j + 1] == 13) && (nlch[j + 2] == 10)) {
            wcase++;
        }

        buff.rewind();
    }

    boolean windowsNewLine = true;
    if (three == nolines) {
        windowsNewLine = false; // lineTerminator = "0D0D0A"
    } else if ((ucase == nolines) && (wcase < nolines)) {
        windowsNewLine = false; // lineTerminator = "0A"
    } else if ((ucase < nolines) && (wcase == nolines)) {
        windowsNewLine = true; //lineTerminator = "0D0A"
    } else if ((mcase == nolines) && (wcase < nolines)) {
        windowsNewLine = false; //lineTerminator = "0D"
    }

    buff.rewind();
    int PORmarkPosition = POR_MARK_POSITION_DEFAULT;
    if (windowsNewLine) {
        PORmarkPosition = PORmarkPosition + 5;
    } else if (three == nolines) {
        PORmarkPosition = PORmarkPosition + 10;
    }

    byte[] pormark = new byte[8];
    buff.position(PORmarkPosition);
    buff.get(pormark, 0, 8);
    String pormarks = new String(pormark);

    //dbgLog.fine("pormark =>" + pormarks + "<-");
    dbgLog.fine(
            "pormark[hex: 53 50 53 53 50 4F 52 54 == SPSSPORT] =>" + new String(Hex.encodeHex(pormark)) + "<-");

    if (pormarks.equals(POR_MARK)) {
        dbgLog.fine("POR ID toke test: Passed");
        init();

        smd.getFileInformation().put("mimeType", MIME_TYPE);
        smd.getFileInformation().put("fileFormat", MIME_TYPE);

    } else {
        dbgLog.fine("this file is NOT spss-por type");
        throw new IllegalArgumentException("decodeHeader: POR ID token was not found");
    }

    // save the POR file without new line characters

    FileOutputStream fileOutPOR = null;
    Writer fileWriter = null;

    // Scanner class can handle three-character line-terminator
    Scanner porScanner = null;

    try {
        tempPORfile = File.createTempFile("tempPORfile.", ".por");
        fileOutPOR = new FileOutputStream(tempPORfile);
        fileWriter = new BufferedWriter(new OutputStreamWriter(fileOutPOR, "utf8"));
        porScanner = new Scanner(stream);

        // Because 64-bit and 32-bit machines decode POR's first 40-byte
        // sequence differently, the first 5 leader lines are skipped from
        // the new-line-stripped file

        int lineCounter = 0;
        while (porScanner.hasNextLine()) {
            lineCounter++;
            if (lineCounter <= 5) {
                String line = porScanner.nextLine().toString();
                dbgLog.fine("line=" + lineCounter + ":" + line.length() + ":" + line);
            } else {
                fileWriter.write(porScanner.nextLine().toString());
            }
        }
    } finally {
        try {
            if (fileWriter != null) {
                fileWriter.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        if (porScanner != null) {
            porScanner.close();
        }
    }

    return tempPORfile;
}

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.por.PORFileReader.java

private File decodeHeader(BufferedInputStream stream) throws IOException {
    dbgLog.fine("decodeHeader(): start");
    File tempPORfile = null;/* w ww  . j  a va  2s . c  om*/

    if (stream == null) {
        throw new IllegalArgumentException("file == null!");
    }

    byte[] headerByes = new byte[POR_HEADER_SIZE];

    if (stream.markSupported()) {
        stream.mark(1000);
    }
    int nbytes = stream.read(headerByes, 0, POR_HEADER_SIZE);

    //printHexDump(headerByes, "hex dump of the byte-array");

    if (nbytes == 0) {
        throw new IOException("decodeHeader: reading failure");
    } else if (nbytes < 491) {
        // Size test: by defnition, it must have at least
        // 491-byte header, i.e., the file size less than this threshold
        // is not a POR file
        dbgLog.fine("this file is NOT spss-por type");
        throw new IllegalArgumentException("file is not spss-por type");
    }
    // rewind the current reading position back to the beginning
    if (stream.markSupported()) {
        stream.reset();
    }

    // line-terminating characters are usually one or two by defnition
    // however, a POR file saved by a genuine SPSS for Windows
    // had a three-character line terminator, i.e., failed to remove the
    // original file's one-character terminator when it was opened, and
    // saved it with the default two-character terminator without
    // removing original terminators. So we have to expect such a rare
    // case
    //
    // terminator
    // windows [0D0A]=>   [1310] = [CR/LF]
    // unix    [0A]  =>   [10]
    // mac     [0D]  =>   [13]
    // 3char  [0D0D0A]=> [131310] spss for windows rel 15
    //
    // terminating characters should be found at the following
    //                             column positions[counting from 0]:
    // unix    case: [0A]   : [80], [161], [242], [323], [404], [485]
    // windows case: [0D0A] : [81], [163], [245], [327], [409], [491]
    //           : [0D0D0A] : [82], [165], [248], [331], [414], [495]

    // convert b into a ByteBuffer

    ByteBuffer buff = ByteBuffer.wrap(headerByes);
    byte[] nlch = new byte[36];
    int pos1;
    int pos2;
    int pos3;
    int ucase = 0;
    int wcase = 0;
    int mcase = 0;
    int three = 0;
    int nolines = 6;
    int nocols = 80;
    for (int i = 0; i < nolines; ++i) {
        int baseBias = nocols * (i + 1);
        // 1-char case
        pos1 = baseBias + i;
        buff.position(pos1);
        dbgLog.finer("\tposition(1)=" + buff.position());
        int j = 6 * i;
        nlch[j] = buff.get();

        if (nlch[j] == 10) {
            ucase++;
        } else if (nlch[j] == 13) {
            mcase++;
        }

        // 2-char case
        pos2 = baseBias + 2 * i;
        buff.position(pos2);
        dbgLog.finer("\tposition(2)=" + buff.position());

        nlch[j + 1] = buff.get();
        nlch[j + 2] = buff.get();

        // 3-char case
        pos3 = baseBias + 3 * i;
        buff.position(pos3);
        dbgLog.finer("\tposition(3)=" + buff.position());

        nlch[j + 3] = buff.get();
        nlch[j + 4] = buff.get();
        nlch[j + 5] = buff.get();

        dbgLog.finer(i + "-th iteration position =" + nlch[j] + "\t" + nlch[j + 1] + "\t" + nlch[j + 2]);
        dbgLog.finer(i + "-th iteration position =" + nlch[j + 3] + "\t" + nlch[j + 4] + "\t" + nlch[j + 5]);

        if ((nlch[j + 3] == 13) && (nlch[j + 4] == 13) && (nlch[j + 5] == 10)) {
            three++;
        } else if ((nlch[j + 1] == 13) && (nlch[j + 2] == 10)) {
            wcase++;
        }

        buff.rewind();
    }

    boolean windowsNewLine = true;
    if (three == nolines) {
        windowsNewLine = false; // lineTerminator = "0D0D0A"
    } else if ((ucase == nolines) && (wcase < nolines)) {
        windowsNewLine = false; // lineTerminator = "0A"
    } else if ((ucase < nolines) && (wcase == nolines)) {
        windowsNewLine = true; //lineTerminator = "0D0A"
    } else if ((mcase == nolines) && (wcase < nolines)) {
        windowsNewLine = false; //lineTerminator = "0D"
    }

    buff.rewind();
    int PORmarkPosition = POR_MARK_POSITION_DEFAULT;
    if (windowsNewLine) {
        PORmarkPosition = PORmarkPosition + 5;
    } else if (three == nolines) {
        PORmarkPosition = PORmarkPosition + 10;
    }

    byte[] pormark = new byte[8];
    buff.position(PORmarkPosition);
    buff.get(pormark, 0, 8);
    String pormarks = new String(pormark);

    //dbgLog.fine("pormark =>" + pormarks + "<-");
    dbgLog.fine(
            "pormark[hex: 53 50 53 53 50 4F 52 54 == SPSSPORT] =>" + new String(Hex.encodeHex(pormark)) + "<-");

    if (pormarks.equals(POR_MARK)) {
        dbgLog.fine("POR ID toke test: Passed");
        init();

        dataTable.setOriginalFileFormat(MIME_TYPE);
        dataTable.setUnf("UNF:6:NOTCALCULATED");

    } else {
        dbgLog.fine("this file is NOT spss-por type");
        throw new IllegalArgumentException("decodeHeader: POR ID token was not found");
    }

    // save the POR file without new line characters

    FileOutputStream fileOutPOR = null;
    Writer fileWriter = null;

    // Scanner class can handle three-character line-terminator
    Scanner porScanner = null;

    try {
        tempPORfile = File.createTempFile("tempPORfile.", ".por");
        fileOutPOR = new FileOutputStream(tempPORfile);
        fileWriter = new BufferedWriter(new OutputStreamWriter(fileOutPOR, "utf8"));
        porScanner = new Scanner(stream);

        // Because 64-bit and 32-bit machines decode POR's first 40-byte
        // sequence differently, the first 5 leader lines are skipped from
        // the new-line-stripped file

        int lineCounter = 0;
        while (porScanner.hasNextLine()) {
            lineCounter++;
            if (lineCounter <= 5) {
                String line = porScanner.nextLine();
                dbgLog.fine("line=" + lineCounter + ":" + line.length() + ":" + line);
            } else {
                fileWriter.write(porScanner.nextLine());
            }
        }
    } finally {
        try {
            if (fileWriter != null) {
                fileWriter.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        if (porScanner != null) {
            porScanner.close();
        }
    }

    return tempPORfile;
}

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

/**
 * Updates free space and row info for a new row of the given size in the
 * given data page.  Positions the page for writing the row data.
 * @return the row number of the new row
 * @usage _advanced_method_/*from w ww .j  av  a2  s  .c om*/
 */
public static int addDataPageRow(ByteBuffer dataPage, int rowSize, JetFormat format, int rowFlags) {
    int rowSpaceUsage = getRowSpaceUsage(rowSize, format);

    // Decrease free space record.
    short freeSpaceInPage = dataPage.getShort(format.OFFSET_FREE_SPACE);
    dataPage.putShort(format.OFFSET_FREE_SPACE, (short) (freeSpaceInPage - rowSpaceUsage));

    // Increment row count record.
    short rowCount = dataPage.getShort(format.OFFSET_NUM_ROWS_ON_DATA_PAGE);
    dataPage.putShort(format.OFFSET_NUM_ROWS_ON_DATA_PAGE, (short) (rowCount + 1));

    // determine row position
    short rowLocation = findRowEnd(dataPage, rowCount, format);
    rowLocation -= rowSize;

    // write row position
    dataPage.putShort(getRowStartOffset(rowCount, format), (short) (rowLocation | rowFlags));

    // set position for row data
    dataPage.position(rowLocation);

    return rowCount;
}