Example usage for java.nio ByteBuffer getShort

List of usage examples for java.nio ByteBuffer getShort

Introduction

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

Prototype

public abstract short getShort();

Source Link

Document

Returns the short at the current position and increases the position by 2.

Usage

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

/**
 * Increase sampleEveryNthPoint to return a smaller grid.
 *
 * Grid max and min values may be skipped.
 *
 * This does not used previously cached data.
 *
 * @param sampleEveryNthPoint/*from w  w  w  .  j  av  a2 s . c om*/
 * @return
 */
public float[] getGrid(int sampleEveryNthPoint) {
    int maxArrayLength = Integer.MAX_VALUE - 10;

    if (subgrids != null) {
        //sample points
        int size = 1000;
        double[][] points = new double[size * size][2];
        int pos = 0;
        for (int i = 0; i < 1000; i++) {
            for (int j = 0; j < 1000; j++) {
                points[pos][0] = xmin + (xmax - xmin) * j / (double) size;
                points[pos][1] = ymax - (ymax - ymin) * i / (double) size;
                pos++;
            }
        }

        return getValues3(points, 64);
    }

    int length = (nrows / sampleEveryNthPoint) * (ncols);

    float[] ret = new float[length];

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

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

        int sz = (int) Math.min(afile.length() / sampleEveryNthPoint / sampleEveryNthPoint, maxArrayLength);
        sz += 8 - sz % 8;
        byte[] b = new byte[sz];

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

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

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

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

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;/* ww  w.j a v  a2s. c  o  m*/

    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:org.neo4j.io.pagecache.PageCacheTest.java

@Test(timeout = SHORT_TIMEOUT_MILLIS)
public void writesOfDifferentUnitsMustHaveCorrectEndianess() throws Exception {
    getPageCache(fs, maxPages, pageCachePageSize, PageCacheTracer.NULL);
    PagedFile pagedFile = pageCache.map(file("a"), 20);

    try (PageCursor cursor = pagedFile.io(0, PF_SHARED_WRITE_LOCK)) {
        assertTrue(cursor.next());//from   w w  w  . j av  a  2  s.c  o  m
        byte[] data = { 42, 43, 44, 45, 46 };

        cursor.putLong(41); //  0+8 = 8
        cursor.putInt(41); //  8+4 = 12
        cursor.putShort((short) 41); // 12+2 = 14
        cursor.putByte((byte) 41); // 14+1 = 15
        cursor.putBytes(data); // 15+5 = 20
    }

    try (PageCursor cursor = pagedFile.io(0, PF_SHARED_WRITE_LOCK)) {
        assertTrue(cursor.next());

        long a = cursor.getLong(); //  8
        int b = cursor.getInt(); // 12
        short c = cursor.getShort();// 14
        byte[] data = new byte[] { cursor.getByte(), // 15
                cursor.getByte(), // 16
                cursor.getByte(), // 17
                cursor.getByte(), // 18
                cursor.getByte(), // 19
                cursor.getByte() // 20
        };
        cursor.setOffset(0);
        cursor.putLong(1 + a);
        cursor.putInt(1 + b);
        cursor.putShort((short) (1 + c));
        for (byte d : data) {
            d++;
            cursor.putByte(d);
        }
    }

    pagedFile.close();

    StoreChannel channel = fs.open(file("a"), "r");
    ByteBuffer buf = ByteBuffer.allocate(20);
    channel.read(buf);
    buf.flip();

    assertThat(buf.getLong(), is(42L));
    assertThat(buf.getInt(), is(42));
    assertThat(buf.getShort(), is((short) 42));
    assertThat(buf.get(), is((byte) 42));
    assertThat(buf.get(), is((byte) 43));
    assertThat(buf.get(), is((byte) 44));
    assertThat(buf.get(), is((byte) 45));
    assertThat(buf.get(), is((byte) 46));
    assertThat(buf.get(), is((byte) 47));
}

From source file:org.zaproxy.zap.extension.ascanrulesAlpha.GitMetadata.java

/**
 * gets a Map of relative file paths to SHA1s using raw Git index file data (which is not
 * verified here)//www.j a va2  s .com
 *
 * @param data the raw binary data from a valid Git index file (Versions 2,3,4 are supported)
 * @return a Map of relative file paths to SHA1s using raw Git index file data
 * @todo consider sharing this method between the Git Spider, and the SourceCodeDisclosure
 *     scanner.
 */
@SuppressWarnings("unused")
public Map<String, String> getIndexSha1s(byte[] data) throws Exception {
    Map<String, String> map = new TreeMap<String, String>();

    // wrap up the data, so we can read it..
    ByteBuffer dataBuffer = ByteBuffer.wrap(data);

    byte[] dircArray = new byte[4];
    dataBuffer.get(dircArray);

    int indexFileVersion = dataBuffer.getInt();
    // if ( log.isDebugEnabled() ) log.debug("The Git index file version is "+
    // indexFileVersion);

    int indexEntryCount = dataBuffer.getInt();
    // if ( log.isDebugEnabled() ) log.debug(indexEntryCount + " entries were found in the Git
    // index file ");

    if (indexFileVersion != 2 && indexFileVersion != 3 && indexFileVersion != 4) {
        throw new Exception(
                "Only Git Index File versions 2, 3, and 4 are currently supported. Git Index File Version "
                        + indexFileVersion + " was found.");
    }

    // for version 4 (and upwards?), we need to know the previous entry name, so store it
    String previousIndexEntryName = "";
    for (int entryIndex = 0; entryIndex < indexEntryCount; entryIndex++) {
        int entryBytesRead = 0;
        int indexEntryCtime1 = dataBuffer.getInt();
        entryBytesRead += 4;
        // if ( log.isDebugEnabled() ) log.debug ("Entry "+ entryIndex + " has indexEntryCtime1
        // "+ indexEntryCtime1);
        int indexEntryCtime2 = dataBuffer.getInt();
        entryBytesRead += 4;
        int indexEntryMtime1 = dataBuffer.getInt();
        entryBytesRead += 4;
        int indexEntryMtime2 = dataBuffer.getInt();
        entryBytesRead += 4;
        int indexEntryDev = dataBuffer.getInt();
        entryBytesRead += 4;
        int indexEntryInode = dataBuffer.getInt();
        entryBytesRead += 4;
        int indexEntryMode = dataBuffer.getInt();
        entryBytesRead += 4;
        int indexEntryUid = dataBuffer.getInt();
        entryBytesRead += 4;
        int indexEntryGid = dataBuffer.getInt();
        entryBytesRead += 4;
        int indexEntrySize = dataBuffer.getInt();
        entryBytesRead += 4;
        // if ( log.isDebugEnabled() ) log.debug("Entry "+ entryIndex + " has size "+
        // indexEntrySize);

        // size is unspecified for the entry id, but it seems to be a 40 hex character, SHA-1
        // string
        // stored as 20 bytes, network order
        byte[] indexEntryIdBuffer = new byte[20];
        dataBuffer.get(indexEntryIdBuffer);
        entryBytesRead += 20;
        String indexEntrySha1 = Hex.encodeHexString(indexEntryIdBuffer);

        short indexEntryFlags = dataBuffer.getShort();
        entryBytesRead += 2;
        // if ( log.isDebugEnabled() ) log.debug ("Entry "+ entryIndex + " has flags " +
        // indexEntryFlags);

        // mask off all but the least significant 12 bits of the index entry flags to get the
        // length of the name in bytes
        int indexEntryNameByteLength = indexEntryFlags & 4095;
        // if ( log.isDebugEnabled() ) log.debug ("Entry "+ entryIndex + " has a name of length
        // " + indexEntryNameByteLength);

        // mask off all but the second most significant 12 bit of the index entry flags to get
        // the extended flag for the entry
        int indexEntryExtendedFlag = ((indexEntryFlags & (1 << 14)) >> 14);
        // if ( log.isDebugEnabled() ) log.debug ("Entry "+ entryIndex + " has an extended flag
        // of " + indexEntryExtendedFlag);

        // check that we parsed out the index entry extended flag correctly.
        // this is more of an assertion than anything. It's already saved my bacon once.
        if (indexEntryExtendedFlag != 0 && indexEntryExtendedFlag != 1) {
            throw new Exception("Error parsing out the extended flag for index entry " + entryIndex
                    + ". We got " + indexEntryExtendedFlag);
        }
        if (indexFileVersion == 2 && indexEntryExtendedFlag != 0) {
            throw new Exception(
                    "Index File Version 2 is supposed to have the extended flag set to 0. For index entry "
                            + entryIndex + ", it is set to " + indexEntryExtendedFlag);
        }

        // specific to version 3 and above, if the extended flag is set for the entry.
        if (indexFileVersion > 2 && indexEntryExtendedFlag == 1) {
            // if ( log.isDebugEnabled() ) log.debug ("For Index file version "+
            // indexFileVersion +", reading an extra 16 bits for Entry "+ entryIndex );
            short indexEntryExtendedFlags = dataBuffer.getShort();
            entryBytesRead += 2;
            // if ( log.isDebugEnabled() ) log.debug ("Entry "+ entryIndex + " has (optional)
            // extended flags " + indexEntryExtendedFlags);
        }

        String indexEntryName = null;
        if (indexFileVersion > 3) {
            // if ( log.isDebugEnabled() ) log.debug("Inflating the (deflated) entry name for
            // index entry "+ entryIndex + " based on the previous entry name, since Index file
            // version "+ indexFileVersion + " requires this");

            // get bytes until we find one with the msb NOT set. count the bytes.
            int n = 0, removeNfromPreviousName = 0;
            byte msbsetmask = (byte) (1 << 7); // 1000 0000
            byte msbunsetmask = (byte) ((~msbsetmask) & 0xFF); // 0111 1111
            while (++n > 0) {
                byte byteRead = dataBuffer.get();
                entryBytesRead++;
                if (n == 1) // zero the msb of the first byte read
                    removeNfromPreviousName = (removeNfromPreviousName << 8)
                            | (0xFF & (byteRead & msbunsetmask));
                else // set the msb of subsequent bytes read
                    removeNfromPreviousName = (removeNfromPreviousName << 8) | (0xFF & (byteRead | msbsetmask));
                if ((byteRead & msbsetmask) == 0)
                    break; // break if msb is NOT set in the byte
            }

            // if (log.isDebugEnabled()) log.debug("We read "+ n + " bytes of variable length
            // data from before the start of the entry name");
            if (n > 4)
                throw new Exception(
                        "An entry name is never expected to be > 2^^32 bytes long. Some file corruption may have occurred, or a parsing error has occurred");

            // now read the (partial) name for the current entry
            int bytesToReadCurrentNameEntry = indexEntryNameByteLength
                    - (previousIndexEntryName.length() - removeNfromPreviousName);
            byte[] indexEntryNameBuffer = new byte[bytesToReadCurrentNameEntry];
            dataBuffer.get(indexEntryNameBuffer);
            entryBytesRead += bytesToReadCurrentNameEntry;

            // build it up
            indexEntryName = previousIndexEntryName.substring(0,
                    previousIndexEntryName.length() - removeNfromPreviousName)
                    + new String(indexEntryNameBuffer);
        } else {
            // indexFileVersion <= 3 (waaaaay simpler logic, but the index file is larger in
            // this version than for v4+)
            byte[] indexEntryNameBuffer = new byte[indexEntryNameByteLength];
            dataBuffer.get(indexEntryNameBuffer);
            entryBytesRead += indexEntryNameByteLength;
            indexEntryName = new String(indexEntryNameBuffer);
        }

        if (log.isDebugEnabled())
            log.debug("Entry " + entryIndex + " has name " + indexEntryName);

        // and store off the index entry name, for the next iteration
        previousIndexEntryName = indexEntryName;
        // skip past the zero byte terminating the string (whose purpose seems completely
        // pointless to me, but hey)
        byte indexEntryNul = dataBuffer.get();
        entryBytesRead++;

        // the padding after the pathname does not exist for versions 4 or later.
        if (indexFileVersion < 4) {
            // if ( log.isDebugEnabled() ) log.debug("Aligning to an 8 byte boundary after Entry
            // "+ entryIndex + ", since Index file version "+ indexFileVersion + " mandates 64
            // bit alignment for index entries");

            int entryBytesToRead = ((8 - (entryBytesRead % 8)) % 8);
            // if ( log.isDebugEnabled() ) {
            //   log.debug ("The number of bytes read for index entry "+ entryIndex + " thus far
            // is: "+ entryBytesRead);
            //   log.debug ("So we must read "+ entryBytesToRead + " bytes to stay on a 64 bit
            // boundary");
            // }

            // read the 0-7 (NUL) bytes to keep reading index entries on an 8 byte boundary
            byte[] indexEntryPadBuffer = new byte[entryBytesToRead];
            dataBuffer.get(indexEntryPadBuffer);
            entryBytesRead += entryBytesToRead;
        } else {
            // if ( log.isDebugEnabled() ) log.debug("Not aligning to an 8 byte boundary after
            // Entry "+ entryIndex + ", since Index file version "+ indexFileVersion + " does
            // not mandate 64 bit alignment for index entries");
        }

        // Git does not store entries for directories, but just files/symlinks/Git links, so no
        // need to handle directories here, unlike with SVN, for instance.
        if (indexEntryName != null && indexEntryName.length() > 0) {
            // log.info("Found file/symbolic link/gitlink "+ indexEntryName + " in the Git
            // entries file");
            map.put(indexEntryName, indexEntrySha1);
        }
    }
    return map;
}

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

private GBDeviceEvent[] decodeDatalog(ByteBuffer buf, short length) {
    boolean ack = true;
    byte command = buf.get();
    byte id = buf.get();
    GBDeviceEventDataLogging devEvtDataLogging = null;
    switch (command) {
    case DATALOG_TIMEOUT:
        LOG.info("DATALOG TIMEOUT. id=" + (id & 0xff) + " - ignoring");
        return null;
    case DATALOG_SENDDATA:
        buf.order(ByteOrder.LITTLE_ENDIAN);
        int items_left = buf.getInt();
        int crc = buf.getInt();
        DatalogSession datalogSession = mDatalogSessions.get(id);
        LOG.info("DATALOG SENDDATA. id=" + (id & 0xff) + ", items_left=" + items_left + ", total length="
                + (length - 10));/*  w w  w . j a  v a 2 s.  c o m*/
        if (datalogSession != null) {
            LOG.info("DATALOG UUID=" + datalogSession.uuid + ", tag=" + datalogSession.tag
                    + datalogSession.getTaginfo() + ", itemSize=" + datalogSession.itemSize + ", itemType="
                    + datalogSession.itemType);
            if (!datalogSession.uuid.equals(UUID_ZERO) && datalogSession.getClass().equals(DatalogSession.class)
                    && mEnablePebbleKit) {
                devEvtDataLogging = datalogSession.handleMessageForPebbleKit(buf, length - 10);
                if (devEvtDataLogging == null) {
                    ack = false;
                }
            } else {
                ack = datalogSession.handleMessage(buf, length - 10);
            }
        }
        break;
    case DATALOG_OPENSESSION:
        UUID uuid = getUUID(buf);
        buf.order(ByteOrder.LITTLE_ENDIAN);
        int timestamp = buf.getInt();
        int log_tag = buf.getInt();
        byte item_type = buf.get();
        short item_size = buf.getShort();
        LOG.info("DATALOG OPENSESSION. id=" + (id & 0xff) + ", App UUID=" + uuid.toString() + ", log_tag="
                + log_tag + ", item_type=" + item_type + ", itemSize=" + item_size);
        if (!mDatalogSessions.containsKey(id)) {
            if (uuid.equals(UUID_ZERO) && log_tag == 81) {
                mDatalogSessions.put(id, new DatalogSessionHealthSteps(id, uuid, timestamp, log_tag, item_type,
                        item_size, getDevice()));
            } else if (uuid.equals(UUID_ZERO) && log_tag == 83) {
                mDatalogSessions.put(id, new DatalogSessionHealthSleep(id, uuid, timestamp, log_tag, item_type,
                        item_size, getDevice()));
            } else if (uuid.equals(UUID_ZERO) && log_tag == 84) {
                mDatalogSessions.put(id, new DatalogSessionHealthOverlayData(id, uuid, timestamp, log_tag,
                        item_type, item_size, getDevice()));
            } else if (uuid.equals(UUID_ZERO) && log_tag == 85) {
                mDatalogSessions.put(id, new DatalogSessionHealthHR(id, uuid, timestamp, log_tag, item_type,
                        item_size, getDevice()));
            } else {
                mDatalogSessions.put(id,
                        new DatalogSession(id, uuid, timestamp, log_tag, item_type, item_size));
            }
        }
        break;
    case DATALOG_CLOSE:
        LOG.info("DATALOG_CLOSE. id=" + (id & 0xff));
        datalogSession = mDatalogSessions.get(id);
        if (datalogSession != null) {
            if (!datalogSession.uuid.equals(UUID_ZERO) && datalogSession.getClass().equals(DatalogSession.class)
                    && mEnablePebbleKit) {
                GBDeviceEventDataLogging dataLogging = new GBDeviceEventDataLogging();
                dataLogging.command = GBDeviceEventDataLogging.COMMAND_FINISH_SESSION;
                dataLogging.appUUID = datalogSession.uuid;
                dataLogging.tag = datalogSession.tag;
                devEvtDataLogging = dataLogging;
            }
            mDatalogSessions.remove(id);
        }
        break;
    default:
        LOG.info("unknown DATALOG command: " + (command & 0xff));
        break;
    }
    GBDeviceEventSendBytes sendBytes = new GBDeviceEventSendBytes();
    if (ack) {
        LOG.info("sending ACK (0x85)");
        sendBytes.encodedBytes = encodeDatalog(id, DATALOG_ACK);
    } else {
        LOG.info("sending NACK (0x86)");
        sendBytes.encodedBytes = encodeDatalog(id, DATALOG_NACK);
    }
    // append ack/nack
    return new GBDeviceEvent[] { devEvtDataLogging, sendBytes };
}

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;/*from   www  .j  av a  2s  .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;
}