Example usage for java.io DataInputStream skipBytes

List of usage examples for java.io DataInputStream skipBytes

Introduction

In this page you can find the example usage for java.io DataInputStream skipBytes.

Prototype

public final int skipBytes(int n) throws IOException 

Source Link

Document

See the general contract of the skipBytes method of DataInput.

Usage

From source file:fr.noop.subtitle.stl.StlParser.java

private StlGsi readGsi(DataInputStream dis) throws IOException, InvalidTimeRangeException {
    // Read and extract metadata from GSI block
    // GSI block is 1024 bytes long
    StlGsi gsi = new StlGsi();

    // Read Code Page Number (CPN)
    byte[] cpnBytes = new byte[3];
    dis.readFully(cpnBytes, 0, 3);/*from w w  w  .  jav a 2s .co m*/
    int cpn = cpnBytes[0] << 16 | cpnBytes[1] << 8 | cpnBytes[2];
    gsi.setCpn(StlGsi.Cpn.getEnum(cpn));

    // Read Disk Format Code (DFC)
    gsi.setDfc(StlGsi.Dfc.getEnum(this.readString(dis, 8)));

    // Read Display Standard Code (DSC)
    gsi.setDsc(StlGsi.Dsc.getEnum(dis.readUnsignedByte()));

    // Read Character Code Table number (CCT)
    gsi.setCct(StlGsi.Cct.getEnum(Short.reverseBytes(dis.readShort())));

    // Read Character Language Code (LC)
    gsi.setLc(Short.reverseBytes(dis.readShort()));

    // Read Original Programme Title (OPT)
    gsi.setOpt(this.readString(dis, 32));

    // Read Original Programme Title (OET)
    gsi.setOet(this.readString(dis, 32));

    // Read Translated Programme Title (TPT)
    gsi.setTpt(this.readString(dis, 32));

    // Read translated Episode Title (TET)
    gsi.setTet(this.readString(dis, 32));

    // Read Translator's Name (TN)
    gsi.setTn(this.readString(dis, 32));

    // Read Translator's Contact Details (TCD)
    gsi.setTcd(this.readString(dis, 32));

    // Read Subtitle List Reference Code (SLR)
    gsi.setSlr(this.readString(dis, 16));

    // Read Creation Date (CD)
    gsi.setCd(this.readDate(this.readString(dis, 6)));

    // Read Revision Date (RD)
    gsi.setRd(this.readDate(this.readString(dis, 6)));

    // Read Revision number RN
    gsi.setRn(Short.reverseBytes(dis.readShort()));

    // Read Total Number of Text and Timing Information (TTI) blocks (TNB)
    gsi.setTnb(Integer.parseInt(this.readString(dis, 5)));

    // Read Total Number of Subtitles (TNS)
    gsi.setTns(Integer.parseInt(this.readString(dis, 5)));

    // Read Total Number of Subtitle Groups (TNG)
    dis.skipBytes(3);

    // Read Maximum Number of Displayable Characters in any text row (MNC)
    gsi.setMnc(Integer.parseInt(this.readString(dis, 2)));

    // Read Maximum Number of Displayable Rows (MNR)
    gsi.setMnr(Integer.parseInt(this.readString(dis, 2)));

    // Read Time Code: Status (TCS)
    gsi.setTcs((short) dis.readUnsignedByte());

    // Read Time Code: Start-of-Programme (TCP)
    gsi.setTcp(this.readTimeCode(this.readString(dis, 8), gsi.getDfc().getFrameRate()));

    // Read Time Code: First In-Cue (TCF)
    gsi.setTcf(this.readTimeCode(this.readString(dis, 8), gsi.getDfc().getFrameRate()));

    // Read Total Number of Disks (TND)
    gsi.setTnd((short) dis.readUnsignedByte());

    // Read Disk Sequence Number (DSN)
    gsi.setDsn((short) dis.readUnsignedByte());

    // Read Country of Origin (CO)
    gsi.setCo(this.readString(dis, 3));

    // Read Publisher (PUB)
    gsi.setPub(this.readString(dis, 32));

    // Read Editor's Name (EN)
    gsi.setEn(this.readString(dis, 32));

    // Read Editor's Contact Details (ECD)
    gsi.setEcd(this.readString(dis, 32));

    // Spare Bytes
    dis.skipBytes(75);

    // Read User-Defined Area (UDA)
    gsi.setUda(this.readString(dis, 576));

    return gsi;
}

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

/**
 * {@inheritDoc}//w  ww .ja  v a2s .  com
 */
@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.xray.parsers.MTZFilter.java

/**
 * Read the structure factors./*from   ww w .j  a  v a 2  s  . co  m*/
 *
 * @param mtzFile
 * @param reflectionList
 * @param fcData
 * @param properties
 * @return
 */
