Example usage for java.nio ByteOrder BIG_ENDIAN

List of usage examples for java.nio ByteOrder BIG_ENDIAN

Introduction

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

Prototype

ByteOrder BIG_ENDIAN

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

Click Source Link

Document

This constant represents big endian.

Usage

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

public boolean getNeedleHeaderFromBuffer(ByteBuffer input) throws Exception {
    try {/* w  ww.j  av  a 2 s.com*/
        // 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:ome.formats.importer.OMEROWrapper.java

/**
 * Obtains an object which represents a given sub-image of a plane within
 * the file.// w w  w  .j a  v a2  s.c o  m
 * @param id The path to the file.
 * @param planeNumber The plane or section within the file to obtain.
 * @param buf Pre-allocated buffer which has a <i>length</i> that can fit
 * the byte count of the sub-image.
 * @param x X coordinate of the upper-left corner of the sub-image
 * @param y Y coordinate of the upper-left corner of the sub-image
 * @param w width of the sub-image
 * @param h height of the sub-image
 * @return an object which represents the sub-image of the plane.
 * @throws FormatException If there is an error parsing the file.
 * @throws IOException If there is an error reading from the file or
 * acquiring permissions to read the file.
 */
public PixelData openPlane2D(String id, int planeNumber, byte[] buf, int x, int y, int w, int h)
        throws FormatException, IOException {
    // FIXME: HACK! The ChannelSeparator isn't exactly what one would call
    // "complete" so we have to work around the fact that it still copies
    // all of the plane data (all three channels) from the file if the file
    // is RGB.
    ByteBuffer plane;
    if (iReader.isRGB() || isLeicaReader()) {
        // System.err.println("RGB, not using cached buffer.");
        byte[] bytePlane = openBytes(planeNumber, x, y, w, h);
        plane = ByteBuffer.wrap(bytePlane);
    } else {
        // System.err.println("Not RGB, using cached buffer.");
        plane = ByteBuffer.wrap(openBytes(planeNumber, buf, x, y, w, h));
    }
    plane.order(isLittleEndian() ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN);
    return new PixelData(FormatTools.getPixelTypeString(getPixelType()), plane);
}

From source file:org.apache.nifi.processors.evtx.parser.BinaryReader.java

/**
 * Reads 4 bytes in big endian order and returns the UnsignedInteger value
 *
 * @return the value//from ww w  .  j a va 2  s  .c  o  m
 */
public UnsignedInteger readDWordBE() {
    ByteBuffer byteBuffer = ByteBuffer.wrap(bytes, position, 4);
    position += 4;
    return UnsignedInteger.fromIntBits(byteBuffer.order(ByteOrder.BIG_ENDIAN).getInt());
}

From source file:ffx.xray.parsers.MTZFilter.java

/**
 * {@inheritDoc}//from w ww  .  j a v  a 2  s .  c o m
 */
@Override
public ReflectionList getReflectionList(File mtzFile, CompositeConfiguration properties) {
    ByteOrder byteOrder = ByteOrder.nativeOrder();
    FileInputStream fileInputStream;
    DataInputStream dataInputStream;
    try {
        fileInputStream = new FileInputStream(mtzFile);
        dataInputStream = new DataInputStream(fileInputStream);

        byte headerOffset[] = new byte[4];
        byte bytes[] = new byte[80];
        int offset = 0;

        // Eat "MTZ" title.
        dataInputStream.read(bytes, offset, 4);
        String mtzstr = new String(bytes);

        // Header offset.
        dataInputStream.read(headerOffset, offset, 4);

        // Machine stamp.
        dataInputStream.read(bytes, offset, 4);
        ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
        int stamp = byteBuffer.order(ByteOrder.BIG_ENDIAN).getInt();
        String stampstr = Integer.toHexString(stamp);
        switch (stampstr.charAt(0)) {
        case '1':
        case '3':
            if (byteOrder.equals(ByteOrder.LITTLE_ENDIAN)) {
                byteOrder = ByteOrder.BIG_ENDIAN;
            }
            break;
        case '4':
            if (byteOrder.equals(ByteOrder.BIG_ENDIAN)) {
                byteOrder = ByteOrder.LITTLE_ENDIAN;
            }
            break;
        }

        byteBuffer = ByteBuffer.wrap(headerOffset);
        int headerOffsetI = byteBuffer.order(byteOrder).getInt();

        // skip to header and parse
        dataInputStream.skipBytes((headerOffsetI - 4) * 4);

        for (Boolean parsing = true; parsing; dataInputStream.read(bytes, offset, 80)) {
            mtzstr = new String(bytes);
            parsing = parseHeader(mtzstr);
        }
    } catch (EOFException e) {
        String message = " MTZ end of file reached.";
        logger.log(Level.WARNING, message, e);
        return null;
    } catch (IOException e) {
        String message = " MTZ IO exception.";
        logger.log(Level.WARNING, message, e);
        return null;
    }

    // column identifiers
    foString = sigFoString = rFreeString = null;
    if (properties != null) {
        foString = properties.getString("fostring", null);
        sigFoString = properties.getString("sigfostring", null);
        rFreeString = properties.getString("rfreestring", null);
    }
    h = k = l = fo = sigFo = rFree = -1;
    fPlus = sigFPlus = fMinus = sigFMinus = rFreePlus = rFreeMinus = -1;
    fc = phiC = -1;
    boolean print = false;
    parseColumns(print);
    parseFcColumns(print);

    if (fo < 0 && fPlus < 0 && sigFo < 0 && sigFPlus < 0 && fc < 0 && phiC < 0) {
        logger.info(" The MTZ header contains insufficient information to generate the reflection list.");
        logger.info(" For non-default column labels set fostring/sigfostring in the properties file.");
        return null;
    }

    Column column;
    if (fo > 0) {
        column = (Column) columns.get(fo);
    } else if (fPlus > 0) {
        column = (Column) columns.get(fPlus);
    } else {
        column = (Column) columns.get(fc);
    }
    Dataset dataSet = (Dataset) dataSets.get(column.id - dsetOffset);

    if (logger.isLoggable(Level.INFO)) {
        StringBuilder sb = new StringBuilder();
        sb.append(format("\n Reading %s\n\n", mtzFile.getName()));
        sb.append(format(" Setting up reflection list based on MTZ file.\n"));
        sb.append(format("  Space group number: %d (name: %s)\n", spaceGroupNum,
                SpaceGroup.spaceGroupNames[spaceGroupNum - 1]));
        sb.append(format("  Resolution:         %8.3f\n", 0.999999 * resHigh));
        sb.append(format("  Cell:               %8.3f %8.3f %8.3f %8.3f %8.3f %8.3f\n", dataSet.cell[0],
                dataSet.cell[1], dataSet.cell[2], dataSet.cell[3], dataSet.cell[4], dataSet.cell[5]));
        logger.info(sb.toString());
    }

    Crystal crystal = new Crystal(dataSet.cell[0], dataSet.cell[1], dataSet.cell[2], dataSet.cell[3],
            dataSet.cell[4], dataSet.cell[5], SpaceGroup.spaceGroupNames[spaceGroupNum - 1]);

    double sampling = 0.6;
    if (properties != null) {
        sampling = properties.getDouble("sampling", 0.6);
    }
    Resolution resolution = new Resolution(0.999999 * resHigh, sampling);

    return new ReflectionList(crystal, resolution, properties);
}

From source file:ffx.realspace.CCP4MapFilter.java

/**
 * {@inheritDoc}/*from  ww w  .  j  ava2 s . com*/
 */
@Override
public boolean readFile(String filename, RealSpaceRefinementData refinementdata,
        CompositeConfiguration properties) {

    int imapData;
    double cellA, cellB, cellC, cellAlpha, cellBeta, cellGamma;
    String stampString;

    ByteOrder byteOrder = ByteOrder.nativeOrder();
    FileInputStream fileInputStream;
    DataInputStream dataInputStream;

    double min = Double.POSITIVE_INFINITY;
    double max = Double.NEGATIVE_INFINITY;
    double mean = 0.0;
    double sd = 0.0;
    double rmsd = 0.0;

    // First determine byte order of file versus system
    try {
        fileInputStream = new FileInputStream(filename);
        dataInputStream = new DataInputStream(fileInputStream);

        dataInputStream.skipBytes(212);
        byte bytes[] = new byte[4];
        dataInputStream.read(bytes, 0, 4);
        ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);

        imapData = byteBuffer.order(ByteOrder.BIG_ENDIAN).getInt();
        stampString = Integer.toHexString(imapData);
        switch (stampString.charAt(0)) {
        case '1':
        case '3':
            if (byteOrder.equals(ByteOrder.LITTLE_ENDIAN)) {
                byteOrder = ByteOrder.BIG_ENDIAN;
            }
            break;
        case '4':
            if (byteOrder.equals(ByteOrder.BIG_ENDIAN)) {
                byteOrder = ByteOrder.LITTLE_ENDIAN;
            }
            break;
        }
        if (logger.isLoggable(Level.INFO)) {
            StringBuilder sb = new StringBuilder();
            sb.append(String.format("\n Opening CCP4 map: %s\n", filename));
            //sb.append(String.format("file type (machine stamp): %s\n", stampString));
            logger.info(sb.toString());
        }

        fileInputStream.close();
    } catch (Exception e) {
        String message = " Fatal exception reading CCP4 map.\n";
        logger.log(Level.SEVERE, message, e);
    }

    try {
        fileInputStream = new FileInputStream(filename);
        dataInputStream = new DataInputStream(fileInputStream);

        byte bytes[] = new byte[2048];

        dataInputStream.read(bytes, 0, 1024);
        ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);

        int ext[] = new int[3];
        ext[0] = byteBuffer.order(byteOrder).getInt();
        ext[1] = byteBuffer.order(byteOrder).getInt();
        ext[2] = byteBuffer.order(byteOrder).getInt();

        // mode (2 = reals, only one we accept)
        int mode = byteBuffer.order(byteOrder).getInt();

        int ori[] = new int[3];
        ori[0] = byteBuffer.order(byteOrder).getInt();
        ori[1] = byteBuffer.order(byteOrder).getInt();
        ori[2] = byteBuffer.order(byteOrder).getInt();

        int ni[] = new int[3];
        ni[0] = byteBuffer.order(byteOrder).getInt();
        ni[1] = byteBuffer.order(byteOrder).getInt();
        ni[2] = byteBuffer.order(byteOrder).getInt();

        cellA = byteBuffer.order(byteOrder).getFloat();
        cellB = byteBuffer.order(byteOrder).getFloat();
        cellC = byteBuffer.order(byteOrder).getFloat();
        cellAlpha = byteBuffer.order(byteOrder).getFloat();
        cellBeta = byteBuffer.order(byteOrder).getFloat();
        cellGamma = byteBuffer.order(byteOrder).getFloat();

        int axisi[] = new int[3];
        for (int i = 0; i < 3; i++) {
            int axis = byteBuffer.order(byteOrder).getInt();
            switch (axis) {
            case 1:
                axisi[0] = i;
                break;
            case 2:
                axisi[1] = i;
                break;
            case 3:
                axisi[2] = i;
                break;
            }
        }

        min = byteBuffer.order(byteOrder).getFloat();
        max = byteBuffer.order(byteOrder).getFloat();
        mean = byteBuffer.order(byteOrder).getFloat();
        int sg = byteBuffer.order(byteOrder).getInt();
        int nsymb = byteBuffer.order(byteOrder).getInt();
        int skew = byteBuffer.order(byteOrder).getInt();

        for (int i = 0; i < 12; i++) {
            byteBuffer.order(byteOrder).getFloat();
        }

        for (int i = 0; i < 15; i++) {
            byteBuffer.order(byteOrder).getInt();
        }

        byte word[] = new byte[2048];
        byteBuffer.order(byteOrder).get(word, 0, 4);
        String mapString = new String(word);
        sd = byteBuffer.order(byteOrder).getFloat();
        rmsd = byteBuffer.order(byteOrder).getFloat();

        if (logger.isLoggable(Level.INFO)) {
            StringBuilder sb = new StringBuilder();
            sb.append(String.format("  Column origin:  %d\t Extent: %d\n", ori[0], ext[0]));
            sb.append(String.format("  Row origin:     %d\t Extent: %d\n", ori[1], ext[1]));
            sb.append(String.format("  Section origin: %d\t Extent: %d\n", ori[2], ext[2]));
            sb.append(String.format("  Axis order:     %d %d %d\n", axisi[0], axisi[1], axisi[2]));
            sb.append(String.format("  Number of X, Y, Z columns: %d %d %d\n", ni[0], ni[1], ni[2]));
            sb.append(String.format("  Spacegroup:     %d (%s)\n", sg, SpaceGroup.spaceGroupNames[sg - 1]));
            sb.append(String.format("  Cell: %8.3f %8.3f %8.3f %8.3f %8.3f %8.3f\n", cellA, cellB, cellC,
                    cellAlpha, cellBeta, cellGamma));
            logger.info(sb.toString());
        }

        int nlabel = byteBuffer.order(byteOrder).getInt();
        for (int i = 0; i < 10; i++) {
            byteBuffer.order(byteOrder).get(word, 0, 80);
            mapString = new String(word);
        }

        if (nsymb > 0) {
            byteBuffer.rewind();
            dataInputStream.read(bytes, 0, nsymb);
            for (int i = 0; i < nsymb / 80; i += 80) {
                byteBuffer.order(byteOrder).get(word, 0, 80);
                mapString = new String(word);
            }
        }

        byteBuffer.rewind();
        dataInputStream.read(bytes, 0, 2048);
        refinementdata.setData(new double[ext[0] * ext[1] * ext[2]]);
        int ijk[] = new int[3];
        int index, x, y, z;
        refinementdata.setOrigin(ori[axisi[0]], ori[axisi[1]], ori[axisi[2]]);
        int nx = ext[axisi[0]];
        int ny = ext[axisi[1]];
        int nz = ext[axisi[2]];
        refinementdata.setExtent(nx, ny, nz);
        refinementdata.setNI(ni[0], ni[1], ni[2]);
        for (ijk[2] = 0; ijk[2] < ext[2]; ijk[2]++) {
            for (ijk[1] = 0; ijk[1] < ext[1]; ijk[1]++) {
                for (ijk[0] = 0; ijk[0] < ext[0]; ijk[0]++) {
                    x = ijk[axisi[0]];
                    y = ijk[axisi[1]];
                    z = ijk[axisi[2]];
                    index = x + nx * (y + ny * z);
                    refinementdata.getData()[index] = byteBuffer.order(byteOrder).getFloat();
                    if (!byteBuffer.hasRemaining()) {
                        byteBuffer.rewind();
                        dataInputStream.read(bytes, 0, 2048);
                    }
                }
            }
        }
        fileInputStream.close();
    } catch (Exception e) {
        String message = " Fatal exception reading CCP4 map.\n";
        logger.log(Level.SEVERE, message, e);
    }

    return true;
}

