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.splunk.shuttl.server.mbeans.ShuttlArchiverMBeanArchiverRootURITest.java

private void set_Backend_archivePath_andAmazonProperties() throws IOException {
    String id = "theId";
    String secret = "theSecret";
    String bucket = "theBucket";
    String archiverRootURI = "s3n://" + id + ":" + secret + "@" + bucket + "/archiver_root";

    createArchiverMbeanWithArchiverRootURI(archiverRootURI);
    assertEquals("s3n", archiverMBean.getBackendName());
    assertEquals("/archiver_root", archiverMBean.getArchivePath());

    Properties amazonProperties = new Properties();
    File amazonPropertiesFile = BackendConfigurationFiles.create()
            .getByName(AWSCredentialsImpl.AMAZON_PROPERTIES_FILENAME);
    amazonProperties.load(FileUtils.openInputStream(amazonPropertiesFile));
    assertEquals(id, amazonProperties.getProperty("aws.id"));
    assertEquals(secret, amazonProperties.getProperty("aws.secret"));
    assertEquals(bucket, amazonProperties.getProperty("s3.bucket"));
}

From source file:ching.icecreaming.actions.FileLink.java

@Action(value = "file-link", results = { @Result(name = "success", type = "stream", params = { "inputName",
        "imageStream", "contentType", "${contentType}", "contentDisposition", "attachment;filename=${fileName}",
        "allowCaching", "false", "bufferSize", "1024" }), @Result(name = "error", location = "errors.jsp") })
public String execute() throws Exception {
    Configuration propertiesConfiguration1 = new PropertiesConfiguration("mimeTypes.properties");
    File file1 = null, file2 = null;
    String string1 = null, fileExtension = null;
    fileExtension = FilenameUtils.getExtension(fileName);
    contentType = "application/octet-stream";
    if (!StringUtils.isBlank(fileExtension)) {
        if (propertiesConfiguration1.containsKey(fileExtension))
            contentType = propertiesConfiguration1.getString(fileExtension);
    } else {//from www  .j a v a 2 s.c  o m
        contentType = "image/png";
    }
    try {
        if (StringUtils.isBlank(sessionId)) {
            sessionId = httpServletRequest.getSession().getId();
        }
        string1 = System.getProperty("java.io.tmpdir") + File.separator + sessionId;
        if (StringUtils.isBlank(fileExtension))
            string1 += File.separator + FilenameUtils.getPath(fileName);
        fileName = FilenameUtils.getName(fileName);
        if (StringUtils.equalsIgnoreCase(fileExtension, "html")) {
            file2 = new File(string1, FilenameUtils.getBaseName(fileName) + ".zip");
            if (file2.exists()) {
                file1 = file2;
                contentType = "application/zip";
                fileName = file2.getName();
            } else {
                file1 = new File(string1, fileName);
            }
        } else {
            file1 = new File(string1, fileName);
        }
        if (file1.exists()) {
            imageStream = new BufferedInputStream(FileUtils.openInputStream(file1));
        }
    } catch (IOException exception1) {
        addActionError(exception1.getMessage());
        return ERROR;
    }
    return SUCCESS;
}

From source file:architecture.ee.web.community.profile.DefaultProfileManager.java

public InputStream getImageInputStream(ProfileImage image) {
    try {//  w w w. j ava2  s.c  o m
        File file = getImageFromCacheIfExist(image);
        return FileUtils.openInputStream(file);
    } catch (IOException e) {
        throw new SystemException(e);
    }
}

From source file:com.hangum.tadpole.commons.dialogs.fileupload.SingleFileuploadDialog.java

private boolean insert() throws Exception {
    BOMInputStream bomInputStream;//from w  ww .  j ava 2  s  .  co m

    File[] arryFiles = receiver.getTargetFiles();
    if (arryFiles.length == 0) {
        throw new Exception(Messages.get().SingleFileuploadDialog_5);
    }

    File userUploadFile = arryFiles[arryFiles.length - 1];
    try {
        // bom?  charset? ? ?.
        bomInputStream = new BOMInputStream(FileUtils.openInputStream(FileUtils.getFile(userUploadFile)));
        ByteOrderMark bom = bomInputStream.getBOM();
        String charsetName = bom == null ? "CP949" : bom.getCharsetName(); //$NON-NLS-1$

        strTxtFile = FileUtils.readFileToString(userUploadFile, charsetName);
        if (bom != null) {
            // ByteOrderMark.UTF_8.equals(strTxtFile.getBytes()[0]);
            //??? ??  BOM? .
            strTxtFile = strTxtFile.substring(1);
        }

    } catch (Exception e) {
        logger.error("file read error", e); //$NON-NLS-1$
        throw new Exception(Messages.get().SingleFileuploadDialog_7 + e.getMessage());
    }

    return true;
}

