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:ke.co.tawi.babblesms.server.servlet.export.csv.ExportCsv.java

/**
 * Returns a zipped MS Excel file of the data specified for exporting.
 *
 * @param request/* w w w.j a v  a 2  s .c o m*/
 * @param response
 * @throws ServletException, IOException
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    ServletOutputStream out = response.getOutputStream();
    response.setContentType("application/zip");
    response.setHeader("Cache-Control", "cache, must-revalidate");
    response.setHeader("Pragma", "public");

    HttpSession session = request.getSession(false);
    Account account;
    String fileName;

    String exportExcelOption = request.getParameter("exportExcel");

    String sessionEmail = (String) session.getAttribute(SessionConstants.ACCOUNT_SIGN_IN_KEY);

    Element element = accountsCache.get(sessionEmail);
    account = (Account) element.getObjectValue();

    fileName = new StringBuffer(account.getUsername()).append(" ").append(SPREADSHEET_NAME).toString();

    response.setHeader("Content-Disposition",
            "attachment; filename=\"" + StringUtils.replace(fileName, ".xlsx", ".zip") + "\"");

    File excelFile = new File(FileUtils.getTempDirectoryPath() + File.separator + fileName);
    File csvFile = new File(StringUtils.replace(excelFile.getCanonicalPath(), ".xlsx", ".csv"));
    File zippedFile = new File(StringUtils.replace(excelFile.getCanonicalPath(), ".xlsx", ".zip"));

    // These are to determine whether or not we have created a CSV & Excel file on disk
    boolean successCSVFile = true, successExcelFile = true;

    if (StringUtils.equalsIgnoreCase(exportExcelOption, "Export All")) { //export all pages
        successCSVFile = dbFileUtils.sqlResultToCSV(getExportTopupsSqlQuery(account), csvFile.toString(), '|');

        if (successCSVFile) {
            successExcelFile = AllTopupsExportUtil.createExcelExport(csvFile.toString(), "|",
                    excelFile.toString());
        }

    } else if (StringUtils.equalsIgnoreCase(exportExcelOption, "Export Page")) { //export a single page

        InboxPage inboxPage = (InboxPage) session.getAttribute("currentInboxPage");

        successExcelFile = AllTopupsExportUtil.createExcelExport(inboxPage.getContents(), networkHash,
                networkHash, "|", excelFile.toString());

    } else { //export search results

        InboxPage topupPage = (InboxPage) session.getAttribute("currentSearchPage");

        successExcelFile = AllTopupsExportUtil.createExcelExport(topupPage.getContents(), networkHash,
                networkHash, "|", excelFile.toString());
    }

    if (successExcelFile) { // If we successfully created the MS Excel File on disk  
        // Zip the Excel file
        List<File> filesToZip = new ArrayList<>();
        filesToZip.add(excelFile);
        ZipUtil.compressFiles(filesToZip, zippedFile.toString());

        // Push the file to the request
        FileInputStream input = FileUtils.openInputStream(zippedFile);
        IOUtils.copy(input, out);
    }

    out.close();

    FileUtils.deleteQuietly(excelFile);
    FileUtils.deleteQuietly(csvFile);
    FileUtils.deleteQuietly(zippedFile);
}

From source file:architecture.ee.web.logo.DefaultLogoManager.java

public InputStream getImageInputStream(LogoImage image) throws IOException {
    try {//from   w ww  .j  a va2 s . c  om
        File file = getImageFromCacheIfExist(image);
        return FileUtils.openInputStream(file);
    } catch (IOException e) {
        throw new SystemException(e);
    }
}

From source file:com.perceptive.epm.perkolcentral.bl.ImageNowLicenseBL.java

@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.SERIALIZABLE, readOnly = true, rollbackFor = ExceptionWrapper.class)
public FileInputStream getSysFpFileInputStream(Imagenowlicenses imagenowlicenses) throws ExceptionWrapper {
    try {//from w  w w  .  ja  v  a 2s. c  o  m
        imagenowlicenses = imageNowLicenseDataAccessor
                .getAllImageNowLicensesByRequestId(imagenowlicenses.getImageNowLicenseRequestId());
        File filePathForThisRequest = new File(
                FilenameUtils.concat(fileUploadPath, imagenowlicenses.getImageNowLicenseRequestId()));
        File fileLocation = new File(
                FilenameUtils.concat(filePathForThisRequest.getAbsolutePath(), imagenowlicenses.getFileName()));
        return FileUtils.openInputStream(fileLocation);

    } catch (Exception ex) {
        throw new ExceptionWrapper(ex);
    }
}

