Example usage for java.nio ByteBuffer order

List of usage examples for java.nio ByteBuffer order

Introduction

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

Prototype

Endianness order

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

Click Source Link

Document

The byte order of this buffer, default is BIG_ENDIAN .

Usage

From source file: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;/*  ww  w.  j  ava  2 s .com*/
        } 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:nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.PebbleProtocol.java

private GBDeviceEventAppManagement decodeAppFetch(ByteBuffer buf) {
    byte command = buf.get();
    if (command == 0x01) {
        UUID uuid = getUUID(buf);
        buf.order(ByteOrder.LITTLE_ENDIAN);
        int app_id = buf.getInt();
        GBDeviceEventAppManagement fetchRequest = new GBDeviceEventAppManagement();
        fetchRequest.type = GBDeviceEventAppManagement.EventType.INSTALL;
        fetchRequest.event = GBDeviceEventAppManagement.Event.REQUEST;
        fetchRequest.token = app_id;//from  w  ww.  j  a v  a 2  s  .c  o  m
        fetchRequest.uuid = uuid;
        return fetchRequest;
    }
    return null;
}

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;
            }//from w w  w .ja  v a  2 s  .c o m
            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:nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.PebbleProtocol.java

private byte[] encodeExtensibleNotification(int id, int timestamp, String title, String subtitle, String body,
        String sourceName, boolean hasHandle, String[] cannedReplies) {
    final short ACTION_LENGTH_MIN = 10;

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

    // Calculate length first
    byte actions_count;
    short actions_length;
    String dismiss_string;//from www  .ja v a2s. c om
    String open_string = "Open on phone";
    String mute_string = "Mute";
    String reply_string = "Reply";
    if (sourceName != null) {
        mute_string += " " + sourceName;
    }

    byte dismiss_action_id;

    if (hasHandle && !"ALARMCLOCKRECEIVER".equals(sourceName)) {
        actions_count = 3;
        dismiss_string = "Dismiss";
        dismiss_action_id = 0x02;
        actions_length = (short) (ACTION_LENGTH_MIN * actions_count + dismiss_string.getBytes().length
                + open_string.getBytes().length + mute_string.getBytes().length);
    } else {
        actions_count = 1;
        dismiss_string = "Dismiss all";
        dismiss_action_id = 0x03;
        actions_length = (short) (ACTION_LENGTH_MIN * actions_count + dismiss_string.getBytes().length);
    }

    int replies_length = -1;
    if (cannedReplies != null && cannedReplies.length > 0) {
        actions_count++;
        for (String reply : cannedReplies) {
            replies_length += reply.getBytes().length + 1;
        }
        actions_length += ACTION_LENGTH_MIN + reply_string.getBytes().length + replies_length + 3; // 3 = attribute id (byte) + length(short)
    }

    byte attributes_count = 0;

    int length = 21 + 10 + actions_length;
    if (parts != null) {
        for (String s : parts) {
            if (s == null || s.equals("")) {
                continue;
            }
            attributes_count++;
            length += (3 + s.getBytes().length);
        }
    }

    // Encode Prefix
    ByteBuffer buf = ByteBuffer.allocate(length + LENGTH_PREFIX);

    buf.order(ByteOrder.BIG_ENDIAN);
    buf.putShort((short) (length));
    buf.putShort(ENDPOINT_EXTENSIBLENOTIFS);

    buf.order(ByteOrder.LITTLE_ENDIAN); // !

    buf.put((byte) 0x00); // ?
    buf.put((byte) 0x01); // add notifications
    buf.putInt(0x00000000); // flags - ?
    buf.putInt(id);
    buf.putInt(0x00000000); // ANCS id
    buf.putInt(timestamp);
    buf.put((byte) 0x01); // layout - ?
    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 > 255)
                partlength = 255;
            buf.put(attribute_id);
            buf.putShort((short) partlength);
            buf.put(s.getBytes(), 0, partlength);
        }
    }

    // dismiss action
    buf.put(dismiss_action_id);
    buf.put((byte) 0x04); // dismiss
    buf.put((byte) 0x01); // number attributes
    buf.put((byte) 0x01); // attribute id (title)
    buf.putShort((short) dismiss_string.getBytes().length);
    buf.put(dismiss_string.getBytes());

    // open and mute actions
    if (hasHandle && !"ALARMCLOCKRECEIVER".equals(sourceName)) {
        buf.put((byte) 0x01);
        buf.put((byte) 0x02); // generic
        buf.put((byte) 0x01); // number attributes
        buf.put((byte) 0x01); // attribute id (title)
        buf.putShort((short) open_string.getBytes().length);
        buf.put(open_string.getBytes());

        buf.put((byte) 0x04);
        buf.put((byte) 0x02); // generic
        buf.put((byte) 0x01); // number attributes
        buf.put((byte) 0x01); // attribute id (title)
        buf.putShort((short) mute_string.getBytes().length);
        buf.put(mute_string.getBytes());

    }

    if (cannedReplies != null && replies_length > 0) {
        buf.put((byte) 0x05);
        buf.put((byte) 0x03); // reply action
        buf.put((byte) 0x02); // number attributes
        buf.put((byte) 0x01); // title
        buf.putShort((short) reply_string.getBytes().length);
        buf.put(reply_string.getBytes());
        buf.put((byte) 0x08); // canned replies
        buf.putShort((short) replies_length);
        for (int i = 0; i < cannedReplies.length - 1; i++) {
            buf.put(cannedReplies[i].getBytes());
            buf.put((byte) 0x00);
        }
        // last one must not be zero terminated, else we get an additional emply reply
        buf.put(cannedReplies[cannedReplies.length - 1].getBytes());
    }

    return buf.array();
}

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

