Example usage for java.nio ByteBuffer putInt

List of usage examples for java.nio ByteBuffer putInt

Introduction

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

Prototype

public abstract ByteBuffer putInt(int value);

Source Link

Document

Writes the given int to the current position and increases the position by 4.

Usage

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

/**
 * CHECKED 2 Prepare key for Get op./*from www.j  ava 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 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.// w ww  .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:nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.PebbleProtocol.java

private byte[] encodeActionResponse(UUID uuid, int iconId, String caption) {
    short length = (short) (29 + caption.getBytes().length);
    ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + length);
    buf.order(ByteOrder.BIG_ENDIAN);
    buf.putShort(length);/*from  w  ww  . j ava 2s .c om*/
    buf.putShort(ENDPOINT_NOTIFICATIONACTION);
    buf.put(NOTIFICATIONACTION_RESPONSE);
    buf.putLong(uuid.getMostSignificantBits());
    buf.putLong(uuid.getLeastSignificantBits());
    buf.order(ByteOrder.LITTLE_ENDIAN);
    buf.put(NOTIFICATIONACTION_ACK);
    buf.put((byte) 2); //nr of attributes
    buf.put((byte) 6); // icon
    buf.putShort((short) 4); // length
    buf.putInt(0x80000000 | iconId);
    buf.put((byte) 2); // title
    buf.putShort((short) caption.getBytes().length);
    buf.put(caption.getBytes());
    return buf.array();
}

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;/*  w  w w.  j a  va2 s.  co  m*/
        } 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 byte[] encodeWeatherForecast(WeatherSpec weatherSpec) {
    final short WEATHER_FORECAST_LENGTH = 20;

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

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

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

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

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

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

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

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

@Override
public byte[] encodeSetMusicInfo(String artist, String album, String track, int duration, int trackCount,
        int trackNr) {
    String[] parts = { artist, album, track };
    if (duration == 0 || mFwMajor < 3) {
        return encodeMessage(ENDPOINT_MUSICCONTROL, MUSICCONTROL_SETMUSICINFO, 0, parts);
    } else {/*  w  w  w  .  ja va 2 s.  com*/
        // Calculate length first
        int length = LENGTH_PREFIX + 9;
        if (parts != null) {
            for (String s : parts) {
                if (s == null || s.equals("")) {
                    length++; // encode null or empty strings as 0x00 later
                    continue;
                }
                length += (1 + s.getBytes().length);
            }
        }

        // Encode Prefix
        ByteBuffer buf = ByteBuffer.allocate(length);
        buf.order(ByteOrder.BIG_ENDIAN);
        buf.putShort((short) (length - LENGTH_PREFIX));
        buf.putShort(ENDPOINT_MUSICCONTROL);
        buf.put(MUSICCONTROL_SETMUSICINFO);

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

            int partlength = s.getBytes().length;
            if (partlength > 255)
                partlength = 255;
            buf.put((byte) partlength);
            buf.put(s.getBytes(), 0, partlength);
        }

        buf.order(ByteOrder.LITTLE_ENDIAN);
        buf.putInt(duration * 1000);
        buf.putShort((short) (trackCount & 0xffff));
        buf.putShort((short) (trackNr & 0xffff));

        return buf.array();
    }
}

From source file:edu.umass.cs.gigapaxos.paxospackets.RequestPacket.java

/**
 * The weird constant above is to try to avoid mistakes in the painful (but
 * totally worth it) byte'ification method below. Using bytes as opposed to
 * json strings makes a non-trivial difference (~2x over json-smart and >4x
 * over org.json. So we just chuck json libraries and use our own byte[]
 * serializer for select packets.//from www  . j av a  2  s . c o  m
 * 
 * The serialization overhead really matters most for RequestPacket and
 * AcceptPacket. Every request, even with batching, must be deserialized by
 * the coordinator and must be serialized back while sending out the
 * AcceptPacket. The critical path is the following at a coordinator and is
 * incurred at least in part even with batching for every request: (1)
 * receive request, (2) send accept, (3) receive accept_replies, (4) send
 * commit Accordingly, we use byteification for {@link RequestPacket},
 * {@link AcceptPacket}, {@link BatchedAcceptReply} and
 * {@link BatchedCommit}.
 * 
 * */

