Example usage for java.nio ByteBuffer order

List of usage examples for java.nio ByteBuffer order

Introduction

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

Prototype

Endianness order

To view the source code for java.nio ByteBuffer order.

Click Source Link

Document

The byte order of this buffer, default is BIG_ENDIAN .

Usage

From source file:au.org.ala.layers.intersect.Grid.java

/**
 * for DomainGenerator//from  ww  w  .j  a  v  a2s.c  o  m
 * <p/>
 * writes out a list of double (same as getGrid() returns) to a file
 * <p/>
 * byteorderlsb
 * data type, FLOAT
 *
 * @param newfilename
 * @param dfiltered
 */
public void writeGrid(String newfilename, int[] dfiltered, double xmin, double ymin, double xmax, double ymax,
        double xres, double yres, int nrows, int ncols) {
    int size, i, length = dfiltered.length;
    double maxvalue = Integer.MAX_VALUE * -1;
    double minvalue = Integer.MAX_VALUE;

    //write data as whole file
    RandomAccessFile afile = null;
    try { //read of random access file can throw an exception
        afile = new RandomAccessFile(newfilename + ".gri", "rw");

        size = 4;
        byte[] b = new byte[size * length];
        ByteBuffer bb = ByteBuffer.wrap(b);

        if (byteorderLSB) {
            bb.order(ByteOrder.LITTLE_ENDIAN);
        } else {
            bb.order(ByteOrder.BIG_ENDIAN);
        }
        for (i = 0; i < length; i++) {
            bb.putInt(dfiltered[i]);
        }

        afile.write(b);
    } catch (Exception e) {
        logger.error("error writing grid file", e);
    } finally {
        if (afile != null) {
            try {
                afile.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }

    writeHeader(newfilename, xmin, ymin, xmin + xres * ncols, ymin + yres * nrows, xres, yres, nrows, ncols,
            minvalue, maxvalue, "INT4BYTES", "-9999");

}

From source file:edu.jhu.cvrg.services.nodeDataService.DataStaging.java

/** Reads the WFDB file from the brokerURL and stores it as the RdtData of a VisualizationData.
 * It is assuming that the file is in RDT format, with 3 leads.
 *
 * @param tempFile - name of a local RDT file containing ECG data. 
 * @param fileSize - used to size the file reading buffer.
 * @param offsetMilliSeconds - number of milliseconds from the beginning of the ECG at which to start the graph.
 * @param durationMilliSeconds - The requested length of the returned data subset, in milliseconds.
 * @param graphWidthPixels - Width of the zoomed graph in pixels(zoom factor*unzoomed width), hence the maximum points needed in the returned VisualizationData.
 * @param callback - call back handler class.
 *     //  w w w.  j  a va 2s  .  c om
 * @see org.cvrgrid.widgets.node.client.BrokerService#fetchSubjectVisualization(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, long, int, int)
 */
private VisualizationData fetchWFDBdataSegment(String tempFile, long fileSize, int offsetMilliSeconds,
        int durationMilliSeconds, int graphWidthPixels) {
    BufferedInputStream rdtBis = null;
    VisualizationData visualizationData = new VisualizationData();
    try {
        //******************************************
        try {
            FileInputStream isFile = new FileInputStream(tempFile);
            //*******************************************
            //    * @param skippedSamples - number of samples to skip after each one returned. To adjust for graph resolution.
            int samplesPerPixel, skippedSamples, durationInSamples;
            rdtBis = new BufferedInputStream(isFile);

            //Read the 4 header bytes
            byte[] header = new byte[HEADERBYTES];
            int result = rdtBis.read(header, 0, HEADERBYTES);

            if (result == HEADERBYTES) {
                ByteBuffer bbHead = ByteBuffer.wrap(header);
                bbHead.order(BYTEORDER);

                short channels = bbHead.getShort();
                short samplingRate = bbHead.getShort(); // replaced with subjectData.setSamplingRate() 
                float fRateMsec = (float) (samplingRate / 1000.0);
                if (offsetMilliSeconds < 0)
                    offsetMilliSeconds = 0; // cannot read before the beginning of the file.
                int vizOffset = (int) (offsetMilliSeconds * fRateMsec);

                //-------------------------------------------------
                // Calculate and Set Visualization parameters
                final int REALBUFFERSIZE = (int) fileSize - HEADERBYTES;
                if (REALBUFFERSIZE % (channels * SHORTBYTES) != 0) {
                    System.err.println("rdt file is not aligned.");
                }
                int counts = REALBUFFERSIZE / (channels * SHORTBYTES);
                byte[][] body = new byte[counts][(channels * SHORTBYTES)];
                byte[] sample = new byte[(channels * SHORTBYTES)]; /** A single reading from all leads. **/
                try {

                    int requestedMaxPoints;
                    durationInSamples = (int) (fRateMsec * durationMilliSeconds);
                    if (durationInSamples > graphWidthPixels) {
                        samplesPerPixel = durationInSamples / graphWidthPixels;
                        requestedMaxPoints = graphWidthPixels;
                    } else {
                        samplesPerPixel = 1;
                        requestedMaxPoints = durationInSamples;
                    }
                    skippedSamples = samplesPerPixel - 1;

                    int availableSamples = counts - vizOffset; // total number of remaining samples from this offset.
                    int availablePoints = availableSamples / samplesPerPixel; // total number of graphable points from this offset.
                    int maxPoints = 0; // maximum data points that can be returned.
                    // ensure that the copying loop doesn't try to go past the end of the data file.
                    if (availablePoints > requestedMaxPoints) {
                        maxPoints = requestedMaxPoints;
                    } else { // Requested duration is longer than the remainder after the offset.
                        if (durationInSamples < counts) { // Requested duration is less than the file contains.
                            // move the offset back so the requested amount of samples can be returned.
                            vizOffset = counts - durationInSamples;
                            maxPoints = requestedMaxPoints;
                        } else { // Requested duration is longer than the file contains.
                            maxPoints = availablePoints;
                        }
                    }
                    visualizationData.setRdtDataLength(maxPoints);
                    visualizationData.setRdtDataLeads(channels);
                    visualizationData.setOffset(vizOffset);
                    visualizationData.setSkippedSamples(skippedSamples);
                    int msDuration = (counts * 1000) / samplingRate;
                    visualizationData.setMsDuration(msDuration);

                    //------------------------------------------------
                    // Read the rest of the file to get the data.
                    ByteBuffer bbSample;
                    double[][] tempData = new double[maxPoints][channels];
                    int fileOffset = vizOffset * channels * SHORTBYTES; //offset in bytes from the beginning of the file.

                    int index1, index2, s, outSample = 0;
                    index2 = vizOffset; // index of the first sample to return data for, index is in samples not bytes.
                    int length, bisOffset, bisLen = sample.length;
                    // read entire file into the local byte array "body"
                    for (index1 = 0; index1 < counts; index1++) {
                        bisOffset = HEADERBYTES + (index1 * bisLen);
                        s = 0;
                        for (int c = 0; c < (bisLen * 4); c++) { // make up to 4 attempts to read 
                            length = rdtBis.read(sample, s, 1);// read one byte into the byte array "sample", explicitly specifying which byte to read.
                            if (length == 1)
                                s++; // successfully read the byte, go to the next one.
                            if (s == bisLen)
                                break; // last byte has been read.
                        }

                        if (index1 == index2) { // add this sample the output data
                            bbSample = ByteBuffer.wrap(sample);
                            bbSample.order(BYTEORDER);

                            for (int ch = 0; ch < channels; ch++) {
                                short value = bbSample.getShort(); // reads a Short, increments position() by 2 bytes.
                                tempData[outSample][ch] = (double) value;
                            }

                            bbSample.clear();
                            index2 = index2 + 1 + skippedSamples;
                            outSample++;
                            if (outSample == maxPoints)
                                break;
                        }
                    }

                    visualizationData.setRdtData(tempData);

                    //*******************************************
                    isFile.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                System.err.println(
                        "fetchSubjectVisualization failed, error occured while reading header of the RDT file:"
                                + tempFile);
            }
            //*******************************************
        } catch (IOException e1) {
            e1.printStackTrace();
        } finally {
            try {
                rdtBis.close();
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return visualizationData;
}

From source file:edu.jhu.cvrg.services.nodeDataService.DataStaging.java

/** Reads the file from the brokerURL and stores it as the RdtData of a VisualizationData.
 * It is assuming that the file is in RDT format, with 3 leads.
 *
 * @param tempFile - name of a local RDT file containing ECG data. 
 * @param fileSize - used to size the file reading buffer.
 * @param offsetMilliSeconds - number of milliseconds from the beginning of the ECG at which to start the graph.
 * @param durationMilliSeconds - The requested length of the returned data subset, in milliseconds.
 * @param graphWidthPixels - Width of the zoomed graph in pixels(zoom factor*unzoomed width), hence the maximum points needed in the returned VisualizationData.
 * @param callback - call back handler class.
 *     //from w  w w.ja v  a  2 s . c  o m
 * @see org.cvrgrid.widgets.node.client.BrokerService#fetchSubjectVisualization(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, long, int, int)
 */
private VisualizationData fetchSubjectVisualization(String tempFile, long fileSize, int offsetMilliSeconds,
        int durationMilliSeconds, int graphWidthPixels) {
    BufferedInputStream rdtBis = null;
    VisualizationData visualizationData = new VisualizationData();
    try {
        //******************************************
        try {
            FileInputStream isFile = new FileInputStream(tempFile);
            //*******************************************

            int samplesPerPixel, skippedSamples, durationInSamples;
            rdtBis = new BufferedInputStream(isFile);

            //Read the 4 header bytes
            byte[] header = new byte[HEADERBYTES];
            int result = rdtBis.read(header, 0, HEADERBYTES);

            if (result == HEADERBYTES) {
                ByteBuffer bbHead = ByteBuffer.wrap(header);
                bbHead.order(BYTEORDER);

                short channels = bbHead.getShort();
                short samplingRate = bbHead.getShort(); // replaced with subjectData.setSamplingRate() 
                float fRateMsec = (float) (samplingRate / 1000.0);
                if (offsetMilliSeconds < 0)
                    offsetMilliSeconds = 0; // cannot read before the beginning of the file.
                int vizOffset = (int) (offsetMilliSeconds * fRateMsec);

                //-------------------------------------------------
                // Calculate and Set Visualization parameters
                final int REALBUFFERSIZE = (int) fileSize - HEADERBYTES;
                if (REALBUFFERSIZE % (channels * SHORTBYTES) != 0) {
                    System.err.println("rdt file is not aligned.");
                }
                int counts = REALBUFFERSIZE / (channels * SHORTBYTES);
                byte[][] body = new byte[counts][(channels * SHORTBYTES)];
                byte[] sample = new byte[(channels * SHORTBYTES)]; /** A single reading from all leads. **/
                try {
                    @SuppressWarnings("unused") // used to test rdtBis.read for exceptions

                    int requestedMaxPoints;
                    durationInSamples = (int) (fRateMsec * durationMilliSeconds);
                    if (durationInSamples > graphWidthPixels) {
                        samplesPerPixel = durationInSamples / graphWidthPixels;
                        requestedMaxPoints = graphWidthPixels;
                    } else {
                        samplesPerPixel = 1;
                        requestedMaxPoints = durationInSamples;
                    }
                    skippedSamples = samplesPerPixel - 1;

                    int availableSamples = counts - vizOffset; // total number of remaining samples from this offset.
                    int availablePoints = availableSamples / samplesPerPixel; // total number of graphable points from this offset.
                    int maxPoints = 0; // maximum data points that can be returned.
                    // ensure that the copying loop doesn't try to go past the end of the data file.
                    if (availablePoints > requestedMaxPoints) {
                        maxPoints = requestedMaxPoints;
                    } else { // Requested duration is longer than the remainder after the offset.
                        if (durationInSamples < counts) { // Requested duration is less than the file contains.
                            // move the offset back so the requested amount of samples can be returned.
                            vizOffset = counts - durationInSamples;
                            maxPoints = requestedMaxPoints;
                        } else { // Requested duration is longer than the file contains.
                            maxPoints = availablePoints;
                        }
                    }
                    visualizationData.setRdtDataLength(maxPoints);
                    visualizationData.setRdtDataLeads(channels);
                    visualizationData.setOffset(vizOffset);
                    visualizationData.setSkippedSamples(skippedSamples);
                    int msDuration = (counts * 1000) / samplingRate;
                    visualizationData.setMsDuration(msDuration);

                    //------------------------------------------------
                    // Read the rest of the file to get the data.
                    ByteBuffer bbSample;
                    double[][] tempData = new double[maxPoints][channels];
                    int fileOffset = vizOffset * channels * SHORTBYTES; //offset in bytes from the beginning of the file.

                    int index1, index2, s, outSample = 0;
                    index2 = vizOffset; // index of the first sample to return data for, index is in samples not bytes.
                    int length, bisOffset, bisLen = sample.length;
                    // read entire file into the local byte array "body"
                    for (index1 = 0; index1 < counts; index1++) {
                        bisOffset = HEADERBYTES + (index1 * bisLen);
                        s = 0;
                        for (int c = 0; c < (bisLen * 4); c++) { // make up to 4 attempts to read 
                            length = rdtBis.read(sample, s, 1);// read one byte into the byte array "sample", explicitly specifying which byte to read.
                            if (length == 1)
                                s++; // successfully read the byte, go to the next one.
                            if (s == bisLen)
                                break; // last byte has been read.
                        }

                        if (index1 == index2) { // add this sample the output data
                            bbSample = ByteBuffer.wrap(sample);
                            bbSample.order(BYTEORDER);

                            for (int ch = 0; ch < channels; ch++) {
                                short value = bbSample.getShort(); // reads a Short, increments position() by 2 bytes.
                                tempData[outSample][ch] = (double) value;
                            }

                            bbSample.clear();
                            index2 = index2 + 1 + skippedSamples;
                            outSample++;
                            if (outSample == maxPoints)
                                break;
                        }
                    }

                    visualizationData.setRdtData(tempData);

                    //*******************************************
                    isFile.close();
                    //             br.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                System.err.println(
                        "fetchSubjectVisualization failed, error occured while reading header of the RDT file:"
                                + tempFile);
            }
            //*******************************************
        } catch (IOException e1) {
            e1.printStackTrace();
        } finally {
            try {
                rdtBis.close();
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return visualizationData;
}

From source file:au.org.ala.layers.intersect.Grid.java

/**
 * for grid cutter//ww  w  .ja v a  2 s .c  o m
 * <p/>
 * writes out a list of double (same as getGrid() returns) to a file
 * <p/>
 * byteorderlsb
 * data type, FLOAT
 *
 * @param newfilename
 * @param dfiltered
 */
public void writeGrid(String newfilename, double[] dfiltered, double xmin, double ymin, double xmax,
        double ymax, double xres, double yres, int nrows, int ncols) {
    int size, i, length = dfiltered.length;
    double maxvalue = Double.MAX_VALUE * -1;
    double minvalue = Double.MAX_VALUE;

    //write data as whole file
    RandomAccessFile afile = null;
    try { //read of random access file can throw an exception
        afile = new RandomAccessFile(newfilename + ".gri", "rw");

        size = 4;
        byte[] b = new byte[size * length];
        ByteBuffer bb = ByteBuffer.wrap(b);

        if (byteorderLSB) {
            bb.order(ByteOrder.LITTLE_ENDIAN);
        } else {
            bb.order(ByteOrder.BIG_ENDIAN);
        }
        for (i = 0; i < length; i++) {
            if (Double.isNaN(dfiltered[i])) {
                bb.putFloat((float) noDataValueDefault);
            } else {
                if (minvalue > dfiltered[i]) {
                    minvalue = dfiltered[i];
                }
                if (maxvalue < dfiltered[i]) {
                    maxvalue = dfiltered[i];
                }
                bb.putFloat((float) dfiltered[i]);
            }
        }

        afile.write(b);
    } catch (Exception e) {
        logger.error("error writing grid file", e);
    } finally {
        if (afile != null) {
            try {
                afile.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }

    writeHeader(newfilename, xmin, ymin, xmin + xres * ncols, ymin + yres * nrows, xres, yres, nrows, ncols,
            minvalue, maxvalue, "FLT4BYTES", String.valueOf(noDataValueDefault));
}

From source file:au.org.ala.layers.intersect.Grid.java

public void writeGrid(String newfilename, float[] dfiltered, double xmin, double ymin, double xmax, double ymax,
        double xres, double yres, int nrows, int ncols) {
    int size, i, length = dfiltered.length;
    double maxvalue = Double.MAX_VALUE * -1;
    double minvalue = Double.MAX_VALUE;

    //write data as whole file
    RandomAccessFile afile = null;
    try { //read of random access file can throw an exception
        afile = new RandomAccessFile(newfilename + ".gri", "rw");

        size = 4;/* w ww  . j ava 2  s . c o  m*/
        byte[] b = new byte[size * length];
        ByteBuffer bb = ByteBuffer.wrap(b);

        if (byteorderLSB) {
            bb.order(ByteOrder.LITTLE_ENDIAN);
        } else {
            bb.order(ByteOrder.BIG_ENDIAN);
        }
        for (i = 0; i < length; i++) {
            if (Double.isNaN(dfiltered[i])) {
                bb.putFloat((float) noDataValueDefault);
            } else {
                if (minvalue > dfiltered[i]) {
                    minvalue = dfiltered[i];
                }
                if (maxvalue < dfiltered[i]) {
                    maxvalue = dfiltered[i];
                }
                bb.putFloat((float) dfiltered[i]);
            }
        }

        afile.write(b);
    } catch (Exception e) {
        logger.error("error writing grid file", e);
    } finally {
        if (afile != null) {
            try {
                afile.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }

    writeHeader(newfilename, xmin, ymin, xmin + xres * ncols, ymin + yres * nrows, xres, yres, nrows, ncols,
            minvalue, maxvalue, "FLT4BYTES", String.valueOf(noDataValueDefault));

}

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

/**
 * Deserialize a raw byte value for this column into an Object
 * @param data The raw byte value/*ww  w.j ava 2 s . co m*/
 * @param order Byte order in which the raw value is stored
 * @return The deserialized Object
 * @usage _advanced_method_
 */
public Object read(byte[] data, ByteOrder order) throws IOException {
    ByteBuffer buffer = ByteBuffer.wrap(data);
    buffer.order(order);
    if (_type == DataType.BOOLEAN) {
        throw new IOException("Tried to read a boolean from data instead of null mask.");
    } else if (_type == DataType.BYTE) {
        return Byte.valueOf(buffer.get());
    } else if (_type == DataType.INT) {
        return Short.valueOf(buffer.getShort());
    } else if (_type == DataType.LONG) {
        return Integer.valueOf(buffer.getInt());
    } else if (_type == DataType.DOUBLE) {
        return Double.valueOf(buffer.getDouble());
    } else if (_type == DataType.FLOAT) {
        return Float.valueOf(buffer.getFloat());
    } else if (_type == DataType.SHORT_DATE_TIME) {
        return readDateValue(buffer);
    } else if (_type == DataType.BINARY) {
        return data;
    } else if (_type == DataType.TEXT) {
        return decodeTextValue(data);
    } else if (_type == DataType.MONEY) {
        return readCurrencyValue(buffer);
    } else if (_type == DataType.OLE) {
        if (data.length > 0) {
            return readLongValue(data);
        }
        return null;
    } else if (_type == DataType.MEMO) {
        if (data.length > 0) {
            return readLongStringValue(data);
        }
        return null;
    } else if (_type == DataType.NUMERIC) {
        return readNumericValue(buffer);
    } else if (_type == DataType.GUID) {
        return readGUIDValue(buffer, order);
    } else if ((_type == DataType.UNKNOWN_0D) || (_type == DataType.UNKNOWN_11)) {
        // treat like "binary" data
        return data;
    } else if (_type == DataType.COMPLEX_TYPE) {
        return new ComplexValueForeignKey(this, buffer.getInt());
    } else if (_type.isUnsupported()) {
        return rawDataWrapper(data);
    } else {
        throw new IOException("Unrecognized data type: " + _type);
    }
}

From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.dta.DTAFileReader.java

void parseValueLabelsRelease105(BufferedInputStream stream) throws IOException {

    dbgLog.fine("***** parseValueLabelsRelease105(): start *****");

    if (stream == null) {
        throw new IllegalArgumentException("stream == null!");
    }/*from  ww  w  . j a  va2s  .  c om*/

    int nvar = (Integer) smd.getFileInformation().get("varQnty");
    int length_label_name = constantTable.get("NAME") + 1;
    // note: caution +1 as the null character, not 9 byte

    int length_value_label_header = value_label_table_length + length_label_name;

    if (dbgLog.isLoggable(Level.FINE))
        dbgLog.fine("value_label_table_length=" + value_label_table_length);
    if (dbgLog.isLoggable(Level.FINE))
        dbgLog.fine("length_value_label_header=" + length_value_label_header);

    int length_lable_name_field = 8;

    /*
    Seg  field         byte    type
    1-1. no of pairs      2    int  (= m)
    1-2. vlt_name        10    includes char+(\0) == name used in Sec2.part 5
     -----------------------------------
                         11
    2-1. values         2*n    int[]
    2-2. labels         8*n    char
    */

    for (int i = 0; i < nvar; i++) {
        if (dbgLog.isLoggable(Level.FINE))
            dbgLog.fine("\n\n" + i + "th value-label table header");

        byte[] valueLabelHeader = new byte[length_value_label_header];

        // Part 1: reading the header of a value-label table if exists
        int nbytes = stream.read(valueLabelHeader, 0, length_value_label_header);

        if (nbytes == 0) {
            throw new IOException("reading value label header: no datum");
        }

        // 1.1 number of value-label pairs in this table (= m)
        ByteBuffer bb_value_label_pairs = ByteBuffer.wrap(valueLabelHeader, 0, value_label_table_length);
        if (isLittleEndian) {
            bb_value_label_pairs.order(ByteOrder.LITTLE_ENDIAN);
            //if (dbgLog.isLoggable(Level.FINE)) dbgLog.fine("value lable table lenth: byte reversed");
        }
        int no_value_label_pairs = bb_value_label_pairs.getShort();

        if (dbgLog.isLoggable(Level.FINE))
            dbgLog.fine("no_value_label_pairs=" + no_value_label_pairs);

        // 1.2 labelName
        String rawLabelName = new String(Arrays.copyOfRange(valueLabelHeader, value_label_table_length,
                (value_label_table_length + length_label_name)), "ISO-8859-1");

        if (dbgLog.isLoggable(Level.FINE))
            dbgLog.fine("rawLabelName(length)=" + rawLabelName.length());
        String labelName = rawLabelName.substring(0, rawLabelName.indexOf(0));

        if (dbgLog.isLoggable(Level.FINE))
            dbgLog.fine("label name = " + labelName + "\n");

        if (dbgLog.isLoggable(Level.FINE))
            dbgLog.fine(i + "-th value-label table");
        // Part 2: reading the value-label table
        // the length of the value-label table is: 2*m + 8*m = 10*m
        int length_value_label_table = (value_label_table_length + length_lable_name_field)
                * no_value_label_pairs;

        if (dbgLog.isLoggable(Level.FINE))
            dbgLog.fine("length_value_label_table=" + length_value_label_table);

        byte[] valueLabelTable_i = new byte[length_value_label_table];
        int noBytes = stream.read(valueLabelTable_i, 0, length_value_label_table);
        if (noBytes == 0) {
            throw new IOException("reading value label table: no datum");
        }

        // 2-1. 2-byte-integer array (2*m): value array (sorted)

        short[] valueList = new short[no_value_label_pairs];
        int offset_value = 0;

        for (int k = 0; k < no_value_label_pairs; k++) {

            ByteBuffer bb_value_list = ByteBuffer.wrap(valueLabelTable_i, offset_value,
                    value_label_table_length);
            if (isLittleEndian) {
                bb_value_list.order(ByteOrder.LITTLE_ENDIAN);
            }
            valueList[k] = bb_value_list.getShort();

            offset_value += value_label_table_length;
        }

        if (dbgLog.isLoggable(Level.FINE))
            dbgLog.fine("value_list=" + Arrays.toString(valueList) + "\n");

        // 2-2. 8-byte chars that store label data (m units of labels)

        if (dbgLog.isLoggable(Level.FINE))
            dbgLog.fine("current offset_value=" + offset_value);

        int offset_start = offset_value;
        int offset_end = offset_value + length_lable_name_field;
        String[] labelList = new String[no_value_label_pairs];

        for (int l = 0; l < no_value_label_pairs; l++) {

            String string_l = new String(Arrays.copyOfRange(valueLabelTable_i, offset_start, offset_end),
                    "ISO-8859-1");

            int null_position = string_l.indexOf(0);
            if (null_position != -1) {
                labelList[l] = string_l.substring(0, null_position);
            } else {
                labelList[l] = string_l;
            }

            offset_start = offset_end;
            offset_end += length_lable_name_field;
        }

        Map<String, String> tmpValueLabelTable = new LinkedHashMap<String, String>();

        for (int j = 0; j < no_value_label_pairs; j++) {
            if (dbgLog.isLoggable(Level.FINE))
                dbgLog.fine(j + "-th pair:" + valueList[j] + "[" + labelList[j] + "]");
            tmpValueLabelTable.put(Integer.toString(valueList[j]), labelList[j]);
        }
        valueLabelTable.put(labelName, tmpValueLabelTable);

        if (stream.available() == 0) {
            // reached the end of this file
            // do exit-processing
            if (dbgLog.isLoggable(Level.FINE))
                dbgLog.fine("***** reached the end of the file at " + i + "th value-label Table *****");
            break;
        }

    } // for-loop

    if (dbgLog.isLoggable(Level.FINE))
        dbgLog.fine("valueLabelTable:\n" + valueLabelTable);

    smd.setValueLabelTable(valueLabelTable);

    dbgLog.fine("***** parseValueLabelsRelease105(): end *****");

}

From source file:au.org.ala.layers.intersect.Grid.java

public void mergeMissingValues(Grid sourceOfMissingValues, boolean hideMissing) {
    float[] cells = sourceOfMissingValues.getGrid();

    float[] actual = getGrid();

    int length = actual.length;

    int i;//  ww w  . j a v  a  2 s.c o  m
    RandomAccessFile afile = null;
    File f2 = new File(filename + ".GRI");

    try { //read of random access file can throw an exception
        if (!f2.exists()) {
            afile = new RandomAccessFile(filename + ".gri", "rw");
        } else {
            afile = new RandomAccessFile(filename + ".GRI", "rw");
        }

        byte[] b = new byte[(int) afile.length()];

        ByteBuffer bb = ByteBuffer.wrap(b);

        if (byteorderLSB) {
            bb.order(ByteOrder.LITTLE_ENDIAN);
        }

        afile.seek(0);

        if (datatype.equalsIgnoreCase("UBYTE")) {
            for (i = 0; i < length; i++) {
                if (hideMissing == Float.isNaN(cells[i])) {
                    if (nodatavalue >= 128) {
                        bb.put((byte) (nodatavalue - 256));
                    } else {
                        bb.put((byte) nodatavalue);
                    }
                } else {
                    if (actual[i] >= 128) {
                        bb.put((byte) (actual[i] - 256));
                    } else {
                        bb.put((byte) actual[i]);
                    }
                }
            }
        } else if (datatype.equalsIgnoreCase("BYTE")) {
            for (i = 0; i < length; i++) {
                bb.put((byte) actual[i]);
            }
        } else if (datatype.equalsIgnoreCase("SHORT")) {
            for (i = 0; i < length; i++) {
                if (hideMissing == Float.isNaN(cells[i])) {
                    bb.putShort((short) nodatavalue);
                } else {
                    bb.putShort((short) actual[i]);
                }
            }
        } else if (datatype.equalsIgnoreCase("INT")) {
            for (i = 0; i < length; i++) {
                if (hideMissing == Float.isNaN(cells[i])) {
                    bb.putInt((int) nodatavalue);
                } else {
                    bb.putInt((int) actual[i]);
                }
            }
        } else if (datatype.equalsIgnoreCase("LONG")) {
            for (i = 0; i < length; i++) {
                if (hideMissing == Float.isNaN(cells[i])) {
                    bb.putLong((long) nodatavalue);
                } else {
                    bb.putLong((long) actual[i]);
                }
            }
        } else if (datatype.equalsIgnoreCase("FLOAT")) {
            for (i = 0; i < length; i++) {
                if (hideMissing == Float.isNaN(cells[i])) {
                    bb.putFloat((float) nodatavalue);
                } else {
                    bb.putFloat(actual[i]);
                }
            }
        } else if (datatype.equalsIgnoreCase("DOUBLE")) {
            for (i = 0; i < length; i++) {
                if (hideMissing == Float.isNaN(cells[i])) {
                    bb.putDouble((double) nodatavalue);
                } else {
                    bb.putDouble((double) actual[i]);
                }
            }
        } else {
            // should not happen
            logger.error("unsupported grid data type: " + datatype);
        }

        afile.write(bb.array());
    } catch (Exception e) {
        logger.error("error getting grid file values", e);
    } finally {
        if (afile != null) {
            try {
                afile.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
}

From source file:au.org.ala.layers.intersect.Grid.java

public void getClassInfo(Map<Float, float[]> info) {

    long length = ((long) nrows) * ((long) ncols);

    RandomAccessFile afile = null;
    File f2 = new File(filename + ".GRI");

    try { //read of random access file can throw an exception
        if (!f2.exists()) {
            afile = new RandomAccessFile(filename + ".gri", "r");
        } else {//from w w  w.ja  v a2s. c  o  m
            afile = new RandomAccessFile(filename + ".GRI", "r");
        }

        byte[] b = new byte[65536];

        long i = 0;
        long max = 0;
        long len;
        float v;
        float ndv = (float) nodatavalue;

        while ((len = afile.read(b)) > 0) {
            ByteBuffer bb = ByteBuffer.wrap(b);

            if (byteorderLSB) {
                bb.order(ByteOrder.LITTLE_ENDIAN);
            }

            if (datatype.equalsIgnoreCase("UBYTE")) {
                max += len;
                max = Math.min(max, length);
                for (; i < max; i++) {
                    v = bb.get();
                    if (v < 0)
                        v += 256;
                    if (v != ndv)
                        updatesStats(info, i, v * rescale);
                }
            } else if (datatype.equalsIgnoreCase("BYTE")) {
                max += len;
                max = Math.min(max, length);
                for (; i < max; i++) {
                    v = bb.get();
                    if (v != ndv)
                        updatesStats(info, i, v * rescale);
                }
            } else if (datatype.equalsIgnoreCase("SHORT")) {
                max += len / 2;
                max = Math.min(max, length);
                for (; i < max; i++) {
                    v = bb.getShort();
                    if (v != ndv)
                        updatesStats(info, i, v * rescale);
                }
            } else if (datatype.equalsIgnoreCase("INT")) {
                max += len / 4;
                max = Math.min(max, length);
                for (; i < max; i++) {
                    v = bb.getInt();
                    if (v != ndv)
                        updatesStats(info, i, v * rescale);
                }
            } else if (datatype.equalsIgnoreCase("LONG")) {
                max += len / 8;
                max = Math.min(max, length);
                for (; i < max; i++) {
                    v = bb.getLong();
                    if (v != ndv)
                        updatesStats(info, i, v * rescale);
                }
            } else if (datatype.equalsIgnoreCase("FLOAT")) {
                max += len / 4;
                max = Math.min(max, length);
                for (; i < max; i++) {
                    v = bb.getFloat();
                    if (v != ndv)
                        updatesStats(info, i, v * rescale);
                }
            } else if (datatype.equalsIgnoreCase("DOUBLE")) {
                max += len / 8;
                max = Math.min(max, length);
                for (; i < max; i++) {
                    v = (float) bb.getDouble();
                    if (v != ndv)
                        updatesStats(info, i, v * rescale);
                }
            } else {
                max += len / 4;
                for (; i < max; i++) {
                    // should not happen; catch anyway...
                }
            }
        }
    } catch (Exception e) {
        logger.error("An error has occurred getting grid class stats", e);
    } finally {
        if (afile != null) {
            try {
                afile.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }

}

From source file:au.org.ala.layers.intersect.Grid.java

public float[] getGrid() {
    int maxArrayLength = Integer.MAX_VALUE - 10;

    if (grid_data != null) {
        return grid_data;
    }// w  ww. j  ava 2 s. co m

    Grid loadedAlready = getLoadedGrid(filename);
    if (loadedAlready != null && loadedAlready.grid_data != null) {
        return loadedAlready.grid_data;
    }

    int length = nrows * ncols;

    float[] ret = new float[length];

    RandomAccessFile afile = null;
    File f2 = new File(filename + ".GRI");

    try { //read of random access file can throw an exception
        if (!f2.exists()) {
            afile = new RandomAccessFile(filename + ".gri", "r");
        } else {
            afile = new RandomAccessFile(filename + ".GRI", "r");
        }

        byte[] b = new byte[(int) Math.min(afile.length(), maxArrayLength)];

        int i = 0;
        int max = 0;
        int len;
        while ((len = afile.read(b)) > 0) {
            ByteBuffer bb = ByteBuffer.wrap(b);

            if (byteorderLSB) {
                bb.order(ByteOrder.LITTLE_ENDIAN);
            }

            if (datatype.equalsIgnoreCase("UBYTE")) {
                max += len;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = bb.get();
                    if (ret[i] < 0) {
                        ret[i] += 256;
                    }
                }
            } else if (datatype.equalsIgnoreCase("BYTE")) {
                max += len;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = bb.get();
                }
            } else if (datatype.equalsIgnoreCase("SHORT")) {
                max += len / 2;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = bb.getShort();
                }
            } else if (datatype.equalsIgnoreCase("INT")) {
                max += len / 4;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = bb.getInt();
                }
            } else if (datatype.equalsIgnoreCase("LONG")) {
                max += len / 8;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = bb.getLong();
                }
            } else if (datatype.equalsIgnoreCase("FLOAT")) {
                max += len / 4;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = bb.getFloat();
                }
            } else if (datatype.equalsIgnoreCase("DOUBLE")) {
                max += len / 8;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = (float) bb.getDouble();
                }
            } else {
                // / should not happen; catch anyway...
                max += len / 4;
                for (; i < max; i++) {
                    ret[i] = Float.NaN;
                }
            }
        }

        //replace not a number
        for (i = 0; i < length; i++) {
            if ((float) ret[i] == (float) nodatavalue) {
                ret[i] = Float.NaN;
            } else {
                ret[i] *= rescale;
            }
        }
    } catch (Exception e) {
        logger.error("An error has occurred - probably a file error", e);
    } finally {
        if (afile != null) {
            try {
                afile.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
    grid_data = ret;
    return ret;
}