Example usage for com.google.common.io LittleEndianDataOutputStream writeInt

List of usage examples for com.google.common.io LittleEndianDataOutputStream writeInt

Introduction

In this page you can find the example usage for com.google.common.io LittleEndianDataOutputStream writeInt.

Prototype

@Override
public void writeInt(int v) throws IOException 

Source Link

Document

Writes an int as specified by DataOutputStream#writeInt(int) , except using little-endian byte order.

Usage

From source file:org.linguafranca.pwdb.kdbx.stream_3_1.KdbxSerializer.java

/**
 * Write a KdbxHeader to the output stream supplied. The header is updated with the
 * message digest of the written stream.
 * @param kdbxHeader the header to write and update
 * @param outputStream the output stream
 * @throws IOException on error/* www . j  ava  2 s  .c om*/
 */
public static void writeKdbxHeader(KdbxHeader kdbxHeader, OutputStream outputStream) throws IOException {
    MessageDigest messageDigest = Encryption.getMessageDigestInstance();
    DigestOutputStream digestOutputStream = new DigestOutputStream(outputStream, messageDigest);
    LittleEndianDataOutputStream ledos = new LittleEndianDataOutputStream(digestOutputStream);

    // write the magic number
    ledos.writeInt(SIG1);
    ledos.writeInt(SIG2);
    // write a file version
    ledos.writeInt(FILE_VERSION_32);

    ledos.writeByte(HeaderType.CIPHER_ID);
    ledos.writeShort(16);
    byte[] b = new byte[16];
    ByteBuffer bb = ByteBuffer.wrap(b);
    bb.putLong(kdbxHeader.getCipherUuid().getMostSignificantBits());
    bb.putLong(8, kdbxHeader.getCipherUuid().getLeastSignificantBits());
    ledos.write(b);

    ledos.writeByte(HeaderType.COMPRESSION_FLAGS);
    ledos.writeShort(4);
    ledos.writeInt(kdbxHeader.getCompressionFlags().ordinal());

    ledos.writeByte(HeaderType.MASTER_SEED);
    ledos.writeShort(kdbxHeader.getMasterSeed().length);
    ledos.write(kdbxHeader.getMasterSeed());

    ledos.writeByte(HeaderType.TRANSFORM_SEED);
    ledos.writeShort(kdbxHeader.getTransformSeed().length);
    ledos.write(kdbxHeader.getTransformSeed());

    ledos.writeByte(HeaderType.TRANSFORM_ROUNDS);
    ledos.writeShort(8);
    ledos.writeLong(kdbxHeader.getTransformRounds());

    ledos.writeByte(HeaderType.ENCRYPTION_IV);
    ledos.writeShort(kdbxHeader.getEncryptionIv().length);
    ledos.write(kdbxHeader.getEncryptionIv());

    ledos.writeByte(HeaderType.PROTECTED_STREAM_KEY);
    ledos.writeShort(kdbxHeader.getProtectedStreamKey().length);
    ledos.write(kdbxHeader.getProtectedStreamKey());

    ledos.writeByte(HeaderType.STREAM_START_BYTES);
    ledos.writeShort(kdbxHeader.getStreamStartBytes().length);
    ledos.write(kdbxHeader.getStreamStartBytes());

    ledos.writeByte(HeaderType.INNER_RANDOM_STREAM_ID);
    ledos.writeShort(4);
    ledos.writeInt(kdbxHeader.getProtectedStreamAlgorithm().ordinal());

    ledos.writeByte(HeaderType.END);
    ledos.writeShort(0);

    MessageDigest digest = digestOutputStream.getMessageDigest();
    kdbxHeader.setHeaderHash(digest.digest());
}

From source file:de.nx42.maps4cim.map.TextureMap.java