protected byte[] toBytes(boolean instrument) {
    // return cached value if already present
    if ((this.getType() == PaxosPacketType.REQUEST || this.getType() == PaxosPacketType.ACCEPT)
            && this.byteifiedSelf != null && !instrument)
        return this.byteifiedSelf;
    // check if we can use byteification at all; if not, use toString()
    if (!((BYTEIFICATION && IntegerMap.allInt()) || instrument)) {
        try {
            if (this.getType() == PaxosPacketType.REQUEST || this.getType() == PaxosPacketType.ACCEPT)
                return this.byteifiedSelf = this.toString().getBytes(CHARSET); // cache
            return this.toString().getBytes(CHARSET);
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
            return null;
        }
    }

    // else byteify
    try {
        int exactLength = 0;
        byte[] array = new byte[this.lengthEstimate()];
        ByteBuffer bbuf = ByteBuffer.wrap(array);
        assert (bbuf.position() == 0);

        // paxospacket stuff
        super.toBytes(bbuf);
        int ppPos = bbuf.position(); // for assertion
        assert (bbuf.position() == ByteBuffer.wrap(array, SIZEOF_PAXOSPACKET_FIXED - 1, 1).get()
                + SIZEOF_PAXOSPACKET_FIXED) : bbuf.position() + " != "
                        + ByteBuffer.wrap(array, SIZEOF_PAXOSPACKET_FIXED - 1, 1).get()
                        + SIZEOF_PAXOSPACKET_FIXED;
        exactLength += (bbuf.position());

        bbuf.putLong(this.requestID);
        bbuf.put(this.stop ? (byte) 1 : (byte) 0);
        exactLength += (Long.BYTES + 1);

        // addresses
        /* Note: 0 is ambiguous with wildcard address, but that's okay
         * because an incoming packet will never come with a wildcard
         * address. */
        bbuf.put(this.clientAddress != null ? this.clientAddress.getAddress().getAddress() : new byte[4]);
        // 0 (not -1) means invalid port
        bbuf.putShort(this.clientAddress != null ? (short) this.clientAddress.getPort() : 0);
        /* Note: 0 is an ambiguous wildcard address that could also be a
         * legitimate value of the listening socket address. If the request
         * happens to have no listening address, we will end up assuming it
         * was received on the wildcard address. At worst, the matching for
         * the corresponding response back to the client can fail. */
        bbuf.put(this.listenAddress != null ? this.listenAddress.getAddress().getAddress() : new byte[4]);
        // 0 (not -1) means invalid port
        bbuf.putShort(this.listenAddress != null ? (short) this.listenAddress.getPort() : 0);
        exactLength += 2 * (Integer.BYTES + Short.BYTES);

        // other non-final fields
        bbuf.putInt(this.entryReplica);
        bbuf.putLong(this.entryTime);
        bbuf.put(this.shouldReturnRequestValue ? (byte) 1 : (byte) 0);
        bbuf.putInt(this.forwardCount);
        exactLength += (Integer.BYTES + Long.BYTES + 1 + Integer.BYTES);

        // digest related fields: broadcasted, digest
        // whether this request was already broadcasted
        bbuf.put(this.broadcasted ? (byte) 1 : (byte) 0);
        exactLength += 1;
        assert (exactLength ==
        // where parent left us off
        ppPos + SIZEOF_REQUEST_FIXED
        // for the three int fields not yet filled
                - 4 * Integer.BYTES) : exactLength + " != [" + ppPos + " + " + SIZEOF_REQUEST_FIXED + " - "
                        + 4 * Integer.BYTES + "]";
        // digest length and digest iteself
        bbuf.putInt(this.digest != null ? this.digest.length : 0);
        exactLength += Integer.BYTES;
        if (this.digest != null)
            bbuf.put(this.digest);
        exactLength += (this.digest != null ? this.digest.length : 0);
        // /////////// end of digest related fields //////////

        // highly variable length fields
        // requestValue
        byte[] reqValBytes = this.requestValue != null ? this.requestValue.getBytes(CHARSET) : new byte[0];
        bbuf.putInt(reqValBytes != null ? reqValBytes.length : 0);
        bbuf.put(reqValBytes);
        exactLength += (4 + reqValBytes.length);

        // responseValue
        byte[] respValBytes = this.responseValue != null ? this.responseValue.getBytes(CHARSET) : new byte[0];
        bbuf.putInt(respValBytes != null ? respValBytes.length : 0);
        bbuf.put(respValBytes);
        exactLength += (4 + respValBytes.length);

        // batched requests batchSize|(length:batchedReqBytes)+
        bbuf.putInt(this.batchSize());
        exactLength += (4);
        if (this.batchSize() > 0)
            for (RequestPacket req : this.batched) {
                byte[] element = req.toBytes();
                bbuf.putInt(element.length);
                bbuf.put(element);
                exactLength += (4 + element.length);
            }

        // bbuf.array() was a generous allocation
        byte[] exactBytes = new byte[exactLength];
        bbuf.flip();
        assert (bbuf.remaining() == exactLength) : bbuf.remaining() + " != " + exactLength;
        bbuf.get(exactBytes);

        if (this.getType() == PaxosPacketType.REQUEST)
            this.byteifiedSelf = exactBytes;

        return exactBytes;

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:edu.umass.cs.gigapaxos.SQLPaxosLogger.java

private static void compactLogfile(File file, PaxosPacketizer packetizer, MessageLogDiskMap msgLog,
        FileIDMap fidMap) throws IOException, JSONException {
    RandomAccessFile raf = null, rafTmp = null;
    File tmpFile = new File(file.toString() + TMP_FILE_SUFFIX);
    int tmpFileSize = 0;
    boolean compacted = false, neededAtAll = false;
    HashMap<String, ArrayList<LogIndexEntry>> logIndexEntries = new HashMap<String, ArrayList<LogIndexEntry>>();

    // quick delete
    if (fidMap.isRemovable(file.toString(), msgLog)) {
        deleteFile(file, msgLog);/*from ww  w . j  a v  a  2s. co m*/
        log.log(Level.INFO, "{0} quick-garbage-collected file {1}", new Object[] { msgLog.disk, file });
        return;
    } else
        log.log(Level.FINE, "{0} not quick-GCing file {1} because dependent paxosIDs = {2}",
                new Object[] { msgLog.disk, file, fidMap.fidMap.get(file.toString()) });

    if (System.currentTimeMillis() - file.lastModified() < LOGFILE_AGE_THRESHOLD * 1000)
        return;

    try {
        long t = System.currentTimeMillis();
        raf = new RandomAccessFile(file.toString(), "r");
        rafTmp = new RandomAccessFile(tmpFile.toString(), "rw");
        while (raf.getFilePointer() < raf.length()) {
            long offset = rafTmp.getFilePointer();
            int length = raf.readInt();
            byte[] msg = new byte[length];
            raf.readFully(msg);
            PaxosPacket pp = packetizer != null ? packetizer.stringToPaxosPacket(msg
            // new String(msg, CHARSET)
            ) : PaxosPacket.getPaxosPacket(new String(msg, CHARSET));
            if (!logIndexEntries.containsKey(pp.getPaxosID()))
                logIndexEntries.put(pp.getPaxosID(), new ArrayList<LogIndexEntry>());
            logIndexEntries.get(pp.getPaxosID()).add(new LogIndexEntry(getSlot(pp), getBallot(pp).ballotNumber,
                    getBallot(pp).coordinatorID, pp.getType().getInt(), file.toString(), offset, length));

            if (isLogMsgNeeded(pp, msgLog)) {
                ByteBuffer bbuf = ByteBuffer.allocate(length + 4);
                bbuf.putInt(length);
                bbuf.put(msg);
                rafTmp.write(bbuf.array());
                neededAtAll = true;
                tmpFileSize += bbuf.capacity();
            } else {
                compacted = true;
                log.log(Level.FINE, "From logfile {0} garbage collecting {1}",
                        new Object[] { file, pp.getSummary() });
            }
        }
        DelayProfiler.updateDelay("compact", t);
    } finally {
        if (raf != null)
            raf.close();
        if (rafTmp != null) {
            rafTmp.getChannel().force(true);
            rafTmp.close();
        }
    }
    assert (tmpFile.exists() && tmpFile.length() == tmpFileSize) : tmpFile.length() + " != " + tmpFileSize;
    if (compacted && neededAtAll)
        synchronized (msgLog) {
            modifyLogfileAndLogIndex(file, tmpFile, logIndexEntries, msgLog, fidMap);
            log.log(Level.INFO, "{0} compacted logfile {1}", new Object[] { msgLog, file });
        }
    else if (!neededAtAll) {
        log.log(Level.INFO, "Deleting logfile {0} as its log entries are no longer needed",
                new Object[] { file });
        deleteFile(file, msgLog);
    } else
        // !compacted
        log.log(Level.INFO, "Logfile {0} unchanged upon compaction attempt", new Object[] { file });
    assert (tmpFile.toString().endsWith(TMP_FILE_SUFFIX));
    if (tmpFile.exists())
        deleteFile(tmpFile, msgLog);
}

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;// w  w  w  .  j a v  a  2  s.c o m
    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);
    }
}

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

