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:com.elasticgrid.storage.rackspace.CloudFilesContainer.java

public Storable uploadStorable(String name, File file) throws StorageException {
    try {//from   ww w  . j av  a 2  s. c o m
        rackspace.login();
        // create directories if needed
        String path = name.substring(0, name.lastIndexOf('/'));
        logger.log(Level.FINE, "Creating full path \"{0}\"", path);
        rackspace.createFullPath(getName(), path);
        // upload the file
        logger.log(Level.FINE, "Uploading \"{0}\"", name);
        InputStream stream = null;
        try {
            stream = FileUtils.openInputStream(file);
            rackspace.storeStreamedObject(getName(), stream, mimes.getContentType(file), name,
                    Collections.<String, String>emptyMap());
        } finally {
            IOUtils.closeQuietly(stream);
        }
        // retrieve rackspace object
        return findStorableByName(name);
    } catch (Exception e) {
        throw new StorageException("Can't upload storable from file", e);
    }
}

From source file:com.orange.ocara.model.export.docx.AuditDocxExporter.java

/**
 * Create OleObject using a sample.//from   ww  w.ja  va 2 s . co m
 *
 * @param from File to embed
 * @param to   Destination file
 */
private void createOleObject(File from, File to) throws IOException, Ole10NativeException {
    File existingOleObject = new File(templateDirectory, "word/embeddings/oleObject.bin");

    OutputStream os = null;
    try {
        // When
        POIFSFileSystem fs = new POIFSFileSystem(FileUtils.openInputStream(existingOleObject));

        fs.getRoot().getEntry(Ole10Native.OLE10_NATIVE).delete();

        Ole10Native ole = new Ole10Native(from.getName(), from.getName(), from.getName(),
                IOUtils.toByteArray(FileUtils.openInputStream(from)));

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ole.writeOut(stream);

        fs.getRoot().createDocument(Ole10Native.OLE10_NATIVE, new ByteArrayInputStream(stream.toByteArray()));

        os = FileUtils.openOutputStream(to);
        fs.writeFilesystem(os);

    } finally {
        IOUtils.closeQuietly(os);
    }
}

From source file:com.buddycloud.mediaserver.MediaServerTest.java

private String getFileShaChecksum(File file) throws IOException {
    return DigestUtils.shaHex(FileUtils.openInputStream(file));
}

From source file:cat.calidos.morfeu.model.injection.DocumentTest.java

private Document parseRelativeLocation(String location)
        throws ParsingException, FetchingException, URISyntaxException, MalformedURLException, IOException {

    String absoluteLocation = this.getClass().getClassLoader().getResource(location).toString();
    URI uri = new URI(absoluteLocation);
    InputStream stream = FileUtils.openInputStream(FileUtils.toFile(uri.toURL()));
    ObjectMapper mapper = JSONMapperModule.produceJSONObjectMapper();
    Document document = DocumentModule.parseDocument(uri, stream, mapper);

    return document;

}

From source file:de.smartics.maven.plugin.jboss.modules.parser.ModulesXmlLocator.java

private void loadModules(final List<ModulesDescriptor> modules, final File rootDirectory) throws IOException {
    final File[] fileList = rootDirectory.listFiles();
    for (final File file : fileList) {
        if (!file.getName().endsWith(".xml")) {
            continue;
        }//from w ww  .jav a2  s  .c o m

        final InputStream input = new BufferedInputStream(FileUtils.openInputStream(file));
        final String fileId = file.getAbsolutePath();
        try {
            final ModulesDescriptor descriptor = parser.parse(fileId, input);
            modules.add(descriptor);
        } catch (final JDOMException e) {
            throw new IOException("Cannot parse XML file: " + fileId, e);
        } finally {
            IOUtils.closeQuietly(input);
        }
    }
}

From source file:controler.util.FileUtil.java

public static InputStream transFileToInputeStream(File initialFile) throws IOException {
    initialFile = new File("C:\\photography-logo-design (21).gif");
    InputStream targetStream = FileUtils.openInputStream(initialFile);
    return targetStream;
}

From source file:com.base2.kagura.core.authentication.FileAuthentication.java