public boolean readFcs(File mtzFile, ReflectionList reflectionList, DiffractionRefinementData fcData,
        CompositeConfiguration properties) {

    int nRead, nIgnore, nRes, nFriedel, nCut;
    ByteOrder byteOrder = ByteOrder.nativeOrder();
    FileInputStream fileInputStream;
    DataInputStream dataInputStream;

    StringBuilder sb = new StringBuilder();
    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 mtzString = null;

        // 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 stampString = Integer.toHexString(stamp);
        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;
        }

        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)) {
            mtzString = new String(bytes);
            parsing = parseHeader(mtzString);
        }

        // Column identifiers.
        fc = phiC = fs = phiS = -1;
        boolean print = true;
        parseFcColumns(print);

        if (h < 0 || k < 0 || l < 0) {
            String message = " Fatal error in MTZ file - no H K L indexes?\n";
            logger.log(Level.SEVERE, message);
            return false;
        }

        // Reopen to start at beginning.
        fileInputStream = new FileInputStream(mtzFile);
        dataInputStream = new DataInputStream(fileInputStream);

        // Skip initial header.
        dataInputStream.skipBytes(80);

        float data[] = new float[nColumns];
        HKL mate = new HKL();

        // Read in data.
        ComplexNumber complexNumber = new ComplexNumber();
        nRead = nIgnore = nRes = nFriedel = nCut = 0;
        for (int i = 0; i < nReflections; i++) {
            for (int j = 0; j < nColumns; j++) {
                dataInputStream.read(bytes, offset, 4);
                byteBuffer = ByteBuffer.wrap(bytes);
                data[j] = byteBuffer.order(byteOrder).getFloat();
            }
            int ih = (int) data[h];
            int ik = (int) data[k];
            int il = (int) data[l];
            boolean friedel = reflectionList.findSymHKL(ih, ik, il, mate, false);
            HKL hkl = reflectionList.getHKL(mate);

            if (hkl != null) {
                if (fc > 0 && phiC > 0) {
                    complexNumber.re(data[fc] * cos(toRadians(data[phiC])));
                    complexNumber.im(data[fc] * sin(toRadians(data[phiC])));
                    fcData.setFc(hkl.index(), complexNumber);
                }
                if (fs > 0 && phiS > 0) {
                    complexNumber.re(data[fs] * cos(toRadians(data[phiS])));
                    complexNumber.im(data[fs] * sin(toRadians(data[phiS])));
                    fcData.setFs(hkl.index(), complexNumber);
                }
                nRead++;
            } else {
                HKL tmp = new HKL(ih, ik, il);
                if (!reflectionList.resolution
                        .inInverseResSqRange(Crystal.invressq(reflectionList.crystal, tmp))) {
                    nRes++;
                } else {
                    nIgnore++;
                }
            }
        }

        if (logger.isLoggable(Level.INFO)) {
            sb.append(format(" MTZ file type (machine stamp): %s\n", stampString));
            sb.append(format(" Fc HKL read in:                             %d\n", nRead));
            sb.append(format(" Fc HKL read as friedel mates:               %d\n", nFriedel));
            sb.append(format(" Fc HKL NOT read in (too high resolution):   %d\n", nRes));
            sb.append(format(" Fc HKL NOT read in (not in internal list?): %d\n", nIgnore));
            sb.append(format(" Fc HKL NOT read in (F/sigF cutoff):         %d\n", nCut));
            sb.append(
                    format(" HKL in internal list:                       %d\n", reflectionList.hkllist.size()));
            logger.info(sb.toString());
        }
    } catch (EOFException e) {
        String message = " MTZ end of file reached.";
        logger.log(Level.WARNING, message, e);
        return false;
    } catch (IOException e) {
        String message = " MTZ IO Exception.";
        logger.log(Level.WARNING, message, e);
        return false;
    }

    return true;
}

From source file:ffx.xray.MTZFilter.java

/**
 * {@inheritDoc}//from  www .j a v  a 2s  .  co m
 */
