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:nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.PebbleProtocol.java

private GBDeviceEvent[] decodeDictToJSONAppMessage(UUID uuid, ByteBuffer buf) throws JSONException {
    buf.order(ByteOrder.LITTLE_ENDIAN);
    byte dictSize = buf.get();
    if (dictSize == 0) {
        LOG.info("dict size is 0, ignoring");
        return null;
    }/* w  w  w  . j  a  v  a  2s  . c  om*/
    JSONArray jsonArray = new JSONArray();
    while (dictSize-- > 0) {
        JSONObject jsonObject = new JSONObject();
        Integer key = buf.getInt();
        byte type = buf.get();
        short length = buf.getShort();
        jsonObject.put("key", key);
        if (type == TYPE_CSTRING) {
            length--;
        }
        jsonObject.put("length", length);
        switch (type) {
        case TYPE_UINT:
            jsonObject.put("type", "uint");
            if (length == 1) {
                jsonObject.put("value", buf.get() & 0xff);
            } else if (length == 2) {
                jsonObject.put("value", buf.getShort() & 0xffff);
            } else {
                jsonObject.put("value", buf.getInt() & 0xffffffffL);
            }
            break;
        case TYPE_INT:
            jsonObject.put("type", "int");
            if (length == 1) {
                jsonObject.put("value", buf.get());
            } else if (length == 2) {
                jsonObject.put("value", buf.getShort());
            } else {
                jsonObject.put("value", buf.getInt());
            }
            break;
        case TYPE_BYTEARRAY:
        case TYPE_CSTRING:
            byte[] bytes = new byte[length];
            buf.get(bytes);
            if (type == TYPE_BYTEARRAY) {
                jsonObject.put("type", "bytes");
                jsonObject.put("value", new String(Base64.encode(bytes, Base64.NO_WRAP)));
            } else {
                jsonObject.put("type", "string");
                jsonObject.put("value", new String(bytes));
                buf.get(); // skip null-termination;
            }
            break;
        default:
            LOG.info("unknown type in appmessage, ignoring");
            return null;
        }
        jsonArray.put(jsonObject);
    }

    GBDeviceEventSendBytes sendBytesAck = null;
    if (mAlwaysACKPebbleKit) {
        // this is a hack we send an ack to the Pebble immediately because somebody said it helps some PebbleKit apps :P
        sendBytesAck = new GBDeviceEventSendBytes();
        sendBytesAck.encodedBytes = encodeApplicationMessageAck(uuid, last_id);
    }
    GBDeviceEventAppMessage appMessage = new GBDeviceEventAppMessage();
    appMessage.appUUID = uuid;
    appMessage.id = last_id & 0xff;
    appMessage.message = jsonArray.toString();
    return new GBDeviceEvent[] { appMessage, sendBytesAck };
}

From source file:org.bimserver.geometry.GeometryRunner.java

private ByteBuffer quantizeNormals(FloatBuffer normals) {
    ByteBuffer quantizedNormals = ByteBuffer.wrap(new byte[normals.capacity()]);
    quantizedNormals.order(ByteOrder.LITTLE_ENDIAN);
    for (int i = 0; i < normals.capacity(); i++) {
        float normal = normals.get(i);
        quantizedNormals.put((byte) (normal * 127));
    }/*from www. j  a v  a 2 s  .co  m*/
    return quantizedNormals;
}

From source file:org.bimserver.geometry.GeometryRunner.java

private ByteBuffer quantizeVertices(float[] vertices, float[] quantizationMatrix, float multiplierToMm) {
    ByteBuffer quantizedBuffer = ByteBuffer.wrap(new byte[vertices.length * 2]);
    quantizedBuffer.order(ByteOrder.LITTLE_ENDIAN);

    float[] vertex = new float[4];
    float[] result = new float[4];
    vertex[3] = 1;// w  w w . jav a2s .c  o m
    int nrVertices = vertices.length;
    for (int i = 0; i < nrVertices; i += 3) {
        vertex[0] = vertices[i];
        vertex[1] = vertices[i + 1];
        vertex[2] = vertices[i + 2];

        if (multiplierToMm != 1f) {
            vertex[0] = vertex[0] * multiplierToMm;
            vertex[1] = vertex[1] * multiplierToMm;
            vertex[2] = vertex[2] * multiplierToMm;
        }

        Matrix.multiplyMV(result, 0, quantizationMatrix, 0, vertex, 0);

        quantizedBuffer.putShort((short) result[0]);
        quantizedBuffer.putShort((short) result[1]);
        quantizedBuffer.putShort((short) result[2]);
    }

    return quantizedBuffer;
}

From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.sav.SAVFileReader.java

