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:ffx.realspace.CCP4MapFilter.java

/**
 * {@inheritDoc}//  www .  j  a v a 2  s .  c  o m
 */
@Override
public Crystal getCrystal(String fileName, CompositeConfiguration properties) {
    int imapData;
    int spaceGroup = -1;
    double cellA = -1.0;
    double cellB = -1.0;
    double cellC = -1.0;
    double cellAlpha = -1.0;
    double cellBeta = -1.0;
    double cellGamma = -1.0;

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

    // 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();
        String 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;
        }
        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);

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

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

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

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

    return new Crystal(cellA, cellB, cellC, cellAlpha, cellBeta, cellGamma,
            SpaceGroup.spaceGroupNames[spaceGroup - 1]);
}

From source file:cn.xiongyihui.wificar.MjpegStream.java

public Bitmap readFrame(DataInputStream in) throws IOException {
    int mContentLength = -1;

    in.mark(FRAME_MAX_LENGTH);//from www.ja  va 2s  .  c  om
    int headerLen = getStartOfSequence(in, SOI_MARKER);
    in.reset();
    byte[] header = new byte[headerLen];
    in.readFully(header);
    try {
        mContentLength = parseContentLength(header);
    } catch (NumberFormatException nfe) {
        mContentLength = getEndOfSeqeunce(in, EOF_MARKER);
    }
    in.reset();
    byte[] frameData = new byte[mContentLength];
    in.skipBytes(headerLen);
    in.readFully(frameData);
    return BitmapFactory.decodeStream(new ByteArrayInputStream(frameData));
}

From source file:ffx.realspace.CCP4MapFilter.java

/**
 * {@inheritDoc}/*from   w w  w.  j a va  2s . c o m*/
 */
@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:ffx.xray.CCP4MapFilter.java

/**
 * {@inheritDoc}/*from  w  ww.ja  va 2s . co m*/
 */