@Override
public boolean readFile(File mtzFile, ReflectionList reflectionlist, DiffractionRefinementData refinementdata,
        CompositeConfiguration properties) {
    int nread, nignore, nres, nfriedel, ncut;
    ByteOrder b = ByteOrder.nativeOrder();
    FileInputStream fis;
    DataInputStream dis;
    boolean transpose = false;

    StringBuilder sb = new StringBuilder();
    //sb.append(String.format("\n Opening %s\n", mtzFile.getName()));
    try {
        fis = new FileInputStream(mtzFile);
        dis = new DataInputStream(fis);

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

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

        // header offset
        dis.read(headeroffset, offset, 4);

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

        bb = ByteBuffer.wrap(headeroffset);
        int headeroffseti = bb.order(b).getInt();

        // skip to header and parse
        dis.skipBytes((headeroffseti - 4) * 4);

        for (Boolean parsing = true; parsing; dis.read(bytes, offset, 80)) {
            mtzstr = new String(bytes);
            parsing = parseHeader(mtzstr);
        }

        // 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;
        boolean print = true;
        parseColumns(print);

        if (h < 0 || k < 0 || l < 0) {
            String message = "Fatal error in MTZ file - no H K L indexes?\n";
            logger.log(Level.SEVERE, message);
            return false;
        }

        // reopen to start at beginning
        fis = new FileInputStream(mtzFile);
        dis = new DataInputStream(fis);

        // skip initial header
        dis.skipBytes(80);

        // check if HKLs need to be transposed or not
        float data[] = new float[nColumns];
        HKL mate = new HKL();
        int nposignore = 0;
        int ntransignore = 0;
        int nzero = 0;
        int none = 0;
        for (int i = 0; i < nReflections; i++) {
            for (int j = 0; j < nColumns; j++) {
                dis.read(bytes, offset, 4);
                bb = ByteBuffer.wrap(bytes);
                data[j] = bb.order(b).getFloat();
            }
            int ih = (int) data[h];
            int ik = (int) data[k];
            int il = (int) data[l];
            boolean friedel = reflectionlist.findSymHKL(ih, ik, il, mate, false);
            HKL hklpos = reflectionlist.getHKL(mate);
            if (hklpos == null) {
                nposignore++;
            }

            friedel = reflectionlist.findSymHKL(ih, ik, il, mate, true);
            HKL hkltrans = reflectionlist.getHKL(mate);
            if (hkltrans == null) {
                ntransignore++;
            }
            if (rfree > 0) {
                if (((int) data[rfree]) == 0) {
                    nzero++;
                } else if (((int) data[rfree]) == 1) {
                    none++;
                }
            }
            if (rfreeplus > 0) {
                if (((int) data[rfreeplus]) == 0) {
                    nzero++;
                } else if (((int) data[rfreeplus]) == 1) {
                    none++;
                }
            }
            if (rfreeminus > 0) {
                if (((int) data[rfreeminus]) == 0) {
                    nzero++;
                } else if (((int) data[rfreeminus]) == 1) {
                    none++;
                }
            }
        }
        if (nposignore > ntransignore) {
            transpose = true;
        }

        if (none > (nzero * 2) && refinementdata.rfreeflag < 0) {
            refinementdata.setFreeRFlag(0);
            sb.append(String.format(" Setting R free flag to %d based on MTZ file data.\n",
                    refinementdata.rfreeflag));
        } else if (nzero > (none * 2) && refinementdata.rfreeflag < 0) {
            refinementdata.setFreeRFlag(1);
            sb.append(String.format(" Setting R free flag to %d based on MTZ file data.\n",
                    refinementdata.rfreeflag));
        } else if (refinementdata.rfreeflag < 0) {
            refinementdata.setFreeRFlag(0);
            sb.append(String.format(" Setting R free flag to MTZ default: %d\n", refinementdata.rfreeflag));
        }

        // reopen to start at beginning
        fis = new FileInputStream(mtzFile);
        dis = new DataInputStream(fis);

        // skip initial header
        dis.skipBytes(80);

        // read in data
        double anofsigf[][] = new double[refinementdata.n][4];
        for (int i = 0; i < refinementdata.n; i++) {
            anofsigf[i][0] = anofsigf[i][1] = anofsigf[i][2] = anofsigf[i][3] = Double.NaN;
        }
        nread = nignore = nres = nfriedel = ncut = 0;
        for (int i = 0; i < nReflections; i++) {
            for (int j = 0; j < nColumns; j++) {
                dis.read(bytes, offset, 4);
                bb = ByteBuffer.wrap(bytes);
                data[j] = bb.order(b).getFloat();
            }
            int ih = (int) data[h];
            int ik = (int) data[k];
            int il = (int) data[l];
            boolean friedel = reflectionlist.findSymHKL(ih, ik, il, mate, transpose);
            HKL hkl = reflectionlist.getHKL(mate);

            if (hkl != null) {
                if (fo > 0 && sigfo > 0) {
                    if (refinementdata.fsigfcutoff > 0.0) {
                        if ((data[fo] / data[sigfo]) < refinementdata.fsigfcutoff) {
                            ncut++;
                            continue;
                        }
                    }
                    if (friedel) {
                        anofsigf[hkl.index()][2] = data[fo];
                        anofsigf[hkl.index()][3] = data[sigfo];
                        nfriedel++;
                    } else {
                        anofsigf[hkl.index()][0] = data[fo];
                        anofsigf[hkl.index()][1] = data[sigfo];
                    }
                } else {
                    if (fplus > 0 && sigfplus > 0) {
                        if (refinementdata.fsigfcutoff > 0.0) {
                            if ((data[fplus] / data[sigfplus]) < refinementdata.fsigfcutoff) {
                                ncut++;
                                continue;
                            }
                        }
                        anofsigf[hkl.index()][0] = data[fplus];
                        anofsigf[hkl.index()][1] = data[sigfplus];
                    }
                    if (fminus > 0 && sigfminus > 0) {
                        if (refinementdata.fsigfcutoff > 0.0) {
                            if ((data[fminus] / data[sigfminus]) < refinementdata.fsigfcutoff) {
                                ncut++;
                                continue;
                            }
                        }
                        anofsigf[hkl.index()][2] = data[fminus];
                        anofsigf[hkl.index()][3] = data[sigfminus];
                    }
                }
                if (rfree > 0) {
                    refinementdata.setFreeR(hkl.index(), (int) data[rfree]);
                } else {
                    if (rfreeplus > 0 && rfreeminus > 0) {
                        // not sure what the correct thing to do here is?
                        refinementdata.setFreeR(hkl.index(), (int) data[rfreeplus]);
                    } else if (rfreeplus > 0) {
                        refinementdata.setFreeR(hkl.index(), (int) data[rfreeplus]);
                    } else if (rfreeminus > 0) {
                        refinementdata.setFreeR(hkl.index(), (int) data[rfreeminus]);
                    }
                }
                nread++;
            } else {
                HKL tmp = new HKL(ih, ik, il);
                if (!reflectionlist.resolution
                        .inInverseResSqRange(Crystal.invressq(reflectionlist.crystal, tmp))) {
                    nres++;
                } else {
                    nignore++;
                }
            }
        }

        // set up fsigf from F+ and F-
        refinementdata.generate_fsigf_from_anofsigf(anofsigf);

        sb.append(String.format(" MTZ file type (machine stamp): %s\n", stampstr));
        sb.append(String.format(" HKL data is %s\n", transpose ? "transposed" : "not transposed"));
        sb.append(String.format(" HKL read in:                             %d\n", nread));
        sb.append(String.format(" HKL read as friedel mates:               %d\n", nfriedel));
        sb.append(String.format(" HKL NOT read in (too high resolution):   %d\n", nres));
        sb.append(String.format(" HKL NOT read in (not in internal list?): %d\n", nignore));
        sb.append(String.format(" HKL NOT read in (F/sigF cutoff):         %d\n", ncut));
        sb.append(
                String.format(" HKL in internal list:                    %d\n", reflectionlist.hkllist.size()));
        if (logger.isLoggable(Level.INFO)) {
            logger.info(sb.toString());
        }

        if (rfree < 0 && rfreeplus < 0 && rfreeminus < 0) {
            refinementdata.generateRFree();
        }
    } catch (EOFException eof) {
        System.out.println("EOF reached ");
        return false;
    } catch (IOException ioe) {
        System.out.println("IO Exception: " + ioe.getMessage());
        return false;
    }

    return true;
}

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