/**
 * Stores the texture map in the specified output stream, storing the integers
 * in little endian byte order//  ww w. j  av a2 s  . c  o m
 * @param out the output stream to write the texture map into
 * @param textureMap the texture map to write
 * @throws MapGeneratorException when the size of the texture map is invalid
 * @throws IOException when the resulting map can't be written
 */
protected void storeByteStream(OutputStream out, int[][] textureMap) throws MapGeneratorException, IOException {

    if (isValidSize(textureMap)) {
        // byte outputput stream, wrapped by a little endian integer processor
        ByteArrayOutputStream bos = new ByteArrayOutputStream(byteAmount);
        LittleEndianDataOutputStream dos = new LittleEndianDataOutputStream(bos);

        // pass the resulting integers to the little endian byte output stream
        for (int y = 0; y < edgeLength; y++) {
            for (int x = 0; x < edgeLength; x++) {
                dos.writeInt(textureMap[x][y]);
            }
        }

        // writeTo to the user defined output streame
        bos.writeTo(out);

        // close streams
        dos.close();
        bos.close();
    } else {
        throw new MapGeneratorException(
                "The size of the texture map is invalid. " + "Only Maps with 2048 * 2048 blocks are allowed");
    }

}

From source file:de.nx42.maps4cim.map.ReliefMap.java

/**
 * Stores the relief map in the specified output stream, transforming
 * the floats to little endian 32 bit integers.
 * @param out the output stream to write the relief map into
 * @param reliefMap the relief map to write
 * @throws MapGeneratorException when the size of the relief map is invalid
 * @throws IOException when the resulting map can't be written
 *//*from  w  ww  . j a  v  a  2s .  c o  m*/
protected void storeByteStream(OutputStream out, float[][] reliefMap)
        throws MapGeneratorException, IOException {

    if (isValidSize(reliefMap)) {
        // byte outputput stream, wrapped by a little endian integer processor
        ByteArrayOutputStream bos = new ByteArrayOutputStream(byteAmount);
        LittleEndianDataOutputStream dos = new LittleEndianDataOutputStream(bos);

        // pass the resulting integers to the little endian byte output stream
        for (int y = 0; y < edgeLength; y++) {
            for (int x = 0; x < edgeLength; x++) {
                // convert the floats (meter) to integers (millimeter)
                dos.writeInt((int) (reliefMap[y][x] * 1000));
            }
        }

        // write to the user defined output stream
        bos.writeTo(out);

        // close streams
        dos.close();
        bos.close();
    } else {
        throw new MapGeneratorException("The size of the relief map is invalid. "
                + "Only Maps with 2049 * 2049 control points are allowed");
    }

}

From source file:org.bimserver.serializers.binarygeometry.BinaryGeometrySerializer.java