private byte[] encodeBlobdbNotification(int id, int timestamp, String title, String subtitle, String body,
        String sourceName, boolean hasHandle, NotificationType notificationType, String[] cannedReplies) {
    final short NOTIFICATION_PIN_LENGTH = 46;
    final short ACTION_LENGTH_MIN = 10;

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

    if (notificationType == null) {
        notificationType = NotificationType.UNKNOWN;
    }//from ww  w. ja v  a 2  s. co  m

    int icon_id = notificationType.icon;
    byte color_id = notificationType.color;

    // Calculate length first
    byte actions_count;
    short actions_length;
    String dismiss_string;
    String open_string = "Open on phone";
    String mute_string = "Mute";
    String reply_string = "Reply";
    if (sourceName != null) {
        mute_string += " " + sourceName;
    }

    byte dismiss_action_id;
    if (hasHandle && !"ALARMCLOCKRECEIVER".equals(sourceName)) {
        actions_count = 3;
        dismiss_string = "Dismiss";
        dismiss_action_id = 0x02;
        actions_length = (short) (ACTION_LENGTH_MIN * actions_count + dismiss_string.getBytes().length
                + open_string.getBytes().length + mute_string.getBytes().length);
    } else {
        actions_count = 1;
        dismiss_string = "Dismiss all";
        dismiss_action_id = 0x03;
        actions_length = (short) (ACTION_LENGTH_MIN * actions_count + dismiss_string.getBytes().length);
    }

    int replies_length = -1;
    if (cannedReplies != null && cannedReplies.length > 0) {
        actions_count++;
        for (String reply : cannedReplies) {
            replies_length += reply.getBytes().length + 1;
        }
        actions_length += ACTION_LENGTH_MIN + reply_string.getBytes().length + replies_length + 3; // 3 = attribute id (byte) + length(short)
    }

    byte attributes_count = 2; // icon
    short attributes_length = (short) (11 + actions_length);
    if (parts != null) {
        for (String s : parts) {
            if (s == null || s.equals("")) {
                continue;
            }
            attributes_count++;
            attributes_length += (3 + s.getBytes().length);
        }
    }

    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(GB_UUID_MASK);
    buf.putLong(id);
    buf.putLong(UUID_NOTIFICATIONS.getMostSignificantBits());
    buf.putLong(UUID_NOTIFICATIONS.getLeastSignificantBits());
    buf.order(ByteOrder.LITTLE_ENDIAN);
    buf.putInt(timestamp); // 32-bit timestamp
    buf.putShort((short) 0); // duration
    buf.put((byte) 0x01); // type (0x01 = notification)
    buf.putShort((short) 0x0001); // flags 0x0001 = ?
    buf.put((byte) 0x04); // layout (0x04 = notification?)
    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;
            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 | icon_id);

    buf.put((byte) 28); // background_color
    buf.putShort((short) 1); // length of int
    buf.put(color_id);

    // dismiss action
    buf.put(dismiss_action_id);
    buf.put((byte) 0x02); // generic action, dismiss did not do anything
    buf.put((byte) 0x01); // number attributes
    buf.put((byte) 0x01); // attribute id (title)
    buf.putShort((short) dismiss_string.getBytes().length);
    buf.put(dismiss_string.getBytes());

    // open and mute actions
    if (hasHandle && !"ALARMCLOCKRECEIVER".equals(sourceName)) {
        buf.put((byte) 0x01);
        buf.put((byte) 0x02); // generic action
        buf.put((byte) 0x01); // number attributes
        buf.put((byte) 0x01); // attribute id (title)
        buf.putShort((short) open_string.getBytes().length);
        buf.put(open_string.getBytes());

        buf.put((byte) 0x04);
        buf.put((byte) 0x02); // generic action
        buf.put((byte) 0x01); // number attributes
        buf.put((byte) 0x01); // attribute id (title)
        buf.putShort((short) mute_string.getBytes().length);
        buf.put(mute_string.getBytes());
    }

    if (cannedReplies != null && replies_length > 0) {
        buf.put((byte) 0x05);
        buf.put((byte) 0x03); // reply action
        buf.put((byte) 0x02); // number attributes
        buf.put((byte) 0x01); // title
        buf.putShort((short) reply_string.getBytes().length);
        buf.put(reply_string.getBytes());
        buf.put((byte) 0x08); // canned replies
        buf.putShort((short) replies_length);
        for (int i = 0; i < cannedReplies.length - 1; i++) {
            buf.put(cannedReplies[i].getBytes());
            buf.put((byte) 0x00);
        }
        // last one must not be zero terminated, else we get an additional emply reply
        buf.put(cannedReplies[cannedReplies.length - 1].getBytes());
    }

    return encodeBlobdb(UUID.randomUUID(), BLOBDB_INSERT, BLOBDB_NOTIFICATION, buf.array());
}

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 w w  . j a v  a  2 s.  c o  m*/
        LOG.warn(ENDPOINT_NAME + ": unknown status " + status + " (token " + (token & 0xffff) + ")");
    }
    return null;
}

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

