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:eu.apenet.dpt.standalone.gui.eaccpf.EacCpfFrame.java

public void createFrame(File eacFile, boolean isNew) {
    try {/*  w w  w . ja v  a2  s. com*/
        createFrame(FileUtils.openInputStream(eacFile), isNew);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.l2jserver.service.core.logging.TruncateToZipFileAppender.java

/**
 * This method creates archive with file instead of deleting it.
 * //from www.  j av  a2 s  . c o  m
 * @param file
 *            file to truncate
 */
protected void truncate(File file) {
    LogLog.debug("Compression of file: " + file.getAbsolutePath() + " started.");

    // Linux systems doesn't provide file creation time, so we have to hope
    // that log files
    // were not modified manually after server starup
    // We can use here Windowns-only solution but that suck :(
    if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) {
        File backupRoot = new File(getBackupDir());
        if (!backupRoot.exists() && !backupRoot.mkdirs()) {
            throw new Error("Can't create backup dir for backup storage");
        }

        SimpleDateFormat df;
        try {
            df = new SimpleDateFormat(getBackupDateFormat());
        } catch (Exception e) {
            throw new Error("Invalid date formate for backup files: " + getBackupDateFormat(), e);
        }
        String date = df.format(new Date(file.lastModified()));

        File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip");

        ZipOutputStream zos = null;
        FileInputStream fis = null;
        try {
            zos = new ZipOutputStream(new FileOutputStream(zipFile));
            ZipEntry entry = new ZipEntry(file.getName());
            entry.setMethod(ZipEntry.DEFLATED);
            entry.setCrc(FileUtils.checksumCRC32(file));
            zos.putNextEntry(entry);
            fis = FileUtils.openInputStream(file);

            byte[] buffer = new byte[1024];
            int readed;
            while ((readed = fis.read(buffer)) != -1) {
                zos.write(buffer, 0, readed);
            }

        } catch (Exception e) {
            throw new Error("Can't create zip file", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    // not critical error
                    LogLog.warn("Can't close zip file", e);
                }
            }

            if (fis != null) {
                try {
                    // not critical error
                    fis.close();
                } catch (IOException e) {
                    LogLog.warn("Can't close zipped file", e);
                }
            }
        }

        if (!file.delete()) {
            throw new Error("Can't delete old log file " + file.getAbsolutePath());
        }
    }
}

From source file:com.silverpeas.sharing.servlets.GetLinkFileServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    RestRequest rest = new RestRequest(request, "myFile");
    String keyFile = rest.getElementValue(PARAM_KEYFILE);
    Ticket ticket = SharingServiceFactory.getSharingTicketService().getTicket(keyFile);
    if (ticket != null && ticket.isValid()) {
        // recherche des infos sur le fichier...
        String filePath = null;// w ww  .  ja va 2s .  co m
        String fileType = null;
        String fileName = null;
        long fileSize = 0;
        if (ticket instanceof SimpleFileTicket) {
            SimpleDocumentPK pk = new SimpleDocumentPK(null, ticket.getComponentId());
            pk.setOldSilverpeasId(ticket.getSharedObjectId());
            SimpleDocument document = AttachmentServiceFactory.getAttachmentService().searchDocumentById(pk,
                    null);
            filePath = document.getAttachmentPath();
            fileType = document.getContentType();
            fileName = document.getFilename();
            fileSize = document.getSize();
        } else if (ticket instanceof VersionFileTicket) {
            SimpleDocumentPK pk = new SimpleDocumentPK(null, ticket.getComponentId());
            pk.setOldSilverpeasId(ticket.getSharedObjectId());
            HistorisedDocument versionedDocument = (HistorisedDocument) AttachmentServiceFactory
                    .getAttachmentService().searchDocumentById(pk, null);
            SimpleDocument document = versionedDocument.getLastPublicVersion();
            filePath = document.getAttachmentPath();
            fileType = document.getContentType();
            fileName = document.getFilename();
            fileSize = document.getSize();
        }
        File realFile = new File(filePath);
        BufferedInputStream input = null;
        OutputStream out = response.getOutputStream();
        try {
            response.setContentType(fileType);
            response.setHeader("Content-Disposition", "inline; filename=\"" + fileName + "\"");
            response.setHeader("Content-Length", String.valueOf(fileSize));
            input = new BufferedInputStream(FileUtils.openInputStream(realFile));
            IOUtils.copy(input, out);
            DownloadDetail download = new DownloadDetail(ticket, new Date(), request.getRemoteAddr());
            SharingServiceFactory.getSharingTicketService().addDownload(download);
            return;
        } catch (Exception ignored) {
        } finally {
            if (input != null) {
                IOUtils.closeQuietly(input);
            }
            IOUtils.closeQuietly(out);
        }
    }
    getServletContext().getRequestDispatcher("/sharing/jsp/invalidTicket.jsp").forward(request, response);
}

From source file:com.aionemu.commons.log4j.appenders.TruncateToZipFileAppender.java