/**
 * {@inheritDoc}//from  w w  w.  j a v  a 2 s. c  o m
 */
@Override
public boolean readFile(File mtzFile, ReflectionList reflectionList, DiffractionRefinementData refinementData,
        CompositeConfiguration properties) {
    int nRead, nIgnore, nRes, nFriedel, nCut;
    ByteOrder byteOrder = ByteOrder.nativeOrder();
    FileInputStream fileInputStream;
    DataInputStream dataInputStream;
    boolean transpose = false;

    StringBuilder sb = new StringBuilder();
    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 = null;

        // 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 stampString = Integer.toHexString(stamp);
        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;
        }

        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);
        }

        // 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;
        boolean print = true;
        parseColumns(print);

        if (h < 0 || k < 0 || l < 0) {
            String message = "Fatal error in MTZ file - no H K L indexes?\n";
            logger.log(Level.SEVERE, message);
            return false;
        }

        // Reopen to start at beginning.
        fileInputStream = new FileInputStream(mtzFile);
        dataInputStream = new DataInputStream(fileInputStream);

        // Skip initial header.
        dataInputStream.skipBytes(80);

        // Check if HKLs need to be transposed or not.
        float data[] = new float[nColumns];
        HKL mate = new HKL();
        int nPosIgnore = 0;
        int nTransIgnore = 0;
        int nZero = 0;
        int none = 0;
        for (int i = 0; i < nReflections; i++) {
            for (int j = 0; j < nColumns; j++) {
                dataInputStream.read(bytes, offset, 4);
                byteBuffer = ByteBuffer.wrap(bytes);
                data[j] = byteBuffer.order(byteOrder).getFloat();
            }
            int ih = (int) data[h];
            int ik = (int) data[k];
            int il = (int) data[l];
            boolean friedel = reflectionList.findSymHKL(ih, ik, il, mate, false);
            HKL hklpos = reflectionList.getHKL(mate);
            if (hklpos == null) {
                nPosIgnore++;
            }

            friedel = reflectionList.findSymHKL(ih, ik, il, mate, true);
            HKL hkltrans = reflectionList.getHKL(mate);
            if (hkltrans == null) {
                nTransIgnore++;
            }
            if (rFree > 0) {
                if (((int) data[rFree]) == 0) {
                    nZero++;
                } else if (((int) data[rFree]) == 1) {
                    none++;
                }
            }
            if (rFreePlus > 0) {
                if (((int) data[rFreePlus]) == 0) {
                    nZero++;
                } else if (((int) data[rFreePlus]) == 1) {
                    none++;
                }
            }
            if (rFreeMinus > 0) {
                if (((int) data[rFreeMinus]) == 0) {
                    nZero++;
                } else if (((int) data[rFreeMinus]) == 1) {
                    none++;
                }
            }
        }
        if (nPosIgnore > nTransIgnore) {
            transpose = true;
        }

        if (none > (nZero * 2) && refinementData.rfreeflag < 0) {
            refinementData.setFreeRFlag(0);
            sb.append(format(" Setting R free flag to %d based on MTZ file data.\n", refinementData.rfreeflag));
        } else if (nZero > (none * 2) && refinementData.rfreeflag < 0) {
            refinementData.setFreeRFlag(1);
            sb.append(format(" Setting R free flag to %d based on MTZ file data.\n", refinementData.rfreeflag));
        } else if (refinementData.rfreeflag < 0) {
            refinementData.setFreeRFlag(0);
            sb.append(format(" Setting R free flag to MTZ default: %d\n", refinementData.rfreeflag));
        }

        // reopen to start at beginning
        fileInputStream = new FileInputStream(mtzFile);
        dataInputStream = new DataInputStream(fileInputStream);

        // skip initial header
        dataInputStream.skipBytes(80);

        // read in data
        double anofSigF[][] = new double[refinementData.n][4];
        for (int i = 0; i < refinementData.n; i++) {
            anofSigF[i][0] = anofSigF[i][1] = anofSigF[i][2] = anofSigF[i][3] = Double.NaN;
        }
        nRead = nIgnore = nRes = nFriedel = nCut = 0;
        for (int i = 0; i < nReflections; i++) {
            for (int j = 0; j < nColumns; j++) {
                dataInputStream.read(bytes, offset, 4);
                byteBuffer = ByteBuffer.wrap(bytes);
                data[j] = byteBuffer.order(byteOrder).getFloat();
            }
            int ih = (int) data[h];
            int ik = (int) data[k];
            int il = (int) data[l];
            boolean friedel = reflectionList.findSymHKL(ih, ik, il, mate, transpose);
            HKL hkl = reflectionList.getHKL(mate);
            if (hkl != null) {
                if (fo > 0 && sigFo > 0) {
                    if (refinementData.fsigfcutoff > 0.0) {
                        if ((data[fo] / data[sigFo]) < refinementData.fsigfcutoff) {
                            nCut++;
                            continue;
                        }
                    }
                    if (friedel) {
                        anofSigF[hkl.index()][2] = data[fo];
                        anofSigF[hkl.index()][3] = data[sigFo];
                        nFriedel++;
                    } else {
                        anofSigF[hkl.index()][0] = data[fo];
                        anofSigF[hkl.index()][1] = data[sigFo];
                    }
                } else {
                    if (fPlus > 0 && sigFPlus > 0) {
                        if (refinementData.fsigfcutoff > 0.0) {
                            if ((data[fPlus] / data[sigFPlus]) < refinementData.fsigfcutoff) {
                                nCut++;
                                continue;
                            }
                        }
                        anofSigF[hkl.index()][0] = data[fPlus];
                        anofSigF[hkl.index()][1] = data[sigFPlus];
                    }
                    if (fMinus > 0 && sigFMinus > 0) {
                        if (refinementData.fsigfcutoff > 0.0) {
                            if ((data[fMinus] / data[sigFMinus]) < refinementData.fsigfcutoff) {
                                nCut++;
                                continue;
                            }
                        }
                        anofSigF[hkl.index()][2] = data[fMinus];
                        anofSigF[hkl.index()][3] = data[sigFMinus];
                    }
                }
                if (rFree > 0) {
                    refinementData.setFreeR(hkl.index(), (int) data[rFree]);
                } else {
                    if (rFreePlus > 0 && rFreeMinus > 0) {
                        // not sure what the correct thing to do here is?
                        refinementData.setFreeR(hkl.index(), (int) data[rFreePlus]);
                    } else if (rFreePlus > 0) {
                        refinementData.setFreeR(hkl.index(), (int) data[rFreePlus]);
                    } else if (rFreeMinus > 0) {
                        refinementData.setFreeR(hkl.index(), (int) data[rFreeMinus]);
                    }
                }
                nRead++;
            } else {
                HKL tmp = new HKL(ih, ik, il);
                if (!reflectionList.resolution
                        .inInverseResSqRange(Crystal.invressq(reflectionList.crystal, tmp))) {
                    nRes++;
                } else {
                    nIgnore++;
                }
            }
        }

        // Set up fsigf from F+ and F-.
        refinementData.generate_fsigf_from_anofsigf(anofSigF);

        // Log results.
        if (logger.isLoggable(Level.INFO)) {
            sb.append(format(" MTZ file type (machine stamp): %s\n", stampString));
            sb.append(format(" HKL data is %s\n", transpose ? "transposed" : "not transposed"));
            sb.append(format(" HKL read in:                             %d\n", nRead));
            sb.append(format(" HKL read as friedel mates:               %d\n", nFriedel));
            sb.append(format(" HKL NOT read in (too high resolution):   %d\n", nRes));
            sb.append(format(" HKL NOT read in (not in internal list?): %d\n", nIgnore));
            sb.append(format(" HKL NOT read in (F/sigF cutoff):         %d\n", nCut));
            sb.append(format(" HKL in internal list:                    %d\n", reflectionList.hkllist.size()));
            logger.info(sb.toString());
        }
        if (rFree < 0 && rFreePlus < 0 && rFreeMinus < 0) {
            refinementData.generateRFree();
        }
    } catch (EOFException e) {
        String message = " MTZ end of file reached.";
        logger.log(Level.WARNING, message, e);
        return false;
    } catch (IOException e) {
        String message = " MTZ IO Exception.";
        logger.log(Level.WARNING, message, e);
        return false;
    }

    return true;
}