public void mergeMissingValues(Grid sourceOfMissingValues, boolean hideMissing) {
    float[] cells = sourceOfMissingValues.getGrid();

    float[] actual = getGrid();

    int length = actual.length;

    int i;/*from  w  w w .  ja va 2 s  . c o  m*/
    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", "rw");
        } else {
            afile = new RandomAccessFile(filename + ".GRI", "rw");
        }

        byte[] b = new byte[(int) afile.length()];

        ByteBuffer bb = ByteBuffer.wrap(b);

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

        afile.seek(0);

        if (datatype.equalsIgnoreCase("UBYTE")) {
            for (i = 0; i < length; i++) {
                if (hideMissing == Float.isNaN(cells[i])) {
                    if (nodatavalue >= 128) {
                        bb.put((byte) (nodatavalue - 256));
                    } else {
                        bb.put((byte) nodatavalue);
                    }
                } else {
                    if (actual[i] >= 128) {
                        bb.put((byte) (actual[i] - 256));
                    } else {
                        bb.put((byte) actual[i]);
                    }
                }
            }
        } else if (datatype.equalsIgnoreCase("BYTE")) {
            for (i = 0; i < length; i++) {
                bb.put((byte) actual[i]);
            }
        } else if (datatype.equalsIgnoreCase("SHORT")) {
            for (i = 0; i < length; i++) {
                if (hideMissing == Float.isNaN(cells[i])) {
                    bb.putShort((short) nodatavalue);
                } else {
                    bb.putShort((short) actual[i]);
                }
            }
        } else if (datatype.equalsIgnoreCase("INT")) {
            for (i = 0; i < length; i++) {
                if (hideMissing == Float.isNaN(cells[i])) {
                    bb.putInt((int) nodatavalue);
                } else {
                    bb.putInt((int) actual[i]);
                }
            }
        } else if (datatype.equalsIgnoreCase("LONG")) {
            for (i = 0; i < length; i++) {
                if (hideMissing == Float.isNaN(cells[i])) {
                    bb.putLong((long) nodatavalue);
                } else {
                    bb.putLong((long) actual[i]);
                }
            }
        } else if (datatype.equalsIgnoreCase("FLOAT")) {
            for (i = 0; i < length; i++) {
                if (hideMissing == Float.isNaN(cells[i])) {
                    bb.putFloat((float) nodatavalue);
                } else {
                    bb.putFloat(actual[i]);
                }
            }
        } else if (datatype.equalsIgnoreCase("DOUBLE")) {
            for (i = 0; i < length; i++) {
                if (hideMissing == Float.isNaN(cells[i])) {
                    bb.putDouble((double) nodatavalue);
                } else {
                    bb.putDouble((double) actual[i]);
                }
            }
        } else {
            // should not happen
            logger.error("unsupported grid data type: " + datatype);
        }

        afile.write(bb.array());
    } catch (Exception e) {
        logger.error("error getting grid file values", e);
    } finally {
        if (afile != null) {
            try {
                afile.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
}