void decodeRecordType7(BufferedInputStream stream) throws IOException {
    dbgLog.fine("***** decodeRecordType7(): start *****");
    int counter = 0;
    int[] headerSection = new int[2];

    // the variables below may no longer needed; 
    // but they may be useful for debugging/logging purposes.

    /// // RecordType 7 
    /// // Subtype 3
    /// List<Integer> releaseMachineSpecificInfo = new ArrayList<Integer>();
    /// List<String> releaseMachineSpecificInfoHex = new ArrayList<String>();

    /// // Subytpe 4
    /// Map<String, Double> OBSTypeValue = new LinkedHashMap<String, Double>();
    /// Map<String, String> OBSTypeHexValue = new LinkedHashMap<String, String>();    
    //Subtype 11/*w ww. j av a  2 s .c o  m*/
    /// List<Integer> measurementLevel = new ArrayList<Integer>();
    /// List<Integer> columnWidth = new ArrayList<Integer>();
    /// List<Integer> alignment = new ArrayList<Integer>();

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

    while (true) {
        try {
            if (stream == null) {
                throw new IllegalArgumentException("RT7: stream == null!");
            }
            // first check the 4-byte header value
            //if (stream.markSupported()){
            stream.mark(1000);
            //}
            // 7.0 check the first 4 bytes
            byte[] headerCodeRt7 = new byte[LENGTH_RECORD_TYPE7_CODE];

            int nbytes_rt7 = stream.read(headerCodeRt7, 0, LENGTH_RECORD_TYPE7_CODE);
            // to-do check against nbytes
            //printHexDump(headerCodeRt7, "RT7 header test");
            ByteBuffer bb_header_code_rt7 = ByteBuffer.wrap(headerCodeRt7, 0, LENGTH_RECORD_TYPE7_CODE);
            if (isLittleEndian) {
                bb_header_code_rt7.order(ByteOrder.LITTLE_ENDIAN);
            }

            int intRT7test = bb_header_code_rt7.getInt();
            dbgLog.fine("RT7: header test value=" + intRT7test);
            if (intRT7test != 7) {
                //if (stream.markSupported()){
                //out.print("iteration="+safteyCounter);
                //dbgLog.fine("iteration="+safteyCounter);
                dbgLog.fine("intRT7test failed=" + intRT7test);
                dbgLog.fine("counter=" + counter);
                stream.reset();
                return;
                //}
            }

            // 7.1 check 4-byte integer Sub-Type Code

            byte[] length_sub_type_code = new byte[LENGTH_RT7_SUB_TYPE_CODE];

            int nbytes_rt7_1 = stream.read(length_sub_type_code, 0, LENGTH_RT7_SUB_TYPE_CODE);
            // to-do check against nbytes

            //printHexDump(length_how_many_line_bytes, "RT7 how_many_line_bytes");
            ByteBuffer bb_sub_type_code = ByteBuffer.wrap(length_sub_type_code, 0, LENGTH_RT7_SUB_TYPE_CODE);
            if (isLittleEndian) {
                bb_sub_type_code.order(ByteOrder.LITTLE_ENDIAN);
            }

            int subTypeCode = bb_sub_type_code.getInt();
            dbgLog.fine("RT7: subTypeCode=" + subTypeCode);

            switch (subTypeCode) {
            case 3:
                // 3: Release andMachine-Specific Integer Information

                //parseRT7SubTypefield(stream);

                headerSection = parseRT7SubTypefieldHeader(stream);
                if (headerSection != null) {
                    int unitLength = headerSection[0];
                    int numberOfUnits = headerSection[1];

                    for (int i = 0; i < numberOfUnits; i++) {
                        dbgLog.finer(i + "-th fieldData");
                        byte[] work = new byte[unitLength];

                        int nb = stream.read(work);
                        dbgLog.finer("raw bytes in Hex:" + new String(Hex.encodeHex(work)));
                        ByteBuffer bb_field = ByteBuffer.wrap(work);
                        if (isLittleEndian) {
                            bb_field.order(ByteOrder.LITTLE_ENDIAN);
                        }
                        String dataInHex = new String(Hex.encodeHex(bb_field.array()));
                        /// releaseMachineSpecificInfoHex.add(dataInHex);

                        dbgLog.finer("raw bytes in Hex:" + dataInHex);
                        if (unitLength == 4) {
                            int fieldData = bb_field.getInt();
                            dbgLog.finer("fieldData(int)=" + fieldData);
                            dbgLog.finer("fieldData in Hex=0x" + Integer.toHexString(fieldData));
                            /// releaseMachineSpecificInfo.add(fieldData);
                        }

                    }

                    /// dbgLog.fine("releaseMachineSpecificInfo="+releaseMachineSpecificInfo);
                    /// dbgLog.fine("releaseMachineSpecificInfoHex="+releaseMachineSpecificInfoHex);

                } else {
                    // throw new IOException
                }

                dbgLog.fine("***** end of subType 3 ***** \n");

                break;
            case 4:
                // Release andMachine-SpecificOBS-Type Information
                headerSection = parseRT7SubTypefieldHeader(stream);
                if (headerSection != null) {
                    int unitLength = headerSection[0];
                    int numberOfUnits = headerSection[1];

                    for (int i = 0; i < numberOfUnits; i++) {
                        dbgLog.finer(i + "-th fieldData:" + RecordType7SubType4Fields.get(i));
                        byte[] work = new byte[unitLength];

                        int nb = stream.read(work);

                        dbgLog.finer("raw bytes in Hex:" + new String(Hex.encodeHex(work)));
                        ByteBuffer bb_field = ByteBuffer.wrap(work);
                        dbgLog.finer("byte order=" + bb_field.order().toString());
                        if (isLittleEndian) {
                            bb_field.order(ByteOrder.LITTLE_ENDIAN);
                        }
                        ByteBuffer bb_field_dup = bb_field.duplicate();
                        OBSTypeHexValue.put(RecordType7SubType4Fields.get(i),
                                new String(Hex.encodeHex(bb_field.array())));
                        //                            dbgLog.finer("raw bytes in Hex:"+
                        //                                OBSTypeHexValue.get(RecordType7SubType4Fields.get(i)));
                        if (unitLength == 8) {
                            double fieldData = bb_field.getDouble();
                            /// OBSTypeValue.put(RecordType7SubType4Fields.get(i), fieldData);
                            dbgLog.finer("fieldData(double)=" + fieldData);
                            OBSTypeHexValue.put(RecordType7SubType4Fields.get(i),
                                    Double.toHexString(fieldData));
                            dbgLog.fine("fieldData in Hex=" + Double.toHexString(fieldData));
                        }
                    }
                    /// dbgLog.fine("OBSTypeValue="+OBSTypeValue);
                    /// dbgLog.fine("OBSTypeHexValue="+OBSTypeHexValue);

                } else {
                    // throw new IOException
                }

                dbgLog.fine("***** end of subType 4 ***** \n");
                break;
            case 5:
                // Variable Sets Information
                parseRT7SubTypefield(stream);
                break;
            case 6:
                // Trends date information
                parseRT7SubTypefield(stream);
                break;
            case 7:
                // Multiple response groups
                parseRT7SubTypefield(stream);
                break;
            case 8:
                // Windows Data Entry data
                parseRT7SubTypefield(stream);
                break;
            case 9:
                //
                parseRT7SubTypefield(stream);
                break;
            case 10:
                // TextSmart data
                parseRT7SubTypefield(stream);
                break;
            case 11:
                // Msmt level, col width, & alignment
                //parseRT7SubTypefield(stream);

                headerSection = parseRT7SubTypefieldHeader(stream);
                if (headerSection != null) {
                    int unitLength = headerSection[0];
                    int numberOfUnits = headerSection[1];

                    for (int i = 0; i < numberOfUnits; i++) {
                        dbgLog.finer(i + "-th fieldData");
                        byte[] work = new byte[unitLength];

                        int nb = stream.read(work);
                        dbgLog.finer("raw bytes in Hex:" + new String(Hex.encodeHex(work)));
                        ByteBuffer bb_field = ByteBuffer.wrap(work);
                        if (isLittleEndian) {
                            bb_field.order(ByteOrder.LITTLE_ENDIAN);
                        }
                        dbgLog.finer("raw bytes in Hex:" + new String(Hex.encodeHex(bb_field.array())));

                        if (unitLength == 4) {
                            int fieldData = bb_field.getInt();
                            dbgLog.finer("fieldData(int)=" + fieldData);
                            dbgLog.finer("fieldData in Hex=0x" + Integer.toHexString(fieldData));

                            int remainder = i % 3;
                            dbgLog.finer("remainder=" + remainder);
                            if (remainder == 0) {
                                /// measurementLevel.add(fieldData);
                            } else if (remainder == 1) {
                                /// columnWidth.add(fieldData);
                            } else if (remainder == 2) {
                                /// alignment.add(fieldData);
                            }
                        }

                    }

                } else {
                    // throw new IOException
                }
                /// dbgLog.fine("measurementLevel="+measurementLevel);
                /// dbgLog.fine("columnWidth="+columnWidth);
                /// dbgLog.fine("alignment="+alignment);
                dbgLog.fine("***** end of subType 11 ***** \n");

                break;
            case 12:
                // Windows Data Entry GUID
                parseRT7SubTypefield(stream);
                break;
            case 13:
                // Extended variable names
                // parseRT7SubTypefield(stream);
                headerSection = parseRT7SubTypefieldHeader(stream);

                if (headerSection != null) {
                    int unitLength = headerSection[0];
                    dbgLog.fine("RT7: unitLength=" + unitLength);
                    int numberOfUnits = headerSection[1];
                    dbgLog.fine("RT7: numberOfUnits=" + numberOfUnits);
                    byte[] work = new byte[unitLength * numberOfUnits];
                    int nbtyes13 = stream.read(work);

                    String[] variableShortLongNamePairs = new String(work, "US-ASCII").split("\t");

                    for (int i = 0; i < variableShortLongNamePairs.length; i++) {
                        dbgLog.fine("RT7: " + i + "-th pair" + variableShortLongNamePairs[i]);
                        String[] pair = variableShortLongNamePairs[i].split("=");
                        shortToLongVarialbeNameTable.put(pair[0], pair[1]);
                    }

                    dbgLog.fine("RT7: shortToLongVarialbeNameTable" + shortToLongVarialbeNameTable);
                    smd.setShortToLongVarialbeNameTable(shortToLongVarialbeNameTable);
                } else {
                    // throw new IOException
                }

                break;
            case 14:
                // Extended strings
                //parseRT7SubTypefield(stream);
                headerSection = parseRT7SubTypefieldHeader(stream);

                if (headerSection != null) {
                    int unitLength = headerSection[0];
                    dbgLog.fine("RT7.14: unitLength=" + unitLength);
                    int numberOfUnits = headerSection[1];
                    dbgLog.fine("RT7.14: numberOfUnits=" + numberOfUnits);
                    byte[] work = new byte[unitLength * numberOfUnits];
                    int nbtyes13 = stream.read(work);

                    String[] extendedVariablesSizePairs = new String(work, defaultCharSet).split("\000\t");

                    for (int i = 0; i < extendedVariablesSizePairs.length; i++) {
                        dbgLog.fine("RT7.14: " + i + "-th pair" + extendedVariablesSizePairs[i]);
                        if (extendedVariablesSizePairs[i].indexOf("=") > 0) {
                            String[] pair = extendedVariablesSizePairs[i].split("=");
                            extendedVariablesSizeTable.put(pair[0], Integer.valueOf(pair[1]));
                        }
                    }

                    dbgLog.fine("RT7.14: extendedVariablesSizeTable" + extendedVariablesSizeTable);
                } else {
                    // throw new IOException
                }

                break;
            case 15:
                // Clementine Metadata
                parseRT7SubTypefield(stream);
                break;
            case 16:
                // 64 bit N of cases
                parseRT7SubTypefield(stream);
                break;
            case 17:
                // File level attributes
                parseRT7SubTypefield(stream);
                break;
            case 18:
                // Variable attributes
                parseRT7SubTypefield(stream);
                break;
            case 19:
                // Extended multiple response groups
                parseRT7SubTypefield(stream);
                break;
            case 20:
                // Encoding, aka code page
                parseRT7SubTypefield(stream);
                /* TODO: This needs to be researched; 
                 * Is this field really used, ever?
                headerSection = parseRT7SubTypefieldHeader(stream);
                        
                if (headerSection != null){
                int unitLength = headerSection[0];
                dbgLog.fine("RT7-20: unitLength="+unitLength);
                int numberOfUnits = headerSection[1];
                dbgLog.fine("RT7-20: numberOfUnits="+numberOfUnits);
                byte[] rt7st20bytes = new byte[unitLength*numberOfUnits];
                int nbytes20 = stream.read(rt7st20bytes);
                        
                String dataCharSet = new String(rt7st20bytes,"US-ASCII");
                        
                if (dataCharSet != null && !(dataCharSet.equals(""))) {
                    dbgLog.fine("RT7-20: data charset: "+ dataCharSet);
                    defaultCharSet = dataCharSet; 
                }
                } else {
                // throw new IOException
                }
                 * 
                 */

                break;
            case 21:
                // Value labels for long strings
                parseRT7SubTypefield(stream);
                break;
            case 22:
                // Missing values for long strings
                parseRT7SubTypefield(stream);
                break;
            default:
                parseRT7SubTypefield(stream);
            }

        } catch (IOException ex) {
            //ex.printStackTrace();
            throw ex;
        }

        counter++;

        if (counter > 20) {
            break;
        }
    }

    dbgLog.fine("RT7: counter=" + counter);
    dbgLog.fine("RT7: ***** decodeRecordType7(): end *****");
}

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