public InputStream openFile(String file) {
    if (!new File(file).exists()) {
        URL dir_url = FileAuthentication.class.getResource(file);
        if (dir_url != null) {
            try {
                return dir_url.openStream();
            } catch (IOException e) {
                e.printStackTrace();//from www. j a  v  a  2s  .c  o  m
            }
        }
        try {
            return new URL(file).openStream();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    try {
        return FileUtils.openInputStream(new File(file));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

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

/**
 * Validates that the reformat compact reads mode is capable of writing the same contents.
 *
 * @throws IOException if there is a problem reading or writing to the files
 *///  w w  w. jav  a  2 s  .co m
@Test
public void zeroEntries() throws IOException {
    final ReformatCompactReadsMode reformat = new ReformatCompactReadsMode();

    final String inputFilename = "test-data/compact-reads/s_1_sequence_short.compact-reads";
    reformat.setInputFilenames(inputFilename);
    reformat.setStartPosition(0L);
    reformat.setEndPosition(0L);
    final String outputFilename = "test-results/reformat-test-zero-zero.compact-reads";
    reformat.setOutputFile(outputFilename);
    reformat.execute();

    final File inputFile = new File(inputFilename);
    final File outputFile = new File(outputFilename);
    assertFalse("The reformatted file should not be the same as the original",
            FileUtils.contentEquals(inputFile, outputFile));

    final ReadsReader reader = new ReadsReader(FileUtils.openInputStream(outputFile));
    assertFalse("There should be no reads in this file", reader.hasNext());
}

From source file:com.norconex.collector.http.crawler.AbstractHttpTest.java

protected List<HttpDocument> getCommitedDocuments(HttpCrawler crawler) throws IOException {
    File addDir = getCommitterAddDir(crawler);
    Collection<File> files = FileUtils.listFiles(addDir, null, true);
    List<HttpDocument> docs = new ArrayList<>();
    for (File file : files) {
        if (file.isDirectory() || !file.getName().endsWith(FileSystemCommitter.EXTENSION_CONTENT)) {
            continue;
        }//from w w w  . java  2  s.  c  o  m
        HttpMetadata meta = new HttpMetadata(file.getAbsolutePath());
        String basePath = StringUtils.removeEnd(file.getAbsolutePath(), FileSystemCommitter.EXTENSION_CONTENT);
        meta.load(FileUtils.openInputStream(new File(basePath + ".meta")));
        String reference = FileUtils.readFileToString(new File(basePath + ".ref"));

        HttpDocument doc = new HttpDocument(reference, crawler.getStreamFactory().newInputStream(file));
        // remove previous reference to avoid duplicates
        doc.getMetadata().remove(HttpMetadata.COLLECTOR_URL);
        doc.getMetadata().load(meta);
        docs.add(doc);
    }
    return docs;
}

From source file:io.hawkcd.agent.components.taskexecutor.executors.UploadArtifactExecutor.java

@Override
public Task executeTask(Task task, StringBuilder report, WorkInfo workInfo) {
    UploadArtifactTask taskDefinition = (UploadArtifactTask) task.getTaskDefinition();

    this.updateTask(task, TaskStatus.PASSED, LocalDateTime.now(), null);

    String uploadingMessage = String.format("Start uploading artifact source: %s ", taskDefinition.getSource());
    LOGGER.debug(uploadingMessage);//from  w  w  w. j  av  a 2 s .co m
    ReportAppender.appendInfoMessage(uploadingMessage, report);

    String pathToFile = AgentConfiguration.getInstallInfo().getAgentSandbox() + File.separator + "Pipelines"
            + File.separator + workInfo.getPipelineDefinitionName() + File.separator
            + taskDefinition.getSource();
    //        if (!taskDefinition.getSource().isEmpty()) {
    //            pathToFile = pathToFile + File.separator + taskDefinition.getSource();
    //        }

    String fullPath = this.fileManagementService.pathCombine(pathToFile);
    String rootPath = this.fileManagementService.getRootPath(fullPath);
    String wildCardPattern = this.fileManagementService.getPattern(rootPath, fullPath);

    if (rootPath.isEmpty()) {
        return this.nullProcessing(report, task,
                String.format("%s is Non-existent source.", taskDefinition.getSource()));
    }

    List<File> files = this.fileManagementService.getFiles(fullPath, wildCardPattern);

    if (files.size() == 0) {
        return this.nullProcessing(report, task, String.format("Error in getting files in %s", fullPath));
    }

    File zipFile = this.fileManagementService
            .generateUniqueFile(AgentConfiguration.getInstallInfo().getAgentTempDirectoryPath(), "zip");

    String errorMessage = this.fileManagementService.zipFiles(zipFile.getPath(), files, rootPath, true);

    if (errorMessage != null) {
        zipFile.delete();
        return this.nullProcessing(report, task, "Error occurred in zipping files!");
    }

    String executionFolder = String.valueOf(workInfo.getPipelineExecutionID());
    UploadArtifactInfo uploadArtifactInfo = new UploadArtifactInfo(zipFile, taskDefinition.getDestination());
    String folderPath = String.format(ConfigConstants.SERVER_CREATE_ARTIFACT_API_ADDRESS,
            workInfo.getPipelineDefinitionName(), executionFolder);
    AgentConfiguration.getInstallInfo().setCreateArtifactApiAddress(
            String.format("%s/%s", AgentConfiguration.getInstallInfo().getServerAddress(), folderPath));

    String destination = null;
    try {
        destination = URLEncoder.encode(taskDefinition.getDestination(), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();

    }

    String requestSource = this.fileManagementService
            .urlCombine(AgentConfiguration.getInstallInfo().getCreateArtifactApiAddress()) + "/upload-artifact"
            + "?destination=" + destination;
    WebResource webResource = this.restClient.resource(requestSource);
    InputStream targetStream = null;
    try {
        targetStream = FileUtils.openInputStream(zipFile);
    } catch (IOException e) {
        e.printStackTrace();
    }

    ClientResponse response = webResource.type(MediaType.MULTIPART_FORM_DATA_TYPE).post(ClientResponse.class,
            targetStream);

    if (response.getStatus() != 200) {
        zipFile.delete();
        return this.nullProcessing(report, task, String
                .format("Error occurred in server response! Returned status code: %s", response.getStatus()));
    }

    zipFile.delete();

    this.updateTask(task, TaskStatus.PASSED, null, LocalDateTime.now());

    return task;
}