From source file:com.book.identification.rest.VolumeResource.java

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)/*from   www.  ja  v a  2s  .  c  o m*/
@Path("upload/")
public Response upload(@FormDataParam("file") InputStream inputStream) throws Exception {
    //Save in temporal file
    File tempFile = File.createTempFile(UUID.randomUUID().toString(), ".temp");
    FileUtils.copyInputStreamToFile(inputStream, tempFile);

    String md5Hex = DigestUtils.md5Hex(FileUtils.openInputStream(tempFile));

    java.nio.file.Path path = new File(System.getProperty("user.dir")).toPath().resolve("books");
    if (!Files.exists(path)) {
        Files.createDirectories(path);
    }
    java.nio.file.Path filePath = path.resolve(md5Hex);

    try {
        Files.copy(tempFile.toPath(), filePath, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        return Response.serverError().build();
    }
    return Response.ok(md5Hex).build();

}

From source file:architecture.ee.web.logo.DefaultLogoManager.java

public InputStream getImageThumbnailInputStream(LogoImage image, int width, int height) {
    try {//from  w  w  w . j  av  a2 s. c om
        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.dataStorage.database.DatabaseMultipartBlobDataStorage.java

/**
 * {@inheritDoc}/*w ww  .ja  v  a 2 s.co m*/
 */
@Override
public InputStream openInputStream(URI handle, boolean compressed) throws DataStoreException {
    checkScheme(handle);
    try {
        return new AutoCloseInputStream(FileUtils.openInputStream(openFile(handle, compressed)));
    } catch (final IOException e) {
        throw new DataStoreException("Could not open input stream for data: ", e);
    }
}

From source file:com.teotigraphix.caustk.utils.RuntimeUtils.java

public static final FileInputStream openInputStream(File file) throws IOException {
    return FileUtils.openInputStream(file);
}

From source file:gov.nih.nci.firebird.web.common.Struts2UploadedFileInfo.java

/**
 * @return file type using magic number.
 * @see MagicFile#getMimeType(java.io.InputStream) .
 *//*from  w ww  .  ja  v  a 2  s .c  o m*/
private String getMagicFileType() {
    byte[] litmus = new byte[(int) Math.min(data.length(), (long) IDENTIFIER.getMinArrayLength())];
    FileInputStream in = null;
    String type = null;
    try {
        in = FileUtils.openInputStream(data);
        in.read(litmus);
        type = IDENTIFIER.identify(litmus, dataFileName, null);
    } catch (IOException ex) {
        LOG.warn(ex);
    } finally {
        IOUtils.closeQuietly(in);
    }
    return type;
}

From source file:it.serverSystem.ClusterTest.java

private static void updateSonarPropertiesFile(Orchestrator orchestrator, Map<String, String> props)
        throws IOException {
    Properties propsFile = new Properties();
    try (FileInputStream conf = FileUtils
            .openInputStream(new File(orchestrator.getServer().getHome(), CONF_FILE_PATH))) {
        propsFile.load(conf);//ww  w  . ja v a2 s  .  c  om
        propsFile.putAll(props);
    }
    try (FileOutputStream conf = FileUtils
            .openOutputStream(new File(orchestrator.getServer().getHome(), CONF_FILE_PATH))) {
        propsFile.store(conf, "");
    }
}

From source file:gov.nih.nci.caarray.application.fileaccess.FileAccessServiceStub.java

@Override
public InputStream openInputStream(URI handle, boolean compressed) throws DataStoreException {
    checkScheme(handle);/*from  w  ww.  j  a  va2  s.  c  o m*/
    try {
        return new AutoCloseInputStream(FileUtils.openInputStream(openFile(handle, compressed)));
    } catch (final IOException e) {
        throw new DataStoreException("Could not open input stream for data " + handle + ":", e);
    }
}