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(int index);

Source Link

Document

Returns the short at the specified index.

Usage

From source file:edu.udo.scaffoldhunter.model.db.StringProperty.java

/**
 * Extracts the BitFingerprint length from the first two bytes
 * //from   ww w  .j a va 2  s .  co m
 * @param bitFingerprint
 *            the bytes
 * @return the length
 */
private short bitFingerprintToLength(byte[] bitFingerprint) {
    Preconditions.checkArgument(bitFingerprint.length >= 3);

    ByteBuffer bb = ByteBuffer.allocate(2);
    bb.order(ByteOrder.LITTLE_ENDIAN);
    bb.put(bitFingerprint[0]);
    bb.put(bitFingerprint[1]);
    short length = bb.getShort(0);

    return length;
}

From source file:org.getspout.spout.packet.PacketCustomBlockChunkOverride.java

public void run(int playerId) {
    ByteBuffer buffer = ByteBuffer.allocate(data.length);
    buffer.put(data);/*w  ww  .ja v a  2 s.  co  m*/
    short[] customIds = new short[16 * 16 * Spoutcraft.getWorld().getMaxHeight()];
    for (int i = 0; i < customIds.length; i++) {
        customIds[i] = buffer.getShort(i * 2);
    }
    Spoutcraft.getWorld().getChunkAt(chunkX, chunkZ).setCustomBlockIds(customIds);
}

From source file:org.getspout.spout.packet.PacketCustomMultiBlockOverride.java

public void run(int playerId) {
    ByteBuffer result = ByteBuffer.allocate(data.length).put(data);
    Chunk chunk = Spoutcraft.getWorld().getChunkAt(chunkX, chunkZ);
    for (int i = 0; i < data.length / 6; i++) {
        int index = i * 6;
        int x = result.get(index) + chunkX * 16;
        int y = result.getShort(index + 1);
        int z = result.get(index + 3) + chunkZ * 16;
        short id = result.getShort(index + 4);
        chunk.setCustomBlockId(x, y, z, id);
    }/*from   w w  w . jav  a  2  s  .  co m*/
}

From source file:com.mbientlab.metawear.app.popup.DataPlotFragment.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    final Collection<DataPoint> convertedX = new ArrayList<>(), convertedY = new ArrayList<>(),
            convertedZ = new ArrayList<>();

    GraphView graph = (GraphView) view.findViewById(R.id.data_plot);
    graph.getViewport().setScrollable(true);
    graph.getViewport().setScalable(true);

    graph.getViewport().setYAxisBoundsManual(true);
    graph.getViewport().setMaxY(8.0);/*  ww  w  . j a  va2  s . com*/
    graph.getViewport().setMinY(-8.0);
    graph.getLegendRenderer().setVisible(true);
    graph.getLegendRenderer().setAlign(LegendRenderer.LegendAlign.MIDDLE);

    for (byte[] dataBytes : accelConfig.polledBytes()) {
        ByteBuffer buffer = ByteBuffer.wrap(dataBytes);
        double tickInS = (double) (buffer.getLong(6) / 1000.0);
        float xAccel, yAccel, zAccel;

        if (accelConfig.firmwarePos() == 0) {
            xAccel = buffer.getShort(0) / 1000.0f;
            yAccel = buffer.getShort(2) / 1000.0f;
            zAccel = buffer.getShort(4) / 1000.0f;
        } else {
            xAccel = BytesInterpreter.bytesToGs(accelConfig.getSamplingConfig(), buffer.getShort(0));
            yAccel = BytesInterpreter.bytesToGs(accelConfig.getSamplingConfig(), buffer.getShort(2));
            zAccel = BytesInterpreter.bytesToGs(accelConfig.getSamplingConfig(), buffer.getShort(4));
        }
        convertedX.add(new DataPoint(tickInS, xAccel));
        convertedY.add(new DataPoint(tickInS, yAccel));
        convertedZ.add(new DataPoint(tickInS, zAccel));

    }

    addDataSeries("X-Axis", convertedX);
    addDataSeries("Y-Axis", convertedY);
    addDataSeries("Z-Axis", convertedZ);

    int colorIndex = 0;
    for (Entry<String, LineGraphSeries<DataPoint>> data : dataSeries.entrySet()) {
        data.getValue().setColor(chartColors[colorIndex]);
        data.getValue().setTitle(data.getKey());
        graph.addSeries(data.getValue());
        colorIndex++;
    }
}

From source file:gridool.memcached.gateway.MemcachedProxyHandler.java

