Example usage for java.nio ByteOrder LITTLE_ENDIAN

List of usage examples for java.nio ByteOrder LITTLE_ENDIAN

Introduction

In this page you can find the example usage for java.nio ByteOrder LITTLE_ENDIAN.

Prototype

ByteOrder LITTLE_ENDIAN

To view the source code for java.nio ByteOrder LITTLE_ENDIAN.

Click Source Link

Document

This constant represents little endian.

Usage

From source file:edu.hawaii.soest.kilonalu.dvp2.DavisWxParser.java

/**
 * get the value from the monthlyEvapoTranspiration field
 *
 * @return monthlyEvapoTranspiration - the monthlyEvapoTranspiration as a float
 *///from ww  w.  ja  va2  s  .  c  o  m
public float getMonthlyEvapoTranspiration() {
    this.monthlyEvapoTranspiration.flip();
    return (float) (this.monthlyEvapoTranspiration.order(ByteOrder.LITTLE_ENDIAN).getShort() / 100);
}

From source file:edu.hawaii.soest.kilonalu.dvp2.DavisWxParser.java

/**
 * get the value from the yearlyEvapoTranspiration field
 *
 * @return yearlyEvapoTranspiration - the yearlyEvapoTranspiration as a float
 *///w  w w .ja v a2s.c  o  m
public float getYearlyEvapoTranspiration() {
    this.yearlyEvapoTranspiration.flip();
    return (float) (this.yearlyEvapoTranspiration.order(ByteOrder.LITTLE_ENDIAN).getShort() / 100);
}

From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.PebbleProtocol.java

private byte[] encodeActionResponse2x(int id, byte actionId, int iconId, String caption) {
    short length = (short) (18 + caption.getBytes().length);
    ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + length);
    buf.order(ByteOrder.BIG_ENDIAN);
    buf.putShort(length);/*w w  w . jav  a 2 s. c  om*/
    buf.putShort(ENDPOINT_EXTENSIBLENOTIFS);
    buf.order(ByteOrder.LITTLE_ENDIAN);
    buf.put(NOTIFICATIONACTION_RESPONSE);
    buf.putInt(id);
    buf.put(actionId);
    buf.put(NOTIFICATIONACTION_ACK);
    buf.put((byte) 2); //nr of attributes
    buf.put((byte) 6); // icon
    buf.putShort((short) 4); // length
    buf.putInt(iconId);
    buf.put((byte) 2); // title
    buf.putShort((short) caption.getBytes().length);
    buf.put(caption.getBytes());
    return buf.array();
}

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