From source file:com.slytechs.file.snoop.SnoopFileCapture.java

private void openFile(final File file, Filter<ProtocolFilterTarget> filter)
        throws IOException, FileFormatException {

    if (file.canRead() == false) {
        throw new FileNotFoundException(
                "File [" + file.getName() + "] is not readable, can not open in [" + mode.toString() + "]mode");
    }//w ww.j ava  2s.  c o m

    if (mode.isAppend() || mode.isContent() || mode.isStructure()) {
        if (file.canWrite() == false) {
            throw new FileNotFoundException(
                    "File [" + file.getName() + "] is readonly, can not open in read-write mode");
        }
    }

    this.editor = new FileEditorImpl(file, this.mode, headerReader, ByteOrder.BIG_ENDIAN, filter, this);
    try {
        this.block = new SnoopBlockRecordImpl(this, this.editor);
    } finally {
        if (this.block == null) {
            /*
             * Make sure to close the editor in case any errors occured, otherwise
             * we could keep the file open until the VM terminates
             */
            this.editor.close();
        }
    }

    final Protocol dlt = SnoopDLT.asConst(block.getLinktype());
    setCaptureDevice(new DefaultCaptureDevice(dlt));

    if (logger.isDebugEnabled()) {
        logger.debug("edito=" + editor.getFlexRegion().toString());
    }

}

