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:com.kitware.tangoproject.paraviewtangorecorder.PointCloudActivity.java

private void writePointCloudToFile(TangoXyzIjData xyzIj, byte[] buffer,
        ArrayList<TangoCoordinateFramePair> framePairs) {

    ByteBuffer myBuffer = ByteBuffer.allocate(xyzIj.xyzCount * 3 * 4);
    myBuffer.order(ByteOrder.LITTLE_ENDIAN);
    myBuffer.put(buffer, xyzIj.xyzParcelFileDescriptorOffset, myBuffer.capacity());

    File mainDir = new File(mMainDirPath);
    if (!mainDir.exists()) {
        boolean created = mainDir.mkdir();
        if (created) {
            Log.i(TAG, "Folder: \"" + mMainDirPath + "\" created\n");
        }//from w  ww  .  ja  v a2  s . c  om
    }

    File dir = new File(mSaveDirAbsPath);
    if (!dir.exists()) {
        boolean created = dir.mkdir();
        if (created) {
            Log.i(TAG, "Folder: \"" + mSaveDirAbsPath + "\" created\n");
        }
    }

    mFilename = "pc_" + mNowTimeString + "_" + String.format("%03d", mNumberOfFilesWritten) + ".vtk";
    mFilenameBuffer.add(mSaveDirAbsPath + mFilename);
    File file = new File(dir, mFilename);

    try {

        DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));

        out.write(("# vtk DataFile Version 3.0\n" + "vtk output\n" + "BINARY\n" + "DATASET POLYDATA\n"
                + "POINTS " + xyzIj.xyzCount + " float\n").getBytes());

        for (int i = 0; i < xyzIj.xyzCount; i++) {

            out.writeFloat(myBuffer.getFloat(3 * i * 4));
            out.writeFloat(myBuffer.getFloat((3 * i + 1) * 4));
            out.writeFloat(myBuffer.getFloat((3 * i + 2) * 4));
        }

        out.write(("\nVERTICES 1 " + String.valueOf(xyzIj.xyzCount + 1) + "\n").getBytes());
        out.writeInt(xyzIj.xyzCount);
        for (int i = 0; i < xyzIj.xyzCount; i++) {
            out.writeInt(i);
        }

        out.write(("\nFIELD FieldData 1\n" + "timestamp 1 1 float\n").getBytes());
        out.writeFloat((float) xyzIj.timestamp);

        out.close();
        mNumberOfFilesWritten++;
        mTimeToTakeSnap = false;

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.bimserver.collada.ColladaSerializer.java