byte[] encodeApplicationMessagePush(short endpoint, UUID uuid, ArrayList<Pair<Integer, Object>> pairs) {
    int length = LENGTH_UUID + 3; // UUID + (PUSH + id + length of dict)
    for (Pair<Integer, Object> pair : pairs) {
        if (pair.first == null || pair.second == null)
            continue;
        length += 7; // key + type + length
        if (pair.second instanceof Integer) {
            length += 4;/*from  w  w w.java  2  s .  c  om*/
        } else if (pair.second instanceof Short) {
            length += 2;
        } else if (pair.second instanceof Byte) {
            length += 1;
        } else if (pair.second instanceof String) {
            length += ((String) pair.second).getBytes().length + 1;
        } else if (pair.second instanceof byte[]) {
            length += ((byte[]) pair.second).length;
        } else {
            LOG.warn("unknown type: " + pair.second.getClass().toString());
        }
    }

    ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + length);
    buf.order(ByteOrder.BIG_ENDIAN);
    buf.putShort((short) length);
    buf.putShort(endpoint); // 48 or 49
    buf.put(APPLICATIONMESSAGE_PUSH);
    buf.put(++last_id);
    buf.putLong(uuid.getMostSignificantBits());
    buf.putLong(uuid.getLeastSignificantBits());
    buf.put((byte) pairs.size());

    buf.order(ByteOrder.LITTLE_ENDIAN);
    for (Pair<Integer, Object> pair : pairs) {
        if (pair.first == null || pair.second == null)
            continue;
        buf.putInt(pair.first);
        if (pair.second instanceof Integer) {
            buf.put(TYPE_INT);
            buf.putShort((short) 4); // length
            buf.putInt((int) pair.second);
        } else if (pair.second instanceof Short) {
            buf.put(TYPE_INT);
            buf.putShort((short) 2); // length
            buf.putShort((short) pair.second);
        } else if (pair.second instanceof Byte) {
            buf.put(TYPE_INT);
            buf.putShort((short) 1); // length
            buf.put((byte) pair.second);
        } else if (pair.second instanceof String) {
            String str = (String) pair.second;
            buf.put(TYPE_CSTRING);
            buf.putShort((short) (str.getBytes().length + 1));
            buf.put(str.getBytes());
            buf.put((byte) 0);
        } else if (pair.second instanceof byte[]) {
            byte[] bytes = (byte[]) pair.second;
            buf.put(TYPE_BYTEARRAY);
            buf.putShort((short) bytes.length);
            buf.put(bytes);
        }
    }

    return buf.array();
}

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.sav.SAVFileReader.java

