Example usage for java.nio ByteOrder LITTLE_ENDIAN

List of usage examples for java.nio ByteOrder LITTLE_ENDIAN

Introduction

In this page you can find the example usage for java.nio ByteOrder LITTLE_ENDIAN.

Prototype

ByteOrder LITTLE_ENDIAN

To view the source code for java.nio ByteOrder LITTLE_ENDIAN.

Click Source Link

Document

This constant represents little endian.

Usage

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   w w w.j  a v a  2s  .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:loci.formats.in.KLBReader.java

private int readUInt32() throws IOException {
    byte[] b = new byte[4];
    in.read(b, 0, 4);// ww  w  . j  av  a  2  s.c  o  m
    ByteBuffer bb = ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN);
    return bb.getInt();
}

From source file:loci.formats.in.KLBReader.java

private long readUInt64() throws IOException {
    byte[] b = new byte[8];
    in.read(b, 0, 8);//from w  ww. j  a v a  2  s .c  o m
    ByteBuffer bb = ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN);
    return bb.getLong();
}

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

private void printMatrix(PrintWriter out, GeometryInfo geometryInfo) {
    ByteBuffer transformation = ByteBuffer.wrap(geometryInfo.getTransformation());
    transformation.order(ByteOrder.LITTLE_ENDIAN);
    FloatBuffer floatBuffer = transformation.asFloatBuffer();
    // Prepare to create the transform matrix.
    float[] matrix = new float[16];
    // Add the first 16 values of the buffer.
    for (int i = 0; i < matrix.length; i++)
        matrix[i] = floatBuffer.get();/*from w w w  . j  a v  a 2 s  .  c o m*/
    // Switch from column-major (x.x ... x.y ... x.z ... 0 ...) to row-major orientation (x.x x.y x.z 0 ...)?
    matrix = Matrix.changeOrientation(matrix);
    // List all 16 elements of the matrix as a single space-delimited String object.
    out.println("    <matrix>" + floatArrayToSpaceDelimitedString(matrix) + "</matrix>");
}

From source file:loci.formats.in.KLBReader.java

private PositiveFloat readFloat32() throws IOException {
    byte[] b = new byte[4];
    in.read(b, 0, 4);// w  w w. j a  v  a  2  s.  c  o  m
    ByteBuffer bb = ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN);
    return new PositiveFloat((double) bb.getFloat());
}

From source file:services.SimulationService.java