private void writeGeometries(OutputStream outputStream) throws IOException {
    long start = System.nanoTime();

    LittleEndianDataOutputStream dataOutputStream = new LittleEndianDataOutputStream(outputStream);
    // Identifier for clients to determine if this server is even serving binary geometry
    dataOutputStream.writeUTF("BGS");

    // Version of the current format being outputted, should be changed for every (released) change in protocol 
    dataOutputStream.writeByte(FORMAT_VERSION);

    Bounds modelBounds = new Bounds();
    int nrObjects = 0;

    // All access to EClass is being done generically to support multiple IFC schema's with 1 serializer
    EClass productClass = getModel().getPackageMetaData().getEClass("IfcProduct");

    List<IdEObject> products = getModel().getAllWithSubTypes(productClass);

    // First iteration, to determine number of objects with geometry and calculate model bounds
    for (IdEObject ifcProduct : products) {
        GeometryInfo geometryInfo = (GeometryInfo) ifcProduct
                .eGet(ifcProduct.eClass().getEStructuralFeature("geometry"));
        if (geometryInfo != null && geometryInfo.getTransformation() != null) {
            Bounds objectBounds = new Bounds(
                    new Float3(geometryInfo.getMinBounds().getX(), geometryInfo.getMinBounds().getY(),
                            geometryInfo.getMinBounds().getZ()),
                    new Float3(geometryInfo.getMaxBounds().getX(), geometryInfo.getMaxBounds().getY(),
                            geometryInfo.getMaxBounds().getZ()));
            modelBounds.integrate(objectBounds);
            nrObjects++;//from   w ww  .j a v a2 s  .  c om
        }
    }
    modelBounds.writeTo(dataOutputStream);
    dataOutputStream.writeInt(nrObjects);
    int bytesSaved = 0;
    int bytesTotal = 0;

    // Keeping track of geometry already sent, this can be used for instancing of reused geometry
    Set<Long> concreteGeometrySent = new HashSet<>();

    // Flushing here so the client can show progressbar etc...
    dataOutputStream.flush();

    int bytes = 6;
    int counter = 0;

    // Second iteration actually writing the geometry
    for (IdEObject ifcProduct : products) {
        GeometryInfo geometryInfo = (GeometryInfo) ifcProduct
                .eGet(ifcProduct.eClass().getEStructuralFeature("geometry"));
        if (geometryInfo != null && geometryInfo.getTransformation() != null) {
            String type = ifcProduct.eClass().getName();
            dataOutputStream.writeUTF(type);
            dataOutputStream.writeLong(ifcProduct.getOid());

            GeometryData geometryData = geometryInfo.getData();
            byte[] vertices = geometryData.getVertices();

            // BEWARE, ByteOrder is always LITTLE_ENDIAN, because that's what GPU's seem to prefer, Java's ByteBuffer default is BIG_ENDIAN though!

            bytesTotal += vertices.length;
            byte geometryType = concreteGeometrySent.contains(geometryData.getOid()) ? GEOMETRY_TYPE_INSTANCE
                    : GEOMETRY_TYPE_TRIANGLES;
            dataOutputStream.write(geometryType);

            bytes += (type.getBytes(Charsets.UTF_8).length + 3);

            // This is an ugly hack to align the bytes, but for 2 different kinds of output (this first one is the websocket implementation)
            int skip = 4 - (bytes % 4); // TODO fix
            if (skip != 0 && skip != 4) {
                dataOutputStream.write(new byte[skip]);
            }

            bytes = 0;

            dataOutputStream.write(geometryInfo.getTransformation());

            if (concreteGeometrySent.contains(geometryData.getOid())) {
                // Reused geometry, only send the id of the reused geometry data
                dataOutputStream.writeLong(geometryData.getOid());
                bytesSaved += vertices.length;
            } else {
                ByteBuffer vertexByteBuffer = ByteBuffer.wrap(vertices);
                dataOutputStream.writeLong(geometryData.getOid());

                Bounds objectBounds = new Bounds(geometryInfo.getMinBounds(), geometryInfo.getMaxBounds());
                objectBounds.writeTo(dataOutputStream);

                ByteBuffer indicesBuffer = ByteBuffer.wrap(geometryData.getIndices());
                dataOutputStream.writeInt(indicesBuffer.capacity() / 4);
                dataOutputStream.write(indicesBuffer.array());

                dataOutputStream.writeInt(vertexByteBuffer.capacity() / 4);
                dataOutputStream.write(vertexByteBuffer.array());

                ByteBuffer normalsBuffer = ByteBuffer.wrap(geometryData.getNormals());
                dataOutputStream.writeInt(normalsBuffer.capacity() / 4);
                dataOutputStream.write(normalsBuffer.array());

                // Only when materials are used we send them
                if (geometryData.getMaterials() != null) {
                    ByteBuffer materialsByteBuffer = ByteBuffer.wrap(geometryData.getMaterials());

                    dataOutputStream.writeInt(materialsByteBuffer.capacity() / 4);
                    dataOutputStream.write(materialsByteBuffer.array());
                } else {
                    // No materials used
                    dataOutputStream.writeInt(0);
                }

                concreteGeometrySent.add(geometryData.getOid());
            }
            counter++;
            if (counter % 12 == 0) {
                // Flushing in batches, this is to limit the amount of WebSocket messages
                dataOutputStream.flush();
            }
        }
    }
    dataOutputStream.flush();
    if (bytesTotal != 0 && bytesSaved != 0) {
        LOGGER.info((100 * bytesSaved / bytesTotal) + "% saved");
    }
    long end = System.nanoTime();
    LOGGER.debug(((end - start) / 1000000) + " ms");
}