From source file:org.apache.hadoop.crypto.CryptoStreamsTestBase.java

private void setCounterBaseForIV(byte[] iv, long counterBase) {
    ByteBuffer buf = ByteBuffer.wrap(iv);
    buf.order(ByteOrder.BIG_ENDIAN);
    buf.putLong(iv.length - 8, counterBase);
}

From source file:nl.salp.warcraft4j.casc.cdn.local.LocalIndexFileParser.java

/**
 * Read and parse the index file header.
 *
 * @param reader The reader to read the header data from.
 *
 * @return The parsed index file header.
 *
 * @throws CascParsingException When the header is invalid.
 * @throws DataReadingException When reading the entry data failed.
 * @throws DataParsingException When parsing the entry data failed.
 *///from   w  w w  .  j  a  va  2 s .  co  m
private IndexHeaderV2 parseHeader(DataReader reader)
        throws CascParsingException, DataReadingException, DataParsingException {
    int indexVersion = reader.readNext(DataTypeFactory.getUnsignedShort(), ByteOrder.LITTLE_ENDIAN);
    if (indexVersion != 0x07) {
        throw new CascParsingException(
                format("Invalid index file header version 0x%02X, requires 0x07", indexVersion));
    }
    byte keyIndex = reader.readNext(DataTypeFactory.getByte());
    byte extraBytes = reader.readNext(DataTypeFactory.getByte());
    byte spanSizeBytes = reader.readNext(DataTypeFactory.getByte());
    byte spanOffsetBytes = reader.readNext(DataTypeFactory.getByte());
    byte keyBytes = reader.readNext(DataTypeFactory.getByte());
    byte segmentBits = reader.readNext(DataTypeFactory.getByte());
    long maxFileOffset = reader.readNext(DataTypeFactory.getLong(), ByteOrder.BIG_ENDIAN);
    if (extraBytes != 0x00 || spanSizeBytes != 0x04 || spanOffsetBytes != 0x05 || keyBytes != 0x09) {
        throw new CascParsingException("Invalid index file header");
    }
    return new IndexHeaderV2(indexVersion, keyIndex, extraBytes, spanSizeBytes, spanOffsetBytes, keyBytes,
            segmentBits, maxFileOffset);
}