@Override
public void insertOpcodes(Map<Integer, INetworkRemoteEvent> swgOpcodes,
        Map<Integer, INetworkRemoteEvent> objControllerOpcodes) {

    objControllerOpcodes.put(ObjControllerOpcodes.DATA_TRANSFORM, new INetworkRemoteEvent() {

        @Override/*from w  w  w  . j a v a 2s .c o  m*/
        public void handlePacket(IoSession session, IoBuffer data) throws Exception {

            data.order(ByteOrder.LITTLE_ENDIAN);

            DataTransform dataTransform = new DataTransform();
            dataTransform.deserialize(data);
            //System.out.println("Movement Counter: " + dataTransform.getMovementCounter());
            Client client = core.getClient(session);

            if (client == null) {
                System.out.println("NULL Client");
                return;
            }

            if (client.getParent() == null) {
                System.out.println("NULL Object");
                return;
            }

            CreatureObject creature = (CreatureObject) client.getParent();
            if (creature.getPosture() == Posture.Dead || creature.getPosture() == Posture.Incapacitated)
                return;

            CreatureObject object = creature;

            if (core.mountService.isMounted(creature)
                    && creature.getObjectID() == ((CreatureObject) creature.getContainer()).getOwnerId()) {
                object = (CreatureObject) object.getContainer();
            }

            Point3D newPos;
            Point3D oldPos;

            synchronized (object.getMutex()) {
                newPos = new Point3D(dataTransform.getXPosition(), dataTransform.getYPosition(),
                        dataTransform.getZPosition());
                if (Float.isNaN(newPos.x) || Float.isNaN(newPos.y) || Float.isNaN(newPos.z))
                    return;
                oldPos = object.getPosition();
            }

            if (object instanceof CreatureObject && object.getOption(Options.MOUNT)) {
                if (!checkLineOfSight(object, newPos)) {
                    newPos = oldPos;
                }
            }

            synchronized (object.getMutex()) {
                //Collection<Client> oldObservers = object.getObservers();
                //Collection<Client> newObservers = new HashSet<Client>();
                if (object.getContainer() == null)
                    move(object, oldPos.x, oldPos.z, newPos.x, newPos.z);
                Quaternion newOrientation = new Quaternion(dataTransform.getWOrientation(),
                        dataTransform.getXOrientation(), dataTransform.getYOrientation(),
                        dataTransform.getZOrientation());
                object.setPosition(newPos);
                creature.setPosition(newPos);
                object.setOrientation(newOrientation);
                creature.setOrientation(newOrientation);
                object.setMovementCounter(dataTransform.getMovementCounter());
                creature.setMovementCounter(dataTransform.getMovementCounter());
            }

            synchronized (creature.getMutex()) {
                if (dataTransform.getSpeed() > 0.0f) {
                    switch (creature.getLocomotion()) {
                    case Locomotion.Prone:
                        creature.setLocomotion(Locomotion.Crawling);
                        break;
                    case Locomotion.ClimbingStationary:
                        creature.setLocomotion(Locomotion.Climbing);
                        break;
                    case Locomotion.Standing:
                    case Locomotion.Running:
                    case Locomotion.Walking:
                        if (dataTransform.getSpeed() >= (creature.getRunSpeed()
                                * (creature.getSpeedMultiplierBase() + creature.getSpeedMultiplierMod()))) {
                            creature.setLocomotion(Locomotion.Running);
                        } else {
                            creature.setLocomotion(Locomotion.Walking);
                        }

                        break;
                    case Locomotion.Sneaking:
                    case Locomotion.CrouchSneaking:
                    case Locomotion.CrouchWalking:
                        if (dataTransform.getSpeed() >= (creature.getRunSpeed()
                                * (creature.getSpeedMultiplierBase() + creature.getSpeedMultiplierMod()))) {
                            creature.setLocomotion(Locomotion.CrouchSneaking);
                        } else {
                            creature.setLocomotion(Locomotion.CrouchWalking);
                        }

                        break;
                    }
                } else {
                    switch (creature.getLocomotion()) {
                    case Locomotion.Crawling:
                        creature.setLocomotion(Locomotion.Prone);
                        break;
                    case Locomotion.Climbing:
                        creature.setLocomotion(Locomotion.ClimbingStationary);
                        break;
                    case Locomotion.Running:
                    case Locomotion.Walking:
                        creature.setLocomotion(Locomotion.Standing);
                        break;
                    case Locomotion.CrouchSneaking:
                    case Locomotion.CrouchWalking:
                        creature.setLocomotion(Locomotion.Sneaking);
                        break;
                    }
                }
            }

            if (object.getContainer() != null) {
                object.getContainer()._remove(object);
                add(object, newPos.x, newPos.z);
            }

            //object.setParentId(0);
            //object.setParent(null);
            //   System.out.println("Parsed Height: " + core.terrainService.getHeight(object.getPlanetId(), dataTransform.getXPosition(), dataTransform.getZPosition())
            //       + " should be: " + dataTransform.getYPosition());
            UpdateTransformMessage utm = new UpdateTransformMessage(object.getObjectID(),
                    dataTransform.getTransformedX(), dataTransform.getTransformedY(),
                    dataTransform.getTransformedZ(), dataTransform.getMovementCounter(),
                    (byte) dataTransform.getMovementAngle(), dataTransform.getSpeed());
            object.notifyObservers(utm, false);

            List<SWGObject> newAwareObjects = get(creature.getPlanet(), newPos.x, newPos.z, 512);
            ArrayList<SWGObject> oldAwareObjects = new ArrayList<SWGObject>(creature.getAwareObjects());
            @SuppressWarnings("unchecked")
            Collection<SWGObject> updateAwareObjects = CollectionUtils.intersection(oldAwareObjects,
                    newAwareObjects);

            for (int i = 0; i < oldAwareObjects.size(); i++) {
                SWGObject obj = oldAwareObjects.get(i);
                if (!updateAwareObjects.contains(obj) && obj != creature
                        && obj.getWorldPosition().getDistance2D(newPos) > 200
                        && obj.isInQuadtree() /*&& obj.getParentId() == 0*/) {
                    if (obj.getAttachment("bigSpawnRange") != null
                            && obj.getWorldPosition().getDistance2D(newPos) < 512)
                        continue;
                    creature.makeUnaware(obj);
                    if (obj.getClient() != null)
                        obj.makeUnaware(creature);
                } else if (obj != creature && obj.getWorldPosition().getDistance2D(newPos) > 200
                        && obj.isInQuadtree() && obj.getAttachment("bigSpawnRange") == null) {
                    creature.makeUnaware(obj);
                    if (obj.getClient() != null)
                        obj.makeUnaware(creature);
                }
            }

            for (int i = 0; i < newAwareObjects.size(); i++) {
                SWGObject obj = newAwareObjects.get(i);
                //System.out.println(obj.getTemplate());
                if (!updateAwareObjects.contains(obj) && obj != creature
                        && !creature.getAwareObjects().contains(obj) && obj.getContainer() != creature
                        && obj.isInQuadtree()) {
                    if (obj.getAttachment("bigSpawnRange") == null
                            && obj.getWorldPosition().getDistance2D(newPos) > 200)
                        continue;
                    creature.makeAware(obj);
                    if (obj.getClient() != null)
                        obj.makeAware(creature);
                }
            }

            checkForCollidables(object);
            object.setAttachment("lastValidPosition", object.getPosition());
            MoveEvent event = new MoveEvent();
            event.object = object;
            object.getEventBus().publish(event);

        }

    });

    objControllerOpcodes.put(ObjControllerOpcodes.DATA_TRANSFORM_WITH_PARENT, new INetworkRemoteEvent() {

        @Override
        public void handlePacket(IoSession session, IoBuffer data) throws Exception {

            data.order(ByteOrder.LITTLE_ENDIAN);

            DataTransformWithParent dataTransform = new DataTransformWithParent();
            dataTransform.deserialize(data);
            Client client = core.getClient(session);

            if (core.objectService.getObject(dataTransform.getCellId()) == null)
                return;

            SWGObject parent = core.objectService.getObject(dataTransform.getCellId());

            if (client == null) {
                System.out.println("NULL Client");
                return;
            }

            if (client.getParent() == null) {
                System.out.println("NULL Object");
                return;
            }

            CreatureObject object = (CreatureObject) client.getParent();
            if (object.getPosture() == Posture.Dead || object.getPosture() == Posture.Incapacitated)
                return;

            if (core.mountService.isMounted(object)) {
                object.sendSystemMessage(OutOfBand.ProsePackage("@pet_menu:cant_mount"), DisplayType.Broadcast);
                core.mountService.dismount(object, (CreatureObject) object.getContainer());
            }

            Point3D newPos = new Point3D(dataTransform.getXPosition(), dataTransform.getYPosition(),
                    dataTransform.getZPosition());
            newPos.setCell((CellObject) parent);
            if (Float.isNaN(newPos.x) || Float.isNaN(newPos.y) || Float.isNaN(newPos.z))
                return;
            Point3D oldPos = object.getPosition();
            Quaternion newOrientation = new Quaternion(dataTransform.getWOrientation(),
                    dataTransform.getXOrientation(), dataTransform.getYOrientation(),
                    dataTransform.getZOrientation());

            UpdateTransformWithParentMessage utm = new UpdateTransformWithParentMessage(object.getObjectID(),
                    dataTransform.getCellId(), dataTransform.getTransformedX(), dataTransform.getTransformedY(),
                    dataTransform.getTransformedZ(), dataTransform.getMovementCounter(),
                    (byte) dataTransform.getMovementAngle(), dataTransform.getSpeed());

            if (object.getContainer() != parent) {
                remove(object, oldPos.x, oldPos.z);
                if (object.getContainer() != null)
                    object.getContainer()._remove(object);
                if (object.getClient() == null)
                    System.err.println("Client is null!  This is a very strange error.");
                //if (object.getClient() != null && object.getClient().isGM() && parent != null && parent instanceof CellObject && parent.getContainer() != null)
                //object.sendSystemMessage("BuildingId - Dec: " + parent.getContainer().getObjectID() + " Hex: " + Long.toHexString(parent.getContainer().getObjectID()) + " CellNumber: " + ((CellObject) parent).getCellNumber(), DisplayType.Broadcast);
                parent._add(object);
            }
            object.setPosition(newPos);
            object.setOrientation(newOrientation);
            object.setMovementCounter(dataTransform.getMovementCounter());
            object.notifyObservers(utm, false);

            checkForCollidables(object);
            object.setAttachment("lastValidPosition", object.getPosition());

            synchronized (object.getMutex()) {
                if (dataTransform.getSpeed() > 0.0f) {
                    switch (object.getLocomotion()) {
                    case Locomotion.Prone:
                        object.setLocomotion(Locomotion.Crawling);
                        break;
                    case Locomotion.ClimbingStationary:
                        object.setLocomotion(Locomotion.Climbing);
                        break;
                    case Locomotion.Standing:
                    case Locomotion.Running:
                    case Locomotion.Walking:
                        if (dataTransform.getSpeed() >= (object.getRunSpeed()
                                * (object.getSpeedMultiplierBase() + object.getSpeedMultiplierMod()))) {
                            object.setLocomotion(Locomotion.Running);
                        } else {
                            object.setLocomotion(Locomotion.Walking);
                        }

                        break;
                    case Locomotion.Sneaking:
                    case Locomotion.CrouchSneaking:
                    case Locomotion.CrouchWalking:
                        if (dataTransform.getSpeed() >= (object.getRunSpeed()
                                * (object.getSpeedMultiplierBase() + object.getSpeedMultiplierMod()))) {
                            object.setLocomotion(Locomotion.CrouchSneaking);
                        } else {
                            object.setLocomotion(Locomotion.CrouchWalking);
                        }

                        break;
                    }
                } else {
                    switch (object.getLocomotion()) {
                    case Locomotion.Crawling:
                        object.setLocomotion(Locomotion.Prone);
                        break;
                    case Locomotion.Climbing:
                        object.setLocomotion(Locomotion.ClimbingStationary);
                        break;
                    case Locomotion.Running:
                    case Locomotion.Walking:
                        object.setLocomotion(Locomotion.Standing);
                        break;
                    case Locomotion.CrouchSneaking:
                    case Locomotion.CrouchWalking:
                        object.setLocomotion(Locomotion.Sneaking);
                        break;
                    }
                }
            }
        }

    });

    swgOpcodes.put(Opcodes.ClientOpenContainerMessage, new INetworkRemoteEvent() {

        @Override
        public void handlePacket(IoSession session, IoBuffer data) throws Exception {
            System.out.println("Open Container Request");
        }

    });

    objControllerOpcodes.put(ObjControllerOpcodes.lookAtTarget, new INetworkRemoteEvent() {

        @Override
        public void handlePacket(IoSession session, IoBuffer data) throws Exception {

            data.order(ByteOrder.LITTLE_ENDIAN);

            Client client = core.getClient(session);

            if (client == null) {
                System.out.println("NULL Client");
                return;
            }

            if (client.getParent() == null) {
                System.out.println("NULL Object");
                return;
            }
            CreatureObject object = (CreatureObject) client.getParent();

            TargetUpdate targetUpdate = new TargetUpdate();
            targetUpdate.deserialize(data);

            object.setLookAtTarget(targetUpdate.getTargetId());

        }

    });

    objControllerOpcodes.put(ObjControllerOpcodes.intendedTarget, new INetworkRemoteEvent() {

        @Override
        public void handlePacket(IoSession session, IoBuffer data) throws Exception {

            data.order(ByteOrder.LITTLE_ENDIAN);

            Client client = core.getClient(session);

            if (client == null) {
                System.out.println("NULL Client");
                return;
            }

            if (client.getParent() == null) {
                System.out.println("NULL Object");
                return;
            }
            CreatureObject object = (CreatureObject) client.getParent();

            TargetUpdate targetUpdate = new TargetUpdate();
            targetUpdate.deserialize(data);

            object.setIntendedTarget(targetUpdate.getTargetId());

        }

    });

}