void decodeRecordType6(BufferedInputStream stream) throws IOException {
    dbgLog.fine("***** decodeRecordType6(): start *****");
    try {//from  w  w  w. ja  v  a  2 s  .  c  o  m
        if (stream == null) {
            throw new IllegalArgumentException("stream == null!");
        }
        // this section is optional; so let's first check the 4-byte header 
        // value and see what type it is. 
        //if (stream.markSupported()){ // -- ? L.A. 4.0 alpha
        stream.mark(1000);
        //}
        // 6.0 check the first 4 bytes
        byte[] headerCodeRt6 = new byte[LENGTH_RECORD_TYPE6_CODE];

        int nbytes_rt6 = stream.read(headerCodeRt6, 0, LENGTH_RECORD_TYPE6_CODE);
        // to-do check against nbytes
        //printHexDump(headerCodeRt6, "RT6 header test");
        ByteBuffer bb_header_code_rt6 = ByteBuffer.wrap(headerCodeRt6, 0, LENGTH_RECORD_TYPE6_CODE);
        if (isLittleEndian) {
            bb_header_code_rt6.order(ByteOrder.LITTLE_ENDIAN);
        }

        int intRT6test = bb_header_code_rt6.getInt();
        dbgLog.fine("RT6: header test value=" + intRT6test);
        if (intRT6test != 6) {
            //if (stream.markSupported()){
            //out.print("iteration="+safteyCounter);
            //dbgLog.fine("iteration="+safteyCounter);
            dbgLog.fine("intRT6test failed=" + intRT6test);

            stream.reset();
            return;
            //}
        }
        // 6.1 check 4-byte integer that tells how many lines follow

        byte[] length_how_many_line_bytes = new byte[LENGTH_RT6_HOW_MANY_LINES];

        int nbytes_rt6_1 = stream.read(length_how_many_line_bytes, 0, LENGTH_RT6_HOW_MANY_LINES);
        // to-do check against nbytes

        //printHexDump(length_how_many_line_bytes, "RT6 how_many_line_bytes");
        ByteBuffer bb_how_many_lines = ByteBuffer.wrap(length_how_many_line_bytes, 0,
                LENGTH_RT6_HOW_MANY_LINES);
        if (isLittleEndian) {
            bb_how_many_lines.order(ByteOrder.LITTLE_ENDIAN);
        }

        int howManyLinesRt6 = bb_how_many_lines.getInt();
        dbgLog.fine("how Many lines follow=" + howManyLinesRt6);

        // 6.2 read 80-char-long lines 
        String[] documentRecord = new String[howManyLinesRt6];

        for (int i = 0; i < howManyLinesRt6; i++) {

            byte[] line = new byte[80];
            int nbytes_rt6_line = stream.read(line);

            documentRecord[i] = StringUtils.stripEnd(
                    new String(Arrays.copyOfRange(line, 0, LENGTH_RT6_DOCUMENT_LINE), defaultCharSet), " ");

            dbgLog.fine(i + "-th line =" + documentRecord[i] + "<-");
        }
        dbgLog.fine("documentRecord:\n" + StringUtils.join(documentRecord, "\n"));

    } catch (IOException ex) {
        //ex.printStackTrace();
        throw ex;
    }

    dbgLog.fine("decodeRecordType6(): end");
}

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