/**
 * This method creates archive with file instead of deleting it.
 *
 * @param file file to truncate// www  .  j a v  a2s  .c  o  m
 */
protected void truncate(File file) {
    LogLog.debug("Compression of file: " + file.getAbsolutePath() + " started.");

    // Linux systems doesn't provide file creation time, so we have to hope
    // that log files
    // were not modified manually after server starup
    // We can use here Windowns-only solution but that suck :(
    if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) {
        File backupRoot = new File(getBackupDir());
        if (!backupRoot.exists() && !backupRoot.mkdirs()) {
            throw new AppenderInitializationError("Can't create backup dir for backup storage");
        }

        SimpleDateFormat df;
        try {
            df = new SimpleDateFormat(getBackupDateFormat());
        } catch (Exception e) {
            throw new AppenderInitializationError(
                    "Invalid date formate for backup files: " + getBackupDateFormat(), e);
        }
        String date = df.format(new Date(file.lastModified()));

        File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip");

        ZipOutputStream zos = null;
        FileInputStream fis = null;
        try {
            zos = new ZipOutputStream(new FileOutputStream(zipFile));
            ZipEntry entry = new ZipEntry(file.getName());
            entry.setMethod(ZipEntry.DEFLATED);
            entry.setCrc(FileUtils.checksumCRC32(file));
            zos.putNextEntry(entry);
            fis = FileUtils.openInputStream(file);

            byte[] buffer = new byte[1024];
            int readed;
            while ((readed = fis.read(buffer)) != -1) {
                zos.write(buffer, 0, readed);
            }

        } catch (Exception e) {
            throw new AppenderInitializationError("Can't create zip file", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    // not critical error
                    LogLog.warn("Can't close zip file", e);
                }
            }

            if (fis != null) {
                try {
                    // not critical error
                    fis.close();
                } catch (IOException e) {
                    LogLog.warn("Can't close zipped file", e);
                }
            }
        }

        if (!file.delete()) {
            throw new AppenderInitializationError("Can't delete old log file " + file.getAbsolutePath());
        }
    }
}

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

private void readChunk(File chunk, CaArrayFile caArrayFile) {
    try {/*w w  w.ja va  2s . co m*/
        final InputStream is = FileUtils.openInputStream(chunk);
        final StorageMetadata metadata = this.dataStorageFacade.addFileChunk(caArrayFile.getDataHandle(), is);
        caArrayFile.setDataHandle(metadata.getHandle());
        caArrayFile.setPartialSize(metadata.getPartialSize());
        IOUtils.closeQuietly(is);
    } catch (final IOException e) {
        throw new FileAccessException("File " + caArrayFile.getName() + " couldn't be read", e);
    }
}

From source file:com.bandstand.web.ImagesController.java

@Get
public InputStream getImageFile(Image image) throws IOException {
    File content = new File(image.getFileName());
    return FileUtils.openInputStream(content);
}

From source file:fr.ippon.wip.config.ZipConfiguration.java

/**
 * Create a zip archive from a configuration.
 * // w  w  w  .j av a2  s  .c o  m
 * @param configuration
 *            the configuration to zip
 * @param out
 *            the stream to be used
 */
