Example usage for org.apache.commons.io FileUtils openInputStream

List of usage examples for org.apache.commons.io FileUtils openInputStream

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils openInputStream.

Prototype

public static FileInputStream openInputStream(File file) throws IOException 

Source Link

Document

Opens a FileInputStream for the specified file, providing better error messages than simply calling new FileInputStream(file).

Usage

From source file:de.haber.xmind2latex.XMindToLatexExporter.java

/**
 * @param xMindSource the xMindSource to set, must not be null
 * /*from www  .  j a va  2s .c  om*/
 * @throws ZipException if a given XMind file may not be extracted.
 * @throws IOException 
 */
private InputStream setxMindSourceInputStream(File xMindSource) throws ZipException, IOException {
    Preconditions.checkNotNull(xMindSource);
    File usedFile = xMindSource;
    if (!usedFile.exists()) {
        throw new FileNotFoundException("The given input file " + xMindSource + " does not exist!");
    }
    if (usedFile.getName().endsWith(".xmind")) {
        ZipFile zip = new ZipFile(usedFile);
        FileHeader fh = zip.getFileHeader("content.xml");
        return zip.getInputStream(fh);
    } else {
        return FileUtils.openInputStream(usedFile);
    }
}

From source file:net.nicholaswilliams.java.teamcity.plugin.buildNumber.PluginConfigurationServiceDefault.java

protected void loadConfiguration() {
    PluginConfigurationServiceDefault.logger.info("Loading the plugin configuration from the XML file.");

    FileInputStream stream = null;
    try {// www .  j  ava2 s .c o m
        stream = FileUtils.openInputStream(this.configFile);
        this.configuration = this.newDigester().parse(stream);
    } catch (IOException e) {
        throw new FatalBeanException("Could not read plugin configuration XML file", e);
    } catch (SAXException e) {
        throw new FatalBeanException("Could not parse plugin configuration XML", e);
    } catch (ParserConfigurationException e) {
        throw new FatalBeanException("Could not configure the configuration XML parser", e);
    } finally {
        try {
            if (stream != null)
                stream.close();
        } catch (IOException e) {
            PluginConfigurationServiceDefault.logger.warn("Failed to close configuration XML file.", e);
        }
    }
}

From source file:com.google.refine.model.medadata.ProjectMetadata.java

@Override
public void loadFromFile(File metadataFile) {
    InputStream targetStream = null;
    try {/*  w  w w.  j  ava  2 s  .  c o m*/
        targetStream = FileUtils.openInputStream(metadataFile);
    } catch (IOException e) {
        logger.error(ExceptionUtils.getStackTrace(e));
    }
    loadFromStream(targetStream);
}

From source file:com.edgenius.core.repository.SimpleRepositoryServiceImpl.java

public List<FileNode> getAllSpaceNodes(ITicket ticket, String type, String spaceUname, boolean withResource)
        throws RepositoryException {

    if (!ticket.isAllowRead()) {
        String error = "Workspace has not read permission " + ticket.getSpacename();
        log.warn(error);/* w  w  w .j a v a 2  s .co m*/
        throw new RepositoryException("Permission denied: " + error);
    }

    CrWorkspace crW = getCrWorkspace(ticket);
    List<CrFileNode> nodes = crFileNodeDAO.getSpaceNodes(type, spaceUname);
    List<FileNode> list = new ArrayList<FileNode>();
    //retrieve all geniuswiki:file nodes under this identifier
    for (Iterator<CrFileNode> iter = nodes.iterator(); iter.hasNext();) {
        CrFileNode fileNode = iter.next();
        //copy geniuswiki:file history as well

        FileNode my = FileNode.copyPersistToNode(fileNode);

        //copy geniuswiki:filenode->nt:resource node as well
        if (withResource) {
            File file = new File(FileUtil.getFullPath(homeDir, crW.getSpaceUuid(), fileNode.getNodeType(),
                    fileNode.getIdentifierUuid(), fileNode.getNodeUuid(),
                    Integer.valueOf(fileNode.getVersion()).toString(),
                    SimpleRepositoryServiceImpl.DEFAULT_FILE_NAME));
            try {
                my.setFile(FileUtils.openInputStream(file));
            } catch (IOException e) {
                log.warn("Failed get node " + file.getAbsolutePath() + " with error " + e);
            }
        }
        list.add(my);
    }

    return list;
}