@Override
public byte[] encodeSetTime() {
    final short LENGTH_SETTIME = 5;
    long ts = System.currentTimeMillis();
    long ts_offset = (SimpleTimeZone.getDefault().getOffset(ts));
    ByteBuffer buf;
    if (mFwMajor >= 3) {
        String timezone = SimpleTimeZone.getDefault().getID();
        short length = (short) (LENGTH_SETTIME + timezone.getBytes().length + 3);
        buf = ByteBuffer.allocate(LENGTH_PREFIX + length);
        buf.order(ByteOrder.BIG_ENDIAN);
        buf.putShort(length);//from   w  w  w  .  j av a2  s. c o m
        buf.putShort(ENDPOINT_TIME);
        buf.put(TIME_SETTIME_UTC);
        buf.putInt((int) (ts / 1000));
        buf.putShort((short) (ts_offset / 60000));
        buf.put((byte) timezone.getBytes().length);
        buf.put(timezone.getBytes());
        LOG.info(timezone);
    } else {
        buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_SETTIME);
        buf.order(ByteOrder.BIG_ENDIAN);
        buf.putShort(LENGTH_SETTIME);
        buf.putShort(ENDPOINT_TIME);
        buf.put(TIME_SETTIME);
        buf.putInt((int) ((ts + ts_offset) / 1000));
    }
    return buf.array();
}

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