@Override
public boolean readFile(String filename, RealSpaceRefinementData refinementdata,
        CompositeConfiguration properties) {

    int imapdata;
    double cella, cellb, cellc, cellalpha, cellbeta, cellgamma;
    String stampstr;

    ByteOrder b = ByteOrder.nativeOrder();

    FileInputStream fis;
    DataInputStream dis;

    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 {
        fis = new FileInputStream(filename);
        dis = new DataInputStream(fis);

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

        imapdata = bb.order(ByteOrder.BIG_ENDIAN).getInt();
        stampstr = Integer.toHexString(imapdata);
        // System.out.println("stamp: " + stampstr);
        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;
        }

        if (logger.isLoggable(Level.INFO)) {
            StringBuilder sb = new StringBuilder();
            sb.append(String.format("\nOpening CCP4 map: %s\n", filename));
            sb.append(String.format("file type (machine stamp): %s\n", stampstr));
            logger.info(sb.toString());
        }

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

    try {
        fis = new FileInputStream(filename);
        dis = new DataInputStream(fis);

        byte bytes[] = new byte[2048];

        dis.read(bytes, 0, 1024);
        ByteBuffer bb = ByteBuffer.wrap(bytes);

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

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

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

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

        cella = bb.order(b).getFloat();
        cellb = bb.order(b).getFloat();
        cellc = bb.order(b).getFloat();
        cellalpha = bb.order(b).getFloat();
        cellbeta = bb.order(b).getFloat();
        cellgamma = bb.order(b).getFloat();

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

        min = bb.order(b).getFloat();
        max = bb.order(b).getFloat();
        mean = bb.order(b).getFloat();

        int sg = bb.order(b).getInt();

        int nsymb = bb.order(b).getInt();

        int skew = bb.order(b).getInt();

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

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

        byte word[] = new byte[2048];
        bb.order(b).get(word, 0, 4);
        String mapstr = new String(word);
        // System.out.println("MAP?: " + mapstr);

        sd = bb.order(b).getFloat();
        rmsd = bb.order(b).getFloat();

        /*
         System.out.println("col: " + ori[0] + " " + ext[0] + " " + ni[0]);
         System.out.println("row: " + ori[1] + " " + ext[1] + " " + ni[1]);
         System.out.println("sec: " + ori[2] + " " + ext[2] + " " + ni[2]);
         System.out.println("order: " + axisi[0] + " " + axisi[1] + " " + axisi[2]);
         System.out.println("min: " + min + " max: " + max + " mean: " + mean);
         System.out.println("sd: " + sd + " rmsd: " + rmsd);
         System.out.println("sg: " + sg);
         System.out.println("a: " + cella + " b: " + cellb + " c: " + cellc
         + " alpha: " + cellalpha + " beta: " + cellbeta + " gamma: " + cellgamma);
         */
        if (logger.isLoggable(Level.INFO)) {
            StringBuilder sb = new StringBuilder();
            sb.append(String.format("  column origin: %d extent: %d\n", ori[0], ext[0]));
            sb.append(String.format("  row origin: %d extent: %d\n", ori[1], ext[1]));
            sb.append(String.format("  section origin: %d 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 (name: %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 = bb.order(b).getInt();

        // System.out.println("nsymb: " + nsymb + " nlabel: " + nlabel);
        for (int i = 0; i < 10; i++) {
            bb.order(b).get(word, 0, 80);
            mapstr = new String(word);
            // System.out.println("label " + i + " : " + mapstr);
        }

        if (nsymb > 0) {
            bb.rewind();
            dis.read(bytes, 0, nsymb);
            for (int i = 0; i < nsymb / 80; i += 80) {
                bb.order(b).get(word, 0, 80);
                mapstr = new String(word);
                // System.out.println("symm: " + mapstr);
            }
        }

        bb.rewind();
        dis.read(bytes, 0, 2048);
        refinementdata.data = new double[ext[0] * ext[1] * ext[2]];
        int ijk[] = new int[3];
        int index, x, y, z;
        refinementdata.ori[0] = ori[axisi[0]];
        refinementdata.ori[1] = ori[axisi[1]];
        refinementdata.ori[2] = ori[axisi[2]];
        int nx = ext[axisi[0]];
        int ny = ext[axisi[1]];
        int nz = ext[axisi[2]];
        refinementdata.ext[0] = nx;
        refinementdata.ext[1] = ny;
        refinementdata.ext[2] = nz;
        refinementdata.ni[0] = ni[0];
        refinementdata.ni[1] = ni[1];
        refinementdata.ni[2] = 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.data[index] = bb.order(b).getFloat();
                    if (!bb.hasRemaining()) {
                        bb.rewind();
                        dis.read(bytes, 0, 2048);
                    }
                }
            }
        }
        fis.close();
    } catch (Exception e) {
        String message = "Fatal exception reading CCP4 map.\n";
        logger.log(Level.SEVERE, message, e);
        System.exit(-1);
    }

    return true;
}

From source file:org.bdval.cache.TableCache.java