From source file:com.evolveum.midpoint.report.impl.ReportManagerImpl.java

@Override
public InputStream getReportOutputData(String reportOutputOid, OperationResult parentResult) {
    Task task = taskManager.createTaskInstance(REPORT_OUTPUT_DATA);

    OperationResult result = parentResult.createSubresult(REPORT_OUTPUT_DATA);
    result.addParam("oid", reportOutputOid);

    InputStream reportData = null;
    try {/*from w w  w.  jav a  2s.  co  m*/
        ReportOutputType reportOutput = modelService
                .getObject(ReportOutputType.class, reportOutputOid, null, task, result).asObjectable();

        String filePath = reportOutput.getFilePath();
        if (StringUtils.isEmpty(filePath)) {
            parentResult.recordFatalError("Report output file path is not defined.");
            return null;
        }
        File file = new File(filePath);
        reportData = FileUtils.openInputStream(file);

        result.recordSuccessIfUnknown();
    } catch (Exception e) {
        LOGGER.trace("Cannot read the report data : {}", e.getMessage());
        result.recordFatalError("Cannot read the report data.", e);
    } finally {
        result.computeStatusIfUnknown();
    }

    return reportData;
}

From source file:edu.cornell.med.icb.goby.modes.TestReformatCompactReadsMode.java

/**
 * Validates that meta data are transfered by reformat.
 * The input file to this test was created with the following command:
 * goby 1g fasta-to-compact  -k key1 -v value1 -k key2 -v value2 test-data/fastx-test-data/test-fastq-1.fq -o test-data/compact-reads/with-meta-data-input.compact-reads
 *
 * @throws IOException if there is a problem reading or writing to the files
 *//*from  w ww .  jav  a 2 s .  c om*/
@Test
public void reformatTransferMetaData() throws IOException {
    final ReformatCompactReadsMode reformat = new ReformatCompactReadsMode();

    final String inputFilename = "test-data/compact-reads/with-meta-data-input.compact-reads";
    reformat.setInputFilenames(inputFilename);

    final String outputFilename = "test-results/with-meta-data-output.compact-reads";
    reformat.setOutputFile(outputFilename);
    reformat.execute();

    ReadsReader reader1 = new ReadsReader(inputFilename);
    for (Reads.ReadEntry it : reader1) {
        System.out.println(it.toString());
        System.out.println();
    }

    ReadsReader reader2 = new ReadsReader(outputFilename);
    for (Reads.ReadEntry it : reader2) {
        System.out.println(it.toString());
        System.out.println();
    }

    assertTrue(FileUtils.contentEquals(new File(inputFilename), new File(outputFilename)));

    final ReadsReader reader = new ReadsReader(FileUtils.openInputStream(new File(outputFilename)));
    assertTrue("There should be reads in this file", reader.hasNext());
    final Reads.ReadEntry entry = reader.next();
    assertNotNull("Entry should not be null", entry);
    Properties keyValuePairs = reader.getMetaData();

    assertEquals("key/value pairs must match", "value1", keyValuePairs.get("key1"));
    assertEquals("key/value pairs must match", "value2", keyValuePairs.get("key2"));

}

From source file:gov.nih.nci.caarray.application.project.FileUploadUtilsTest.java

@Test
public void testUnpackFiles_SingleZip() throws Exception {
    CaArrayFile mockFile = mock(CaArrayFile.class);
    when(mockStorageFacade.openInputStream(any(URI.class), eq(false)))
            .thenReturn(FileUtils.openInputStream(File.createTempFile("aaa", "bbb")));

    uploadUtils.unpackFiles(project, Lists.newArrayList(mockFile));
    verify(mockStorageFacade).openInputStream(any(URI.class), eq(false));
}

From source file:edu.cornell.med.icb.goby.modes.CompactFileStatsMode.java

/**
 * Print statistics about a reads file in the Goby compact form.
 *
 * @param file The file to display statistics about
 * @throws IOException if the file cannot be read
 *//*from   w ww.  j a va2  s .c om*/