/**
 * @return calculated min and max values of a grid file as float [] where [0] is min and [1] is max.
 *//*from  w w  w  . ja v a2 s. c  om*/
public float[] calculatetMinMax() {

    float[] ret = new float[2];
    ret[0] = Float.MAX_VALUE;
    ret[1] = Float.MAX_VALUE * -1;

    long i;
    int size;
    byte[] b;
    RandomAccessFile afile = null;

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

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

        if (datatype.equalsIgnoreCase("BYTE")) {
            size = 1;
            b = new byte[size];
            for (i = 0; i < length; i++) {
                f = afile.readByte();
                if (f != (float) nodatavalue) {
                    ret[0] = Math.min(f * rescale, ret[0]);
                    ret[1] = Math.max(f * rescale, ret[1]);
                }
            }
        } else if (datatype.equalsIgnoreCase("UBYTE")) {
            size = 1;
            b = new byte[size];
            for (i = 0; i < length; i++) {
                f = afile.readByte();
                if (f < 0) {
                    f += 256;
                }
                if (f != (float) nodatavalue) {
                    ret[0] = Math.min(f * rescale, ret[0]);
                    ret[1] = Math.max(f * rescale, ret[1]);
                }
            }
        } else if (datatype.equalsIgnoreCase("SHORT")) {
            size = 2;
            b = new byte[size];
            for (i = 0; i < length; i++) {
                afile.read(b);
                if (byteorderLSB) {
                    f = (short) (((0xFF & b[1]) << 8) | (b[0] & 0xFF));
                } else {
                    f = (short) (((0xFF & b[0]) << 8) | (b[1] & 0xFF));
                }
                if (f != (float) nodatavalue) {
                    ret[0] = Math.min(f * rescale, ret[0]);
                    ret[1] = Math.max(f * rescale, ret[1]);
                }
            }
        } else if (datatype.equalsIgnoreCase("INT")) {
            size = 4;
            b = new byte[size];
            for (i = 0; i < length; i++) {
                afile.read(b);
                if (byteorderLSB) {
                    f = ((0xFF & b[3]) << 24) | ((0xFF & b[2]) << 16) + ((0xFF & b[1]) << 8) + (b[0] & 0xFF);
                } else {
                    f = ((0xFF & b[0]) << 24)
                            | ((0xFF & b[1]) << 16) + ((0xFF & b[2]) << 8) + ((0xFF & b[3]) & 0xFF);
                }
                if (f != (float) nodatavalue) {
                    ret[0] = Math.min(f * rescale, ret[0]);
                    ret[1] = Math.max(f * rescale, ret[1]);
                }
            }
        } else if (datatype.equalsIgnoreCase("LONG")) {
            size = 8;
            b = new byte[size];
            for (i = 0; i < length; i++) {
                afile.read(b);
                if (byteorderLSB) {
                    f = ((long) (0xFF & b[7]) << 56) + ((long) (0xFF & b[6]) << 48)
                            + ((long) (0xFF & b[5]) << 40) + ((long) (0xFF & b[4]) << 32)
                            + ((long) (0xFF & b[3]) << 24) + ((long) (0xFF & b[2]) << 16)
                            + ((long) (0xFF & b[1]) << 8) + (0xFF & b[0]);
                } else {
                    f = ((long) (0xFF & b[0]) << 56) + ((long) (0xFF & b[1]) << 48)
                            + ((long) (0xFF & b[2]) << 40) + ((long) (0xFF & b[3]) << 32)
                            + ((long) (0xFF & b[4]) << 24) + ((long) (0xFF & b[5]) << 16)
                            + ((long) (0xFF & b[6]) << 8) + (0xFF & b[7]);
                }
                if (f != (float) nodatavalue) {
                    ret[0] = Math.min(f * rescale, ret[0]);
                    ret[1] = Math.max(f * rescale, ret[1]);
                }
            }
        } else if (datatype.equalsIgnoreCase("FLOAT")) {
            size = 4;
            b = new byte[size];
            for (i = 0; i < length; i++) {
                afile.read(b);
                ByteBuffer bb = ByteBuffer.wrap(b);
                if (byteorderLSB) {
                    bb.order(ByteOrder.LITTLE_ENDIAN);
                }
                f = bb.getFloat();
                if (f != (float) nodatavalue) {
                    ret[0] = Math.min(f * rescale, ret[0]);
                    ret[1] = Math.max(f * rescale, ret[1]);
                }
            }
        } else if (datatype.equalsIgnoreCase("DOUBLE")) {
            size = 8;
            b = new byte[8];
            for (i = 0; i < length; i++) {
                afile.read(b);
                ByteBuffer bb = ByteBuffer.wrap(b);
                if (byteorderLSB) {
                    bb.order(ByteOrder.LITTLE_ENDIAN);
                }
                f = (float) bb.getDouble();
                if (f != (float) nodatavalue) {
                    ret[0] = Math.min(f * rescale, ret[0]);
                    ret[1] = Math.max(f * rescale, ret[1]);
                }
            }
        } else {
            logger.error("datatype not supported in Grid.getValues: " + datatype);
        }
    } catch (Exception e) {
        logger.error("error calculating min/max of a grid file", e);
    } finally {
        if (afile != null) {
            try {
                afile.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
    return ret;
}

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

private GBDeviceEvent[] decodeAction(ByteBuffer buf) {
    buf.order(ByteOrder.LITTLE_ENDIAN);
    byte command = buf.get();
    if (command == NOTIFICATIONACTION_INVOKE) {
        int id;/*www. ja v a 2  s .  c o m*/
        UUID uuid = new UUID(0, 0);
        if (mFwMajor >= 3) {
            uuid = getUUID(buf);
            id = (int) (uuid.getLeastSignificantBits() & 0xffffffffL);
        } else {
            id = buf.getInt();
        }
        byte action = buf.get();
        if (action >= 0x00 && action <= 0x05) {
            GBDeviceEventNotificationControl devEvtNotificationControl = new GBDeviceEventNotificationControl();
            devEvtNotificationControl.handle = id;
            String caption = "undefined";
            int icon_id = 1;
            boolean needsAck2x = true;
            switch (action) {
            case 0x01:
                devEvtNotificationControl.event = GBDeviceEventNotificationControl.Event.OPEN;
                caption = "Opened";
                icon_id = PebbleIconID.DURING_PHONE_CALL;
                break;
            case 0x02:
                devEvtNotificationControl.event = GBDeviceEventNotificationControl.Event.DISMISS;
                caption = "Dismissed";
                icon_id = PebbleIconID.RESULT_DISMISSED;
                needsAck2x = false;
                break;
            case 0x03:
                devEvtNotificationControl.event = GBDeviceEventNotificationControl.Event.DISMISS_ALL;
                caption = "All dismissed";
                icon_id = PebbleIconID.RESULT_DISMISSED;
                needsAck2x = false;
                break;
            case 0x04:
                devEvtNotificationControl.event = GBDeviceEventNotificationControl.Event.MUTE;
                caption = "Muted";
                icon_id = PebbleIconID.RESULT_MUTE;
                break;
            case 0x05:
            case 0x00:
                boolean failed = true;
                byte attribute_count = buf.get();
                if (attribute_count > 0) {
                    byte attribute = buf.get();
                    if (attribute == 0x01) { // reply string is in attribute 0x01
                        short length = buf.getShort();
                        if (length > 64)
                            length = 64;
                        byte[] reply = new byte[length];
                        buf.get(reply);
                        devEvtNotificationControl.phoneNumber = null;
                        if (buf.remaining() > 1 && buf.get() == 0x0c) {
                            short phoneNumberLength = buf.getShort();
                            byte[] phoneNumberBytes = new byte[phoneNumberLength];
                            buf.get(phoneNumberBytes);
                            devEvtNotificationControl.phoneNumber = new String(phoneNumberBytes);
                        }
                        devEvtNotificationControl.event = GBDeviceEventNotificationControl.Event.REPLY;
                        devEvtNotificationControl.reply = new String(reply);
                        caption = "SENT";
                        icon_id = PebbleIconID.RESULT_SENT;
                        failed = false;
                    }
                }
                if (failed) {
                    caption = "FAILED";
                    icon_id = PebbleIconID.RESULT_FAILED;
                    devEvtNotificationControl = null; // error
                }
                break;
            }
            GBDeviceEventSendBytes sendBytesAck = null;
            if (mFwMajor >= 3 || needsAck2x) {
                sendBytesAck = new GBDeviceEventSendBytes();
                if (mFwMajor >= 3) {
                    sendBytesAck.encodedBytes = encodeActionResponse(uuid, icon_id, caption);
                } else {
                    sendBytesAck.encodedBytes = encodeActionResponse2x(id, action, 6, caption);
                }
            }
            return new GBDeviceEvent[] { sendBytesAck, devEvtNotificationControl };
        }
        LOG.info("unexpected action: " + action);
    }

    return null;
}

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.sav.SAVFileReader.java

void decodeRecordType7(BufferedInputStream stream) throws IOException {
    dbgLog.fine("decodeRecordType7(): start");
    int counter = 0;
    int[] headerSection = new int[2];

    // the variables below may no longer needed; 
    // but they may be useful for debugging/logging purposes.

    /// // RecordType 7 
    /// // Subtype 3
    /// List<Integer> releaseMachineSpecificInfo = new ArrayList<Integer>();
    /// List<String> releaseMachineSpecificInfoHex = new ArrayList<String>();

    /// // Subytpe 4
    /// Map<String, Double> OBSTypeValue = new LinkedHashMap<String, Double>();
    /// Map<String, String> OBSTypeHexValue = new LinkedHashMap<String, String>();    
    //Subtype 11//www.  j a  va 2  s.c o m
    /// List<Integer> measurementLevel = new ArrayList<Integer>();
    /// List<Integer> columnWidth = new ArrayList<Integer>();
    /// List<Integer> alignment = new ArrayList<Integer>();

    while (true) {
        try {
            if (stream == null) {
                throw new IllegalArgumentException("RT7: stream == null!");
            }
            // first check the 4-byte header value
            //if (stream.markSupported()){
            stream.mark(1000);
            //}
            // 7.0 check the first 4 bytes
            byte[] headerCodeRt7 = new byte[LENGTH_RECORD_TYPE7_CODE];

            int nbytes_rt7 = stream.read(headerCodeRt7, 0, LENGTH_RECORD_TYPE7_CODE);
            // to-do check against nbytes
            //printHexDump(headerCodeRt7, "RT7 header test");
            ByteBuffer bb_header_code_rt7 = ByteBuffer.wrap(headerCodeRt7, 0, LENGTH_RECORD_TYPE7_CODE);
            if (isLittleEndian) {
                bb_header_code_rt7.order(ByteOrder.LITTLE_ENDIAN);
            }

            int intRT7test = bb_header_code_rt7.getInt();
            dbgLog.fine("RT7: header test value=" + intRT7test);
            if (intRT7test != 7) {
                //if (stream.markSupported()){
                //out.print("iteration="+safteyCounter);
                //dbgLog.fine("iteration="+safteyCounter);
                dbgLog.fine("intRT7test failed=" + intRT7test);
                dbgLog.fine("counter=" + counter);
                stream.reset();
                return;
                //}
            }

            // 7.1 check 4-byte integer Sub-Type Code

            byte[] length_sub_type_code = new byte[LENGTH_RT7_SUB_TYPE_CODE];

            int nbytes_rt7_1 = stream.read(length_sub_type_code, 0, LENGTH_RT7_SUB_TYPE_CODE);
            // to-do check against nbytes

            //printHexDump(length_how_many_line_bytes, "RT7 how_many_line_bytes");
            ByteBuffer bb_sub_type_code = ByteBuffer.wrap(length_sub_type_code, 0, LENGTH_RT7_SUB_TYPE_CODE);
            if (isLittleEndian) {
                bb_sub_type_code.order(ByteOrder.LITTLE_ENDIAN);
            }

            int subTypeCode = bb_sub_type_code.getInt();
            dbgLog.fine("RT7: subTypeCode=" + subTypeCode);

            switch (subTypeCode) {
            case 3:
                // 3: Release andMachine-Specific Integer Information

                //parseRT7SubTypefield(stream);

                headerSection = parseRT7SubTypefieldHeader(stream);
                if (headerSection != null) {
                    int unitLength = headerSection[0];
                    int numberOfUnits = headerSection[1];

                    for (int i = 0; i < numberOfUnits; i++) {
                        dbgLog.finer(i + "-th fieldData");
                        byte[] work = new byte[unitLength];

                        int nb = stream.read(work);
                        dbgLog.finer("raw bytes in Hex:" + new String(Hex.encodeHex(work)));
                        ByteBuffer bb_field = ByteBuffer.wrap(work);
                        if (isLittleEndian) {
                            bb_field.order(ByteOrder.LITTLE_ENDIAN);
                        }
                        String dataInHex = new String(Hex.encodeHex(bb_field.array()));
                        /// releaseMachineSpecificInfoHex.add(dataInHex);

                        dbgLog.finer("raw bytes in Hex:" + dataInHex);
                        if (unitLength == 4) {
                            int fieldData = bb_field.getInt();
                            dbgLog.finer("fieldData(int)=" + fieldData);
                            dbgLog.finer("fieldData in Hex=0x" + Integer.toHexString(fieldData));
                            /// releaseMachineSpecificInfo.add(fieldData);
                        }

                    }

                    /// dbgLog.fine("releaseMachineSpecificInfo="+releaseMachineSpecificInfo);
                    /// dbgLog.fine("releaseMachineSpecificInfoHex="+releaseMachineSpecificInfoHex);

                } else {
                    // throw new IOException
                }

                dbgLog.fine("***** end of subType 3 ***** \n");

                break;
            case 4:
                // Release andMachine-SpecificOBS-Type Information
                headerSection = parseRT7SubTypefieldHeader(stream);
                if (headerSection != null) {
                    int unitLength = headerSection[0];
                    int numberOfUnits = headerSection[1];

                    for (int i = 0; i < numberOfUnits; i++) {
                        dbgLog.finer(i + "-th fieldData:" + RecordType7SubType4Fields.get(i));
                        byte[] work = new byte[unitLength];

                        int nb = stream.read(work);

                        dbgLog.finer("raw bytes in Hex:" + new String(Hex.encodeHex(work)));
                        ByteBuffer bb_field = ByteBuffer.wrap(work);
                        dbgLog.finer("byte order=" + bb_field.order().toString());
                        if (isLittleEndian) {
                            bb_field.order(ByteOrder.LITTLE_ENDIAN);
                        }
                        ByteBuffer bb_field_dup = bb_field.duplicate();
                        OBSTypeHexValue.put(RecordType7SubType4Fields.get(i),
                                new String(Hex.encodeHex(bb_field.array())));
                        //                            dbgLog.finer("raw bytes in Hex:"+
                        //                                OBSTypeHexValue.get(RecordType7SubType4Fields.get(i)));
                        if (unitLength == 8) {
                            double fieldData = bb_field.getDouble();
                            /// OBSTypeValue.put(RecordType7SubType4Fields.get(i), fieldData);
                            dbgLog.finer("fieldData(double)=" + fieldData);
                            OBSTypeHexValue.put(RecordType7SubType4Fields.get(i),
                                    Double.toHexString(fieldData));
                            dbgLog.fine("fieldData in Hex=" + Double.toHexString(fieldData));
                        }
                    }
                    /// dbgLog.fine("OBSTypeValue="+OBSTypeValue);
                    /// dbgLog.fine("OBSTypeHexValue="+OBSTypeHexValue);

                } else {
                    // throw new IOException
                }

                dbgLog.fine("***** end of subType 4 ***** \n");
                break;
            case 5:
                // Variable Sets Information
                parseRT7SubTypefield(stream);
                break;
            case 6:
                // Trends date information
                parseRT7SubTypefield(stream);
                break;
            case 7:
                // Multiple response groups
                parseRT7SubTypefield(stream);
                break;
            case 8:
                // Windows Data Entry data
                parseRT7SubTypefield(stream);
                break;
            case 9:
                //
                parseRT7SubTypefield(stream);
                break;
            case 10:
                // TextSmart data
                parseRT7SubTypefield(stream);
                break;
            case 11:
                // Msmt level, col width, & alignment
                //parseRT7SubTypefield(stream);

                headerSection = parseRT7SubTypefieldHeader(stream);
                if (headerSection != null) {
                    int unitLength = headerSection[0];
                    int numberOfUnits = headerSection[1];

                    for (int i = 0; i < numberOfUnits; i++) {
                        dbgLog.finer(i + "-th fieldData");
                        byte[] work = new byte[unitLength];

                        int nb = stream.read(work);
                        dbgLog.finer("raw bytes in Hex:" + new String(Hex.encodeHex(work)));
                        ByteBuffer bb_field = ByteBuffer.wrap(work);
                        if (isLittleEndian) {
                            bb_field.order(ByteOrder.LITTLE_ENDIAN);
                        }
                        dbgLog.finer("raw bytes in Hex:" + new String(Hex.encodeHex(bb_field.array())));

                        if (unitLength == 4) {
                            int fieldData = bb_field.getInt();
                            dbgLog.finer("fieldData(int)=" + fieldData);
                            dbgLog.finer("fieldData in Hex=0x" + Integer.toHexString(fieldData));

                            int remainder = i % 3;
                            dbgLog.finer("remainder=" + remainder);
                            if (remainder == 0) {
                                /// measurementLevel.add(fieldData);
                            } else if (remainder == 1) {
                                /// columnWidth.add(fieldData);
                            } else if (remainder == 2) {
                                /// alignment.add(fieldData);
                            }
                        }

                    }

                } else {
                    // throw new IOException
                }
                /// dbgLog.fine("measurementLevel="+measurementLevel);
                /// dbgLog.fine("columnWidth="+columnWidth);
                /// dbgLog.fine("alignment="+alignment);
                dbgLog.fine("end of subType 11\n");

                break;
            case 12:
                // Windows Data Entry GUID
                parseRT7SubTypefield(stream);
                break;
            case 13:
                // Extended variable names
                // parseRT7SubTypefield(stream);
                headerSection = parseRT7SubTypefieldHeader(stream);

                if (headerSection != null) {
                    int unitLength = headerSection[0];
                    dbgLog.fine("RT7: unitLength=" + unitLength);
                    int numberOfUnits = headerSection[1];
                    dbgLog.fine("RT7: numberOfUnits=" + numberOfUnits);
                    byte[] work = new byte[unitLength * numberOfUnits];
                    int nbtyes13 = stream.read(work);

                    String[] variableShortLongNamePairs = new String(work, "US-ASCII").split("\t");

                    for (int i = 0; i < variableShortLongNamePairs.length; i++) {
                        dbgLog.fine("RT7: " + i + "-th pair" + variableShortLongNamePairs[i]);
                        String[] pair = variableShortLongNamePairs[i].split("=");
                        shortToLongVariableNameTable.put(pair[0], pair[1]);
                    }

                    dbgLog.fine("RT7: shortToLongVarialbeNameTable" + shortToLongVariableNameTable);
                    // We are saving the short-to-long name map; at the
                    // end of ingest, we'll go through the data variables and
                    // change the names accordingly. 

                    // smd.setShortToLongVarialbeNameTable(shortToLongVarialbeNameTable);
                } else {
                    // throw new IOException
                }

                break;
            case 14:
                // Extended strings
                //parseRT7SubTypefield(stream);
                headerSection = parseRT7SubTypefieldHeader(stream);

                if (headerSection != null) {
                    int unitLength = headerSection[0];
                    dbgLog.fine("RT7.14: unitLength=" + unitLength);
                    int numberOfUnits = headerSection[1];
                    dbgLog.fine("RT7.14: numberOfUnits=" + numberOfUnits);
                    byte[] work = new byte[unitLength * numberOfUnits];
                    int nbtyes13 = stream.read(work);

                    String[] extendedVariablesSizePairs = new String(work, defaultCharSet).split("\000\t");

                    for (int i = 0; i < extendedVariablesSizePairs.length; i++) {
                        dbgLog.fine("RT7.14: " + i + "-th pair" + extendedVariablesSizePairs[i]);
                        if (extendedVariablesSizePairs[i].indexOf("=") > 0) {
                            String[] pair = extendedVariablesSizePairs[i].split("=");
                            extendedVariablesSizeTable.put(pair[0], Integer.valueOf(pair[1]));
                        }
                    }

                    dbgLog.fine("RT7.14: extendedVariablesSizeTable" + extendedVariablesSizeTable);
                } else {
                    // throw new IOException
                }

                break;
            case 15:
                // Clementine Metadata
                parseRT7SubTypefield(stream);
                break;
            case 16:
                // 64 bit N of cases
                parseRT7SubTypefield(stream);
                break;
            case 17:
                // File level attributes
                parseRT7SubTypefield(stream);
                break;
            case 18:
                // Variable attributes
                parseRT7SubTypefield(stream);
                break;
            case 19:
                // Extended multiple response groups
                parseRT7SubTypefield(stream);
                break;
            case 20:
                // Character encoding, aka code page.
                // Must be a version 16+ feature (?).
                // Starting v.16, the default character encoding for SAV
                // files is UTF-8; but then it is possible to specify an 
                // alternative encoding here. 
                // A typical use case would be people setting it to "ISO-Latin" 
                // or "windows-1252", or a similar 8-bit encoding to store 
                // text with standard Western European accents.
                // -- L.A.

                headerSection = parseRT7SubTypefieldHeader(stream);

                if (headerSection != null) {
                    int unitLength = headerSection[0];
                    dbgLog.fine("RT7-20: unitLength=" + unitLength);
                    int numberOfUnits = headerSection[1];
                    dbgLog.fine("RT7-20: numberOfUnits=" + numberOfUnits);
                    byte[] rt7st20bytes = new byte[unitLength * numberOfUnits];
                    int nbytes20 = stream.read(rt7st20bytes);

                    String dataCharSet = new String(rt7st20bytes, "US-ASCII");

                    if (dataCharSet != null && !(dataCharSet.equals(""))) {
                        dbgLog.fine("RT7-20: data charset: " + dataCharSet);
                        defaultCharSet = dataCharSet;
                    }
                } /*else {
                  // TODO: 
                  // decide if the exception should actually be thrown here!
                  // -- L.A. 4.0 beta
                  // throw new IOException
                  }*/

                break;
            case 21:
                // Value labels for long strings
                parseRT7SubTypefield(stream);
                break;
            case 22:
                // Missing values for long strings
                parseRT7SubTypefield(stream);
                break;
            default:
                parseRT7SubTypefield(stream);
            }

        } catch (IOException ex) {
            //ex.printStackTrace();
            throw ex;
        }

        counter++;

        if (counter > 20) {
            break;
        }
    }

    dbgLog.fine("RT7: counter=" + counter);
    dbgLog.fine("RT7: decodeRecordType7(): end");
}

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

private GBDeviceEvent decodeBlobDb(ByteBuffer buf) {
    final String ENDPOINT_NAME = "BLOBDB";
    final String statusString[] = { "unknown", "success", "general failure", "invalid operation",
            "invalid database id", "invalid data", "key does not exist", "database full", "data stale", };
    buf.order(ByteOrder.LITTLE_ENDIAN);
    short token = buf.getShort();
    byte status = buf.get();

    if (status >= 0 && status < statusString.length) {
        LOG.info(ENDPOINT_NAME + ": " + statusString[status] + " (token " + (token & 0xffff) + ")");
    } else {//from w  ww. ja  v a2  s.  c  om
        LOG.warn(ENDPOINT_NAME + ": unknown status " + status + " (token " + (token & 0xffff) + ")");
    }
    return null;
}