float[] getGrid(double xmin, double ymin, double xmax, double ymax) {
    //expects largest y at the top
    //expects input ranges inside of grid ranges

    int width = (int) ((xmax - xmin) / xres);
    int height = (int) ((ymax - ymin) / yres);
    int startx = (int) ((xmin - this.xmin) / xres);
    int endx = startx + width;
    int starty = (int) ((ymin - this.ymin) / yres);
    //int endy = starty + height;

    int length = width * height;

    float[] ret = new float[length];
    int pos = 0;//from   w w w .  ja va2 s  . c  om

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

    int size = 4;
    if (datatype.equals("BYTE") || datatype.equals("UBYTE")) {
        size = 1;
    } else if (datatype.equals("SHORT")) {
        size = 2;
    } else if (datatype.equals("INT")) {
        size = 4;
    } else if (datatype.equals("LONG")) {
        size = 8;
    } else if (datatype.equals("FLOAT")) {
        size = 4;
    } else if (datatype.equals("DOUBLE")) {
        size = 8;
    }

    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");
        }

        //seek to first raster
        afile.seek(((long) this.ncols) * starty * size);

        //read relevant rasters
        int readSize = this.ncols * height * size;
        int readLen = this.ncols * height;
        byte[] b = new byte[readSize];
        afile.read(b);
        ByteBuffer bb = ByteBuffer.wrap(b);

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

        if (datatype.equalsIgnoreCase("BYTE")) {
            for (i = 0; i < readLen; i++) {
                int x = i % this.ncols;
                if (x < startx || x >= endx) {
                    bb.get();
                } else {
                    ret[pos++] = bb.get();
                }
            }
        } else if (datatype.equalsIgnoreCase("UBYTE")) {
            for (i = 0; i < readLen; i++) {
                int x = i % this.ncols;
                if (x < startx || x >= endx) {
                    bb.get();
                } else {
                    ret[pos] = bb.get();
                    if (ret[pos] < 0) {
                        ret[pos] += 256;
                    }
                    pos++;
                }
            }
        } else if (datatype.equalsIgnoreCase("SHORT")) {
            for (i = 0; i < readLen; i++) {
                int x = i % this.ncols;
                if (x < startx || x >= endx) {
                    bb.getShort();
                } else {
                    ret[pos++] = bb.getShort();
                }
            }
        } else if (datatype.equalsIgnoreCase("INT")) {
            for (i = 0; i < readLen; i++) {
                int x = i % this.ncols;
                if (x < startx || x >= endx) {
                    bb.getInt();
                } else {
                    ret[pos++] = bb.getInt();
                }
            }
        } else if (datatype.equalsIgnoreCase("LONG")) {
            for (i = 0; i < readLen; i++) {
                int x = i % this.ncols;
                if (x < startx || x >= endx) {
                    bb.getLong();
                } else {
                    ret[pos++] = bb.getLong();
                }
            }
        } else if (datatype.equalsIgnoreCase("FLOAT")) {
            for (i = 0; i < readLen; i++) {
                int x = i % this.ncols;
                if (x < startx || x >= endx) {
                    bb.getFloat();
                } else {
                    ret[pos++] = bb.getFloat();
                }
            }
        } else if (datatype.equalsIgnoreCase("DOUBLE")) {
            for (i = 0; i < readLen; i++) {
                int x = i % this.ncols;
                if (x < startx || x >= endx) {
                    bb.getDouble();
                } else {
                    ret[pos++] = (float) bb.getDouble();
                }
            }
        } else {
            // / should not happen; catch anyway...
            for (i = 0; i < length; 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("GRID: " + e.toString(), e);
    } finally {
        if (afile != null) {
            try {
                afile.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
    grid_data = ret;
    return ret;
}

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.dta.DTAFileReader.java

private void decodeExpansionFields(BufferedInputStream stream) throws IOException {

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

    if (stream == null) {
        throw new IllegalArgumentException("stream == null!");
    }//from  w  w  w .  ja v a2 s.  c om

    // Added since release 105
    // [1-byte byte_field][short(2)/int(4)_field][variable_field whose
    // length is specified by the previous short/int field]

    int int_type_expansion_field = constantTable.get("EXPANSION");
    if (dbgLog.isLoggable(Level.FINE))
        dbgLog.fine("int_type_expansion_field=" + int_type_expansion_field);
    while (true) {
        byte[] firstByte = new byte[1];
        byte[] lengthBytes = new byte[int_type_expansion_field];

        int nbyte = stream.read(firstByte, 0, 1);
        dbgLog.fine("read 1st byte");
        int nbytes = stream.read(lengthBytes, 0, int_type_expansion_field);
        dbgLog.fine("read next integer");

        ByteBuffer bb_field_length = ByteBuffer.wrap(lengthBytes);

        if (isLittleEndian) {
            bb_field_length.order(ByteOrder.LITTLE_ENDIAN);
            dbgLog.fine("byte reversed");
        }

        int field_length;

        if (int_type_expansion_field == 2) {
            field_length = bb_field_length.getShort();
        } else {
            field_length = bb_field_length.getInt();
        }

        if (dbgLog.isLoggable(Level.FINE))
            dbgLog.fine("field_length=" + field_length);
        if (dbgLog.isLoggable(Level.FINE))
            dbgLog.fine("firstByte[0]=" + firstByte[0]);
        if ((field_length + firstByte[0]) == 0) {
            // reached the end of this field
            break;
        } else {
            byte[] stringField = new byte[field_length];
            nbyte = stream.read(stringField, 0, field_length);

        }
    }

    dbgLog.fine("decodeExpansionFields(): end");

}

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

private void decodeData(BufferedInputStream stream) throws IOException {

    dbgLog.fine("\n***** decodeData(): start *****");

    if (stream == null) {
        throw new IllegalArgumentException("stream == null!");
    }//from  w  ww  .  j  av  a2s .  c o  m

    int nvar = (Integer) smd.getFileInformation().get("varQnty");
    int nobs = (Integer) smd.getFileInformation().get("caseQnty");
    if (dbgLog.isLoggable(Level.FINE))
        dbgLog.fine("data diminsion[rxc]=(" + nobs + "," + nvar + ")");
    if (dbgLog.isLoggable(Level.FINE))
        dbgLog.fine("bytes per row=" + bytes_per_row + " bytes");

    if (dbgLog.isLoggable(Level.FINE))
        dbgLog.fine("variableTypelList=" + Arrays.deepToString(variableTypelList));
    if (dbgLog.isLoggable(Level.FINE))
        dbgLog.fine("StringVariableTable=" + StringVariableTable);

    FileOutputStream fileOutTab = null;
    PrintWriter pwout = null;

    // create a File object to save the tab-delimited data file
    File tabDelimitedDataFile = File.createTempFile("tempTabfile.", ".tab");

    String tabDelimitedDataFileName = tabDelimitedDataFile.getAbsolutePath();

    // save the temp file name in the metadata object
    smd.getFileInformation().put("tabDelimitedDataFileLocation", tabDelimitedDataFileName);

    fileOutTab = new FileOutputStream(tabDelimitedDataFile);

    pwout = new PrintWriter(new OutputStreamWriter(fileOutTab, "utf8"), true);

    // data storage
    // Object[][] dataTable = new Object[nobs][nvar];
    // for later variable-wise calculations of statistics
    // dataTable2 sotres cut-out data columnwise
    Object[][] dataTable2 = new Object[nvar][nobs];
    String[][] dateFormat = new String[nvar][nobs];

    for (int i = 0; i < nobs; i++) {
        byte[] dataRowBytes = new byte[bytes_per_row];
        Object[] dataRow = new Object[nvar];

        int nbytes = stream.read(dataRowBytes, 0, bytes_per_row);

        if (nbytes == 0) {
            String errorMessage = "reading data: no data were read at(" + i + "th row)";
            throw new IOException(errorMessage);
        }
        // decoding each row
        int byte_offset = 0;
        for (int columnCounter = 0; columnCounter < variableTypelList.length; columnCounter++) {

            Integer varType = variableTypeMap.get(variableTypelList[columnCounter]);

            String variableFormat = variableFormats[columnCounter];

            boolean isDateTimeDatum = isDateTimeDatumList[columnCounter];

            switch (varType != null ? varType : 256) {
            case -5:
                // Byte case
                // note: 1 byte signed
                byte byte_datum = dataRowBytes[byte_offset];

                if (dbgLog.isLoggable(Level.FINER))
                    dbgLog.finer(i + "-th row " + columnCounter + "=th column byte =" + byte_datum);
                if (byte_datum >= BYTE_MISSING_VALUE) {
                    if (dbgLog.isLoggable(Level.FINER))
                        dbgLog.finer(i + "-th row " + columnCounter + "=th column byte MV=" + byte_datum);
                    dataRow[columnCounter] = MissingValueForTextDataFileNumeric;
                    dataTable2[columnCounter][i] = null; //use null reference to indicate missing value in data that is passed to UNF
                } else {
                    dataRow[columnCounter] = byte_datum;
                    dataTable2[columnCounter][i] = byte_datum;
                }

                byte_offset++;
                break;
            case -4:
                // Stata-int (=java's short: 2byte) case
                // note: 2-byte signed int, not java's int
                ByteBuffer int_buffer = ByteBuffer.wrap(dataRowBytes, byte_offset, 2);
                if (isLittleEndian) {
                    int_buffer.order(ByteOrder.LITTLE_ENDIAN);

                }
                short short_datum = int_buffer.getShort();

                if (dbgLog.isLoggable(Level.FINER))
                    dbgLog.finer(i + "-th row " + columnCounter + "=th column stata int =" + short_datum);
                if (short_datum >= INT_MISSIG_VALUE) {
                    if (dbgLog.isLoggable(Level.FINER))
                        dbgLog.finer(i + "-th row " + columnCounter + "=th column stata long missing value="
                                + short_datum);
                    dataTable2[columnCounter][i] = null; //use null reference to indicate missing value in data that is passed to UNF
                    if (isDateTimeDatum) {
                        dataRow[columnCounter] = MissingValueForTextDataFileString;
                    } else {
                        dataRow[columnCounter] = MissingValueForTextDataFileNumeric;
                    }
                } else {

                    if (isDateTimeDatum) {

                        DecodedDateTime ddt = decodeDateTimeData("short", variableFormat,
                                Short.toString(short_datum));
                        if (dbgLog.isLoggable(Level.FINER))
                            dbgLog.finer(i + "-th row , decodedDateTime " + ddt.decodedDateTime + ", format="
                                    + ddt.format);
                        dataRow[columnCounter] = ddt.decodedDateTime;
                        dateFormat[columnCounter][i] = ddt.format;
                        dataTable2[columnCounter][i] = dataRow[columnCounter];

                    } else {
                        dataTable2[columnCounter][i] = short_datum;
                        dataRow[columnCounter] = short_datum;
                    }
                }
                byte_offset += 2;
                break;
            case -3:
                // stata-Long (= java's int: 4 byte) case
                // note: 4-byte singed, not java's long
                dbgLog.fine("DATreader: stata long");

                ByteBuffer long_buffer = ByteBuffer.wrap(dataRowBytes, byte_offset, 4);
                if (isLittleEndian) {
                    long_buffer.order(ByteOrder.LITTLE_ENDIAN);

                }
                int int_datum = long_buffer.getInt();

                if (dbgLog.isLoggable(Level.FINE))
                    dbgLog.fine(i + "-th row " + columnCounter + "=th column stata long =" + int_datum);
                if (int_datum >= LONG_MISSING_VALUE) {
                    if (dbgLog.isLoggable(Level.FINE))
                        dbgLog.fine(i + "-th row " + columnCounter + "=th column stata long missing value="
                                + int_datum);
                    dataTable2[columnCounter][i] = null; //use null reference to indicate missing value in data that is passed to UNF
                    if (isDateTimeDatum) {
                        dataRow[columnCounter] = MissingValueForTextDataFileString;
                    } else {
                        dataRow[columnCounter] = MissingValueForTextDataFileNumeric;
                    }
                } else {
                    if (isDateTimeDatum) {
                        DecodedDateTime ddt = decodeDateTimeData("int", variableFormat,
                                Integer.toString(int_datum));
                        if (dbgLog.isLoggable(Level.FINER))
                            dbgLog.finer(i + "-th row , decodedDateTime " + ddt.decodedDateTime + ", format="
                                    + ddt.format);
                        dataRow[columnCounter] = ddt.decodedDateTime;
                        dateFormat[columnCounter][i] = ddt.format;
                        dataTable2[columnCounter][i] = dataRow[columnCounter];

                    } else {
                        dataTable2[columnCounter][i] = int_datum;
                        dataRow[columnCounter] = int_datum;
                    }

                }
                byte_offset += 4;
                break;
            case -2:
                // float case
                // note: 4-byte
                ByteBuffer float_buffer = ByteBuffer.wrap(dataRowBytes, byte_offset, 4);
                if (isLittleEndian) {
                    float_buffer.order(ByteOrder.LITTLE_ENDIAN);
                }
                float float_datum = float_buffer.getFloat();

                if (dbgLog.isLoggable(Level.FINER))
                    dbgLog.finer(i + "-th row " + columnCounter + "=th column float =" + float_datum);
                if (FLOAT_MISSING_VALUE_SET.contains(float_datum)) {
                    if (dbgLog.isLoggable(Level.FINER))
                        dbgLog.finer(i + "-th row " + columnCounter + "=th column float missing value="
                                + float_datum);
                    dataTable2[columnCounter][i] = null; //use null reference to indicate missing value in data that is passed to UNF
                    if (isDateTimeDatum) {
                        dataRow[columnCounter] = MissingValueForTextDataFileString;
                    } else {
                        dataRow[columnCounter] = MissingValueForTextDataFileNumeric;
                    }

                } else {

                    if (isDateTimeDatum) {
                        DecodedDateTime ddt = decodeDateTimeData("float", variableFormat,
                                doubleNumberFormatter.format(float_datum));
                        if (dbgLog.isLoggable(Level.FINER))
                            dbgLog.finer(i + "-th row , decodedDateTime " + ddt.decodedDateTime + ", format="
                                    + ddt.format);
                        dataRow[columnCounter] = ddt.decodedDateTime;
                        dateFormat[columnCounter][i] = ddt.format;
                        dataTable2[columnCounter][i] = dataRow[columnCounter];
                    } else {
                        dataTable2[columnCounter][i] = float_datum;
                        dataRow[columnCounter] = float_datum;
                    }

                }
                byte_offset += 4;
                break;
            case -1:
                // double case
                // note: 8-byte
                ByteBuffer double_buffer = ByteBuffer.wrap(dataRowBytes, byte_offset, 8);
                if (isLittleEndian) {
                    double_buffer.order(ByteOrder.LITTLE_ENDIAN);
                }
                double double_datum = double_buffer.getDouble();

                if (DOUBLE_MISSING_VALUE_SET.contains(double_datum)) {
                    dataTable2[columnCounter][i] = null; //use null reference to indicate missing value in data that is passed to UNF
                    if (dbgLog.isLoggable(Level.FINER))
                        dbgLog.finer(i + "-th row " + columnCounter + "=th column double missing value="
                                + double_datum);
                    if (isDateTimeDatum) {
                        dataRow[columnCounter] = MissingValueForTextDataFileString;
                    } else {
                        dataRow[columnCounter] = MissingValueForTextDataFileNumeric;
                    }
                } else {

                    if (isDateTimeDatum) {
                        DecodedDateTime ddt = decodeDateTimeData("double", variableFormat,
                                doubleNumberFormatter.format(double_datum));
                        if (dbgLog.isLoggable(Level.FINER))
                            dbgLog.finer(i + "-th row , decodedDateTime " + ddt.decodedDateTime + ", format="
                                    + ddt.format);
                        dataRow[columnCounter] = ddt.decodedDateTime;
                        dateFormat[columnCounter][i] = ddt.format;
                        dataTable2[columnCounter][i] = dataRow[columnCounter];
                    } else {
                        dataTable2[columnCounter][i] = double_datum;
                        dataRow[columnCounter] = doubleNumberFormatter.format(double_datum);
                    }

                }
                byte_offset += 8;
                break;
            case 0:
                // String case
                int strVarLength = StringVariableTable.get(columnCounter);
                String raw_datum = new String(
                        Arrays.copyOfRange(dataRowBytes, byte_offset, (byte_offset + strVarLength)),
                        "ISO-8859-1");
                String string_datum = getNullStrippedString(raw_datum);
                if (dbgLog.isLoggable(Level.FINER))
                    dbgLog.finer(i + "-th row " + columnCounter + "=th column string =" + string_datum);
                if (string_datum.equals("")) {
                    if (dbgLog.isLoggable(Level.FINER))
                        dbgLog.finer(i + "-th row " + columnCounter + "=th column string missing value="
                                + string_datum);
                    dataRow[columnCounter] = MissingValueForTextDataFileString;
                    dataTable2[columnCounter][i] = null; //use null reference to indicate missing value in data that is passed to UNF
                } else {
                    String escapedString = string_datum.replaceAll("\"", Matcher.quoteReplacement("\\\""));
                    /*
                     * Fixing the bug we've had in the Stata reader for 
                     * a longest time: new lines and tabs need to 
                     * be escaped too - otherwise it breaks our 
                     * TAB file structure! -- L.A. 
                     */
                    escapedString = escapedString.replaceAll("\t", Matcher.quoteReplacement("\\t"));
                    escapedString = escapedString.replaceAll("\n", Matcher.quoteReplacement("\\n"));
                    escapedString = escapedString.replaceAll("\r", Matcher.quoteReplacement("\\r"));
                    // the escaped version of the string will be 
                    // stored in the tab file: 
                    dataRow[columnCounter] = "\"" + escapedString + "\"";
                    // but note that the "raw" version of it is 
                    // used for the UNF:
                    dataTable2[columnCounter][i] = string_datum;
                }
                byte_offset += strVarLength;
                break;
            default:
                dbgLog.fine("unknown variable type found");
                String errorMessage = "unknow variable Type found at data section";
                throw new InvalidObjectException(errorMessage);
            } // switch
        } // for-columnCounter

        // dump the row of data to the external file
        pwout.println(StringUtils.join(dataRow, "\t"));

        if (dbgLog.isLoggable(Level.FINE))
            dbgLog.fine(i + "-th row's data={" + StringUtils.join(dataRow, ",") + "};");

    } // for- i (row)

    pwout.close();
    if (dbgLog.isLoggable(Level.FINER)) {
        dbgLog.finer("\ndataTable2(variable-wise):\n");
        dbgLog.finer(Arrays.deepToString(dataTable2));
        dbgLog.finer("\ndateFormat(variable-wise):\n");
        dbgLog.finer(Arrays.deepToString(dateFormat));
    }
    if (dbgLog.isLoggable(Level.FINE)) {
        dbgLog.fine("variableTypelList:\n" + Arrays.deepToString(variableTypelList));
        dbgLog.fine("variableTypelListFinal:\n" + Arrays.deepToString(variableTypelListFinal));
    }
    String[] unfValues = new String[nvar];

    for (int j = 0; j < nvar; j++) {
        String variableType_j = variableTypelListFinal[j];

        unfValues[j] = getUNF(dataTable2[j], dateFormat[j], variableType_j, unfVersionNumber, j);
        if (dbgLog.isLoggable(Level.FINE))
            dbgLog.fine(j + "th unf value" + unfValues[j]);

    }

    if (dbgLog.isLoggable(Level.FINE))
        dbgLog.fine("unf set:\n" + Arrays.deepToString(unfValues));

    fileUnfValue = UNF5Util.calculateUNF(unfValues);

    if (dbgLog.isLoggable(Level.FINE))
        dbgLog.fine("file-unf=" + fileUnfValue);

    stataDataSection.setUnf(unfValues);

    stataDataSection.setFileUnf(fileUnfValue);

    smd.setVariableUNF(unfValues);

    smd.getFileInformation().put("fileUNF", fileUnfValue);
    if (dbgLog.isLoggable(Level.FINE))
        dbgLog.fine("unf values:\n" + unfValues);

    stataDataSection.setData(dataTable2);

    // close the stream

    dbgLog.fine("***** decodeData(): end *****\n\n");

}

From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.PebbleProtocol.java

private byte[] encodeWeatherPin(int timestamp, String title, String subtitle, String body, String location,
        int iconId) {
    final short NOTIFICATION_PIN_LENGTH = 46;
    final short ACTION_LENGTH_MIN = 10;

    String[] parts = { title, subtitle, body, location, "test", "test" };

    // Calculate length first
    byte actions_count = 1;
    short actions_length;
    String remove_string = "Remove";
    actions_length = (short) (ACTION_LENGTH_MIN * actions_count + remove_string.getBytes().length);

    byte attributes_count = 3;
    short attributes_length = (short) (21 + actions_length);
    if (parts != null) {
        for (String s : parts) {
            if (s == null || s.equals("")) {
                continue;
            }/* w w w .  ja  v a2  s  .  c om*/
            attributes_count++;
            attributes_length += (3 + s.getBytes().length);
        }
    }

    UUID uuid = UUID.fromString("61b22bc8-1e29-460d-a236-3fe409a43901");

    short pin_length = (short) (NOTIFICATION_PIN_LENGTH + attributes_length);

    ByteBuffer buf = ByteBuffer.allocate(pin_length);

    // pin (46 bytes)
    buf.order(ByteOrder.BIG_ENDIAN);
    buf.putLong(uuid.getMostSignificantBits());
    buf.putLong(uuid.getLeastSignificantBits());
    buf.putLong(uuid.getMostSignificantBits());
    buf.putLong(uuid.getLeastSignificantBits() | 0xff);
    buf.order(ByteOrder.LITTLE_ENDIAN);
    buf.putInt(timestamp); // 32-bit timestamp
    buf.putShort((short) 0); // duration
    buf.put((byte) 0x02); // type (0x02 = pin)
    buf.putShort((short) 0x0001); // flags 0x0001 = ?
    buf.put((byte) 0x06); // layout (0x06 = weather)
    buf.putShort(attributes_length); // total length of all attributes and actions in bytes
    buf.put(attributes_count);
    buf.put(actions_count);

    byte attribute_id = 0;
    // Encode Pascal-Style Strings
    if (parts != null) {
        for (String s : parts) {
            attribute_id++;
            if (s == null || s.equals("")) {
                continue;
            }

            int partlength = s.getBytes().length;
            if (partlength > 512)
                partlength = 512;
            if (attribute_id == 4) {
                buf.put((byte) 11);
            } else if (attribute_id == 5) {
                buf.put((byte) 25);
            } else if (attribute_id == 6) {
                buf.put((byte) 26);
            } else {
                buf.put(attribute_id);
            }
            buf.putShort((short) partlength);
            buf.put(s.getBytes(), 0, partlength);
        }
    }

    buf.put((byte) 4); // icon
    buf.putShort((short) 4); // length of int
    buf.putInt(0x80000000 | iconId);

    buf.put((byte) 6); // icon
    buf.putShort((short) 4); // length of int
    buf.putInt(0x80000000 | iconId);

    buf.put((byte) 14); // last updated
    buf.putShort((short) 4); // length of int
    buf.putInt(timestamp);

    // remove action
    buf.put((byte) 123); // action id
    buf.put((byte) 0x09); // remove
    buf.put((byte) 0x01); // number attributes
    buf.put((byte) 0x01); // attribute id (title)
    buf.putShort((short) remove_string.getBytes().length);
    buf.put(remove_string.getBytes());

    return encodeBlobdb(uuid, BLOBDB_INSERT, BLOBDB_PIN, buf.array());
}

From source file:edu.hawaii.soest.kilonalu.dvp2.DavisWxParser.java

/**
 * get the value from the consoleBatteryVoltage field
 *
 * @return consoleBatteryVoltage - the consoleBatteryVoltage as a float
 *//*from  w w  w . ja v  a2  s .c  om*/
public float getConsoleBatteryVoltage() {
    this.consoleBatteryVoltage.flip();
    float consoleBatteryVoltage = (float) this.consoleBatteryVoltage.order(ByteOrder.LITTLE_ENDIAN).getShort();

    consoleBatteryVoltage = ((consoleBatteryVoltage * 300.0f) / 512.0f) / 100.0f; // from the instrument guide
    return consoleBatteryVoltage;
}

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.dta.DTAFileReader.java

void parseValueLabelsRelease105(BufferedInputStream stream) throws IOException {

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

    if (stream == null) {
        throw new IllegalArgumentException("stream == null!");
    }//w w w.jav a  2 s.  c  o m

    int nvar = dataTable.getVarQuantity().intValue();
    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
     */

    // This map will hold a temporary lookup table for all the categorical
    // value-label groups we are going to find here:
    // These groups have unique names, and a group *may be shared* between
    // multiple variables. In the method decodeDescriptorValueLabel above
    // we have populated a lookup table where variables are linked to the 
    // corresponding value-label groups by name. Thus we must fully populate 
    // the full map of all the variable groups, then go through the list 
    // of variables and create the dataverse variable categories from 
    // them. -- L.A. 4.0       
    Map<String, Map<String, String>> tempValueLabelTable = new LinkedHashMap<>();

    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;
        }

        // Finally, we've reached the actual value-label pairs. We'll go 
        // through them and put them on the temporary lookup map: 

        tempValueLabelTable.put(labelName, new LinkedHashMap<>());

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

            // TODO: do we need any null/empty string checks here? -- L.A. 4.0
            tempValueLabelTable.get(labelName).put(Integer.toString(valueList[j]), labelList[j]);
        }

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

    } // for nvar loop

    // And now we can go through the list of variables, see if any have 
    // value-label groups linked, then build dataverse VariableCategory 
    // objects for them, using the values stored in the temporary map 
    // we've just built:

    for (int i = 0; i < nvar; i++) {
        if (valueLabelsLookupTable[i] != null) {
            if (tempValueLabelTable.get(valueLabelsLookupTable[i]) != null) {
                // What if it is null? -- is it a legit condition, that 
                // a variable was advertised as having categorical values,
                // but no such cat value group exists under this name?
                // -- L.A.
                for (String value : tempValueLabelTable.get(valueLabelsLookupTable[i]).keySet()) {
                    VariableCategory cat = new VariableCategory();

                    cat.setValue(value);
                    cat.setLabel(tempValueLabelTable.get(valueLabelsLookupTable[i]).get(value));

                    /* cross-link the variable and category to each other: */
                    cat.setDataVariable(dataTable.getDataVariables().get(i));
                    dataTable.getDataVariables().get(i).getCategories().add(cat);
                }
            }
        }
    }

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

}

