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:edu.cornell.med.icb.goby.modes.TestReformatCompactReadsMode.java

/**
* Validates that reformating does not change quality score length by default.
* @throws IOException if there is a problem reading or writing to the files
*///from ww w . j a va 2s .c o m
@Test
public void reformatQualityScoreLength() 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-same.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();
    assertEquals(12, entry.getQualityScores().size());

}

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

@Test
public void testUnpackFiles_IOException() throws Exception {
    CaArrayFile mockFile = mock(CaArrayFile.class);
    InputStream input = FileUtils.openInputStream(File.createTempFile("aaa", "bbb"));
    IOUtils.closeQuietly(input);/* www. jav a  2s  . c o  m*/
    when(mockStorageFacade.openInputStream(any(URI.class), eq(false))).thenReturn(input);

    try {
        uploadUtils.unpackFiles(project, Lists.newArrayList(mockFile));
        fail("An InvalidFileException should have been thrown!");
    } catch (InvalidFileException e) {
        assertTrue(e.getCause() instanceof IOException);
    }
}

From source file:com.cts.ptms.carrier.ups.UPSHTTPClient.java

/**
 * This method to load the property file(s)
 *//*from w  w w  .  j  a  v  a  2 s  .  c  om*/
private void loadProperties() {
    try {
        File initialFile = new File(ShippingConstants.buildPropertiesPath);
        InputStream inputStream = FileUtils.openInputStream(initialFile);
        properties.load(inputStream);

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.buddycloud.mediaserver.business.dao.MediaDAO.java

protected Thumbnail getPreview(String entityId, String mediaId, Integer maxHeight, Integer maxWidth,
        String mediaDirectory)/*from   w ww.j a va2 s  . co  m*/
        throws MetadataSourceException, IOException, InvalidPreviewFormatException, MediaNotFoundException {
    File media = new File(mediaDirectory + File.separator + mediaId);

    if (!media.exists()) {
        throw new MediaNotFoundException(mediaId, entityId);
    }

    String previewId = dataSource.getPreviewId(mediaId, maxHeight, maxWidth);

    if (previewId != null) {
        File preview = new File(mediaDirectory + File.separator + previewId);

        if (!preview.exists()) {
            dataSource.deletePreview(previewId);
        } else {
            return new Thumbnail(dataSource.getPreviewMimeType(previewId),
                    IOUtils.toByteArray(FileUtils.openInputStream(preview)));
        }
    } else {
        // generate random id
        previewId = RandomStringUtils.randomAlphanumeric(20);
    }

    return buildNewPreview(media, mediaId, previewId, mediaDirectory, maxHeight, maxWidth);
}

From source file:key.secretkey.crypto.PgpHandler.java

public void decryptAndVerify(Intent data) {
    data.setAction(OpenPgpApi.ACTION_DECRYPT_VERIFY);

    findViewById(R.id.progress_bar).setVisibility(View.VISIBLE);

    try {//from ww w . j ava  2s  .c o m
        InputStream is = FileUtils.openInputStream(new File(getIntent().getExtras().getString("FILE_PATH")));

        ByteArrayOutputStream os = new ByteArrayOutputStream();

        OpenPgpApi api = new OpenPgpApi(this, mServiceConnection.getService());
        api.executeApiAsync(data, is, os, new PgpCallback(true, os, REQUEST_CODE_DECRYPT_AND_VERIFY));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.buddycloud.mediaserver.business.dao.MediaDAO.java

protected String getFileShaChecksum(File file) {
    try {//from w  w  w  .  j av a  2  s  .  c o m
        return DigestUtils.shaHex(FileUtils.openInputStream(file));
    } catch (IOException e) {
        LOGGER.error("Error during media SHA1 checksum generation.", e);
    }

    return null;
}

From source file:key.secretkey.crypto.PgpHandler.java

public void edit(Intent data) {
    // exactly same as decrypt, only we want a different callback
    data.setAction(OpenPgpApi.ACTION_DECRYPT_VERIFY);

    findViewById(R.id.progress_bar).setVisibility(View.VISIBLE);

    try {/*from   w w  w .  j  av a 2 s.  c o m*/
        InputStream is = FileUtils.openInputStream(new File(getIntent().getExtras().getString("FILE_PATH")));

        ByteArrayOutputStream os = new ByteArrayOutputStream();

        OpenPgpApi api = new OpenPgpApi(this, mServiceConnection.getService());
        api.executeApiAsync(data, is, os, new PgpCallback(true, os, REQUEST_CODE_EDIT));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:edu.ku.brc.specify.utilapps.sp5utils.Sp5Forms.java

@SuppressWarnings({ "unchecked" })
private void openXML() {
    FileDialog fileDlg = new FileDialog((Frame) UIRegistry.getTopWindow(), "", FileDialog.LOAD);

    fileDlg.setFilenameFilter(new FilenameFilter() {
        @Override// w w  w  . j a va2  s  . c o m
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".xml");
        }
    });
    fileDlg.setVisible(true);

    String fileName = fileDlg.getFile();
    if (fileName != null) {
        File iFile = new File(fileDlg.getDirectory() + File.separator + fileName);

        XStream xstream = new XStream();
        FormInfo.configXStream(xstream);
        FormFieldInfo.configXStream(xstream);

        try {
            forms = (Vector<FormInfo>) xstream.fromXML(FileUtils.openInputStream(iFile));
            formsTable.setModel(new FormCellModel(forms));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.vmware.photon.controller.deployer.xenon.workflow.BatchCreateManagementWorkflowService.java

private void generateCertificate(DeploymentService.State deploymentState) {
    if (!deploymentState.oAuthEnabled) {
        sendStageProgressPatch(TaskStage.STARTED, TaskState.SubStage.CREATE_VMS);
        return;/*ww  w.  j  a v a 2s. c o m*/
    }

    List<String> command = new ArrayList<>();
    command.add("./" + GENERATE_CERTIFICATE_SCRIPT_NAME);
    command.add(deploymentState.oAuthServerAddress);
    command.add(deploymentState.oAuthPassword);
    command.add(deploymentState.oAuthTenantName);
    command.add(PhotonControllerXenonHost.KEYSTORE_FILE);
    command.add(PhotonControllerXenonHost.KEYSTORE_PASSWORD);

    DeployerContext deployerContext = HostUtils.getDeployerContext(this);
    File scriptLogFile = new File(deployerContext.getScriptLogDirectory(),
            GENERATE_CERTIFICATE_SCRIPT_NAME + ".log");

    ScriptRunner scriptRunner = new ScriptRunner.Builder(command, deployerContext.getScriptTimeoutSec())
            .directory(deployerContext.getScriptDirectory())
            .redirectOutput(ProcessBuilder.Redirect.to(scriptLogFile)).build();

    ListenableFutureTask<Integer> futureTask = ListenableFutureTask.create(scriptRunner);
    HostUtils.getListeningExecutorService(this).submit(futureTask);

    Futures.addCallback(futureTask, new FutureCallback<Integer>() {
        @Override
        public void onSuccess(@javax.validation.constraints.NotNull Integer result) {
            try {
                if (result != 0) {
                    logScriptErrorAndFail(result, scriptLogFile);
                } else {
                    // Set the inInstaller flag to true which would allow us to override the xenon service client to talk
                    // to the auth enabled newly deployed management plane using https with two way SSL.
                    ((PhotonControllerXenonHost) getHost()).setInInstaller(true);

                    // need to switch the ssl context for the thrift clients to use
                    // the generated certs to be able to talk to the authenticated
                    // agents
                    try {
                        SSLContext sslContext = SSLContext.getInstance(KeyStoreUtils.THRIFT_PROTOCOL);
                        TrustManagerFactory tmf = null;

                        tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                        KeyStore keyStore = KeyStore.getInstance("JKS");
                        InputStream in = FileUtils
                                .openInputStream(new File(PhotonControllerXenonHost.KEYSTORE_FILE));
                        keyStore.load(in, PhotonControllerXenonHost.KEYSTORE_PASSWORD.toCharArray());
                        tmf.init(keyStore);
                        sslContext.init(null, tmf.getTrustManagers(), null);
                        ((PhotonControllerXenonHost) getHost()).regenerateThriftClients(sslContext);

                        KeyStoreUtils.acceptAllCerts(KeyStoreUtils.THRIFT_PROTOCOL);
                    } catch (Throwable t) {
                        ServiceUtils.logSevere(BatchCreateManagementWorkflowService.this,
                                "Regenerating the SSL Context for thrift failed, ignoring to make tests pass, it fail later");
                        ServiceUtils.logSevere(BatchCreateManagementWorkflowService.this, t);
                    }
                    sendStageProgressPatch(TaskStage.STARTED, TaskState.SubStage.CREATE_VMS);
                }
            } catch (Throwable t) {
                failTask(t);
            }
        }

        @Override
        public void onFailure(Throwable throwable) {
            failTask(throwable);
        }
    });
}

From source file:eu.cloud4soa.soa.ApplicationDeployment.java

@Override
public InputStream dumpDatabase(String applicationInstanceUriId, String paaSInstanceUriId,
        String dbStorageComponentUriId) throws SOAException {
    InputStream inputStream = null;
    logger.debug("received applicationInstanceUriId: " + applicationInstanceUriId);
    logger.debug("received paaSInstanceUriId: " + paaSInstanceUriId);
    logger.debug("received dbStorageComponentUriId: " + dbStorageComponentUriId);

    logger.debug("call applicationProfilesRepository.getApplicationInstance(applicationInstanceUriId)");

    ApplicationInstance applicationInstance;
    try {//from   www  .ja  v  a 2 s .c  om
        applicationInstance = applicationProfilesRepository.getApplicationInstance(applicationInstanceUriId);
    } catch (RepositoryException ex) {
        throw new SOAException(Response.Status.INTERNAL_SERVER_ERROR, ex.getMessage());
    }

    logger.debug("retrieved applicationInstance: " + applicationInstance);
    PaaSInstance paaSInstance;
    try {
        paaSInstance = paaSOfferingProfilesRepository.getPaaSInstance(paaSInstanceUriId);
    } catch (RepositoryException ex) {
        throw new SOAException(Response.Status.INTERNAL_SERVER_ERROR, ex.getMessage());
    }
    logger.debug("retrived paaSInstance: " + paaSInstance);

    //check if the application is deployed (The application should be stopped or not deployed during the db initialization)
    if (applicationInstance.getPaaSOfferingDeploymentName() != null) {
        if (applicationInstance.getStatus().compareTo(StatusType.Stopped) != 0)
            throw new SOAException(Response.Status.BAD_REQUEST,
                    "The selected application is deployed and running.");
    }

    String dbUrl = null;
    String dbName = null;
    String dbUser = null;
    String dbPassword = null;
    String dbType = null;

    List<SoftwareComponentInstance> softwareComponents = applicationInstance.getSoftwareComponents();

    for (SoftwareComponentInstance softwareComponentInstance : softwareComponents) {
        String uriId = softwareComponentInstance.getUriId();
        if (softwareComponentInstance instanceof DBStorageComponentInstance
                && uriId.equals(dbStorageComponentUriId)) {
            logger.debug("found DBStorageComponent having dbStorageComponentUriId: " + dbStorageComponentUriId);
            DBStorageComponentInstance dbStorageComponentInstance = (DBStorageComponentInstance) softwareComponentInstance;

            //check if the db is already created
            if (dbStorageComponentInstance.getDeploymentLocationUriId() == null) {
                throw new SOAException(Response.Status.BAD_REQUEST, "The selected db has to be created first.");
            }

            dbName = dbStorageComponentInstance.getDbname();
            dbUser = dbStorageComponentInstance.getDbuser();
            dbPassword = dbStorageComponentInstance.getDbpassword();
            dbType = dbStorageComponentInstance.getRelatedhwcategoryInstance().getTitle();

            UserPaaSCredentials userCredentialsForPaaS = userManagementAndSecurityModule
                    .readUserCredentialsForPaaS(applicationInstance.getOwnerUriId(), paaSInstance.getUriId());
            File dumpFile;
            try {
                dumpFile = File.createTempFile(dbName + "_" + "dump", ".sql");
            } catch (IOException ex) {
                String error = "Impossible to dump database: " + dbName
                        + " since the temp file cannot be created - cause: " + ex.getMessage();
                logger.error(error);
                throw new SOAException(Response.Status.INTERNAL_SERVER_ERROR,
                        "Error in dumping the DB: " + dbName);
            }
            try {
                executionManagementServiceModule.downloadDataBase(applicationInstance,
                        userCredentialsForPaaS.getPublicKey(), userCredentialsForPaaS.getSecretKey(), dbName,
                        dbUser, dbPassword, dbType, dumpFile.getAbsolutePath());
                inputStream = FileUtils.openInputStream(dumpFile);
            } catch (IOException ex) {
                String error = "Impossible to dump database: " + dbName
                        + " since the temp file cannot be read - cause: " + ex.getMessage();
                logger.error(error);
                throw new SOAException(Response.Status.INTERNAL_SERVER_ERROR,
                        "Error in dumping the DB: " + dbName);
            } catch (Cloud4SoaException ex) {
                String error = "Impossible to dump database: " + dbName + " cause: " + ex.getMessage();
                logger.error(error);
                throw new SOAException(Response.Status.INTERNAL_SERVER_ERROR,
                        "Error in dumping the DB: " + dbName);
            }
        }
    }

    return inputStream;
}