@Override
public byte[] handleGet(byte[] key) {
    final ByteBuffer reqPacket = ByteBuffer.allocate(HEADER_LENGTH + key.length);
    // request header
    Header header = new Header(MAGIC_BYTE_REQUEST, OPCODE_GET);
    header.setBodyLength(GET_EXTRA_LENGTH, key.length, 0);
    header.encode(reqPacket);/*from  w  ww  . ja  v a2 s.c om*/
    // request body (key)
    reqPacket.put(key);
    reqPacket.flip();

    final byte[] value;
    final SocketAddress sockAddr = getSocket(key);
    final ByteChannel channel = sockPool.borrowObject(sockAddr);
    try {
        // handle request
        NIOUtils.writeFully(channel, reqPacket);

        // handle response header
        ByteBuffer responseHeaderPacket = ByteBuffer.allocate(HEADER_LENGTH);
        NIOUtils.readFully(channel, responseHeaderPacket);
        responseHeaderPacket.flip();
        // handle response body 
        int totalBody = responseHeaderPacket.getInt(8);
        int keyLen = responseHeaderPacket.getShort(2);
        int extraLen = responseHeaderPacket.get(4);
        int bodyPos = extraLen + keyLen;
        int bodyLen = totalBody - bodyPos;
        if (bodyLen <= 0) {
            return null;
        }
        ByteBuffer responseBodyPacket = ByteBuffer.allocate(totalBody);
        NIOUtils.readFully(channel, responseBodyPacket);
        responseBodyPacket.flip();
        value = new byte[bodyLen];
        responseBodyPacket.get(value, 0, bodyLen);
    } catch (IOException e) {
        LOG.error(e);
        return null;
    } finally {
        sockPool.returnObject(sockAddr, channel);
    }
    return value;
}

From source file:edu.umn.cs.spatialHadoop.nasa.HDFRecordReader.java

/**
 * Recovers all missing entries using a two-dimensional interpolation technique.
 * @param values The dataset that need to be recovered
 * @param fillValue The marker that marks missing values
 * @param waterMask A bit-mask with <code>true</code> values in water areas
 * and <code>false</code> values for land areas.
 *///  www .  j av  a2 s .c  om
public static void recoverXYShorts(ByteBuffer values, short fillValue, BitArray waterMask) {
    // Resolution of the dataset which is the size of each of its two dimensions
    // e.g., 1200x1200, 2400x2400, or 4800x4800
    int resolution = (int) Math.sqrt(values.limit() / 2);
    // This array stores all the runs of true (non-fill) values. The size is
    // always even where the two values point to the first and last positions
    // of the run, respectively
    ShortArray[] trueRuns = findTrueRuns(values, fillValue);

    // Now, scan the dataset column by column to recover missing values
    for (short col = 0; col < resolution; col++) {
        // Find runs of fillValues and recover all of them
        short row1 = 0;
        while (row1 < resolution) {
            // Skip as many true values as we can
            while (row1 < resolution && values.getShort(2 * (row1 * resolution + col)) != fillValue)
                row1++;
            // Now, row1 points to the first fillValue
            if (row1 == resolution) {
                // All entries in the column have true values. No processing needed
                continue;
            }
            short row2 = (short) (row1 + 1);
            // Skip as many fillValues as we can
            while (row2 < resolution && values.getShort(2 * (row2 * resolution + col)) == fillValue)
                row2++;
            // Now, row2 points to a true value

            // Offsets of the four true values to the (top, bottom, left, right)
            short[] offsetsToInterpolate = { -1, -1, -1, -1 };
            short[] valuesToInterpolate = new short[4];
            if (row1 > 0) {
                offsetsToInterpolate[0] = (short) (row1 - 1);
                valuesToInterpolate[0] = values.getShort(2 * (offsetsToInterpolate[0] * resolution + col));
            }
            if (row2 < resolution) {
                offsetsToInterpolate[1] = row2;
                valuesToInterpolate[1] = values.getShort(2 * (offsetsToInterpolate[1] * resolution + col));
            }

            for (int row = row1; row < row2; row++) {
                if (values.getShort(2 * (row * resolution + col)) == fillValue
                        && !waterMask.get((row * resolution + col))) {
                    // The point at (row, col) is on land and has a fill (empty) value
                    // Find the position of the run in this row to find points to the left and right
                    int position = -trueRuns[row].binarySearch(col) - 1;
                    if (position > 0) {
                        // There's a true value to the left
                        offsetsToInterpolate[2] = trueRuns[row].get(position - 1);
                        valuesToInterpolate[2] = values
                                .getShort(2 * (row * resolution + offsetsToInterpolate[2]));
                    } else {
                        offsetsToInterpolate[2] = -1;
                    }
                    if (position < trueRuns[row].size()) {
                        // There's a true value to the right
                        offsetsToInterpolate[3] = trueRuns[row].get(position);
                        valuesToInterpolate[3] = values
                                .getShort(2 * (row * resolution + offsetsToInterpolate[3]));
                    } else {
                        offsetsToInterpolate[3] = -1;
                    }
                    short interpolatedValue = interpolatePoint(row, col, offsetsToInterpolate,
                            valuesToInterpolate, fillValue);
                    values.putShort(2 * (row * resolution + col), interpolatedValue);
                }
            }

            // Skip the current empty run and go to the next one
            row1 = row2;
        }
    }
}

From source file:com.l2jfree.gameserver.geodata.pathfinding.geonodes.GeoPathFinding.java

