Example usage for java.nio ByteBuffer putShort

List of usage examples for java.nio ByteBuffer putShort

Introduction

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

Prototype

public abstract ByteBuffer putShort(short value);

Source Link

Document

Writes the given short to the current position and increases the position by 2.

Usage

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);
        buf.putShort(ENDPOINT_TIME);/*from  ww  w.  j  a va2  s  .  c om*/
        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:nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.PebbleProtocol.java

byte[] encodeInstallMetadata(UUID uuid, String appName, short appVersion, short sdkVersion, int flags,
        int iconId) {
    final short METADATA_LENGTH = 126;

    byte[] name_buf = new byte[96];
    System.arraycopy(appName.getBytes(), 0, name_buf, 0, appName.getBytes().length);
    ByteBuffer buf = ByteBuffer.allocate(METADATA_LENGTH);

    buf.order(ByteOrder.BIG_ENDIAN);
    buf.putLong(uuid.getMostSignificantBits()); // watchapp uuid
    buf.putLong(uuid.getLeastSignificantBits());
    buf.order(ByteOrder.LITTLE_ENDIAN);
    buf.putInt(flags);//from   w  ww . j a  v  a2  s.c  o m
    buf.putInt(iconId);
    buf.putShort(appVersion);
    buf.putShort(sdkVersion);
    buf.put((byte) 0); // app_face_bgcolor
    buf.put((byte) 0); // app_face_template_id
    buf.put(name_buf); // 96 bytes

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

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

private byte[] encodeTimelinePin(UUID uuid, int timestamp, short duration, int icon_id, String title,
        String subtitle) {/*from w  w w  .ja  va 2  s.  com*/
    final short TIMELINE_PIN_LENGTH = 46;

    icon_id |= 0x80000000;
    byte attributes_count = 2;
    byte actions_count = 0;

    int attributes_length = 10 + title.getBytes().length;
    if (subtitle != null && !subtitle.isEmpty()) {
        attributes_length += 3 + subtitle.getBytes().length;
        attributes_count += 1;
    }

    int pin_length = TIMELINE_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(0); // parent
    buf.putLong(0);
    buf.order(ByteOrder.LITTLE_ENDIAN);
    buf.putInt(timestamp); // 32-bit timestamp
    buf.putShort(duration);
    buf.put((byte) 0x02); // type (0x02 = pin)
    buf.putShort((short) 0x0001); // flags 0x0001 = ?
    buf.put((byte) 0x01); // layout was (0x02 = pin?), 0x01 needed for subtitle but seems to do no harm if there isn't one

    buf.putShort((short) attributes_length); // total length of all attributes and actions in bytes
    buf.put(attributes_count);
    buf.put(actions_count);

    buf.put((byte) 4); // icon
    buf.putShort((short) 4); // length of int
    buf.putInt(icon_id);
    buf.put((byte) 1); // title
    buf.putShort((short) title.getBytes().length);
    buf.put(title.getBytes());
    if (subtitle != null && !subtitle.isEmpty()) {
        buf.put((byte) 2); //subtitle
        buf.putShort((short) subtitle.getBytes().length);
        buf.put(subtitle.getBytes());
    }

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

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

@Override
public byte[] encodeSetCannedMessages(CannedMessagesSpec cannedMessagesSpec) {

    if (cannedMessagesSpec.cannedMessages == null || cannedMessagesSpec.cannedMessages.length == 0) {
        return null;
    }//from  w  w w .  j av  a 2 s.  c  om

    String blobDBKey;
    switch (cannedMessagesSpec.type) {
    case CannedMessagesSpec.TYPE_MISSEDCALLS:
        blobDBKey = "com.pebble.android.phone";
        break;
    case CannedMessagesSpec.TYPE_NEWSMS:
        blobDBKey = "com.pebble.sendText";
        break;
    default:
        return null;
    }

    int replies_length = -1;

    for (String reply : cannedMessagesSpec.cannedMessages) {
        replies_length += reply.getBytes().length + 1;
    }

    ByteBuffer buf = ByteBuffer.allocate(12 + replies_length);
    buf.order(ByteOrder.LITTLE_ENDIAN);
    buf.putInt(0x00000000); // unknown
    buf.put((byte) 0x00); // attributes count?
    buf.put((byte) 0x01); // actions count?

    // action
    buf.put((byte) 0x00); // action id
    buf.put((byte) 0x03); // action type = reply
    buf.put((byte) 0x01); // attributes count
    buf.put((byte) 0x08); // canned messages
    buf.putShort((short) replies_length);
    for (int i = 0; i < cannedMessagesSpec.cannedMessages.length - 1; i++) {
        buf.put(cannedMessagesSpec.cannedMessages[i].getBytes());
        buf.put((byte) 0x00);
    }
    // last one must not be zero terminated, else we get an additional empty reply
    buf.put(cannedMessagesSpec.cannedMessages[cannedMessagesSpec.cannedMessages.length - 1].getBytes());

    return encodeBlobdb(blobDBKey, BLOBDB_INSERT, BLOBDB_CANNED_MESSAGES, buf.array());
}

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

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

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

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

    byte attributes_count = 3;
    short attributes_length = (short) (21 + actions_length);
    if (parts != null) {
        for (String s : parts) {
            if (s == null || s.equals("")) {
                continue;
            }//  w  ww.j a  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:com.skratchdot.electribe.model.esx.impl.SampleImpl.java

/**
 * <!-- begin-user-doc -->/*  www . ja  v  a  2 s.  com*/
 * @return Returns a byte array that combines/mixes channel1 and channel2
 * <!-- end-user-doc -->
 * @generated NOT
 */
public byte[] getAudioDataChannelBoth() {
    if (this.isEmpty()) {
        return new byte[0];
    }
    ByteBuffer bufferChannel1 = ByteBuffer.wrap(this.getAudioDataChannel1());
    ByteBuffer bufferChannel2 = ByteBuffer.wrap(this.getAudioDataChannel2());
    ByteBuffer bufferChannelBoth = ByteBuffer.allocate(bufferChannel1.capacity());
    int dataChannel1;
    int dataChannel2;
    short dataChannelBoth;
    for (int j = 0; j < this.getNumberOfSampleFrames(); j++) {
        dataChannel1 = bufferChannel1.getShort();
        dataChannel2 = bufferChannel2.getShort();
        dataChannelBoth = (short) ((dataChannel1 + dataChannel2) / 2);
        bufferChannelBoth.putShort(dataChannelBoth);
    }
    return bufferChannelBoth.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;
    }//  w w  w.  j  av 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:com.inclouds.hbase.rowcache.RowCache.java

/**
 * CHECKED 2 Prepare key for Get op./*from  w  w  w .  ja  v a 2s.com*/
 * 
 * @param buf
 *          the buf
 * @param tableName
 *          the table name
 * @param row
 *          the row
 * @param offset
 *          the offset
 * @param size
 *          the size
 * @param columnFamily
 *          the column family
 * @param column
 *          the column
 */
private void prepareKeyForGet(ByteBuffer buf, byte[] tableName, byte[] row, int offset, int size,
        byte[] columnFamily, byte[] column) {

    buf.clear();
    int totalSize = 2 + tableName.length + // table
            2 + size + // row
            ((columnFamily != null) ? (2 + columnFamily.length) : 0) + // family
            ((column != null) ? (4 + column.length) : 0); // column
    buf.putInt(totalSize);
    // 4 bytes to keep key length;
    buf.putShort((short) tableName.length);
    buf.put(tableName);
    buf.putShort((short) size);
    buf.put(row, offset, size);
    if (columnFamily != null) {
        buf.putShort((short) columnFamily.length);
        buf.put(columnFamily);
    }
    if (column != null) {
        buf.putInt(column.length);
        buf.put(column);
    }
    // prepare for read
    // buf.flip();

}

From source file:com.inclouds.hbase.rowcache.RowCache.java

/**
 * CHECKED 2 Prepare key for Get op./*from www. j a v  a 2  s . c o  m*/
 * 
 * @param buf
 *          the buf
 * @param tableName
 *          the table name
 * @param row
 *          the row
 * @param offset
 *          the offset
 * @param size
 *          the size
 * @param columnFamily
 *          the column family
 * @param column
 *          the column
 */
private void prepareKeyForPut(ByteBuffer buf, byte[] tableName, byte[] row, int offset, int size,
        byte[] columnFamily, byte[] column) {

    buf.clear();
    int totalSize = 2 + tableName.length + // table
            2 + size + // row
            ((columnFamily != null) ? (2 + columnFamily.length) : 0) + // family
            ((column != null) ? (4 + column.length) : 0); // column
    buf.putInt(totalSize);
    // 4 bytes to keep key length;
    // skip 4 bytyes for Value length
    buf.position(8);
    buf.putShort((short) tableName.length);
    buf.put(tableName);
    buf.putShort((short) size);
    buf.put(row, offset, size);
    if (columnFamily != null) {
        buf.putShort((short) columnFamily.length);
        buf.put(columnFamily);
    }
    if (column != null) {
        buf.putInt(column.length);
        buf.put(column);
    }
    // prepare for read
    // buf.flip();

}

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

public void replaceValues(Map<Integer, Integer> translation) {

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

    Integer minv = null;/*from   ww  w.jav a  2 s  . com*/
    Integer maxv = null;
    for (Integer i : translation.values()) {
        if (minv == null || i < minv)
            minv = i;
        if (maxv == null || i > maxv)
            maxv = i;
    }

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

    try { //read of random access file can throw an exception
        out = new RandomAccessFile(newGrid, "rw");

        if (!f2.exists()) {
            afile = new RandomAccessFile(filename + ".gri", "r");
        } else {
            afile = new RandomAccessFile(filename + ".GRI", "r");
        }

        byte[] b = new byte[65536];
        byte[] bout = new byte[65536];

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

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

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

            if (datatype.equalsIgnoreCase("UBYTE")) {
                throw new Exception("UBYTE translation not supported");
            } else if (datatype.equalsIgnoreCase("BYTE")) {
                throw new Exception("BYTE translation not supported");
            } else if (datatype.equalsIgnoreCase("SHORT")) {
                max += len / 2;
                max = Math.min(max, length);
                for (; i < max; i++) {
                    v = bb.getShort();
                    if (v != ndv && translation.get((int) (v * rescale)) == null) {
                        v = v;
                    }
                    if (v != ndv && translation.get((int) (v * rescale)) != null)
                        v = translation.get((int) (v * rescale));
                    bbout.putShort((short) v);
                }
            } else if (datatype.equalsIgnoreCase("INT")) {
                max += len / 4;
                max = Math.min(max, length);
                for (; i < max; i++) {
                    v = bb.getInt();
                    if (v != ndv && translation.get((int) (v * rescale)) != null)
                        v = translation.get((int) (v * rescale));
                    bbout.putInt((int) v);
                }
            } else if (datatype.equalsIgnoreCase("LONG")) {
                max += len / 8;
                max = Math.min(max, length);
                for (; i < max; i++) {
                    v = bb.getLong();
                    if (v != ndv && translation.get((int) (v * rescale)) != null)
                        v = translation.get((int) (v * rescale));
                    bbout.putLong((long) v);
                }
            } else if (datatype.equalsIgnoreCase("FLOAT")) {
                throw new Exception("FLOAT translation not supported");
            } else if (datatype.equalsIgnoreCase("DOUBLE")) {
                throw new Exception("DOUBLE translation not supported");
            } else {
                max += len / 4;
                for (; i < max; i++) {
                    // should not happen; catch anyway...
                }
            }

            out.write(bout, 0, (int) len);
        }

        writeHeader(filename + ".new", xmin, ymin, xmin + xres * ncols, ymin + yres * nrows, xres, yres, nrows,
                ncols, minv, maxv, datatype, nodatavalue + "");
    } catch (Exception e) {
        logger.error("An error has occurred getting grid class stats", e);
    } finally {
        if (afile != null) {
            try {
                afile.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }

        if (out != null) {
            try {
                out.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }

    try {
        if (!new File(filename + ".gri.old").exists())
            FileUtils.moveFile(new File(filename + ".gri"), new File(filename + ".gri.old"));
        if (!new File(filename + ".grd.old").exists())
            FileUtils.moveFile(new File(filename + ".grd"), new File(filename + ".grd.old"));

        FileUtils.moveFile(new File(filename + ".gri.new"), new File(filename + ".gri"));
        FileUtils.moveFile(new File(filename + ".new.grd"), new File(filename + ".grd"));
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}