From source file:org.bimserver.serializers.binarygeometry.BinaryGeometryMessagingSerializer.java

private boolean writeStart(OutputStream outputStream) throws IOException {
    LittleEndianDataOutputStream dataOutputStream = new LittleEndianDataOutputStream(outputStream);
    // Identifier for clients to determine if this server is even serving binary geometry
    dataOutputStream.writeByte(MessageType.INIT.getId());
    dataOutputStream.writeUTF("BGS");

    // Version of the current format being outputted, should be changed for every (released) change in protocol 
    dataOutputStream.writeByte(FORMAT_VERSION);

    Bounds modelBounds = new Bounds();
    int nrObjects = 0;

    // All access to EClass is being done generically to support multiple IFC schema's with 1 serializer
    EClass productClass = model.getPackageMetaData().getEClass("IfcProduct");

    List<IdEObject> products = model.getAllWithSubTypes(productClass);

    // First iteration, to determine number of objects with geometry and calculate model bounds
    for (IdEObject ifcProduct : products) {
        GeometryInfo geometryInfo = (GeometryInfo) ifcProduct
                .eGet(ifcProduct.eClass().getEStructuralFeature("geometry"));
        if (geometryInfo != null && geometryInfo.getTransformation() != null) {
            Bounds objectBounds = new Bounds(
                    new Float3(geometryInfo.getMinBounds().getX(), geometryInfo.getMinBounds().getY(),
                            geometryInfo.getMinBounds().getZ()),
                    new Float3(geometryInfo.getMaxBounds().getX(), geometryInfo.getMaxBounds().getY(),
                            geometryInfo.getMaxBounds().getZ()));
            modelBounds.integrate(objectBounds);
            nrObjects++;// ww  w .j a  va2s  .com
        }
    }

    int skip = 4 - (7 % 4);
    if (skip != 0 && skip != 4) {
        dataOutputStream.write(new byte[skip]);
    }

    modelBounds.writeTo(dataOutputStream);
    dataOutputStream.writeInt(nrObjects);

    concreteGeometrySent = new HashMap<Long, Object>();
    EClass productEClass = packageMetaData.getEClass("IfcProduct");
    iterator = model.getAllWithSubTypes(productEClass).iterator();

    return nrObjects > 0;
}

From source file:org.bimserver.serializers.binarygeometry.BinaryGeometryMessagingSerializer.java