/**
 * Writes a numeric value./* ww w  .j  ava2 s .  co m*/
 */
private void writeNumericValue(ByteBuffer buffer, Object value) throws IOException {
    Object inValue = value;
    try {
        BigDecimal decVal = toBigDecimal(value);
        inValue = decVal;

        int signum = decVal.signum();
        if (signum < 0) {
            decVal = decVal.negate();
        }

        // write sign byte
        buffer.put((signum < 0) ? NUMERIC_NEGATIVE_BYTE : 0);

        // adjust scale according to this column type (will cause the an
        // ArithmeticException if number has too many decimal places)
        decVal = decVal.setScale(getScale());

        // check precision
        if (decVal.precision() > getPrecision()) {
            throw new IOException(
                    "Numeric value is too big for specified precision " + getPrecision() + ": " + decVal);
        }

        // convert to unscaled BigInteger, big-endian bytes
        byte[] intValBytes = toUnscaledByteArray(decVal, getType().getFixedSize() - 1);
        if (buffer.order() != ByteOrder.BIG_ENDIAN) {
            fixNumericByteOrder(intValBytes);
        }
        buffer.put(intValBytes);
    } catch (ArithmeticException e) {
        throw (IOException) new IOException("Numeric value '" + inValue + "' out of range").initCause(e);
    }
}

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