private void setGeometry(PrintWriter out, IfcProduct ifcProductObject, String material)
        throws RenderEngineException, SerializerException {
    // Mostly just skips IfcOpeningElements which one would probably not want to end up in the Collada file.
    if (ifcProductObject instanceof IfcFeatureElementSubtraction)
        return;//  ww w. j  a va2s. c  o m
    //
    GeometryInfo geometryInfo = ifcProductObject.getGeometry();
    if (geometryInfo != null && geometryInfo.getTransformation() != null) {
        GeometryData geometryData = geometryInfo.getData();
        ByteBuffer indicesBuffer = ByteBuffer.wrap(geometryData.getIndices());
        indicesBuffer.order(ByteOrder.LITTLE_ENDIAN);
        // TODO: In Blender (3d modeling tool) and Three.js, normals are ignored in favor of vertex order. The incoming geometry seems to be in order 0 1 2 when it needs to be in 1 0 2. Need more test cases.
        // Failing order: (0, 1050, 2800), (0, 1050, 3100), (3580, 1050, 3100)
        // Successful order: (0, 1050, 3100), (0, 1050, 2800), (3580, 1050, 3100)
        List<Integer> list = new ArrayList<Integer>();
        while (indicesBuffer.hasRemaining())
            list.add(indicesBuffer.getInt());
        indicesBuffer.rewind();
        for (int i = 0; i < list.size(); i += 3) {
            Integer first = list.get(i);
            Integer next = list.get(i + 1);
            list.set(i, next);
            list.set(i + 1, first);
        }
        // Positions the X or the Y or the Z of (X, Y, Z).
        ByteBuffer positionsBuffer = ByteBuffer.wrap(geometryData.getVertices());
        positionsBuffer.order(ByteOrder.LITTLE_ENDIAN);
        // Do pass to find highest Z for considered objects.
        while (positionsBuffer.hasRemaining()) {
            float x = positionsBuffer.getFloat();
            float y = positionsBuffer.getFloat();
            float z = positionsBuffer.getFloat();
            // X
            if (x > highestObserved.x())
                highestObserved.x(x);
            else if (x < lowestObserved.x())
                lowestObserved.x(x);
            // Y
            if (y > highestObserved.y())
                highestObserved.y(y);
            else if (y < lowestObserved.y())
                lowestObserved.y(y);
            // Z
            if (z > highestObserved.z())
                highestObserved.z(z);
            else if (z < lowestObserved.z())
                lowestObserved.z(z);
        }
        positionsBuffer.rewind();
        //
        ByteBuffer normalsBuffer = ByteBuffer.wrap(geometryData.getNormals());
        normalsBuffer.order(ByteOrder.LITTLE_ENDIAN);
        // Create a geometry identification number in the form of: geom-320450
        long oid = ifcProductObject.getOid();
        String id = String.format("geom-%d", oid);
        // If the material doesn't exist in the converted map, add it.
        if (!converted.containsKey(material))
            converted.put(material, new HashSet<IfcProduct>());
        // Add the current IfcProduct to the appropriate entry in the material map.
        converted.get(material).add(ifcProductObject);
        // Name for geometry.
        String name = (ifcProductObject.getGlobalId() == null) ? "[NO_GUID]" : ifcProductObject.getGlobalId();
        // Counts.
        int vertexComponentsTotal = positionsBuffer.capacity() / 4,
                normalComponentsTotal = normalsBuffer.capacity() / 4;
        int verticesCount = positionsBuffer.capacity() / 12, normalsCount = normalsBuffer.capacity() / 12,
                triangleCount = indicesBuffer.capacity() / 12;
        // Vertex scalars as one long string: 4.05 2 1 55.0 34.01 2
        String stringPositionScalars = byteBufferToFloatingPointSpaceDelimitedString(positionsBuffer);
        // Normal scalars as one long string: 4.05 2 1 55.0 34.01 2
        String stringNormalScalars = byteBufferToFloatingPointSpaceDelimitedString(normalsBuffer); //doubleBufferToFloatingPointSpaceDelimitedString(flippedNormalsBuffer);
        // Vertex indices as one long string: 1 0 2 0 3 2 5 4 6
        String stringIndexScalars = listToSpaceDelimitedString(list, intFormat);
        // Write geometry block for this IfcProduct (i.e. IfcRoof, IfcSlab, etc).
        out.println(" <geometry id=\"" + id + "\" name=\"" + name + "\">");
        out.println("  <mesh>");
        out.println("   <source id=\"positions-" + oid + "\" name=\"positions-" + oid + "\">");
        out.println("    <float_array id=\"positions-array-" + oid + "\" count=\"" + vertexComponentsTotal
                + "\">" + stringPositionScalars + "</float_array>");
        out.println("    <technique_common>");
        out.println("     <accessor count=\"" + verticesCount + "\" offset=\"0\" source=\"#positions-array-"
                + oid + "\" stride=\"3\">");
        out.println("      <param name=\"X\" type=\"float\"></param>");
        out.println("      <param name=\"Y\" type=\"float\"></param>");
        out.println("      <param name=\"Z\" type=\"float\"></param>");
        out.println("     </accessor>");
        out.println("    </technique_common>");
        out.println("   </source>");
        out.println("   <source id=\"normals-" + oid + "\" name=\"normals-" + oid + "\">");
        out.println("    <float_array id=\"normals-array-" + oid + "\" count=\"" + normalComponentsTotal + "\">"
                + stringNormalScalars + "</float_array>");
        out.println("    <technique_common>");
        out.println("     <accessor count=\"" + normalsCount + "\" offset=\"0\" source=\"#normals-array-" + oid
                + "\" stride=\"3\">");
        out.println("      <param name=\"X\" type=\"float\"></param>");
        out.println("      <param name=\"Y\" type=\"float\"></param>");
        out.println("      <param name=\"Z\" type=\"float\"></param>");
        out.println("     </accessor>");
        out.println("    </technique_common>");
        out.println("   </source>");
        out.println("   <vertices id=\"vertices-" + oid + "\">");
        out.println("    <input semantic=\"POSITION\" source=\"#positions-" + oid + "\"/>");
        out.println("    <input semantic=\"NORMAL\" source=\"#normals-" + oid + "\"/>");
        out.println("   </vertices>");
        out.println("   <triangles count=\"" + triangleCount + "\" material=\"Material-" + oid + "\">");
        out.println("    <input offset=\"0\" semantic=\"VERTEX\" source=\"#vertices-" + oid + "\"/>");
        out.println("    <p>" + stringIndexScalars + "</p>");
        out.println("   </triangles>");
        out.println("  </mesh>");
        out.println(" </geometry>");
    }
}