private void describeCompactReads(final File file) throws IOException {
    stream.printf("Compact reads filename = %s%n", file);

    // keep the read lengths for computing quantiles
    final DoubleArrayList readLengths = new DoubleArrayList();

    int minLength = Integer.MAX_VALUE;
    int maxLength = Integer.MIN_VALUE;

    int numberOfIdentifiers = 0;
    int numberOfDescriptions = 0;
    int numberOfSequences = 0;
    int numberOfSequencePairs = 0;
    int numberOfQualityScores = 0;
    int numberOfQualityScorePairs = 0;

    long totalReadLength = 0;
    long totalReadLengthPair = 0;
    final DistinctIntValueCounterBitSet allQueryIndices = new DistinctIntValueCounterBitSet();

    ReadsReader reader = null;
    boolean checkedForPaired = false;

    try {
        final long size = file.length();
        reader = new ReadsReader(FileUtils.openInputStream(file));
        for (final Reads.ReadEntry entry : reader) {
            final int readLength = entry.getReadLength();

            for (int i = 0; i < entry.getMetaDataCount(); i++) {
                Reads.MetaData metaData = entry.getMetaData(i);
                stream.printf("meta-data key=%s value=%s%n", metaData.getKey(), metaData.getValue());

            }

            // across this file
            allQueryIndices.observe(entry.getReadIndex());
            totalReadLength += readLength;
            totalReadLengthPair += entry.getReadLengthPair();

            // across all files
            numberOfReads++;
            numberOfDescriptions += entry.hasDescription() ? 1 : 0;
            cumulativeReadLength += readLength;

            if (verbose && entry.hasDescription()) {
                stream.println("Description found: " + entry.getDescription());
            }
            numberOfIdentifiers += entry.hasReadIdentifier() ? 1 : 0;
            if (verbose && entry.hasReadIdentifier()) {
                stream.printf("Identifier found: %s    /  size=%,d%n", entry.getReadIdentifier(), readLength);
            }
            numberOfSequences += entry.hasSequence() && !entry.getSequence().isEmpty() ? 1 : 0;
            final boolean samplePaired = entry.hasSequencePair() && !entry.getSequencePair().isEmpty();
            if (samplePaired) {
                numberOfSequencePairs += 1;
            }
            if (!checkedForPaired) {
                // Check only the very first entry.
                checkedForPaired = true;
                pairedSamples.add(samplePaired);
            }
            if (entry.hasQualityScores() && !entry.getQualityScores().isEmpty()) {
                numberOfQualityScores += 1;
                final int qualityLength = entry.getQualityScores().size();
                minQualityLength = Math.min(minQualityLength, qualityLength);
                maxQualityLength = Math.max(maxQualityLength, qualityLength);
            }

            numberOfQualityScorePairs += entry.hasQualityScoresPair() && !entry.getQualityScoresPair().isEmpty()
                    ? 1
                    : 0;

            // we only need to keep all the read lengths if quantiles are being computed
            if (computeQuantiles) {
                readLengths.add(readLength);
            }
            minLength = Math.min(minLength, readLength);
            maxLength = Math.max(maxLength, readLength);

            // adjust the min/max length of across all files
            minReadLength = Math.min(minReadLength, readLength);
            maxReadLength = Math.max(maxReadLength, readLength);
        }

        stream.printf("Average bytes per entry: %f%n", divide(size, allQueryIndices.count()));
        stream.printf("Average bytes per base: %f%n", divide(size, cumulativeReadLength));
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
    final int numReadEntries = allQueryIndices.count();
    stream.printf("Has identifiers = %s (%,d) %n", numberOfIdentifiers > 0, numberOfIdentifiers);
    stream.printf("Has descriptions = %s (%,d) %n", numberOfDescriptions > 0, numberOfDescriptions);
    stream.printf("Has sequences = %s (%,d) %n", numberOfSequences > 0, numberOfSequences);
    stream.printf("Has sequencePairs = %s (%,d) %n", numberOfSequencePairs > 0, numberOfSequencePairs);
    stream.printf("Has quality scores = %s (%,d) %n", numberOfQualityScores > 0, numberOfQualityScores);
    stream.printf("Has quality score Pairs = %s (%,d) %n", numberOfQualityScorePairs > 0,
            numberOfQualityScorePairs);

    stream.printf("Number of entries = %,d%n", numReadEntries);
    stream.printf("Min read length = %,d%n", numReadEntries > 0 ? minLength : 0);
    stream.printf("Max read length = %,d%n", numReadEntries > 0 ? maxLength : 0);
    stream.printf("Min quality length = %,d%n", numberOfQualityScores > 0 ? minQualityLength : 0);
    stream.printf("Max quality length = %,d%n", numberOfQualityScores > 0 ? maxQualityLength : 0);
    stream.printf("Avg read length = %,d%n", numReadEntries > 0 ? totalReadLength / numReadEntries : 0);
    stream.printf("Avg read pair length = %,d%n",
            numReadEntries > 0 ? totalReadLengthPair / numReadEntries : 0);

    // compute quantiles
    if (computeQuantiles) {
        final Percentile percentile = new Percentile();
        final double[] increasingReadLengths = readLengths.toDoubleArray();
        Arrays.sort(increasingReadLengths);
        stream.printf("Read length quantiles = [ ");
        for (int quantile = 1; quantile < numberOfQuantiles + 1; quantile++) {
            stream.printf("%,f ", percentile.evaluate(increasingReadLengths, quantile));
        }
        stream.printf("]%n");
    }
}

From source file:com.cws.esolutions.security.dao.certmgmt.impl.CertificateManagerImpl.java

/**
 * @see com.cws.esolutions.security.dao.certmgmt.interfaces.ICertificateManager#applyCertificateRequest(String, File, File, String)
 *//*  ww  w. j  a  va 2  s. c om*/
public synchronized boolean applyCertificateRequest(final String commonName, final File certificateFile,
        final File keystoreFile, final String storePassword) throws CertificateManagementException {
    final String methodName = ICertificateManager.CNAME
            + "#applyCertificateRequest(final String commonName, final File certificateFile, final File keystoreFile, final String storePassword) throws CertificateManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", commonName);
        DEBUGGER.debug("Value: {}", certificateFile);
        DEBUGGER.debug("Value: {}", keystoreFile);
    }

    final File rootDirectory = certConfig.getRootDirectory();
    final File certificateDirectory = FileUtils
            .getFile(certConfig.getCertificateDirectory() + "/" + commonName);
    final File storeDirectory = FileUtils.getFile(certConfig.getStoreDirectory() + "/" + commonName);

    if (DEBUG) {
        DEBUGGER.debug("rootDirectory: {}", rootDirectory);
        DEBUGGER.debug("certificateDirectory: {}", certificateDirectory);
        DEBUGGER.debug("storeDirectory: {}", storeDirectory);
        DEBUGGER.debug("certificateFile: {}", certificateFile);
        DEBUGGER.debug("keystoreFile: {}", keystoreFile);
    }

    boolean isComplete = false;
    FileInputStream certStream = null;
    FileOutputStream storeStream = null;
    FileInputStream keystoreInput = null;
    FileInputStream rootCertStream = null;
    FileInputStream intermediateCertStream = null;

    try {
        if (!(rootDirectory.exists())) {
            throw new CertificateManagementException(
                    "Root certificate directory either does not exist or cannot be written to. Cannot continue.");
        }

        if (!(rootDirectory.canWrite())) {
            throw new CertificateManagementException(
                    "Root certificate directory either does not exist or cannot be written to. Cannot continue.");
        }

        if (!(certConfig.getRootCertificateFile().exists())) {
            throw new CertificateManagementException("Root certificate file does not exist. Cannot continue.");
        }

        if (!(certConfig.getIntermediateCertificateFile().exists())) {
            throw new CertificateManagementException(
                    "Intermediate certificate file does not exist. Cannot continue.");
        }

        if (!(storeDirectory.canWrite())) {
            throw new CertificateManagementException(
                    "Keystore directory either does not exist or cannot be written to. Cannot continue.");
        }

        if (!(keystoreFile.canWrite())) {
            throw new CertificateManagementException(
                    "Unable to write to applicable keystore. Cannot continue.");
        }

        keystoreInput = FileUtils.openInputStream(keystoreFile);
        certStream = FileUtils.openInputStream(certificateFile);

        if (DEBUG) {
            DEBUGGER.debug("keystoreInput: {}", keystoreInput);
            DEBUGGER.debug("certStream: {}", certStream);
        }

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(keystoreInput, storePassword.toCharArray());

        if (DEBUG) {
            DEBUGGER.debug("KeyStore: {}", keyStore);
        }

        Key privateKey = keyStore.getKey(commonName, storePassword.toCharArray());
        CertificateFactory certFactory = CertificateFactory.getInstance(certConfig.getCertificateType());

        if (DEBUG) {
            DEBUGGER.debug("CertificateFactory: {}", certFactory);
        }

        rootCertStream = FileUtils.openInputStream(FileUtils.getFile(certConfig.getRootCertificateFile()));
        intermediateCertStream = FileUtils
                .openInputStream(FileUtils.getFile(certConfig.getIntermediateCertificateFile()));

        if (DEBUG) {
            DEBUGGER.debug("rootCertStream: {}", rootCertStream);
            DEBUGGER.debug("intermediateCertStream: {}", intermediateCertStream);
        }

        X509Certificate[] responseCert = new X509Certificate[] {
                (X509Certificate) certFactory.generateCertificate(rootCertStream),
                (X509Certificate) certFactory.generateCertificate(intermediateCertStream),
                (X509Certificate) certFactory.generateCertificate(certStream) };

        if (DEBUG) {
            DEBUGGER.debug("X509Certificate[]", (Object) responseCert);
        }

        storeStream = FileUtils.openOutputStream(keystoreFile);
        keyStore.setKeyEntry(commonName, privateKey, storePassword.toCharArray(), responseCert);
        keyStore.store(storeStream, storePassword.toCharArray());

        isComplete = true;
    } catch (FileNotFoundException fnfx) {
        throw new CertificateManagementException(fnfx.getMessage(), fnfx);
    } catch (IOException iox) {
        throw new CertificateManagementException(iox.getMessage(), iox);
    } catch (NoSuchAlgorithmException nsax) {
        throw new CertificateManagementException(nsax.getMessage(), nsax);
    } catch (IllegalStateException isx) {
        throw new CertificateManagementException(isx.getMessage(), isx);
    } catch (KeyStoreException ksx) {
        throw new CertificateManagementException(ksx.getMessage(), ksx);
    } catch (CertificateException cx) {
        throw new CertificateManagementException(cx.getMessage(), cx);
    } catch (UnrecoverableKeyException ukx) {
        throw new CertificateManagementException(ukx.getMessage(), ukx);
    } finally {
        if (storeStream != null) {
            IOUtils.closeQuietly(storeStream);
        }

        if (intermediateCertStream != null) {
            IOUtils.closeQuietly(intermediateCertStream);
        }

        if (rootCertStream != null) {
            IOUtils.closeQuietly(rootCertStream);
        }

        if (certStream != null) {
            IOUtils.closeQuietly(certStream);
        }

        if (keystoreInput != null) {
            IOUtils.closeQuietly(keystoreInput);
        }
    }

    return isComplete;
}

From source file:gov.nih.nci.caarray.application.project.FileUploadUtilsTest.java

@Test
public void testUnpackFiles_MultipleZips() throws Exception {
    CaArrayFile mockFile = mock(CaArrayFile.class);
    CaArrayFile mockFile2 = mock(CaArrayFile.class);
    when(mockStorageFacade.openInputStream(any(URI.class), eq(false))).thenAnswer(new Answer<InputStream>() {
        @Override/*w  w  w .  j  a v  a2 s.  c  o m*/
        public InputStream answer(InvocationOnMock invocation) throws Throwable {
            return FileUtils.openInputStream(File.createTempFile("aaa", "bbb"));
        }

    });

    uploadUtils.unpackFiles(project, Lists.newArrayList(mockFile, mockFile2));
    verify(mockStorageFacade, times(2)).openInputStream(any(URI.class), eq(false));
}