@Override
public GBDeviceEvent[] decodeResponse(byte[] responseData) {
    ByteBuffer buf = ByteBuffer.wrap(responseData);
    buf.order(ByteOrder.BIG_ENDIAN);
    short length = buf.getShort();
    short endpoint = buf.getShort();
    GBDeviceEvent devEvts[] = null;/* w  ww . ja v a2s  .  co  m*/
    byte pebbleCmd;
    switch (endpoint) {
    case ENDPOINT_MUSICCONTROL:
        pebbleCmd = buf.get();
        GBDeviceEventMusicControl musicCmd = new GBDeviceEventMusicControl();
        switch (pebbleCmd) {
        case MUSICCONTROL_NEXT:
            musicCmd.event = GBDeviceEventMusicControl.Event.NEXT;
            break;
        case MUSICCONTROL_PREVIOUS:
            musicCmd.event = GBDeviceEventMusicControl.Event.PREVIOUS;
            break;
        case MUSICCONTROL_PLAY:
            musicCmd.event = GBDeviceEventMusicControl.Event.PLAY;
            break;
        case MUSICCONTROL_PAUSE:
            musicCmd.event = GBDeviceEventMusicControl.Event.PAUSE;
            break;
        case MUSICCONTROL_PLAYPAUSE:
            musicCmd.event = GBDeviceEventMusicControl.Event.PLAYPAUSE;
            break;
        case MUSICCONTROL_VOLUMEUP:
            musicCmd.event = GBDeviceEventMusicControl.Event.VOLUMEUP;
            break;
        case MUSICCONTROL_VOLUMEDOWN:
            musicCmd.event = GBDeviceEventMusicControl.Event.VOLUMEDOWN;
            break;
        default:
            break;
        }
        devEvts = new GBDeviceEvent[] { musicCmd };
        break;
    case ENDPOINT_PHONECONTROL:
        pebbleCmd = buf.get();
        GBDeviceEventCallControl callCmd = new GBDeviceEventCallControl();
        switch (pebbleCmd) {
        case PHONECONTROL_HANGUP:
            callCmd.event = GBDeviceEventCallControl.Event.END;
            break;
        default:
            LOG.info("Unknown PHONECONTROL event" + pebbleCmd);
            break;
        }
        devEvts = new GBDeviceEvent[] { callCmd };
        break;
    case ENDPOINT_FIRMWAREVERSION:
        pebbleCmd = buf.get();
        GBDeviceEventVersionInfo versionCmd = new GBDeviceEventVersionInfo();

        buf.getInt(); // skip
        versionCmd.fwVersion = getFixedString(buf, 32);

        mFwMajor = versionCmd.fwVersion.charAt(1) - 48;
        LOG.info("Pebble firmware major detected as " + mFwMajor);

        byte[] tmp = new byte[9];
        buf.get(tmp, 0, 9);
        int hwRev = buf.get() + 8;
        if (hwRev >= 0 && hwRev < hwRevisions.length) {
            versionCmd.hwVersion = hwRevisions[hwRev];
        }
        devEvts = new GBDeviceEvent[] { versionCmd };
        break;
    case ENDPOINT_APPMANAGER:
        pebbleCmd = buf.get();
        switch (pebbleCmd) {
        case APPMANAGER_GETAPPBANKSTATUS:
            GBDeviceEventAppInfo appInfoCmd = new GBDeviceEventAppInfo();
            int slotCount = buf.getInt();
            int slotsUsed = buf.getInt();
            appInfoCmd.apps = new GBDeviceApp[slotsUsed];
            boolean[] slotInUse = new boolean[slotCount];

            for (int i = 0; i < slotsUsed; i++) {
                int id = buf.getInt();
                int index = buf.getInt();
                slotInUse[index] = true;
                String appName = getFixedString(buf, 32);
                String appCreator = getFixedString(buf, 32);

                int flags = buf.getInt();

                GBDeviceApp.Type appType;
                if ((flags & 16) == 16) { // FIXME: verify this assumption
                    appType = GBDeviceApp.Type.APP_ACTIVITYTRACKER;
                } else if ((flags & 1) == 1) { // FIXME: verify this assumption
                    appType = GBDeviceApp.Type.WATCHFACE;
                } else {
                    appType = GBDeviceApp.Type.APP_GENERIC;
                }
                Short appVersion = buf.getShort();
                appInfoCmd.apps[i] = new GBDeviceApp(tmpUUIDS.get(i), appName, appCreator,
                        appVersion.toString(), appType);
            }
            for (int i = 0; i < slotCount; i++) {
                if (!slotInUse[i]) {
                    appInfoCmd.freeSlot = (byte) i;
                    LOG.info("found free slot " + i);
                    break;
                }
            }
            devEvts = new GBDeviceEvent[] { appInfoCmd };
            break;
        case APPMANAGER_GETUUIDS:
            GBDeviceEventSendBytes sendBytes = new GBDeviceEventSendBytes();
            sendBytes.encodedBytes = encodeSimpleMessage(ENDPOINT_APPMANAGER, APPMANAGER_GETAPPBANKSTATUS);
            devEvts = new GBDeviceEvent[] { sendBytes };
            tmpUUIDS.clear();
            slotsUsed = buf.getInt();
            for (int i = 0; i < slotsUsed; i++) {
                UUID uuid = getUUID(buf);
                LOG.info("found uuid: " + uuid);
                tmpUUIDS.add(uuid);
            }
            break;
        case APPMANAGER_REMOVEAPP:
            GBDeviceEventAppManagement deleteRes = new GBDeviceEventAppManagement();
            deleteRes.type = GBDeviceEventAppManagement.EventType.DELETE;

            int result = buf.getInt();
            switch (result) {
            case APPMANAGER_RES_SUCCESS:
                deleteRes.event = GBDeviceEventAppManagement.Event.SUCCESS;
                break;
            default:
                deleteRes.event = GBDeviceEventAppManagement.Event.FAILURE;
                break;
            }
            devEvts = new GBDeviceEvent[] { deleteRes };
            break;
        default:
            LOG.info("Unknown APPMANAGER event" + pebbleCmd);
            break;
        }
        break;
    case ENDPOINT_PUTBYTES:
        pebbleCmd = buf.get();
        GBDeviceEventAppManagement installRes = new GBDeviceEventAppManagement();
        installRes.type = GBDeviceEventAppManagement.EventType.INSTALL;
        switch (pebbleCmd) {
        case PUTBYTES_INIT:
            installRes.token = buf.getInt();
            installRes.event = GBDeviceEventAppManagement.Event.SUCCESS;
            break;
        default:
            installRes.token = buf.getInt();
            installRes.event = GBDeviceEventAppManagement.Event.FAILURE;
            break;
        }
        devEvts = new GBDeviceEvent[] { installRes };
        break;
    case ENDPOINT_APPLICATIONMESSAGE:
    case ENDPOINT_LAUNCHER:
        pebbleCmd = buf.get();
        last_id = buf.get();
        UUID uuid = getUUID(buf);

        switch (pebbleCmd) {
        case APPLICATIONMESSAGE_PUSH:
            LOG.info((endpoint == ENDPOINT_LAUNCHER ? "got LAUNCHER PUSH from UUID : "
                    : "got APPLICATIONMESSAGE PUSH from UUID : ") + uuid);
            AppMessageHandler handler = mAppMessageHandlers.get(uuid);
            if (handler != null) {
                if (handler.isEnabled()) {
                    if (endpoint == ENDPOINT_APPLICATIONMESSAGE) {
                        ArrayList<Pair<Integer, Object>> dict = decodeDict(buf);
                        devEvts = handler.handleMessage(dict);
                    } else {
                        currentRunningApp = uuid;
                        devEvts = handler.onAppStart();
                    }
                } else {
                    devEvts = new GBDeviceEvent[] { null };
                }
            } else {
                try {
                    if (endpoint == ENDPOINT_APPLICATIONMESSAGE) {
                        devEvts = decodeDictToJSONAppMessage(uuid, buf);
                    } else {
                        currentRunningApp = uuid;
                        GBDeviceEventAppManagement gbDeviceEventAppManagement = new GBDeviceEventAppManagement();
                        gbDeviceEventAppManagement.uuid = uuid;
                        gbDeviceEventAppManagement.type = GBDeviceEventAppManagement.EventType.START;
                        gbDeviceEventAppManagement.event = GBDeviceEventAppManagement.Event.SUCCESS;
                        devEvts = new GBDeviceEvent[] { gbDeviceEventAppManagement };
                    }
                } catch (JSONException e) {
                    LOG.error(e.getMessage());
                    return null;
                }
            }
            break;
        case APPLICATIONMESSAGE_ACK:
            LOG.info("got APPLICATIONMESSAGE/LAUNCHER (EP " + endpoint + ")  ACK");
            devEvts = new GBDeviceEvent[] { null };
            break;
        case APPLICATIONMESSAGE_NACK:
            LOG.info("got APPLICATIONMESSAGE/LAUNCHER (EP " + endpoint + ")  NACK");
            devEvts = new GBDeviceEvent[] { null };
            break;
        case APPLICATIONMESSAGE_REQUEST:
            LOG.info("got APPLICATIONMESSAGE/LAUNCHER (EP " + endpoint + ")  REQUEST");
            devEvts = new GBDeviceEvent[] { null };
            break;
        default:
            break;
        }
        break;
    case ENDPOINT_PHONEVERSION:
        pebbleCmd = buf.get();
        switch (pebbleCmd) {
        case PHONEVERSION_REQUEST:
            LOG.info("Pebble asked for Phone/App Version - repLYING!");
            GBDeviceEventSendBytes sendBytes = new GBDeviceEventSendBytes();
            sendBytes.encodedBytes = encodePhoneVersion(PHONEVERSION_REMOTE_OS_ANDROID);
            devEvts = new GBDeviceEvent[] { sendBytes };
            break;
        default:
            break;
        }
        break;
    case ENDPOINT_DATALOG:
        devEvts = decodeDatalog(buf, length);
        break;
    case ENDPOINT_SCREENSHOT:
        devEvts = new GBDeviceEvent[] { decodeScreenshot(buf, length) };
        break;
    case ENDPOINT_EXTENSIBLENOTIFS:
    case ENDPOINT_NOTIFICATIONACTION:
        devEvts = decodeAction(buf);
        break;
    case ENDPOINT_PING:
        devEvts = new GBDeviceEvent[] { decodePing(buf) };
        break;
    case ENDPOINT_APPFETCH:
        devEvts = new GBDeviceEvent[] { decodeAppFetch(buf) };
        break;
    case ENDPOINT_SYSTEMMESSAGE:
        devEvts = new GBDeviceEvent[] { decodeSystemMessage(buf) };
        break;
    case ENDPOINT_APPRUNSTATE:
        devEvts = decodeAppRunState(buf);
        break;
    case ENDPOINT_BLOBDB:
        devEvts = new GBDeviceEvent[] { decodeBlobDb(buf) };
        break;
    case ENDPOINT_APPREORDER:
        devEvts = new GBDeviceEvent[] { decodeAppReorder(buf) };
        break;
    case ENDPOINT_APPLOGS:
        decodeAppLogs(buf);
        break;
    //            case ENDPOINT_VOICECONTROL:
    //                devEvts = new GBDeviceEvent[]{decodeVoiceControl(buf)};
    //            case ENDPOINT_AUDIOSTREAM:
    //                LOG.debug(GB.hexdump(responseData, 0, responseData.length));
    //                break;
    default:
        break;
    }

    return devEvts;
}

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