From source file:org.kalypso.grid.BinaryGeoGrid.java

/**
 * @param binFile//from   w  ww . jav  a  2 s. c om
 *          If set, this file will be deleted on dispose
 */
protected BinaryGeoGrid(final FileChannel channel, final File binFile, final Coordinate origin,
        final Coordinate offsetX, final Coordinate offsetY, final String sourceCRS) throws IOException {
    super(origin, offsetX, offsetY, sourceCRS);

    m_binFile = binFile;
    m_channel = channel;

    /* Read header */
    m_channel.position(0);

    m_header = BinaryGeoGridHeader.read(m_channel);

    m_readBuffer = ByteBuffer.allocate(4 * getSizeX() * BUFFER_LINES);
    m_readBuffer.order(ByteOrder.BIG_ENDIAN);

    /* mark buffer as not writable */
    // TODO: prohibits that a grid may be opened for reading AND writing; we should give this information from outside
    m_writeBuffer = null;

    /* Read statistical data */
    readStatistically();
}

From source file:eu.faircode.netguard.SinkholeService.java

private void startDebug(final ParcelFileDescriptor pfd) {
    if (!debug)//  w  w w .  j a  v  a  2s. c o  m
        return;

    thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                FileInputStream in = new FileInputStream(pfd.getFileDescriptor());
                FileOutputStream out = new FileOutputStream(pfd.getFileDescriptor());

                ByteBuffer buffer = ByteBuffer.allocate(32767);
                buffer.order(ByteOrder.BIG_ENDIAN);

                Log.i(TAG, "Start receiving");
                while (!Thread.currentThread().isInterrupted() && pfd.getFileDescriptor() != null
                        && pfd.getFileDescriptor().valid())
                    try {
                        buffer.clear();
                        int length = in.read(buffer.array());
                        if (length > 0) {
                            buffer.limit(length);
                            Packet pkt = new Packet(buffer);

                            if (pkt.IPv4.protocol == Packet.IPv4Header.TCP && pkt.TCP.SYN) {
                                int uid = pkt.getUid4();
                                if (uid < 0)
                                    Log.w(TAG, "uid not found");

                                String[] pkg = getPackageManager().getPackagesForUid(uid);
                                if (pkg == null)
                                    pkg = new String[] { uid == 0 ? "root" : "unknown" };

                                Log.i(TAG, "Connect " + pkt.IPv4.destinationAddress + ":"
                                        + pkt.TCP.destinationPort + " uid=" + uid + " pkg=" + pkg[0]);

                                // Send RST
                                pkt.swapAddresses();
                                pkt.TCP.clearFlags();
                                pkt.TCP.RST = true;
                                long ack = pkt.TCP.acknowledgementNumber;
                                pkt.TCP.acknowledgementNumber = (pkt.TCP.sequenceNumber + 1) & 0xFFFFFFFFL;
                                pkt.TCP.sequenceNumber = (ack + 1) & 0xFFFFFFFFL;
                                pkt.send(out);
                            }
                        }
                    } catch (Throwable ex) {
                        Log.e(TAG, ex.toString());
                    }
                Log.i(TAG, "End receiving");
            } catch (Throwable ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
            }
        }
    });
    thread.start();
}