From source file:org.opensc.pkcs15.token.impl.CardOSToken.java

private DF selectDFInternal(CommandAPDU cmd, TokenPath targetPath) throws IOException {

    try {/*from  w  w w .ja va 2 s  .  co m*/
        ResponseAPDU resp = this.channel.transmit(cmd);

        DataInputStream dis = getSelectFileData(resp);

        long bodySize = 0;
        int acLifeCycle = TokenFileAcl.AC_ALWAYS;
        int acUpdate = TokenFileAcl.AC_ALWAYS;
        int acAppend = TokenFileAcl.AC_ALWAYS;
        int acDeactivate = TokenFileAcl.AC_ALWAYS;
        int acActivate = TokenFileAcl.AC_ALWAYS;
        int acDelete = TokenFileAcl.AC_ALWAYS;
        int acAdmin = TokenFileAcl.AC_ALWAYS;
        int acCreate = TokenFileAcl.AC_ALWAYS;

        int tag;

        while ((tag = dis.read()) >= 0) {
            int n = dis.read();
            if (n < 0)
                break;

            switch (tag) {
            case 0x81:
                if (n != 2)
                    throw new IOException("Invalid length [" + n + "] of FCI tag 0x81.");
                bodySize = dis.readUnsignedShort();
                break;

            case 0x83:
                if (n != 2)
                    throw new IOException("Invalid length [" + n + "] of FCI tag 0x83.");
                int tpath = dis.readUnsignedShort();
                if (tpath != targetPath.getTailID())
                    throw new IOException("File ID [" + PathHelper.formatID(tpath)
                            + "] reported by SELECT FILE differs from requested ID ["
                            + PathHelper.formatID(targetPath.getTailID()) + "].");
                break;

            case 0x86:
                if (n >= 1)
                    acLifeCycle = dis.read();
                if (n >= 2)
                    acUpdate = dis.read();
                if (n >= 3)
                    acAppend = dis.read();
                if (n >= 4)
                    acDeactivate = dis.read();
                if (n >= 5)
                    acActivate = dis.read();
                if (n >= 6)
                    acDelete = dis.read();
                if (n >= 7)
                    acAdmin = dis.read();
                if (n >= 8)
                    acCreate = dis.read();

                if (n != 8)
                    log.warn("Invalid length [" + n + "] of FCI tag 0x86 for DF.");

                if (n > 8)
                    dis.skipBytes(n - 8);
                break;

            default:
                byte[] tmp = new byte[n];
                dis.readFully(tmp);
                log.warn("skipping FCI tag [0x" + Integer.toHexString(tag) + "], data [" + Util.asHex(tmp)
                        + "].");
            }
        }

        DF df = new DF(targetPath, bodySize, acLifeCycle, acUpdate, acAppend, acDeactivate, acActivate,
                acDelete, acAdmin, acCreate);

        this.currentFile = df;
        return df;

    } catch (CardException e) {
        throw new PKCS15Exception("Error sending select MF", e);
    }
}