From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.sav.SAVFileReader.java

void decodeRecordType1(BufferedInputStream stream) throws IOException {
    dbgLog.fine("***** decodeRecordType1(): start *****");

    if (stream == null) {
        throw new IllegalArgumentException("stream == null!");
    }// w  w  w.  j ava  2 s. c  om
    // how to read each recordType
    // 1. set-up the following objects before reading bytes
    // a. the working byte array
    // b. the storage object
    // the length of this field: 172bytes = 60 + 4 + 12 + 4 + 8 + 84
    // this field consists of 6 distinct blocks

    byte[] recordType1 = new byte[LENGTH_RECORDTYPE1];
    // int caseWeightVariableOBSIndex = 0; 

    try {
        int nbytes = stream.read(recordType1, 0, LENGTH_RECORDTYPE1);

        //printHexDump(recordType1, "recordType1");

        if (nbytes == 0) {
            throw new IOException("reading recordType1: no byte was read");
        }

        // 1.1 60 byte-String that tells the platform/version of SPSS that
        // wrote this file

        int offset_start = 0;
        int offset_end = LENGTH_SPSS_PRODUCT_INFO; // 60 bytes

        String productInfo = new String(Arrays.copyOfRange(recordType1, offset_start, offset_end), "US-ASCII");

        dbgLog.fine("productInfo:\n" + productInfo + "\n");

        // add the info to the fileInfo
        smd.getFileInformation().put("productInfo", productInfo);

        // try to parse out the SPSS version that created this data
        // file: 

        String spssVersionNumberTag = null;

        String regexpVersionNumber = ".*Release ([0-9]*)";
        Pattern patternJsession = Pattern.compile(regexpVersionNumber);
        Matcher matcher = patternJsession.matcher(productInfo);
        if (matcher.find()) {
            spssVersionNumberTag = matcher.group(1);
            dbgLog.fine("SPSS Version Number: " + spssVersionNumberTag);
        }

        if (spssVersionNumberTag != null && !spssVersionNumberTag.equals("")) {
            spssVersionNumber = Integer.valueOf(spssVersionNumberTag).intValue();

            /*
             *  Starting with SPSS version 16, the default encoding is 
             *  UTF-8. 
             *  But we are only going to use it if the user did not explicitly
             *  specify the encoding on the addfiles page. Then we'd want 
             *  to stick with whatever they entered. 
             */
            if (spssVersionNumber > 15) {
                if (getDataLanguageEncoding() == null) {
                    defaultCharSet = "UTF-8";
                }
            }
        }

        smd.getFileInformation().put("charset", defaultCharSet);

        // 1.2) 4-byte file-layout-code (byte-order)

        offset_start = offset_end;
        offset_end += LENGTH_FILE_LAYOUT_CODE; // 4 byte

        ByteBuffer bb_fileLayout_code = ByteBuffer.wrap(recordType1, offset_start, LENGTH_FILE_LAYOUT_CODE);

        ByteBuffer byteOderTest = bb_fileLayout_code.duplicate();
        // interprete the 4 byte as int

        int int2test = byteOderTest.getInt();

        if (int2test == 2 || int2test == 3) {
            dbgLog.fine("integer == " + int2test + ": the byte-oder of the writer is the same "
                    + "as the counterpart of Java: Big Endian");
        } else {
            // Because Java's byte-order is always big endian, 
            // this(!=2) means this sav file was  written on a little-endian machine
            // non-string, multi-bytes blocks must be byte-reversed

            bb_fileLayout_code.order(ByteOrder.LITTLE_ENDIAN);

            int2test = bb_fileLayout_code.getInt();

            if (int2test == 2 || int2test == 3) {
                dbgLog.fine("The sav file was saved on a little endian machine");
                dbgLog.fine("Reveral of the bytes is necessary to decode " + "multi-byte, non-string blocks");

                isLittleEndian = true;

            } else {
                throw new IOException("reading recordType1:unknown file layout code=" + int2test);
            }
        }

        dbgLog.fine("Endian of this platform:" + ByteOrder.nativeOrder().toString());

        smd.getFileInformation().put("OSByteOrder", ByteOrder.nativeOrder().toString());
        smd.getFileInformation().put("byteOrder", int2test);

        // 1.3 4-byte Number_Of_OBS_Units_Per_Case 
        // (= how many RT2 records => how many varilables)

        offset_start = offset_end;
        offset_end += LENGTH_NUMBER_OF_OBS_UNITS_PER_CASE; // 4 byte

        ByteBuffer bb_OBS_units_per_case = ByteBuffer.wrap(recordType1, offset_start,
                LENGTH_NUMBER_OF_OBS_UNITS_PER_CASE);

        if (isLittleEndian) {
            bb_OBS_units_per_case.order(ByteOrder.LITTLE_ENDIAN);
        }

        OBSUnitsPerCase = bb_OBS_units_per_case.getInt();

        dbgLog.fine("RT1: OBSUnitsPerCase=" + OBSUnitsPerCase);

        smd.getFileInformation().put("OBSUnitsPerCase", OBSUnitsPerCase);

        // 1.4 4-byte Compression_Switch

        offset_start = offset_end;
        offset_end += LENGTH_COMPRESSION_SWITCH; // 4 byte

        ByteBuffer bb_compression_switch = ByteBuffer.wrap(recordType1, offset_start,
                LENGTH_COMPRESSION_SWITCH);

        if (isLittleEndian) {
            bb_compression_switch.order(ByteOrder.LITTLE_ENDIAN);
        }

        int compression_switch = bb_compression_switch.getInt();
        if (compression_switch == 0) {
            // data section is not compressed
            isDataSectionCompressed = false;
            dbgLog.fine("data section is not compressed");
        } else {
            dbgLog.fine("data section is compressed:" + compression_switch);
        }

        smd.getFileInformation().put("compressedData", compression_switch);

        // 1.5 4-byte Case-Weight Variable Index
        // warning: this variable index starts from 1, not 0

        offset_start = offset_end;
        offset_end += LENGTH_CASE_WEIGHT_VARIABLE_INDEX; // 4 byte

        ByteBuffer bb_Case_Weight_Variable_Index = ByteBuffer.wrap(recordType1, offset_start,
                LENGTH_CASE_WEIGHT_VARIABLE_INDEX);

        if (isLittleEndian) {
            bb_Case_Weight_Variable_Index.order(ByteOrder.LITTLE_ENDIAN);
        }

        caseWeightVariableOBSIndex = bb_Case_Weight_Variable_Index.getInt();

        smd.getFileInformation().put("caseWeightVariableOBSIndex", caseWeightVariableOBSIndex);

        // 1.6 4-byte Number of Cases

        offset_start = offset_end;
        offset_end += LENGTH_NUMBER_OF_CASES; // 4 byte

        ByteBuffer bb_Number_Of_Cases = ByteBuffer.wrap(recordType1, offset_start, LENGTH_NUMBER_OF_CASES);

        if (isLittleEndian) {
            bb_Number_Of_Cases.order(ByteOrder.LITTLE_ENDIAN);
        }

        int numberOfCases = bb_Number_Of_Cases.getInt();

        if (numberOfCases < 0) {
            // -1 if numberOfCases is unknown
            throw new RuntimeException("number of cases is not recorded in the header");
        } else {
            dbgLog.fine("RT1: number of cases is recorded= " + numberOfCases);
            caseQnty = numberOfCases;
            smd.getFileInformation().put("caseQnty", numberOfCases);
        }

        // 1.7 8-byte compression-bias [not long but double]

        offset_start = offset_end;
        offset_end += LENGTH_COMPRESSION_BIAS; // 8 byte

        ByteBuffer bb_compression_bias = ByteBuffer
                .wrap(Arrays.copyOfRange(recordType1, offset_start, offset_end));

        if (isLittleEndian) {
            bb_compression_bias.order(ByteOrder.LITTLE_ENDIAN);
        }

        Double compressionBias = bb_compression_bias.getDouble();

        if (compressionBias == 100d) {
            // 100 is expected
            dbgLog.fine("compressionBias is 100 as expected");
            smd.getFileInformation().put("compressionBias", 100);
        } else {
            dbgLog.fine("compression bias is not 100: " + compressionBias);
            smd.getFileInformation().put("compressionBias", compressionBias);
        }

        // 1.8 84-byte File Creation Information (date/time: dd MM yyhh:mm:ss +
        // 64-bytelabel)

        offset_start = offset_end;
        offset_end += LENGTH_FILE_CREATION_INFO; // 84 bytes

        String fileCreationInfo = getNullStrippedString(
                new String(Arrays.copyOfRange(recordType1, offset_start, offset_end), "US-ASCII"));

        dbgLog.fine("fileCreationInfo:\n" + fileCreationInfo + "\n");

        String fileCreationDate = fileCreationInfo.substring(0, length_file_creation_date);
        int dateEnd = length_file_creation_date + length_file_creation_time;
        String fileCreationTime = fileCreationInfo.substring(length_file_creation_date, (dateEnd));
        String fileCreationNote = fileCreationInfo.substring(dateEnd, length_file_creation_label);

        dbgLog.fine("fileDate=" + fileCreationDate);
        dbgLog.fine("fileTime=" + fileCreationTime);
        dbgLog.fine("fileNote" + fileCreationNote);

        smd.getFileInformation().put("fileDate", fileCreationDate);
        smd.getFileInformation().put("fileTime", fileCreationTime);
        smd.getFileInformation().put("fileNote", fileCreationNote);
        smd.getFileInformation().put("varFormat_schema", "SPSS");

        // add the info to the fileInfo

        smd.getFileInformation().put("mimeType", MIME_TYPE[0]);
        smd.getFileInformation().put("fileFormat", MIME_TYPE[0]);

        smd.setValueLabelMappingTable(valueVariableMappingTable);

    } catch (IOException ex) {
        //ex.printStackTrace();
        throw ex;
    }

    dbgLog.fine("***** decodeRecordType1(): end *****");
}

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 va2 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:edu.vu.isis.ammo.dash.provider.IncidentSyncAdaptor.java