From source file:edu.mbl.jif.imaging.mmtiff.MultipageTiffWriter.java

private void writeNullOffsetAfterLastImage() throws IOException {
    ByteBuffer buffer = ByteBuffer.allocate(4);
    buffer.order(BYTE_ORDER);
    buffer.putInt(0, 0);/*from w w w  . j  av a  2  s. co m*/
    fileChannel_.write(buffer, nextIFDOffsetLocation_);
}

From source file:de.tum.frm2.nicos_android.nicos.NicosClient.java

public void event_handler() {
    DataInputStream din = new DataInputStream(eventSocketIn);
    while (true) {
        try {//from   w ww. j a v a2s .  c  o m
            // receive STX (1 byte) + eventcode (2) + length (4)
            byte[] start = new byte[7];
            try {
                //noinspection ResultOfMethodCallIgnored
                din.read(start);
            } catch (IOException e) {
                if (!disconnecting) {
                    signal("broken", "Server connection broken.");
                    _close();
                }
                return;
            }
            if (start[0] != daemon.STX) {
                // Every event starts with STX. Else, something's wrong.
                if (!disconnecting) {
                    signal("broken", "Server connection broken.");
                    _close();
                }
                return;
            }
            byte[] slice = Arrays.copyOfRange(start, 3, 7);
            ByteBuffer bb = ByteBuffer.wrap(slice);
            bb.order(ByteOrder.BIG_ENDIAN);

            // Get length, allocate byte buffer.
            int length = bb.getInt();
            byte[] buf = new byte[length];

            // Read length bytes and store them in buf.
            din.readFully(buf, 0, length);

            boolean should_signal = true;
            String event = null;
            Object data = null;
            try {
                // Stackoverflow magic to convert 2 bytes to int which can be compared in
                // daemon.command2event().
                int eventcode = ((start[1] & 0xff) << 8) | (start[2] & 0x00ff);
                event = daemon.command2event(eventcode);
                // serialized or raw data?
                if (daemon.eventNeedsUnserialize(event)) {
                    Unpickler unpickler = new Unpickler();
                    data = unpickler.loads(buf);
                } else {
                    data = buf;
                }
            } catch (Exception e) {
                // Garbled event
                should_signal = false;
            }
            if (should_signal) {
                signal(event, data);
            }
        } catch (Exception e) {
            if (!disconnecting) {
                signal("broken", "Server connection broken.");
                _close();
            }
            return;
        }
    }
}

From source file:io.pcp.parfait.dxm.PcpMmvWriter.java

private void preparePerMetricBufferSlices() {
    for (PcpValueInfo info : metricData.values()) {
        TypeHandler<?> rawHandler = info.getTypeHandler();
        int bufferPosition = rawHandler.requiresLargeStorage() ? info.getLargeValue().getOffset()
                : info.getOffset();/*from   ww  w .j a  va 2 s  .c om*/
        // need to position the original buffer first, as the sliced buffer starts from there
        dataFileBuffer.position(bufferPosition);
        ByteBuffer metricByteBufferSlice = dataFileBuffer.slice();
        metricByteBufferSlice.limit(rawHandler.getDataLength());
        perMetricByteBuffers.put(info, metricByteBufferSlice);
        metricByteBufferSlice.order(dataFileBuffer.order());
    }
}