private Node readNode(short node_x, short node_y, byte layer) {
    short regoffset = getRegionOffset(getRegionX(node_x), getRegionY(node_y));
    if (!pathNodesExist(regoffset))
        return null;
    short nbx = getNodeBlock(node_x);
    short nby = getNodeBlock(node_y);
    int idx = _pathNodesIndex.get(regoffset).get((nby << 8) + nbx);
    ByteBuffer pn = _pathNodes.get(regoffset);
    //reading/* w  w  w. j  ava 2 s  .  c  o m*/
    byte nodes = pn.get(idx);
    idx += layer * 10 + 1;//byte + layer*10byte
    if (nodes < layer) {
        _log.warn("SmthWrong!");
    }
    short node_z = pn.getShort(idx);
    idx += 2;
    return new GeoNode(node_x, node_y, node_z, idx);
}

From source file:com.l2jfree.gameserver.geodata.pathfinding.geonodes.GeoPathFinding.java

private Node readNode(int gx, int gy, short z) {
    short node_x = getNodePos(gx);
    short node_y = getNodePos(gy);
    short regoffset = getRegionOffset(getRegionX(node_x), getRegionY(node_y));
    if (!pathNodesExist(regoffset))
        return null;
    short nbx = getNodeBlock(node_x);
    short nby = getNodeBlock(node_y);
    int idx = _pathNodesIndex.get(regoffset).get((nby << 8) + nbx);
    ByteBuffer pn = _pathNodes.get(regoffset);
    //reading//  w  ww .  ja v a 2 s.c  o  m
    byte nodes = pn.get(idx++);
    int idx2 = 0; //create index to nearlest node by z
    short last_z = Short.MIN_VALUE;
    while (nodes > 0) {
        short node_z = pn.getShort(idx);
        if (Math.abs(last_z - z) > Math.abs(node_z - z)) {
            last_z = node_z;
            idx2 = idx + 2;
        }
        idx += 10; //short + 8 byte
        nodes--;
    }
    return new GeoNode(node_x, node_y, last_z, idx2);
}

From source file:com.mbientlab.metawear.app.AccelerometerFragment.java

private void writeDataToFile() {
    dataFilename = String.format(Locale.US, "metawear_accelerometer_data-%s-%s.csv",
            FullScaleRange.values()[accelConfig.fsrPos()].toString(),
            OutputDataRate.values()[accelConfig.odrPos()].toString());
    try {/*  w  ww. ja  v  a2  s  . c om*/
        FileOutputStream fos = getActivity().openFileOutput(dataFilename, Context.MODE_PRIVATE);
        fos.write(CSV_HEADER.getBytes());

        for (byte[] dataBytes : accelConfig.polledBytes()) {
            ByteBuffer buffer = ByteBuffer.wrap(dataBytes);
            double tickInS = (double) (buffer.getLong(6) / 1000.0);
            float xAccel, yAccel, zAccel;

            if (accelConfig.firmwarePos() == 0) {
                xAccel = buffer.getShort(0) / 1000.0f;
                yAccel = buffer.getShort(2) / 1000.0f;
                zAccel = buffer.getShort(4) / 1000.0f;
            } else {
                xAccel = BytesInterpreter.bytesToGs(accelConfig.getSamplingConfig(), buffer.getShort(0));
                yAccel = BytesInterpreter.bytesToGs(accelConfig.getSamplingConfig(), buffer.getShort(2));
                zAccel = BytesInterpreter.bytesToGs(accelConfig.getSamplingConfig(), buffer.getShort(4));
            }

            fos.write(String.format(Locale.US, "%.3f,%.3f,%.3f,%.3f%n", tickInS, xAccel, yAccel, zAccel)
                    .getBytes());
        }

        fos.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:gridool.memcached.gateway.MemcachedProxyHandler.java

@Override
public short handleSet(byte[] key, byte[] value, int flags, int expiry) {
    final ByteBuffer reqPacket = ByteBuffer
            .allocate(HEADER_LENGTH + SET_EXTRA_LENGTH + key.length + value.length);
    // request header
    Header header = new Header(MAGIC_BYTE_REQUEST, OPCODE_SET);
    header.setBodyLength(SET_EXTRA_LENGTH, key.length, value.length);
    header.encode(reqPacket);//from   w  w  w. j a v  a 2  s .  co  m
    // request body (flags, expiration, key, value)
    reqPacket.putInt(flags);
    reqPacket.putInt(expiry);
    reqPacket.put(key);
    reqPacket.put(value);
    reqPacket.flip();

    final ByteBuffer resPacket = ByteBuffer.allocate(HEADER_LENGTH);
    final SocketAddress sockAddr = getSocket(key);
    final ByteChannel channel = sockPool.borrowObject(sockAddr);
    try {
        NIOUtils.writeFully(channel, reqPacket);
        NIOUtils.readFully(channel, resPacket);
    } catch (IOException e) {
        LOG.error(e);
        return ResponseStatus.UNKNOWN.status;
    } finally {
        sockPool.returnObject(sockAddr, channel);
    }
    resPacket.flip();
    short status = resPacket.getShort(6);
    return status;
}