@SuppressWarnings("unchecked")
private boolean writeData(OutputStream outputStream) throws IOException {
    IdEObject ifcProduct = iterator.next();
    LittleEndianDataOutputStream dataOutputStream = new LittleEndianDataOutputStream(outputStream);
    GeometryInfo geometryInfo = (GeometryInfo) ifcProduct
            .eGet(ifcProduct.eClass().getEStructuralFeature("geometry"));
    if (geometryInfo != null && geometryInfo.getTransformation() != null) {
        GeometryData geometryData = geometryInfo.getData();

        int totalNrIndices = geometryData.getIndices().length / 4;
        int maxIndexValues = 16389;

        Object reuse = concreteGeometrySent.get(geometryData.getOid());
        MessageType messageType = null;//from w w w. j av a 2  s .com
        if (reuse == null) {
            if (totalNrIndices > maxIndexValues) {
                messageType = MessageType.GEOMETRY_TRIANGLES_PARTED;
            } else {
                messageType = MessageType.GEOMETRY_TRIANGLES;
            }
        } else {
            if (reuse instanceof List) {
                messageType = MessageType.GEOMETRY_INSTANCE_PARTED;
            } else {
                messageType = MessageType.GEOMETRY_INSTANCE;
            }
        }
        dataOutputStream.writeByte(messageType.getId());
        dataOutputStream.writeUTF(ifcProduct.eClass().getName());
        Long roid = model.getPidRoidMap().get(ifcProduct.getPid());
        dataOutputStream.writeLong(roid);
        dataOutputStream.writeLong(ifcProduct.getOid());

        // BEWARE, ByteOrder is always LITTLE_ENDIAN, because that's what GPU's seem to prefer, Java's ByteBuffer default is BIG_ENDIAN though!

        int skip = 4 - ((3 + ifcProduct.eClass().getName().getBytes(Charsets.UTF_8).length) % 4);
        if (skip != 0 && skip != 4) {
            dataOutputStream.write(new byte[skip]);
        }

        dataOutputStream.write(geometryInfo.getTransformation());

        if (reuse != null && reuse instanceof Long) {
            // Reused geometry, only send the id of the reused geometry data
            dataOutputStream.writeLong(geometryData.getOid());
        } else if (reuse != null && reuse instanceof List) {
            List<Long> list = (List<Long>) reuse;
            dataOutputStream.writeInt(list.size());
            for (long coreId : list) {
                dataOutputStream.writeLong(coreId);
            }
        } else {
            if (totalNrIndices > maxIndexValues) {
                // Split geometry, this algorithm - for now - just throws away all the reuse of vertices that might be there
                // Also, although usually the vertices buffers are too large, this algorithm is based on the indices, so we
                // probably are not cramming as much data as we can in each "part", but that's not really a problem I think

                int nrParts = (totalNrIndices + maxIndexValues - 1) / maxIndexValues;
                dataOutputStream.writeInt(nrParts);

                Bounds objectBounds = new Bounds(geometryInfo.getMinBounds(), geometryInfo.getMaxBounds());
                objectBounds.writeTo(dataOutputStream);

                ByteBuffer indicesBuffer = ByteBuffer.wrap(geometryData.getIndices());
                indicesBuffer.order(ByteOrder.LITTLE_ENDIAN);
                IntBuffer indicesIntBuffer = indicesBuffer.asIntBuffer();

                ByteBuffer vertexBuffer = ByteBuffer.wrap(geometryData.getVertices());
                vertexBuffer.order(ByteOrder.LITTLE_ENDIAN);
                FloatBuffer verticesFloatBuffer = vertexBuffer.asFloatBuffer();

                ByteBuffer normalsBuffer = ByteBuffer.wrap(geometryData.getNormals());
                normalsBuffer.order(ByteOrder.LITTLE_ENDIAN);
                FloatBuffer normalsFloatBuffer = normalsBuffer.asFloatBuffer();

                for (int part = 0; part < nrParts; part++) {
                    long splitId = splitCounter--;
                    dataOutputStream.writeLong(splitId);

                    int indexCounter = 0;
                    int upto = Math.min((part + 1) * maxIndexValues, totalNrIndices);
                    dataOutputStream.writeInt(upto - part * maxIndexValues);
                    for (int i = part * maxIndexValues; i < upto; i++) {
                        dataOutputStream.writeInt(indexCounter++);
                    }

                    dataOutputStream.writeInt((upto - part * maxIndexValues) * 3);
                    for (int i = part * maxIndexValues; i < upto; i += 3) {
                        int oldIndex1 = indicesIntBuffer.get(i);
                        int oldIndex2 = indicesIntBuffer.get(i + 1);
                        int oldIndex3 = indicesIntBuffer.get(i + 2);
                        dataOutputStream.writeFloat(verticesFloatBuffer.get(oldIndex1 * 3));
                        dataOutputStream.writeFloat(verticesFloatBuffer.get(oldIndex1 * 3 + 1));
                        dataOutputStream.writeFloat(verticesFloatBuffer.get(oldIndex1 * 3 + 2));
                        dataOutputStream.writeFloat(verticesFloatBuffer.get(oldIndex2 * 3));
                        dataOutputStream.writeFloat(verticesFloatBuffer.get(oldIndex2 * 3 + 1));
                        dataOutputStream.writeFloat(verticesFloatBuffer.get(oldIndex2 * 3 + 2));
                        dataOutputStream.writeFloat(verticesFloatBuffer.get(oldIndex3 * 3));
                        dataOutputStream.writeFloat(verticesFloatBuffer.get(oldIndex3 * 3 + 1));
                        dataOutputStream.writeFloat(verticesFloatBuffer.get(oldIndex3 * 3 + 2));
                    }
                    dataOutputStream.writeInt((upto - part * maxIndexValues) * 3);
                    for (int i = part * maxIndexValues; i < upto; i += 3) {
                        int oldIndex1 = indicesIntBuffer.get(i);
                        int oldIndex2 = indicesIntBuffer.get(i + 1);
                        int oldIndex3 = indicesIntBuffer.get(i + 2);

                        dataOutputStream.writeFloat(normalsFloatBuffer.get(oldIndex1 * 3));
                        dataOutputStream.writeFloat(normalsFloatBuffer.get(oldIndex1 * 3 + 1));
                        dataOutputStream.writeFloat(normalsFloatBuffer.get(oldIndex1 * 3 + 2));
                        dataOutputStream.writeFloat(normalsFloatBuffer.get(oldIndex2 * 3));
                        dataOutputStream.writeFloat(normalsFloatBuffer.get(oldIndex2 * 3 + 1));
                        dataOutputStream.writeFloat(normalsFloatBuffer.get(oldIndex2 * 3 + 2));
                        dataOutputStream.writeFloat(normalsFloatBuffer.get(oldIndex3 * 3));
                        dataOutputStream.writeFloat(normalsFloatBuffer.get(oldIndex3 * 3 + 1));
                        dataOutputStream.writeFloat(normalsFloatBuffer.get(oldIndex3 * 3 + 2));
                    }

                    dataOutputStream.writeInt(0);
                }
            } else {
                Bounds objectBounds = new Bounds(geometryInfo.getMinBounds(), geometryInfo.getMaxBounds());
                objectBounds.writeTo(dataOutputStream);

                dataOutputStream.writeLong(geometryData.getOid());

                ByteBuffer indicesBuffer = ByteBuffer.wrap(geometryData.getIndices());
                dataOutputStream.writeInt(indicesBuffer.capacity() / 4);
                dataOutputStream.write(indicesBuffer.array());

                ByteBuffer vertexByteBuffer = ByteBuffer.wrap(geometryData.getVertices());
                dataOutputStream.writeInt(vertexByteBuffer.capacity() / 4);
                dataOutputStream.write(vertexByteBuffer.array());

                ByteBuffer normalsBuffer = ByteBuffer.wrap(geometryData.getNormals());
                dataOutputStream.writeInt(normalsBuffer.capacity() / 4);
                dataOutputStream.write(normalsBuffer.array());

                // Only when materials are used we send them
                if (geometryData.getMaterials() != null) {
                    ByteBuffer materialsByteBuffer = ByteBuffer.wrap(geometryData.getMaterials());

                    dataOutputStream.writeInt(materialsByteBuffer.capacity() / 4);
                    dataOutputStream.write(materialsByteBuffer.array());
                } else {
                    // No materials used
                    dataOutputStream.writeInt(0);
                }
                List<Long> arrayList = new ArrayList<Long>();
                arrayList.add(geometryData.getOid());
                concreteGeometrySent.put(geometryData.getOid(), arrayList);
            }
        }
    }
    return iterator.hasNext();
}