Example usage for java.io DataInputStream read

List of usage examples for java.io DataInputStream read

Introduction

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

Prototype

public final int read(byte b[], int off, int len) throws IOException 

Source Link

Document

Reads up to len bytes of data from the contained input stream into an array of bytes.

Usage

From source file:com.cohesionforce.dis.BinaryConverter.java

public void run() {
    int count = 0;

    System.out.println("Opening file to convert: " + inputFile);
    FileInputStream fis;/*  w  w w . j  a  v  a2 s.co  m*/
    try {
        fis = new FileInputStream(inputFile);
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
        return;
    }

    DataInputStream dis = new DataInputStream(fis);
    startWriters();

    System.out.println("Starting to convert PDUs");

    while (done == false) {
        byte buffer[] = new byte[MAX_PDU_SIZE];

        byte pduType;
        try {
            pduType = dis.readByte();
            int pduSize = dis.readInt();
            int skip = dis.read(buffer, 0, 19);
            assert (skip == 19);
            int numberRead = dis.read(buffer, 0, pduSize);
            assert (numberRead == pduSize);
            ++count;

            // Convert the byte array to an object
            Object object;
            object = unmarshaller.getPdu(buffer);
            if (object != null) {
                logPdu(object, pduType);
            }
        } catch (EOFException e) {
            done = true;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            done = true;
            e.printStackTrace();
        }

        if (count % 100000 == 0) {
            System.out.println("Converted " + count + " PDUs");
        }
    } // end loop
    try {
        dis.close();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    System.out.print("Waiting on writers to clear their queues");

    boolean emptyQueue = false;
    while (!emptyQueue) {
        emptyQueue = true;
        for (LogWriter<?> writer : writers) {
            // If any queue is not empty, sleep and check again
            if (!writer.getQueue().isEmpty()) {
                try {
                    emptyQueue = false;
                    System.out.print(".");
                    Thread.sleep(1000);
                    break;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    System.out.println("");
    System.out.println("PDUs converted: " + count);
    System.out.println("Shutting down logging threads");
    threadGroup.interrupt();
    int tries = 0;
    while (threadGroup.activeCount() > 0 && tries < 10) {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
        }
        ++tries;
    }
    System.out.println("Completed logging threads shutdown");

}

From source file:ffx.xray.MTZFilter.java

/**
 * {@inheritDoc}//  w w  w.  j  a v  a 2  s.c o 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:org.tacografo.file.FileBlockTGD.java

/**
 * Lectura de los bloques con formato :tag(fid)-longitud-value
 * //from ww w .jav  a2s.  co m
 * @param entrada
 * @throws IOException
 * @throws ErrorFile ocurrido cuando no es un fichero tgd o falla en la lectura de algun bloque
 * porque no encuentre el tag(fid)
 */
private void lectura_bloque(DataInputStream entrada) throws IOException, ErrorFile {
    boolean existe_fid = true;
    while (existe_fid) {
        // la lectura tiene que ser con readUnsignedShort debido a que
        // los fid c108 y c100
        // los detecta con signo y me los rellenas como ffffc108 y
        // ffffc100
        int fid = entrada.readUnsignedShort();

        existe_fid = this.existe_Fid(fid);
        if (existe_fid) {
            // tipo de archivo 0 = bloque de dato -- 1 = certificado
            byte tipo = entrada.readByte();
            Integer longitud = Integer.valueOf(entrada.readChar());
            byte[] datos = new byte[longitud];

            entrada.read(datos, 0, longitud);
            // tipo de bloque
            if (tipo == 0) {
                CardBlock block = FactoriaBloques.getFactoria(fid, datos);
                if (block != null) {
                    this.lista_bloque.put(block.getFID(), block);
                }

            }
        } else {
            throw new ErrorFile();
        }
    }
}

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   ww w  .j a v a2  s.c  o 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;
}

From source file:com.trigger_context.Main_Service.java

private void recvFile(DataInputStream in, String path) {
    Log.i("recvFile", "Start");
    // path should end with "/"
    String Filename = null;//  w  w  w .  j  av  a2s .c  om
    long size = 0;
    try {
        Filename = in.readUTF();
        size = in.readLong();
    } catch (IOException e1) {
        Log.i(Main_Service.LOG_TAG, "recvFile--error in readins file name and lngth");
    }

    OutputStream outfile = null;
    // noti("path of recv folder:",path);
    try {
        outfile = new FileOutputStream(path + Filename);
    } catch (FileNotFoundException e1) {
        Log.i(Main_Service.LOG_TAG, "recvFile--Error file not found exception");
    }

    byte[] buff = new byte[1024];
    int readbytes;
    try {
        while (size > 0 && (readbytes = in.read(buff, 0, (int) Math.min(buff.length, size))) != -1) {
            try {
                outfile.write(buff, 0, readbytes);
                size -= readbytes;
            } catch (IOException e) {
                Log.i(Main_Service.LOG_TAG, "recvFile--Error file write");
            }
        }
    } catch (IOException e) {
        Log.i(Main_Service.LOG_TAG, "recvFile--Error socket read");
        e.printStackTrace();
    }
    try {
        outfile.close();
    } catch (IOException e) {
        Log.i(Main_Service.LOG_TAG, "recvFile--Erro oufile close");
    }
}

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

/**
 * {@inheritDoc}/*w w w  .  j  ava2s  .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:org.apache.sshd.server.sftp.SftpSubsystem.java

public void run() {
    DataInputStream dis = null;
    try {//  w  w w. j a  v  a2  s.  co  m
        dis = new DataInputStream(in);
        while (true) {
            int length = dis.readInt();
            if (length < 5) {
                throw new IllegalArgumentException();
            }
            Buffer buffer = new Buffer(length + 4);
            buffer.putInt(length);
            int nb = length;
            while (nb > 0) {
                int l = dis.read(buffer.array(), buffer.wpos(), nb);
                if (l < 0) {
                    throw new IllegalArgumentException();
                }
                buffer.wpos(buffer.wpos() + l);
                nb -= l;
            }
            process(buffer);
        }
    } catch (Throwable t) {
        if (!closed && !(t instanceof EOFException)) { // Ignore han
            log.error("Exception caught in SFTP subsystem", t);
        }
    } finally {
        if (dis != null) {
            try {
                dis.close();
            } catch (IOException ioe) {
                log.error("Could not close DataInputStream", ioe);
            }
        }

        if (handles != null) {
            for (Map.Entry<String, Handle> entry : handles.entrySet()) {
                Handle handle = entry.getValue();
                try {
                    handle.close();
                } catch (IOException ioe) {
                    log.error("Could not close open handle: " + entry.getKey(), ioe);
                }
            }
        }
        dis = null;

        callback.onExit(0);
    }
}

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

/**
 * Read the structure factors./*from w w  w .j  a v a2 s .  c  o 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:org.apache.jsp.fileUploader_jsp.java

private String UpdateToShare(byte[] bytes, String mimeType, String title, String description, String prevId,
        Set<String> communities, boolean isJson, String type, boolean newShare, HttpServletRequest request,
        HttpServletResponse response) {//from  w w w  . jav a2 s.  c o m
    String charset = "UTF-8";
    String url = "";
    try {
        if (isJson) {
            //first check if bytes are actually json
            try {
                new JsonParser().parse(new String(bytes));
            } catch (Exception ex) {
                return "Failed, file was not valid JSON";
            }
            if (newShare)
                url = API_ROOT + "social/share/add/json/" + URLEncoder.encode(type, charset) + "/"
                        + URLEncoder.encode(title, charset) + "/" + URLEncoder.encode(description, charset)
                        + "/";
            else
                url = API_ROOT + "social/share/update/json/" + prevId + "/" + URLEncoder.encode(type, charset)
                        + "/" + URLEncoder.encode(title, charset) + "/"
                        + URLEncoder.encode(description, charset) + "/";
        } else {
            if (newShare)
                url = API_ROOT + "social/share/add/binary/" + URLEncoder.encode(title, charset) + "/"
                        + URLEncoder.encode(description, charset) + "/";
            else
                url = API_ROOT + "social/share/update/binary/" + prevId + "/"
                        + URLEncoder.encode(title, charset) + "/" + URLEncoder.encode(description, charset)
                        + "/";
        }

        if (localCookie)
            CookieHandler.setDefault(cm);
        URLConnection connection = new URL(url).openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Accept-Charset", charset);
        String cookieVal = getBrowserInfiniteCookie(request);
        if (cookieVal != null) {
            connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestProperty("Accept-Charset", "UTF-8");
        }
        if (mimeType != null && mimeType.length() > 0)
            connection.setRequestProperty("Content-Type", mimeType + ";charset=" + charset);
        DataOutputStream output = new DataOutputStream(connection.getOutputStream());
        output.write(bytes);
        DataInputStream responseStream = new DataInputStream(connection.getInputStream());

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int nRead;
        byte[] data = new byte[16384];
        while ((nRead = responseStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }

        String json = buffer.toString();
        String newCookie = getConnectionInfiniteCookie(connection);
        if (newCookie != null && response != null) {
            setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
        }
        buffer.flush();
        buffer.close();
        output.close();
        responseStream.close();

        if (isJson) {
            jsonResponse jr = new Gson().fromJson(json, jsonResponse.class);
            if (jr == null) {
                return "Failed: " + json;
            }
            if (jr.response.success == true) {
                if (jr.data != null && jr.data._id != null) {
                    addRemoveCommunities(jr.data._id, communities, request, response);
                    return jr.data._id; //When a new upload, mr.data contains the ShareID for the upload
                }
            }
            return "Upload Failed: " + jr.response.message;
        } else {
            modResponse mr = new Gson().fromJson(json, modResponse.class);
            if (mr == null) {
                return "Failed: " + json;
            }
            if (mr.response.success == true) {
                if (prevId != null && mr.data == null) {
                    addRemoveCommunities(prevId, communities, request, response);
                    return prevId;
                } else {
                    addRemoveCommunities(mr.data, communities, request, response);
                    return mr.data; //When a new upload, mr.data contains the ShareID for the upload
                }
            } else {
                return "Upload Failed: " + mr.response.message;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        return "Upload Failed: " + e.getMessage();
    }
}

From source file:ffx.xray.MTZFilter.java

/**
 * {@inheritDoc}/*from  www.ja  v  a2 s .c  o  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;
}