From source file:org.opensc.pkcs15.token.impl.CardOSToken.java

@Override
public EF selectEF(int path) throws IOException {

    if (this.currentFile == null)
        throw new IOException("No current DF selected.");

    // SELECT FILE, P1=0x02, P2=0x00, no data -> select EF
    CommandAPDU cmd = new CommandAPDU(0x00, 0xA4, 0x02, 0x00, PathHelper.idToPath(path), DEFAULT_LE);

    try {/*www .  j  av a  2s . c  o  m*/
        ResponseAPDU resp = this.channel.transmit(cmd);

        DataInputStream dis = getSelectFileData(resp);

        long fileSize = 0;
        int acRead = TokenFileAcl.AC_ALWAYS;
        int acUpdate = TokenFileAcl.AC_ALWAYS;
        int acAppend = TokenFileAcl.AC_ALWAYS;
        int acDeactivate = TokenFileAcl.AC_ALWAYS;
        int acActivate = TokenFileAcl.AC_ALWAYS;
        int acDelete = TokenFileAcl.AC_ALWAYS;
        int acAdmin = TokenFileAcl.AC_ALWAYS;
        int acIncrease = TokenFileAcl.AC_ALWAYS;
        int acDecrease = TokenFileAcl.AC_ALWAYS;

        int tag;

        while ((tag = dis.read()) >= 0) {
            int n = dis.read();
            if (n < 0)
                break;

            switch (tag) {
            case 0x80:
                if (n != 2)
                    throw new IOException("Invalid length [" + n + "] of FCI tag 0x80.");
                fileSize = dis.readUnsignedShort();
                break;

            case 0x83:
                if (n != 2)
                    throw new IOException("Invalid length [" + n + "] of FCI tag 0x83.");
                int tpath = dis.readUnsignedShort();
                if (tpath != path)
                    throw new IOException("File ID [" + PathHelper.formatID(tpath)
                            + "] reported by SELECT FILE differs from requested ID ["
                            + PathHelper.formatID(path) + "].");
                break;

            case 0x86:
                if (n >= 1)
                    acRead = dis.read();
                if (n >= 2)
                    acUpdate = dis.read();
                if (n >= 3)
                    acAppend = dis.read();
                if (n >= 4)
                    acDeactivate = dis.read();
                if (n >= 5)
                    acActivate = dis.read();
                if (n >= 6)
                    acDelete = dis.read();
                if (n >= 7)
                    acAdmin = dis.read();
                if (n >= 8)
                    acIncrease = dis.read();
                if (n >= 9)
                    acDecrease = dis.read();

                if (n != 9)
                    log.warn("Invalid length [" + n + "] of FCI tag 0x86 for EF.");

                if (n > 9)
                    dis.skipBytes(n - 9);
                break;

            default:
                byte[] tmp = new byte[n];
                dis.readFully(tmp);
                log.warn("skipping FCI tag [0x" + Integer.toHexString(tag) + "], data [" + Util.asHex(tmp)
                        + "].");
            }
        }

        EF ef = new EF(new TokenPath(this.currentFile.getPath(), path), fileSize, acRead, acUpdate, acAppend,
                acDeactivate, acActivate, acDelete, acAdmin, acIncrease, acDecrease);

        this.currentFile = ef;
        return ef;

    } catch (CardException e) {
        throw new PKCS15Exception("Error sending select MF", e);
    }
}