/**
 * Serialize an Object into a raw byte value for this column
 * @param obj Object to serialize// www .ja v a2s.  c  om
 * @param order Order in which to serialize
 * @return A buffer containing the bytes
 * @usage _advanced_method_
 */
public ByteBuffer write(Object obj, int remainingRowLength, ByteOrder order) throws IOException {
    if (isRawData(obj)) {
        // just slap it right in (not for the faint of heart!)
        return ByteBuffer.wrap(((RawData) obj).getBytes());
    }

    if (!isVariableLength() || !getType().isVariableLength()) {
        return writeFixedLengthField(obj, order);
    }

    // var length column
    if (!getType().isLongValue()) {

        // this is an "inline" var length field
        switch (getType()) {
        case NUMERIC:
            // don't ask me why numerics are "var length" columns...
            ByteBuffer buffer = getPageChannel().createBuffer(getType().getFixedSize(), order);
            writeNumericValue(buffer, obj);
            buffer.flip();
            return buffer;

        case TEXT:
            byte[] encodedData = encodeTextValue(obj, 0, getLengthInUnits(), false).array();
            obj = encodedData;
            break;

        case BINARY:
        case UNKNOWN_0D:
        case UNSUPPORTED_VARLEN:
            // should already be "encoded"
            break;
        default:
            throw new RuntimeException("unexpected inline var length type: " + getType());
        }

        ByteBuffer buffer = ByteBuffer.wrap(toByteArray(obj));
        buffer.order(order);
        return buffer;
    }

    // var length, long value column
    switch (getType()) {
    case OLE:
        // should already be "encoded"
        break;
    case MEMO:
        int maxMemoChars = DataType.MEMO.toUnitSize(DataType.MEMO.getMaxSize());
        obj = encodeTextValue(obj, 0, maxMemoChars, false).array();
        break;
    default:
        throw new RuntimeException("unexpected var length, long value type: " + getType());
    }

    // create long value buffer
    return writeLongValue(toByteArray(obj), remainingRowLength);
}