Example usage for java.io FileInputStream available

List of usage examples for java.io FileInputStream available

Introduction

In this page you can find the example usage for java.io FileInputStream available.

Prototype

public int available() throws IOException 

Source Link

Document

Returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.

Usage

From source file:gov.nih.nci.rembrandt.web.taglib.KaplanMeierPlotTag.java

public int doStartTag() {

    ServletRequest request = pageContext.getRequest();
    HttpSession session = pageContext.getSession();
    Object o = request.getAttribute(beanName);
    JspWriter out = pageContext.getOut();
    ServletResponse response = pageContext.getResponse();
    String dataName;// w w w .j a v a2s.com
    try {
        dataName = BeanUtils.getSimpleProperty(o, datasetName);
        KaplanMeierStoredData cacheData = (KaplanMeierStoredData) presentationTierCache
                .getSessionGraphingData(session.getId(), dataName);
        JFreeChart chart = CaIntegratorChartFactory
                .getKaplanMeierGraph(cacheData.getPlotPointSeriesCollection());

        RembrandtImageFileHandler imageHandler = new RembrandtImageFileHandler(session.getId(), "png", 700,
                500);
        //The final complete path to be used by the webapplication
        String finalPath = imageHandler.getSessionTempFolder();
        /**
         * Create the actual chart, writing it to the session temp folder
         */
        ChartUtilities.writeChartAsPNG(new FileOutputStream(finalPath), chart, 700, 500);
        /*
         *   This is here to put the thread into a loop while it waits for the
         *   image to be available.  It has an unsophisticated timer but at 
         *   least it is something to avoid an endless loop.
         *  
         */
        boolean imageReady = false;
        int timeout = 1000;
        FileInputStream inputStream = null;
        while (!imageReady) {
            timeout--;
            try {
                inputStream = new FileInputStream(finalPath);
                inputStream.available();
                imageReady = true;
                inputStream.close();
            } catch (IOException ioe) {
                imageReady = false;
                if (inputStream != null) {
                    inputStream.close();
                }
            }
            if (timeout <= 1) {

                break;
            }
        }
        out.print(imageHandler.getImageTag());
        out.print(createLegend(cacheData));
    } catch (IllegalAccessException e1) {
        logger.error(e1);
    } catch (InvocationTargetException e1) {
        logger.error(e1);
    } catch (NoSuchMethodException e1) {
        logger.error(e1);
    } catch (IOException e) {
        logger.error(e);
    } catch (Exception e) {
        logger.error(e);
    } catch (Throwable t) {
        logger.error(t);
    }

    return EVAL_BODY_INCLUDE;
}

From source file:org.torproject.collector.bridgedescs.BridgeSnapshotReader.java

/**
 * Reads the half-hourly snapshots of bridge descriptors from Bifroest.
 *//*from w ww. j  a  va2  s  .  com*/