From source file:com.warfrog.bitmapallthethings.BattEngine.java

private InputStream generateBitmapHeader(int width, int height, int fileSize, int fillerBytes) {
    ByteBuffer buffer = ByteBuffer.allocate(54);
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    buffer.put((byte) 0x42); //B
    buffer.put((byte) 0x4D); //M
    buffer.putInt(fileSize + 54); //total file size
    buffer.putInt(fileSize); //unofficial -- used to save the file size
    buffer.putInt(54); //pixel info offset
    buffer.putInt(40); //size of the bitmap info header
    buffer.putInt(width); //width
    buffer.putInt(height); //height
    buffer.putShort((short) 1); //number of color planes
    buffer.putShort((short) getBytesPerPixel()); //bytes per pixel
    buffer.putInt(0); //no compression
    buffer.putInt(fileSize); //size of the raw pixel array
    buffer.putInt(2835); //horizontal resolution
    buffer.putInt(2835); //vertical resolution
    buffer.putInt(0); //number of colors
    buffer.putInt(0); //important colors
    return new ByteArrayInputStream(buffer.array());
}

From source file:com.yobidrive.diskmap.needles.Needle.java

public boolean getNeedleHeaderFromBuffer(ByteBuffer input) throws Exception {
    try {//from  w  w w  .  j av  a  2 s  .co  m
        // Reinit needle
        keyBytes = null;
        version = null;
        flags = 0x00;
        size = 0;
        data = null;
        previousNeedle = null; // Chaining
        readBytes = 0;
        // Processes reading
        input.rewind();
        int startPosition = input.position();
        int magic = input.getInt();
        if (magic == MAGICSTART_BADENDIAN) {
            if (input.order().equals(ByteOrder.BIG_ENDIAN))
                input.order(ByteOrder.LITTLE_ENDIAN);
            else
                input.order(ByteOrder.BIG_ENDIAN);
        } else if (magic != MAGICSTART) {
            logger.error("Buffer not starting with needle");
            return false;
        }
        needleNumber = input.getLong();
        flags = input.get();
        int keyLen = input.getInt();
        if (keyLen > 2028) {
            logger.error("Crazy needle key len");
            return false;
        }
        keyBytes = new byte[keyLen];
        input.get(keyBytes);
        int versionLen = input.getInt();
        if (versionLen > 1024 * 16) {
            logger.error("Crazy needle version len");
            return false;
        }
        if (versionLen == 0)
            version = null;
        else {
            byte[] versionBytes = new byte[versionLen];
            input.get(versionBytes);
            version = new VectorClock(versionBytes);
        }
        int previousLogNumber = input.getInt(); // Chaining
        long previousNeedleOffset = input.getLong(); // Chaining
        if (previousLogNumber != -1 && previousNeedleOffset != -1L) {
            previousNeedle = new NeedlePointer();
            previousNeedle.setNeedleFileNumber(previousLogNumber);
            previousNeedle.setNeedleOffset(previousNeedleOffset);
        }
        originalFileNumber = input.getInt(); // Original needle location (for cleaning)
        originalSize = input.getInt(); // Original needle size (for cleaning)
        size = input.getInt();

        readBytes = input.position() - startPosition;
        input.rewind();
        // input.mark() ;
        return true;
    } catch (BufferUnderflowException bue) {
        return false;
    }
}

From source file:org.bimserver.GeometryGenerator.java

private void setTransformationMatrix(GeometryInfo geometryInfo, float[] transformationMatrix) {
    ByteBuffer byteBuffer = ByteBuffer.allocate(16 * 4);
    byteBuffer.order(ByteOrder.nativeOrder());
    FloatBuffer asFloatBuffer = byteBuffer.asFloatBuffer();
    for (float f : transformationMatrix) {
        asFloatBuffer.put(f);//from w w w.  j av a 2  s.  c  o  m
    }
    geometryInfo.setTransformation(byteBuffer.array());
}