protected long deserializer(File file, IMyWriter writer) {
    logger.debug("::deserializer");
    InputStream ins;//from w w w  . jav a2 s  .  c o m
    try {
        ins = new FileInputStream(file);
    } catch (FileNotFoundException e1) {
        return -1;
    }
    BufferedInputStream bufferedInput = new BufferedInputStream(ins);
    byte[] buffer = new byte[1024];
    StringBuilder sb = new StringBuilder();
    long rowId = -1;
    String label = "";
    byte[] payloadSizeBuf = new byte[4];
    int payloadSize = 0;
    byte[] payloadBuf = null;
    int payloadPos = 0;
    try {
        int bytesBuffered = bufferedInput.read(buffer);
        int bufferPos = 0;
        int state = READING_META;
        boolean eod = false;
        while (bytesBuffered > -1) {
            if (bytesBuffered == bufferPos) {
                bytesBuffered = bufferedInput.read(buffer);
                bufferPos = 0; // reset buffer position
            }
            if (bytesBuffered < 0)
                eod = true;

            switch (state) {
            case READING_META:
                if (eod) {
                    writer.meta(sb);
                    break;
                }
                for (; bytesBuffered > bufferPos; bufferPos++) {
                    byte b = buffer[bufferPos];
                    if (b == '\0') {
                        bufferPos++;
                        state = READING_LABEL;
                        rowId = writer.meta(sb);
                        sb = new StringBuilder();
                        break;
                    }
                    sb.append((char) b);
                }
                break;
            case READING_LABEL:
                if (eod)
                    break;

                for (; bytesBuffered > bufferPos; bufferPos++) {
                    byte b = buffer[bufferPos];
                    if (b == '\0') {
                        label = sb.toString();
                        bufferPos++;
                        state = READING_PAYLOAD_SIZE;
                        payloadPos = 0;
                        break;
                    }
                    sb.append((char) b);
                }
                break;
            case READING_PAYLOAD_SIZE:
                if ((bytesBuffered - bufferPos) < (payloadSizeBuf.length - payloadPos)) {
                    // buffer doesn't contain the last byte of the length
                    for (; bytesBuffered > bufferPos; bufferPos++, payloadPos++) {
                        payloadSizeBuf[payloadPos] = buffer[bufferPos];
                    }
                } else {
                    // buffer contains the last byte of the length
                    for (; payloadSizeBuf.length > payloadPos; bufferPos++, payloadPos++) {
                        payloadSizeBuf[payloadPos] = buffer[bufferPos];
                    }
                    ByteBuffer dataSizeBuf = ByteBuffer.wrap(payloadSizeBuf);
                    dataSizeBuf.order(ByteOrder.LITTLE_ENDIAN);
                    payloadSize = dataSizeBuf.getInt();
                    payloadBuf = new byte[payloadSize];
                    payloadPos = 0;
                    state = READING_PAYLOAD;
                }
                break;
            case READING_PAYLOAD:
                if ((bytesBuffered - bufferPos) < (payloadSize - payloadPos)) {
                    for (; bytesBuffered > bufferPos; bufferPos++, payloadPos++) {
                        payloadBuf[payloadPos] = buffer[bufferPos];
                    }
                } else {
                    for (; payloadSize > payloadPos; bufferPos++, payloadPos++) {
                        payloadBuf[payloadPos] = buffer[bufferPos];
                    }

                    payloadPos = 0;
                    state = READING_PAYLOAD_CHECK;
                }
                break;
            case READING_PAYLOAD_CHECK:
                if ((bytesBuffered - bufferPos) < (payloadSizeBuf.length - payloadPos)) {
                    for (; bytesBuffered > bufferPos; bufferPos++, payloadPos++) {
                        payloadSizeBuf[payloadPos] = buffer[bufferPos];
                    }
                } else {
                    for (; payloadSizeBuf.length > payloadPos; bufferPos++, payloadPos++) {
                        payloadSizeBuf[payloadPos] = buffer[bufferPos];
                    }
                    ByteBuffer dataSizeBuf = ByteBuffer.wrap(payloadSizeBuf);
                    dataSizeBuf.order(ByteOrder.LITTLE_ENDIAN);
                    if (payloadSize != dataSizeBuf.getInt()) {
                        logger.error("message garbled {} {}", payloadSize, dataSizeBuf.getInt());
                        state = READING_LABEL;
                        break;
                    }
                    writer.payload(rowId, label, payloadBuf);
                    state = READING_LABEL;
                }
                break;
            }
        }
        bufferedInput.close();
    } catch (IOException e) {
        logger.error("could not read serialized file");
        return -1;
    }
    return rowId;
}