From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.PebbleProtocol.java

private byte[] encodeWeatherForecast(WeatherSpec weatherSpec) {
    final short WEATHER_FORECAST_LENGTH = 20;

    String[] parts = { weatherSpec.location, weatherSpec.currentCondition };

    // Calculate length first
    short attributes_length = 0;
    if (parts != null) {
        for (String s : parts) {
            if (s == null || s.equals("")) {
                continue;
            }//w  w w  .  j  a v a2  s. c o  m
            attributes_length += (2 + s.getBytes().length);
        }
    }

    short pin_length = (short) (WEATHER_FORECAST_LENGTH + attributes_length);

    ByteBuffer buf = ByteBuffer.allocate(pin_length);
    buf.order(ByteOrder.LITTLE_ENDIAN);
    buf.put((byte) 3); // unknown, always 3?
    buf.putShort((short) (weatherSpec.currentTemp - 273));
    buf.put(Weather.mapToPebbleCondition(weatherSpec.currentConditionCode));
    buf.putShort((short) (weatherSpec.todayMaxTemp - 273));
    buf.putShort((short) (weatherSpec.todayMinTemp - 273));
    buf.put(Weather.mapToPebbleCondition(weatherSpec.tomorrowConditionCode));
    buf.putShort((short) (weatherSpec.tomorrowMaxTemp - 273));
    buf.putShort((short) (weatherSpec.tomorrowMinTemp - 273));
    buf.putInt(weatherSpec.timestamp);
    buf.put((byte) 0); // automatic location 0=manual 1=auto
    buf.putShort(attributes_length);

    // Encode Pascal-Style Strings
    if (parts != null) {
        for (String s : parts) {
            if (s == null || s.equals("")) {
                continue;
            }

            int partlength = s.getBytes().length;
            if (partlength > 512)
                partlength = 512;
            buf.putShort((short) partlength);
            buf.put(s.getBytes(), 0, partlength);
        }
    }

    return encodeBlobdb(UUID_LOCATION, BLOBDB_INSERT, BLOBDB_WEATHER, buf.array());
}