From source file:org.opensc.pkcs15.token.impl.CardOSToken.java

@Override
public MF selectMF() throws IOException {

    // SELECT FILE, P1=0x00, P2=0x00, no data -> select MF
    CommandAPDU cmd = new CommandAPDU(0x00, 0xA4, 0x00, 0x00, DEFAULT_LE);

    try {/*www.  j  ava2s  . com*/
        ResponseAPDU resp = this.channel.transmit(cmd);

        DataInputStream dis = getSelectFileData(resp);

        long bodySize = 0;
        int acLifeCycle = TokenFileAcl.AC_ALWAYS;
        int acUpdate = TokenFileAcl.AC_ALWAYS;
        int acAppend = TokenFileAcl.AC_ALWAYS;
        int acDeactivate = TokenFileAcl.AC_ALWAYS;
        int acActivate = TokenFileAcl.AC_ALWAYS;
        int acDelete = TokenFileAcl.AC_ALWAYS;
        int acAdmin = TokenFileAcl.AC_ALWAYS;
        int acCreate = TokenFileAcl.AC_ALWAYS;
        int acExecute = TokenFileAcl.AC_ALWAYS;
        int acAllocate = TokenFileAcl.AC_ALWAYS;

        int tag;

        while ((tag = dis.read()) >= 0) {
            int n = dis.read();
            if (n < 0)
                break;

            switch (tag) {
            case 0x81:
                if (n != 2)
                    throw new IOException("Invalid length [" + n + "] of FCI tag 0x81.");
                bodySize = dis.readUnsignedShort();
                break;

            case 0x83:
                if (n != 2)
                    throw new IOException("Invalid length [" + n + "] of FCI tag 0x83.");
                int tpath = dis.readUnsignedShort();
                if (tpath != PathHelper.MF_ID)
                    throw new IOException("File ID [" + PathHelper.formatID(tpath)
                            + "] reported by SELECT FILE differs from requested ID ["
                            + PathHelper.formatID(PathHelper.MF_ID) + "].");
                break;

            case 0x86:
                if (n >= 1)
                    acLifeCycle = dis.read();
                if (n >= 2)
                    acUpdate = dis.read();
                if (n >= 3)
                    acAppend = dis.read();
                if (n >= 4)
                    acDeactivate = dis.read();
                if (n >= 5)
                    acActivate = dis.read();
                if (n >= 6)
                    acDelete = dis.read();
                if (n >= 7)
                    acAdmin = dis.read();
                if (n >= 8)
                    acCreate = dis.read();
                if (n >= 9)
                    acExecute = dis.read();
                if (n >= 10)
                    acAllocate = dis.read();

                if (n != 10)
                    log.warn("Invalid length [" + n + "] of FCI tag 0x86 for MF.");

                if (n > 10)
                    dis.skipBytes(n - 10);
                break;

            default:
                byte[] tmp = new byte[n];
                dis.readFully(tmp);
                log.warn("skipping FCI tag [0x" + Integer.toHexString(tag) + "], data [" + Util.asHex(tmp)
                        + "].");
            }
        }

        MF mf = new MF(PathHelper.MF_PATH, bodySize, acLifeCycle, acUpdate, acAppend, acDeactivate, acActivate,
                acDelete, acAdmin, acCreate, acExecute, acAllocate);

        this.currentFile = mf;
        return mf;

    } catch (CardException e) {
        throw new PKCS15Exception("Error sending select MF", e);
    }
}