From source file:trendplot.TrendPlot.java

private void findMinMax(String datFileName) throws FileNotFoundException, IOException {
    File datFile = new File(datFileName);
    try (BufferedInputStream ins = new BufferedInputStream(new FileInputStream(datFile))) {
        boolean eof = false;
        min = Float.MAX_VALUE;//from w w  w.j  a  v  a2 s . com
        minMax = Float.MIN_VALUE;
        max = Float.MIN_VALUE;
        maxMin = Float.MAX_VALUE;
        tmin = Float.MAX_VALUE;
        tmax = Float.MIN_VALUE;
        byte[] b = new byte[Float.SIZE / 8];
        int count = 0;
        int nread;
        while (!eof) {
            try {
                nread = ins.read(b);
                float time = ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).getFloat();
                nread += ins.read(b);
                float inmin = ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).getFloat();
                nread += ins.read(b);
                float mean = ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).getFloat();
                nread += ins.read(b);
                float inmax = ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).getFloat();
                if (nread == Float.SIZE / 8 * 4) {
                    count++;
                    tmin = Math.min(tmin, time);
                    tmax = Math.max(tmax, time);
                    min = Math.min(min, inmin);
                    minMax = Math.max(minMax, inmin);
                    max = Math.max(max, inmax);
                    maxMin = Math.min(maxMin, inmax);
                } else {
                    eof = true;
                    ins.close();
                }
            } catch (EOFException ex) {
                eof = true;
                ins.close();
            } catch (IOException ex) {
                ins.close();
                throw ex;
            }
        }
    }
}