From source file:org.zuinnote.hadoop.bitcoin.format.BitcoinBlockReader.java

public ByteBuffer readRawBlock() throws BitcoinBlockReadException, IOException {
    boolean readBlock = false;
    byte[] magicNo = new byte[4];
    byte[] blockSizeByte = new byte[4];
    long blockSize = 0;
    while (readBlock == false) { // in case of filtering by magic no we skip blocks until we reach a valid magicNo or end of Block
        // check if more to read
        if (this.bin.available() < 1) {
            return null;
        }/*from www. j  ava 2 s.c  om*/
        // mark bytestream so we can peak into it
        this.bin.mark(8);
        // read magic

        int magicNoReadSize = this.bin.read(magicNo, 0, 4);
        if (magicNoReadSize != 4)
            return null; // no more magics to read
        // read blocksize

        int blockSizeReadSize = this.bin.read(blockSizeByte, 0, 4);
        if (blockSizeReadSize != 4)
            return null; // no more size to read
        blockSize = BitcoinUtil.getSize(blockSizeByte) + 8;
        // read the full block
        this.bin.reset();
        //filter by magic numbers?
        if (filterSpecificMagic == true) {
            for (int i = 0; i < specificMagicByteArray.length; i++) {
                byte[] currentFilter = specificMagicByteArray[i];
                boolean doesMatchOneMagic = BitcoinUtil.compareMagics(currentFilter, magicNo);
                // correspond to filter? read it!
                if (doesMatchOneMagic == true) {
                    readBlock = true;
                    break;
                }
            }
            if (readBlock == false) { // skip it
                // Skip block
                this.bin.reset();
                this.bin.skip(blockSize);
            }
        } else {
            readBlock = true;
        }
    }
    // check if it is larger than maxsize, include 8 bytes for the magic and size header
    blockSize = BitcoinUtil.getSize(blockSizeByte) + 8;
    if (blockSize == 0)
        throw new BitcoinBlockReadException("Error: Blocksize too small");
    if (blockSize < 0)
        throw new BitcoinBlockReadException(
                "Error: This block size cannot be handled currently (larger then largest number in positive signed int)");
    if (blockSize > this.maxSizeBitcoinBlock)
        throw new BitcoinBlockReadException(
                "Error: Block size is larger then defined in configuration - Please increase it if this is a valid block");
    // read full block into ByteBuffer
    int blockSizeInt = new Long(blockSize).intValue();
    byte[] fullBlock = new byte[blockSizeInt];
    int readByte = 0;
    int totalByteRead = 0;
    while ((readByte = this.bin.read(fullBlock, totalByteRead, blockSizeInt - totalByteRead)) > -1) {
        totalByteRead += readByte;
        if (totalByteRead >= blockSize)
            break;
    }
    if (totalByteRead != blockSize)
        throw new BitcoinBlockReadException("Error: Could not read full block");
    ByteBuffer result = null;
    if (this.useDirectBuffer == false) {
        result = ByteBuffer.wrap(fullBlock);
    } else {
        preAllocatedDirectByteBuffer.clear(); // clear out old bytebuffer
        preAllocatedDirectByteBuffer.limit(fullBlock.length); // limit the bytebuffer
        result = preAllocatedDirectByteBuffer;
        result.put(fullBlock);
        result.flip(); // put in read mode
    }
    result.order(ByteOrder.LITTLE_ENDIAN);
    return result;
}

From source file:org.bimserver.GeometryGenerator.java

private byte[] intArrayToByteArray(int[] indices) {
    if (indices == null) {
        return null;
    }/*from  ww  w. j a v  a 2 s. c  o  m*/
    ByteBuffer buffer = ByteBuffer.wrap(new byte[indices.length * 4]);
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    IntBuffer asIntBuffer = buffer.asIntBuffer();
    for (int i : indices) {
        asIntBuffer.put(i);
    }
    return buffer.array();
}