From source file:net.larry1123.elec.util.logger.LoggerDirectoryHandler.java

protected void packFile(File file, ZipArchiveOutputStream zipArchiveOutputStream) throws IOException {
    String relative = getDirectoryPath().relativize(file.toPath()).toString();
    // Make an Entry in the archive
    ArchiveEntry archiveEntry = zipArchiveOutputStream.createArchiveEntry(file, relative);
    FileInputStream fileInputStream = FileUtils.openInputStream(file);
    zipArchiveOutputStream.putArchiveEntry(archiveEntry);
    // Copy file content into archive
    IOUtils.copy(fileInputStream, zipArchiveOutputStream);
    zipArchiveOutputStream.closeArchiveEntry();
}

From source file:functionaltests.RestSchedulerPushPullFileTest.java

public void testIt(String spaceName, String spacePath, String destPath, boolean encode) throws Exception {
    File testPushFile = RestFuncTHelper.getDefaultJobXmlfile();
    // you can test pushing pulling a big file :
    // testPushFile = new File("path_to_a_big_file");
    File destFile = new File(new File(spacePath, destPath), testPushFile.getName());
    if (destFile.exists()) {
        destFile.delete();/*from  w  ww .j a  v  a2s  .c o  m*/
    }

    // PUSHING THE FILE
    String pushfileUrl = getResourceUrl("dataspace/" + spaceName + "/"
            + (encode ? URLEncoder.encode(destPath, "UTF-8") : destPath.replace("\\", "/")));
    // either we encode or we test human readable path (with no special character inside)

    HttpPost reqPush = new HttpPost(pushfileUrl);
    setSessionHeader(reqPush);
    // we push a xml job as a simple test

    MultipartEntity multipartEntity = new MultipartEntity();
    multipartEntity.addPart("fileName", new StringBody(testPushFile.getName()));
    multipartEntity.addPart("fileContent", new InputStreamBody(FileUtils.openInputStream(testPushFile),
            MediaType.APPLICATION_OCTET_STREAM, null));
    reqPush.setEntity(multipartEntity);
    HttpResponse response = executeUriRequest(reqPush);

    System.out.println(response.getStatusLine());
    assertHttpStatusOK(response);
    Assert.assertTrue(destFile + " exists for " + spaceName, destFile.exists());

    Assert.assertTrue("Original file and result are equals for " + spaceName,
            FileUtils.contentEquals(testPushFile, destFile));

    // LISTING THE TARGET DIRECTORY
    String pullListUrl = getResourceUrl("dataspace/" + spaceName + "/"
            + (encode ? URLEncoder.encode(destPath, "UTF-8") : destPath.replace("\\", "/")));

    HttpGet reqPullList = new HttpGet(pullListUrl);
    setSessionHeader(reqPullList);

    HttpResponse response2 = executeUriRequest(reqPullList);

    System.out.println(response2.getStatusLine());
    assertHttpStatusOK(response2);

    InputStream is = response2.getEntity().getContent();
    List<String> lines = IOUtils.readLines(is);
    HashSet<String> content = new HashSet<>(lines);
    System.out.println(lines);
    Assert.assertTrue("Pushed file correctly listed", content.contains(testPushFile.getName()));

    // PULLING THE FILE
    String pullfileUrl = getResourceUrl("dataspace/" + spaceName + "/"
            + (encode ? URLEncoder.encode(destPath + "/" + testPushFile.getName(), "UTF-8")
                    : destPath.replace("\\", "/") + "/" + testPushFile.getName()));

    HttpGet reqPull = new HttpGet(pullfileUrl);
    setSessionHeader(reqPull);

    HttpResponse response3 = executeUriRequest(reqPull);

    System.out.println(response3.getStatusLine());
    assertHttpStatusOK(response3);

    InputStream is2 = response3.getEntity().getContent();

    File answerFile = tmpFolder.newFile();
    FileUtils.copyInputStreamToFile(is2, answerFile);

    Assert.assertTrue("Original file and result are equals for " + spaceName,
            FileUtils.contentEquals(answerFile, testPushFile));

    // DELETING THE HIERARCHY
    String rootPath = destPath.substring(0, destPath.contains("/") ? destPath.indexOf("/") : destPath.length());
    String deleteUrl = getResourceUrl("dataspace/" + spaceName + "/"
            + (encode ? URLEncoder.encode(rootPath, "UTF-8") : rootPath.replace("\\", "/")));
    HttpDelete reqDelete = new HttpDelete(deleteUrl);
    setSessionHeader(reqDelete);

    HttpResponse response4 = executeUriRequest(reqDelete);

    System.out.println(response4.getStatusLine());

    assertHttpStatusOK(response4);

    Assert.assertTrue(destFile + " still exist", !destFile.exists());
}

From source file:architecture.ee.web.community.profile.DefaultProfileManager.java