From source file:org.opensc.pkcs15.token.impl.CardOSToken.java

@Override
public TokenFile select(int path) throws IOException {

    if (this.currentFile == null)
        throw new IOException("No current DF selected.");

    // SELECT FILE, P1=0x00, P2=0x00, ID -> select EF or DF
    CommandAPDU cmd = new CommandAPDU(0x00, 0xA4, 0x00, 0x00, PathHelper.idToPath(path), DEFAULT_LE);

    try {//from w w w .j  a v a 2 s .  c  om
        ResponseAPDU resp = this.channel.transmit(cmd);

        DataInputStream dis = getSelectFileData(resp);

        long bodySize = -1;
        long fileSize = -1;
        int acRead = TokenFileAcl.AC_ALWAYS;
        int acUpdate = TokenFileAcl.AC_ALWAYS;
        int acAppend = TokenFileAcl.AC_ALWAYS;
        int acDeactivate = TokenFileAcl.AC_ALWAYS;
        int acActivate = TokenFileAcl.AC_ALWAYS;
        int acDelete = TokenFileAcl.AC_ALWAYS;
        int acAdmin = TokenFileAcl.AC_ALWAYS;
        int acIncrease = TokenFileAcl.AC_ALWAYS;
        int acDecrease = TokenFileAcl.AC_ALWAYS;

        int tag;

        while ((tag = dis.read()) >= 0) {
            int n = dis.read();
            if (n < 0)
                break;

            switch (tag) {
            case 0x80:
                if (n != 2)
                    throw new IOException("Invalid length [" + n + "] of FCI tag 0x80.");
                fileSize = dis.readUnsignedShort();
                break;

            case 0x83:
                if (n != 2)
                    throw new IOException("Invalid length [" + n + "] of FCI tag 0x83.");
                int tpath = dis.readUnsignedShort();
                if (tpath != path)
                    throw new IOException("File ID [" + PathHelper.formatID(tpath)
                            + "] reported by SELECT FILE differs from requested ID ["
                            + PathHelper.formatID(path) + "].");
                break;

            case 0x81:
                if (n != 2)
                    throw new IOException("Invalid length [" + n + "] of FCI tag 0x81.");
                bodySize = dis.readUnsignedShort();
                break;

            case 0x86:
                if (n >= 1)
                    acRead = dis.read();
                if (n >= 2)
                    acUpdate = dis.read();
                if (n >= 3)
                    acAppend = dis.read();
                if (n >= 4)
                    acDeactivate = dis.read();
                if (n >= 5)
                    acActivate = dis.read();
                if (n >= 6)
                    acDelete = dis.read();
                if (n >= 7)
                    acAdmin = dis.read();
                if (n >= 8)
                    acIncrease = dis.read();
                if (n >= 9)
                    acDecrease = dis.read();

                if (n != 9 && n != 8)
                    log.warn("Invalid length [" + n + "] of FCI tag 0x86 for EF.");

                if (n > 9)
                    dis.skipBytes(n - 9);
                break;

            default:
                byte[] tmp = new byte[n];
                dis.readFully(tmp);
                log.warn("skipping FCI tag [0x" + Integer.toHexString(tag) + "], data [" + Util.asHex(tmp)
                        + "].");
            }
        }

        if (fileSize >= 0)
            this.currentFile = new EF(new TokenPath(this.currentFile.getPath(), path), fileSize, acRead,
                    acUpdate, acAppend, acDeactivate, acActivate, acDelete, acAdmin, acIncrease, acDecrease);
        else if (bodySize >= 0)
            this.currentFile = new DF(new TokenPath(this.currentFile.getPath(), path), bodySize, acRead,
                    acUpdate, acAppend, acDeactivate, acActivate, acDelete, acAdmin, acIncrease);
        else
            throw new IOException("No 0x80 or 0x81 tag specified in order to distinguish between DF an EF.");

        return this.currentFile;

    } catch (CardException e) {
        throw new PKCS15Exception("Error sending SELECT FILE", e);
    }
}