public BridgeSnapshotReader(BridgeDescriptorParser bdp, File bridgeDirectoriesDir, File statsDirectory)
        throws ConfigurationException {

    if (bdp == null || bridgeDirectoriesDir == null || statsDirectory == null) {
        throw new IllegalArgumentException();
    }

    SortedSet<String> parsed = new TreeSet<String>();
    File bdDir = bridgeDirectoriesDir;
    File pbdFile = new File(statsDirectory, "parsed-bridge-directories");
    boolean modified = false;
    if (bdDir.exists()) {
        if (pbdFile.exists()) {
            logger.debug("Reading file " + pbdFile.getAbsolutePath() + "...");
            try {
                BufferedReader br = new BufferedReader(new FileReader(pbdFile));
                String line = null;
                while ((line = br.readLine()) != null) {
                    parsed.add(line);
                }
                br.close();
                logger.debug("Finished reading file " + pbdFile.getAbsolutePath() + ".");
            } catch (IOException e) {
                logger.warn("Failed reading file " + pbdFile.getAbsolutePath() + "!", e);
                return;
            }
        }
        logger.debug("Importing files in directory " + bridgeDirectoriesDir + "/...");
        Set<String> descriptorImportHistory = new HashSet<String>();
        int parsedFiles = 0;
        int skippedFiles = 0;
        int parsedStatuses = 0;
        int parsedServerDescriptors = 0;
        int skippedServerDescriptors = 0;
        int parsedExtraInfoDescriptors = 0;
        int skippedExtraInfoDescriptors = 0;
        Stack<File> filesInInputDir = new Stack<File>();
        filesInInputDir.add(bdDir);
        while (!filesInInputDir.isEmpty()) {
            File pop = filesInInputDir.pop();
            if (pop.isDirectory()) {
                for (File f : pop.listFiles()) {
                    filesInInputDir.add(f);
                }
            } else if (!parsed.contains(pop.getName())) {
                try {
                    FileInputStream in = new FileInputStream(pop);
                    if (in.available() > 0) {
                        TarArchiveInputStream tais = null;
                        if (pop.getName().endsWith(".tar.gz")) {
                            GzipCompressorInputStream gcis = new GzipCompressorInputStream(in);
                            tais = new TarArchiveInputStream(gcis);
                        } else if (pop.getName().endsWith(".tar")) {
                            tais = new TarArchiveInputStream(in);
                        } else {
                            continue;
                        }
                        BufferedInputStream bis = new BufferedInputStream(tais);
                        String fn = pop.getName();
                        String[] fnParts = fn.split("-");
                        if (fnParts.length != 5) {
                            logger.warn("Invalid bridge descriptor tarball file name: " + fn + ".  Skipping.");
                            continue;
                        }
                        String authorityPart = String.format("%s-%s-", fnParts[0], fnParts[1]);
                        String datePart = String.format("%s-%s-%s", fnParts[2], fnParts[3], fnParts[4]);
                        String authorityFingerprint;
                        switch (authorityPart) {
                        case "from-tonga-":
                            authorityFingerprint = "4A0CCD2DDC7995083D73F5D667100C8A5831F16D";
                            break;
                        case "from-bifroest-":
                            authorityFingerprint = "1D8F3A91C37C5D1C4C19B1AD1D0CFBE8BF72D8E1";
                            break;
                        default:
                            logger.warn("Did not recognize the bridge authority that " + "generated " + fn
                                    + ".  Skipping.");
                            continue;
                        }
                        String dateTime = datePart.substring(0, 10) + " " + datePart.substring(11, 13) + ":"
                                + datePart.substring(13, 15) + ":" + datePart.substring(15, 17);
                        while ((tais.getNextTarEntry()) != null) {
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            int len;
                            byte[] data = new byte[1024];
                            while ((len = bis.read(data, 0, 1024)) >= 0) {
                                baos.write(data, 0, len);
                            }
                            byte[] allData = baos.toByteArray();
                            if (allData.length == 0) {
                                continue;
                            }
                            String fileDigest = Hex.encodeHexString(DigestUtils.sha(allData));
                            String ascii = new String(allData, "US-ASCII");
                            BufferedReader br3 = new BufferedReader(new StringReader(ascii));
                            String firstLine = null;
                            while ((firstLine = br3.readLine()) != null) {
                                if (firstLine.startsWith("@")) {
                                    continue;
                                } else {
                                    break;
                                }
                            }
                            if (firstLine == null) {
                                continue;
                            }
                            if (firstLine.startsWith("published ") || firstLine.startsWith("flag-thresholds ")
                                    || firstLine.startsWith("r ")) {
                                bdp.parse(allData, dateTime, authorityFingerprint);
                                parsedStatuses++;
                            } else if (descriptorImportHistory.contains(fileDigest)) {
                                /* Skip server descriptors or extra-info descriptors if
                                 * we parsed them before. */
                                skippedFiles++;
                                continue;
                            } else {
                                int start = -1;
                                int sig = -1;
                                int end = -1;
                                String startToken = firstLine.startsWith("router ") ? "router " : "extra-info ";
                                String sigToken = "\nrouter-signature\n";
                                String endToken = "\n-----END SIGNATURE-----\n";
                                while (end < ascii.length()) {
                                    start = ascii.indexOf(startToken, end);
                                    if (start < 0) {
                                        break;
                                    }
                                    sig = ascii.indexOf(sigToken, start);
                                    if (sig < 0) {
                                        break;
                                    }
                                    sig += sigToken.length();
                                    end = ascii.indexOf(endToken, sig);
                                    if (end < 0) {
                                        break;
                                    }
                                    end += endToken.length();
                                    byte[] descBytes = new byte[end - start];
                                    System.arraycopy(allData, start, descBytes, 0, end - start);
                                    String descriptorDigest = Hex.encodeHexString(DigestUtils.sha(descBytes));
                                    if (!descriptorImportHistory.contains(descriptorDigest)) {
                                        bdp.parse(descBytes, dateTime, authorityFingerprint);
                                        descriptorImportHistory.add(descriptorDigest);
                                        if (firstLine.startsWith("router ")) {
                                            parsedServerDescriptors++;
                                        } else {
                                            parsedExtraInfoDescriptors++;
                                        }
                                    } else {
                                        if (firstLine.startsWith("router ")) {
                                            skippedServerDescriptors++;
                                        } else {
                                            skippedExtraInfoDescriptors++;
                                        }
                                    }
                                }
                            }
                            descriptorImportHistory.add(fileDigest);
                            parsedFiles++;
                        }
                        bis.close();
                    }
                    in.close();

                    /* Let's give some memory back, or we'll run out of it. */
                    System.gc();

                    parsed.add(pop.getName());
                    modified = true;
                } catch (IOException e) {
                    logger.warn("Could not parse bridge snapshot " + pop.getName() + "!", e);
                    continue;
                }
            }
        }
        logger.debug("Finished importing files in directory " + bridgeDirectoriesDir
                + "/.  In total, we parsed " + parsedFiles + " files (skipped " + skippedFiles + ") containing "
                + parsedStatuses + " statuses, " + parsedServerDescriptors + " server descriptors (skipped "
                + skippedServerDescriptors + "), and " + parsedExtraInfoDescriptors + " extra-info descriptors "
                + "(skipped " + skippedExtraInfoDescriptors + ").");
        if (!parsed.isEmpty() && modified) {
            logger.debug("Writing file " + pbdFile.getAbsolutePath() + "...");
            pbdFile.getParentFile().mkdirs();
            try (BufferedWriter bw = new BufferedWriter(new FileWriter(pbdFile))) {
                for (String f : parsed) {
                    bw.append(f + "\n");
                }
                logger.debug("Finished writing file " + pbdFile.getAbsolutePath() + ".");
            } catch (IOException e) {
                logger.warn("Failed writing file " + pbdFile.getAbsolutePath() + "!", e);
            }
        }
    }
}