public void zip(WIPConfiguration configuration, ZipOutputStream out) {
    XMLConfigurationDAO xmlConfigurationDAO = new XMLConfigurationDAO(FileUtils.getTempDirectoryPath());

    /*
     * a configuration with the same name may already has been unzipped in
     * the temp directory, so we try to delete it for avoiding name
     * modification (see ConfigurationDAO.correctConfigurationName).
     */
    xmlConfigurationDAO.delete(configuration);
    xmlConfigurationDAO.create(configuration);

    String configName = configuration.getName();

    try {
        int[] types = new int[] { XMLConfigurationDAO.FILE_NAME_CLIPPING,
                XMLConfigurationDAO.FILE_NAME_TRANSFORM, XMLConfigurationDAO.FILE_NAME_CONFIG };
        for (int type : types) {
            File file = xmlConfigurationDAO.getConfigurationFile(configName, type);
            ZipEntry entry = new ZipEntry(file.getName());
            out.putNextEntry(entry);
            copy(FileUtils.openInputStream(file), out);
            out.closeEntry();
        }

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

From source file:edu.cornell.med.icb.goby.reads.TestReadsWriter.java

@Test
public void testReadFastBufferredOneChunk() throws IOException {
    final String[] sequences = { "ACTGCGCGCG", "AAAAATTTTGGGGGCCCCCCC",
            "AAAAATTTTGGGGGCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC" };
    final String[] descriptions = { "hello world", "descr2", "description 3" };
    final String filename = "test-results/reads/written-101.bin";

    final ReadsWriter writer = new ReadsWriterImpl(new FileOutputStream(new File(filename)));
    ReadsReader reader;//  w  ww .ja v a2  s . c o  m

    int expectedCount = 0;
    writer.setNumEntriesPerChunk(9);
    final int totalNumSeqs = 13;
    for (int i = 0; i < totalNumSeqs; i++) {
        int j = 0;
        for (final String sequence : sequences) {
            writer.setSequence(sequence);
            writer.setDescription(descriptions[j]);
            writer.appendEntry();
            ++j;
            expectedCount++;
        }
    }
    writer.close();

    FastBufferedInputStream stream = new FastBufferedInputStream(FileUtils.openInputStream(new File(filename)));
    // start at 10 and end at 15 should return no sequences at all.
    reader = new ReadsReader(10, 15, stream);
    MutableString sequence = new MutableString();
    assertFalse(reader.hasNext());

    stream = new FastBufferedInputStream(FileUtils.openInputStream(new File(filename)));
    // start at 138 (precise start of a chunk) and end at 139 should return 9 sequences exactly.
    reader = new ReadsReader(138, 139, stream);
    sequence = new MutableString();
    int count = 0;

    while (reader.hasNext()) {
        final Reads.ReadEntry entry = reader.next();
        ReadsReader.decodeSequence(entry, sequence);
        // check that the sequence matches what was encoded:
        assertEquals(sequences[count % sequences.length], sequence.toString());
        assertEquals(descriptions[count % descriptions.length], entry.getDescription());
        //  assertEquals(count+9, entry.getReadIndex());
        //        System.out.println("desc: " +entry.getDescription() );
        count++;
    }
    // should have skipped 2:
    assertEquals(9, count);
}

From source file:net.frogmouth.ddf.jpeginputtransformer.TestJpegInputTransformer.java

@Test()
public void testSonyDSCHXV5() throws IOException, CatalogTransformerException, UnsupportedQueryException,
        SourceUnavailableException, FederationException, ParseException {
    File file = new File(TEST_DATA_PATH + "Sony DSC-HX5V.jpg");
    FileInputStream fis = FileUtils.openInputStream(file);
    Metacard metacard = createTransformer().transform(fis);

    assertNotNull(metacard);//from w ww  .j  a v  a2 s. co m

    assertNotNull(metacard.getCreatedDate());
    assertThat(metacard.getCreatedDate().getYear() + 1900, is(2010));
    assertThat(metacard.getCreatedDate().getMonth() + 1, is(7));
    assertThat(metacard.getCreatedDate().getDate(), is(14));
    assertThat(metacard.getCreatedDate().getHours(), is(11));
    assertThat(metacard.getCreatedDate().getMinutes(), is(00));
    assertThat(metacard.getCreatedDate().getSeconds(), is(23));

    assertNotNull(metacard.getModifiedDate());
    assertThat(metacard.getModifiedDate().getYear() + 1900, is(2010));
    assertThat(metacard.getModifiedDate().getMonth() + 1, is(7));
    assertThat(metacard.getModifiedDate().getDate(), is(14));
    assertThat(metacard.getModifiedDate().getHours(), is(11));
    assertThat(metacard.getModifiedDate().getMinutes(), is(00));
    assertThat(metacard.getModifiedDate().getSeconds(), is(23));

    WKTReader reader = new WKTReader();
    Geometry geometry = reader.read(metacard.getLocation());
    assertEquals(-104.303846389, geometry.getCoordinate().x, 0.00001);
    assertEquals(39.5698783333, geometry.getCoordinate().y, 0.00001);

    byte[] thumbnail = metacard.getThumbnail();
    assertNotNull(thumbnail);
    assertThat(thumbnail.length, is(11490));
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.legacyExcel.ExcelWorkbook.java

/**
 * Load a workbook from a given template type and template filename
 *//* www .j  a  v  a  2 s  . c  om*/
protected void loadWorkbookFromTemplateFileName(TemplateType templateTypeParameter,
        String assignedTemplateFileName) {

    LOGGER.debug("Loading Template as Input File [" + assignedTemplateFileName + "]");

    this.templateType = templateTypeParameter;

    String templateFileName;
    if (assignedTemplateFileName.isEmpty()) {
        templateFileName = getDefaultTemplateForTemplateType();
    } else {
        templateFileName = assignedTemplateFileName;
    }

    File templateFile = templateLocatorService.getFile(templateType, templateFileName);

    InputStream is = null;

    try {
        is = FileUtils.openInputStream(templateFile);
    } catch (FileNotFoundException e) {
        String msg = String.format("The template file %s could not be found", templateFile);
        LOGGER.error(msg, e);
        throw new IteraplanBusinessException(IteraplanErrorMessages.INVALID_EXCEL_TEMPLATE, msg, e);
    } catch (IOException e) {
        String msg = String.format("The template file %s is a directory or could not be read", templateFile);
        LOGGER.error(msg, e);
        throw new IteraplanBusinessException(IteraplanErrorMessages.INVALID_EXCEL_TEMPLATE, msg, e);
    }

    loadWorkbookFromInputStream(is);
}