public ObjectSet<CharSequence> getTableColumnIds(final int splitId, final String splitType,
        final String datasetName) {
    final File cachedTableFile = getCachedTableFile(splitId, splitType, datasetName);
    final ObjectSet<CharSequence> result = new ObjectOpenHashSet<CharSequence>();
    DataInputStream dataInput = null;
    try {/*from   ww w .j  a v  a2s  . c o  m*/
        dataInput = new DataInputStream(new FastBufferedInputStream(new FileInputStream(cachedTableFile)));
        final int numberOfColumns = dataInput.readInt();
        LOG.info("Reading cached table with " + numberOfColumns + " columns");
        for (int i = 0; i < numberOfColumns; i++) {
            final String colType = dataInput.readUTF();
            final String colId = dataInput.readUTF();

            result.add(colId);

            if ("s".equals(colType)) {
                final int numStrings = dataInput.readInt();

                for (int j = 0; j < numStrings; j++) {
                    dataInput.readUTF();
                }
            } else if ("d".equals(colType)) {
                final int numDoubles = dataInput.readInt();
                // we don't need to read these doubles, just skip them;
                final int numBytes = Double.SIZE * numDoubles / 8;
                final int actualBytes = dataInput.skipBytes(numBytes);
                if (actualBytes != numBytes) {
                    LOG.warn("actual bytes skipped (" + actualBytes + ") does " + "not equal expected of "
                            + numBytes);
                }
            } else {
                LOG.error("UNKNOWN COLUMN TYPE " + colType + " cannot read cached table from file "
                        + filenameOf(cachedTableFile));
                return null;
            }
        }
        return result;
    } catch (IOException e) {
        LOG.error("Error getting column ids", e);
        return null;
    } finally {
        IOUtils.closeQuietly(dataInput);
    }
}

From source file:org.bdval.cache.TableCache.java

/**
 * Retrieve a cached table from the cache. isTableCached should be called
 * before calling this to verify that the table is cached. Null will
 * be returned if the table wasn't in the cache or there was a problem
 * reading the table./*from ww w .  ja v  a  2s. co  m*/
 *
 * @param splitId        The split id
 * @param splitType      The Split type
 * @param datasetName    The dataset name
 * @param geneListFilter A gene list. If not null, the gene list is queried with each double
 * column identifier to determine if the identifier is contained in the gene list. Columns
 * that do not match the gene list are not loaded.
 * @return the table read from the cache (or null if it could not be read)
 */
public Table getCachedTable(final int splitId, final String splitType, final String datasetName,
        final GeneList geneListFilter) {
    final File cachedTableFile = getCachedTableFile(splitId, splitType, datasetName);

    if (geneListFilter != null && !(geneListFilter instanceof FullGeneList)) {
        final ObjectSet<CharSequence> tableColumnIds = getTableColumnIds(splitId, splitType, datasetName);
        geneListFilter.calculateProbeSetSelection(tableColumnIds);
    }
    DataInputStream dataInput = null;
    try {
        dataInput = new DataInputStream(new FastBufferedInputStream(new FileInputStream(cachedTableFile)));
        final ArrayTable result = new ArrayTable();
        final int numberOfColumns = dataInput.readInt();
        LOG.info("Reading cached table with " + numberOfColumns + " columns");
        for (int i = 0; i < numberOfColumns; i++) {
            final String colType = dataInput.readUTF();
            final String colId = dataInput.readUTF();

            if ("s".equals(colType)) {
                final int numStrings = dataInput.readInt();
                resize(result, numStrings);
                final int columnIndex = result.addColumn(colId, String.class);
                for (int j = 0; j < numStrings; j++) {
                    result.appendObject(columnIndex, dataInput.readUTF());
                }
            } else if ("d".equals(colType)) {
                final int numDoubles = dataInput.readInt();
                resize(result, numDoubles);
                if (geneListFilter != null && !geneListFilter.isProbesetInList(colId)) {
                    // the column does not match the gene list. Skip this column
                    // we don't need to read these doubles, just skip them;
                    final int numBytes = Double.SIZE * numDoubles / 8;
                    final int actualBytes = dataInput.skipBytes(numBytes);
                    if (actualBytes != numBytes) {
                        LOG.warn("actual bytes skipped (" + actualBytes + ") does" + "not equal expected of "
                                + numBytes);
                    }
                    continue;
                }

                final int columnIndex = result.addColumn(colId, double.class);
                for (int j = 0; j < numDoubles; j++) {
                    result.appendDoubleValue(columnIndex, dataInput.readDouble());
                }

            } else {
                LOG.error("UNKNOWN COLUMN TYPE " + colType + " cannot read cached table from file "
                        + filenameOf(cachedTableFile));
                return null;
            }
        }
        return result;
    } catch (IOException e) {
        LOG.error(e);
        return null;
    } catch (TypeMismatchException e) {
        LOG.error("TypeMismatchException adding data to Table " + filenameOf(cachedTableFile), e);
        return null;
    } finally {
        IOUtils.closeQuietly(dataInput);
    }
}