From source file:org.eclipse.uomo.xml.test.XMLTestCase.java

protected void compareFiles(String filename1, String filename2)
        throws IOException, UOMoException, InterruptedException {
    FileInputStream one = new FileInputStream(new File(filename1));
    FileInputStream two = new FileInputStream(new File(filename2));
    boolean same = one.available() == two.available();
    while (same && one.available() > 0) {
        same = one.read() == two.read();
    }//from www  . j  a  v  a2 s  . c  o  m

    if (!same) {
        if (!SKIP_THIRD_PARTY)
            Runtime.getRuntime().exec(COMPARE_PATH + " \"" + filename1 + "\" \"" + filename2 + "\"");
        Thread.sleep(1000);
        throw new UOMoException("Content is not as expected @ " + Integer.toString(one.available()));
    }
}

From source file:gov.nih.nci.ispy.web.taglib.CatCorrPlotTag.java

public int doStartTag() {

    ServletRequest request = pageContext.getRequest();
    HttpSession session = pageContext.getSession();
    Object o = request.getAttribute(beanName);
    JspWriter out = pageContext.getOut();
    ServletResponse response = pageContext.getResponse();

    ISPYCategoricalCorrelationFinding corrFinding = (ISPYCategoricalCorrelationFinding) businessTierCache
            .getSessionFinding(session.getId(), taskId);

    try {/*from www  .ja  v a2 s . c om*/
        List<DataPointVector> dataSet = corrFinding.getDataVectors();
        List<ReporterInfo> reporterInfoList = corrFinding.getCatCorrRequest().getReporters();

        //get better labels for X and Y axis.
        ContinuousType ct = corrFinding.getContType();
        String xLabel, yLabel;
        if (ct == ContinuousType.GENE) {
            yLabel = "Log base 2 expression value";
        } else {
            yLabel = ct.toString();
        }

        //if there are reporters involved then send them in so that they can be used to create
        //a series.

        ISPYCategoricalCorrelationPlot plot = new ISPYCategoricalCorrelationPlot(dataSet, reporterInfoList,
                "Category", yLabel, corrFinding.getContType(), ColorByType.CLINICALRESPONSE);

        chart = plot.getChart();
        ISPYImageFileHandler imageHandler = new ISPYImageFileHandler(session.getId(), "png", 650, 600);
        //The final complete path to be used by the webapplication
        String finalPath = imageHandler.getSessionTempFolder();
        String finalURLpath = imageHandler.getFinalURLPath();
        /*
         * Create the actual charts, writing it to the session temp folder
        */
        ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        String mapName = imageHandler.createUniqueMapName();
        //PrintWriter writer = new PrintWriter(new FileWriter(mapName));
        ChartUtilities.writeChartAsPNG(new FileOutputStream(finalPath), chart, 650, 600, info);
        //ImageMapUtil.writeBoundingRectImageMap(writer,"PCAimageMap",info,true);
        //writer.close();

        /*   This is here to put the thread into a loop while it waits for the
         *   image to be available.  It has an unsophisticated timer but at 
         *   least it is something to avoid an endless loop.
         **/
        boolean imageReady = false;
        int timeout = 1000;
        FileInputStream inputStream = null;
        while (!imageReady) {
            timeout--;
            try {
                inputStream = new FileInputStream(finalPath);
                inputStream.available();
                imageReady = true;
                inputStream.close();
            } catch (IOException ioe) {
                imageReady = false;
                if (inputStream != null) {
                    inputStream.close();
                }
            }
            if (timeout <= 1) {

                break;
            }
        }

        out.print(ImageMapUtil.getBoundingRectImageMapTag(mapName, true, info));
        finalURLpath = finalURLpath.replace("\\", "/");
        long randomness = System.currentTimeMillis(); //prevent image caching
        out.print("<img id=\"geneChart\" name=\"geneChart\" src=\"" + finalURLpath + "?" + randomness
                + "\" usemap=\"#" + mapName + "\" border=\"0\" />");

        //(imageHandler.getImageTag(mapFileName));

    } catch (IOException e) {
        logger.error(e);
    } catch (Exception e) {
        logger.error(e);
    } catch (Throwable t) {
        logger.error(t);
    }

    return EVAL_BODY_INCLUDE;
}