public InputStream getImageThumbnailInputStream(ProfileImage image, int width, int height) {
    try {/*  w  w w  .j a  va 2  s  .  c o m*/
        File file = getThumbnailFromCacheIfExist(image, width, height);
        return FileUtils.openInputStream(file);
    } catch (IOException e) {
        throw new SystemException(e);
    } finally {

    }
}

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

private void unpackUploadedFile(Project project, File currentFile, String fileName)
        throws InvalidFileException {
    checkIsZipFile(fileName);/*w ww .j a  va 2  s  . c  o  m*/
    try {
        final InputStream input = FileUtils.openInputStream(currentFile);
        unpackFile(project, fileName, input);
    } catch (final IOException e) {
        throw new InvalidFileException(fileName, UNPACKING_ERROR_KEY, result, UNPACKING_ERROR_MESSAGE, e);
    }
}

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

private void runIndexing(final Indexer indexer, final DirectoryScanner scanner) {
    scanner.scan();/* w w  w  .  j  a v a2s  .  c  o m*/

    for (final String fileName : scanner.getIncludedFiles()) {
        if (!fileName.endsWith(".class")) {
            continue;
        }

        final File file = new File(scanner.getBasedir(), fileName);
        InputStream input = null;
        try {
            input = FileUtils.openInputStream(file);
            final ClassInfo info = indexer.index(input);

            if (verbose) {
                getLog().info(String.format("Indexed %2d annotations in file %s.", info.annotations().size(),
                        info.name()));
            }
        } catch (final IOException e) {
            IOUtils.closeQuietly(input);
        }
    }
}

From source file:gov.usgs.anss.query.MultiplexedMSOutputer.java

/**
 * This does the hard work of sorting - called as a shutdown hook.
 * TODO: consider recursion.//from  www  . j  ava2  s .com
 * @param outputName name for the output file.
 * @param files list of MiniSEED files to multiplex.
 * @param cleanup flag indicating whether to cleanup after ourselves or not.
 * @throws IOException
 */
public static void multiplexFiles(String outputName, List<File> files, boolean cleanup, boolean allowEmpty)
        throws IOException {
    ArrayList<File> cleanupFiles = new ArrayList<File>(files);
    ArrayList<File> moreFiles = new ArrayList<File>();

    File outputFile = new File(outputName);
    File tempOutputFile = new File(outputName + ".tmp");

    do {
        // This checks if we're in a subsequent (i.e. not the first) iteration and if there are any more files to process...?
        if (!moreFiles.isEmpty()) {
            logger.info("more files left to multiplex...");
            FileUtils.deleteQuietly(tempOutputFile);
            FileUtils.moveFile(outputFile, tempOutputFile);

            cleanupFiles.add(tempOutputFile);
            moreFiles.add(tempOutputFile);
            files = moreFiles;
            moreFiles = new ArrayList<File>();
        }

        logger.log(Level.FINE, "Multiplexing blocks from {0} temp files to {1}",
                new Object[] { files.size(), outputName });
        BufferedOutputStream out = new BufferedOutputStream(FileUtils.openOutputStream(outputFile));

        // The hard part, sorting the temp files...
        TreeMap<MiniSeed, FileInputStream> blks = new TreeMap<MiniSeed, FileInputStream>(
                new MiniSeedTimeOnlyComparator());
        // Prime the TreeMap
        logger.log(Level.FINEST, "Priming the TreeMap with files: {0}", files);
        for (File file : files) {
            logger.log(Level.INFO, "Reading first block from {0}", file.toString());
            try {
                FileInputStream fs = FileUtils.openInputStream(file);
                MiniSeed ms = getNextValidMiniSeed(fs, allowEmpty);
                if (ms != null) {
                    blks.put(ms, fs);
                } else {
                    logger.log(Level.WARNING, "Failed to read valid MiniSEED block from {0}", file.toString());
                }
            } catch (IOException ex) {
                // Catch "Too many open files" i.e. hitting ulimit, throw anything else.
                if (ex.getMessage().contains("Too many open files")) {
                    logger.log(Level.INFO, "Too many open files - {0} deferred.", file.toString());
                    moreFiles.add(file);
                } else
                    throw ex;
            }
        }

        while (!blks.isEmpty()) {
            MiniSeed next = blks.firstKey();
            out.write(next.getBuf(), 0, next.getBlockSize());

            FileInputStream fs = blks.remove(next);
            next = getNextValidMiniSeed(fs, allowEmpty);
            if (next != null) {
                blks.put(next, fs);
            } else {
                fs.close();
            }
        }

        out.close();
    } while (!moreFiles.isEmpty());

    if (cleanup) {
        logger.log(Level.INFO, "Cleaning up...");
        for (File file : cleanupFiles) {
            FileUtils.deleteQuietly(file);
        }
    }
}