From source file:net.sergetk.mobile.lcdui.BitmapFont.java

/**
 * Creates a new font from the resource. The capacity of the color cache defines maximum size of
 * the color cache.//from  w ww  .  j  av a2  s. co m
 * 
 * @param fontPath
 *            the resource name
 * @param colorCacheCapacity
 *            the maximum color cache size
 */
public BitmapFont(String fontPath, int colorCacheCapacity) {
    this.style = Font.STYLE_PLAIN;
    this.currentColor = 0;
    this.colorCache = new CacheEntry[colorCacheCapacity];
    this.colorUsageCounts = new IntHashMap(colorCacheCapacity * 2);

    try {
        InputStream input = new Object().getClass().getResourceAsStream(fontPath);
        if (input == null) {
            throw new IOException();
        }

        DataInputStream data = new DataInputStream(input);

        int streamLen = data.available();

        this.fontFilePath = fontPath;

        this.version = data.readByte();
        this.height = data.readByte();
        this.baseline = data.readByte();
        this.xIndent = data.readByte();
        this.yIndent = data.readByte();
        this.spaceWidth = data.readByte();

        characterMap = data.readUTF();
        int count = characterMap.length();

        // read characters widthes
        this.widths = new int[count];
        this.x = new int[count];
        this.y = new int[count];

        for (int i = 0; i < count; i++) {
            widths[i] = data.readByte();
        }

        baseImage = null;

        // the original implementation supported multiple-images
        // in the font file, but this is not necessary. Because I do
        // not want to change the encoding, I am leaving this byte that
        // used to represent the number of PNGs in the file
        data.skipBytes(1);

        short pngLen = data.readShort();
        byte[] buffer = new byte[pngLen];

        data.read(buffer, 0, pngLen);
        this.pngOffset = (short) (streamLen - pngLen);
        baseImage = Image.createImage(buffer, 0, pngLen);
        currentImage = baseImage;

        // calculate characters coordinates
        int curX = 0, curY = 0;
        for (int i = 0; i < count; i++) {
            if (widths[i] < 0) {
                // negative width points to another character
                int sourceIndex = -widths[i];
                widths[i] = widths[sourceIndex];
                x[i] = x[sourceIndex];
                y[i] = y[sourceIndex];
            } else {
                x[i] = curX;
                y[i] = curY;
                curX += widths[i];
            }
        }

        if (defaultFont == null)
            defaultFont = this;
    } catch (IOException e) {
        // Log.warn("IOException reading font: ", e);
        System.err.println("IOException reading font: " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.serenegiant.media.TLMediaEncoder.java

private void checkLastSequence() {
    if (DEBUG)/*from  ww  w.jav a 2  s.  c o  m*/
        Log.v(TAG, "checkLastSequence:");
    int sequence = -1;
    MediaFormat configFormat = null;
    try {
        final DataInputStream in = openInputStream(mBaseDir, mType, 0);
        if (in != null)
            try {
                // read MediaFormat data for MediaCodec and for MediaMuxer
                readHeader(in);
                configFormat = asMediaFormat(in.readUTF()); // for MediaCodec
                in.readUTF(); // for MediaMuxer
                // search last sequence
                // this is not a effective implementation for large intermediate file.
                // ex. it may be better to split into multiple files for each sequence
                // or split into two files; file for control block and file for raw bit stream.
                final TLMediaFrameHeader header = new TLMediaFrameHeader();
                for (; mIsRunning;) {
                    readHeader(in, header);
                    in.skipBytes(header.size);
                    sequence = Math.max(sequence, header.sequence);
                }
            } finally {
                in.close();
            }
    } catch (Exception e) {
        // ignore
    }
    mSequence = sequence;
    mConfigFormat = configFormat;
    if (sequence < 0) {
        // if intermediate files do not exist or invalid, remove them and re-create intermediate directory
        delete(mBaseDir);
        mBaseDir.mkdirs();
    }
    if (DEBUG)
        Log.v(TAG, "checkLastSequence:finished. sequence=" + sequence);
}

From source file:ffx.xray.MTZFilter.java

/**
 * {@inheritDoc}/*from  ww  w .j  a v a  2  s  .co m*/
 */
@Override
public ReflectionList getReflectionList(File mtzFile, CompositeConfiguration properties) {
    ByteOrder b = ByteOrder.nativeOrder();
    FileInputStream fis;
    DataInputStream dis;
    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);
        }
    } catch (EOFException eof) {
        System.out.println("EOF reached ");
    } catch (IOException ioe) {
        System.out.println("IO Exception: " + ioe.getMessage());
        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.\n For non-default column labels set fostring/sigfostring in the properties file.");
        return null;
    }

    Column c;
    if (fo > 0) {
        c = (Column) columns.get(fo);
    } else if (fplus > 0) {
        c = (Column) columns.get(fplus);
    } else {
        c = (Column) columns.get(fc);
    }
    Dataset d = (Dataset) datasets.get(c.id - dsetoffset);

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

    Crystal crystal = new Crystal(d.cell[0], d.cell[1], d.cell[2], d.cell[3], d.cell[4], d.cell[5],
            SpaceGroup.spaceGroupNames[sgnum - 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.MTZFilter.java

public boolean readFcs(File mtzFile, ReflectionList reflectionlist, DiffractionRefinementData fcdata,
        CompositeConfiguration properties) {
    int nread, nignore, nres, nfriedel, ncut;
    ByteOrder b = ByteOrder.nativeOrder();
    FileInputStream fis;//from w  w w .  ja  va  2  s.co m
    DataInputStream dis;

    StringBuilder sb = new StringBuilder();
    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
        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
        fis = new FileInputStream(mtzFile);
        dis = new DataInputStream(fis);

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

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

        // read in data
        ComplexNumber c = new ComplexNumber();
        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, false);
            HKL hkl = reflectionlist.getHKL(mate);

            if (hkl != null) {
                if (fc > 0 && phic > 0) {
                    c.re(data[fc] * cos(toRadians(data[phic])));
                    c.im(data[fc] * sin(toRadians(data[phic])));
                    fcdata.setFc(hkl.index(), c);
                }
                if (fs > 0 && phis > 0) {
                    c.re(data[fs] * cos(toRadians(data[phis])));
                    c.im(data[fs] * sin(toRadians(data[phis])));
                    fcdata.setFs(hkl.index(), c);
                }
                nread++;
            } else {
                HKL tmp = new HKL(ih, ik, il);
                if (!reflectionlist.resolution
                        .inInverseResSqRange(Crystal.invressq(reflectionlist.crystal, tmp))) {
                    nres++;
                } else {
                    nignore++;
                }
            }
        }

        sb.append(String.format(" MTZ file type (machine stamp): %s\n", stampstr));
        sb.append(String.format(" Fc HKL read in:                             %d\n", nread));
        sb.append(String.format(" Fc HKL read as friedel mates:               %d\n", nfriedel));
        sb.append(String.format(" Fc HKL NOT read in (too high resolution):   %d\n", nres));
        sb.append(String.format(" Fc HKL NOT read in (not in internal list?): %d\n", nignore));
        sb.append(String.format(" Fc 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());
        }
    } catch (EOFException eof) {
        System.out.println("EOF reached ");
        return false;
    } catch (IOException ioe) {
        System.out.println("IO Exception: " + ioe.getMessage());
        return false;
    }

    return true;
}