From source file:Networking.Client.java

public void loadIVAndMsg(int len) {
    try {//from ww w .j  a v a2 s  . co m
        FileInputStream IVMsg = new FileInputStream("./read_iv.txt");
        iv = new byte[16];
        IVMsg.read(iv);
        msg = new byte[IVMsg.available()];
        IVMsg.read(msg);
        IVMsg.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.apache.hama.manager.util.UITemplate.java

/**
 * read template file contents/*from   www.j av a 2  s. c  o m*/
 * 
 * @param template fileName
 */
protected String loadTemplateFile(String fileName) {

    FileInputStream fis = null;
    int bytesRemain; // the number of remaining bytes
    StringBuilder sb = new StringBuilder();

    try {
        fis = new FileInputStream(fileName);

        while ((bytesRemain = fis.available()) > 0) {
            byte[] data = new byte[bytesRemain];
            int bytesRead = fis.read(data);
            if (bytesRead == -1) {
                break;
            }
            sb.append(new String(data));
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return sb.toString();
}

From source file:org.jwebsocket.util.Tools.java

/**
 * Guess whether given file is binary. Just checks for anything under 0x09.
 *
 * @param aFile/*from w ww . j a v  a 2  s.c om*/
 * @return boolean if the file is binary or not
 * @throws java.io.FileNotFoundException
 */
public static boolean isBinaryFile(File aFile) throws FileNotFoundException, IOException {
    FileInputStream in = new FileInputStream(aFile);
    int size = in.available();
    if (size > 1024) {
        size = 1024;
    }
    byte[] data = new byte[size];
    in.read(data);
    in.close();

    int lAsci = 0;
    int lOther = 0;

    for (int i = 0; i < data.length; i++) {
        byte b = data[i];
        if (b < 0x09) {
            return true;
        }

        if (b == 0x09 || b == 0x0A || b == 0x0C || b == 0x0D) {
            lAsci++;
        } else if (b >= 0x20 && b <= 0x7E) {
            lAsci++;
        } else {
            lOther++;
        }
    }

    if (lOther == 0) {
        return false;
    }

    return (lAsci + lOther) * 100 / lOther > 95;
}

From source file:com.linkedin.pinot.common.utils.ClientSSLContextGenerator.java

private TrustManager[] setupTrustManagers()
        throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException {
    // This is the cert authority that validates server's cert, so we need to put it in our
    // trustStore.
    if (_serverCACertFile != null) {
        LOGGER.info("Initializing trust store from {}", _serverCACertFile);
        FileInputStream is = new FileInputStream(new File(_serverCACertFile));
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null);/*from   ww  w  . j  a v a  2 s. co m*/
        CertificateFactory certificateFactory = CertificateFactory.getInstance(CERTIFICATE_TYPE);
        int i = 0;
        while (is.available() > 0) {
            X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(is);
            LOGGER.info("Read certificate serial number {} by issuer {} ", cert.getSerialNumber().toString(16),
                    cert.getIssuerDN().toString());

            String serverKey = "https-server-" + i;
            trustStore.setCertificateEntry(serverKey, cert);
            i++;
        }

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(CERTIFICATE_TYPE);
        tmf.init(trustStore);
        LOGGER.info("Successfully initialized trust store");
        return tmf.getTrustManagers();
    }
    // Server verification disabled. Trust all servers
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
                throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
                throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    } };
    return trustAllCerts;
}

From source file:Enrichissement.GraphViz.java

/**
 * It will call the external dot program, and return the image in
 * binary format.//from  w ww .  j  a v a  2s .com
 * @param dot Source of the graph (in dot language).
 * @param type Type of the output image to be produced, e.g.: gif, dot, fig, pdf, ps, svg, png.
 * @param representationType Type of how you want to represent the graph:
 * <ul>
 *    <li>dot</li>
 *    <li>neato</li>
 *    <li>fdp</li>
 *    <li>sfdp</li>
 *    <li>twopi</li>
 *    <li>circo</li>
 * </ul>
 * @see http://www.graphviz.org under the Roadmap title
 * @return The image of the graph in .gif format.
 */
private byte[] get_img_stream(File dot, String type, String representationType) {
    File img;
    byte[] img_stream = null;

    try {
        img = File.createTempFile("graph_", "." + type, new File(GraphViz.TEMP_DIR));
        Runtime rt = Runtime.getRuntime();

        // patch by Mike Chenault
        // representation type with -K argument by Olivier Duplouy
        String[] args = { DOT, "-T" + type, "-K" + representationType, "-Gdpi=" + dpiSizes[this.currentDpiPos],
                dot.getAbsolutePath(), "-o", img.getAbsolutePath() };
        Process p = rt.exec(args);
        p.waitFor();

        FileInputStream in = new FileInputStream(img.getAbsolutePath());
        img_stream = new byte[in.available()];
        in.read(img_stream);
        // Close it if we need to
        if (in != null)
            in.close();

        if (img.delete() == false)
            System.err.println("Warning: " + img.getAbsolutePath() + " could not be deleted!");
    } catch (java.io.IOException ioe) {
        System.err.println("Error:    in I/O processing of tempfile in dir " + GraphViz.TEMP_DIR + "\n");
        System.err.println("       or in calling external command");
        ioe.printStackTrace();
    } catch (java.lang.InterruptedException ie) {
        System.err.println("Error: the execution of the external program was interrupted");
        ie.printStackTrace();
    }

    return img_stream;
}

From source file:org.eclipse.uomo.xml.test.XMLTestCase.java

protected void compareXMLs(String filename1, String filename2, String name1, String name2, boolean makePretty)
        throws IOException, UOMoException, InterruptedException, SAXException {

    FileInputStream one = new FileInputStream(new File(filename1));
    FileInputStream two = new FileInputStream(new File(filename2));
    int size1 = one.available();
    int size2 = two.available();

    boolean same = true;
    int count = 0;
    int ia1 = -1;
    int ia2 = -1;

    while (same && one.available() > 0 && two.available() > 0) {
        int i1 = ia1 != -1 ? ia1 : one.read();
        ia1 = -1;/*from w  w w .j  a  va2  s .  co m*/
        int i2 = ia2 != -1 ? ia2 : two.read();
        ia2 = -1;
        if (i1 == CR) {
            i1 = LF;
            ia1 = one.read();
            if (ia1 == LF)
                ia1 = -1;
        }
        if (i2 == CR) {
            i2 = LF;
            ia2 = two.read();
            if (ia2 == LF)
                ia2 = -1;
        }
        same = i1 == i2;
        count++;
    }

    int left1 = one.available();
    int left2 = two.available();

    one.close();
    two.close();

    if (!same || left1 > 0 || left2 > 0) {
        if (!same)
            showDiff(filename1, filename2, name1, name2, makePretty,
                    "Content is not as expected @ " + Integer.toString(count) + " of " + Integer.toString(size1)
                            + "/" + Integer.toString(size2));
        else
            showDiff(filename1, filename2, name1, name2, makePretty, "Content is same until end of file @ "
                    + Integer.toString(size1) + "/" + Integer.toString(size2));
    }

}