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:architecture.ee.web.community.struts2.action.ajax.MyAttachmentAction.java

public String updateAttachment() throws Exception {
    if (attachmentId > 0) {
        Attachment attachment = this.getTargetAttachment();
        for (FileInfo f : attachments) {
            attachment.setName(f.getName());
            attachment.setContentType(f.getContentType());
            attachment.setSize((int) FileUtils.sizeOf(f.getFile()));
            try {
                attachment.setInputStream(FileUtils.openInputStream(f.getFile()));
            } catch (IOException e) {
                log.debug(e);/*  ww  w. j  ava2  s  .com*/
            }
            attachmentManager.saveAttachment(attachment);
        }
    }
    return success();
}

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

/**
 * Validates that a file can be reformatted to change the chunk size.
 *
 * @throws IOException if there is a problem reading or writing to the files
 *//*from  w w  w  .  ja v a 2s  .c  o  m*/
@Test
public void reformatChunkSize() throws IOException {
    final ReformatCompactReadsMode reformat = new ReformatCompactReadsMode();

    final String inputFilename = "test-data/compact-reads/s_1_sequence_short.compact-reads";
    reformat.setInputFilenames(inputFilename);
    reformat.setSequencePerChunk(1);
    final String outputFilename = "test-results/reformat-test-chunk-size.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 inputReader = new ReadsReader(FileUtils.openInputStream(inputFile));
    assertTrue("There should be reads in this file", inputReader.hasNext());

    final List<Reads.ReadEntry> inputEntries = new ArrayList<Reads.ReadEntry>(73);
    for (final Reads.ReadEntry entry : inputReader) {
        inputEntries.add(entry);
    }

    final ReadsReader outputReader = new ReadsReader(FileUtils.openInputStream(outputFile));
    assertTrue("There should be reads in this file", outputReader.hasNext());

    final List<Reads.ReadEntry> outputEntries = new ArrayList<Reads.ReadEntry>(73);
    for (final Reads.ReadEntry entry : outputReader) {
        outputEntries.add(entry);
    }

    assertEquals("The entries of both files should be equal", inputEntries, outputEntries);
}

From source file:com.mirth.connect.util.ArchiveUtils.java

/**
 * Extracts an archive using generic stream factories provided by commons-compress.
 *//*from   w w  w  .j  a va 2  s .c o  m*/
private static void extractGenericArchive(File archiveFile, File destinationFolder) throws CompressException {
    try {
        InputStream inputStream = new BufferedInputStream(FileUtils.openInputStream(archiveFile));

        try {
            inputStream = new CompressorStreamFactory().createCompressorInputStream(inputStream);
        } catch (CompressorException e) {
            // a compressor was not recognized in the stream, in this case we leave the inputStream as-is
        }

        ArchiveInputStream archiveInputStream = new ArchiveStreamFactory()
                .createArchiveInputStream(inputStream);
        ArchiveEntry entry;
        int inputOffset = 0;
        byte[] buffer = new byte[BUFFER_SIZE];

        try {
            while (null != (entry = archiveInputStream.getNextEntry())) {
                File outputFile = new File(
                        destinationFolder.getAbsolutePath() + IOUtils.DIR_SEPARATOR + entry.getName());

                if (entry.isDirectory()) {
                    FileUtils.forceMkdir(outputFile);
                } else {
                    FileOutputStream outputStream = null;

                    try {
                        outputStream = FileUtils.openOutputStream(outputFile);
                        int bytesRead;
                        int outputOffset = 0;

                        while ((bytesRead = archiveInputStream.read(buffer, inputOffset, BUFFER_SIZE)) > 0) {
                            outputStream.write(buffer, outputOffset, bytesRead);
                            inputOffset += bytesRead;
                            outputOffset += bytesRead;
                        }
                    } finally {
                        IOUtils.closeQuietly(outputStream);
                    }
                }
            }
        } finally {
            IOUtils.closeQuietly(archiveInputStream);
        }
    } catch (Exception e) {
        throw new CompressException(e);
    }
}

From source file:com.ariatemplates.attester.maven.ArtifactExtractor.java

public static void unzip(File zipFile, File outputFolder) throws IOException {
    ZipInputStream zipInputStream = null;
    try {/*from  w  ww  . ja v a  2s.  c o m*/
        ZipEntry entry = null;
        zipInputStream = new ZipInputStream(FileUtils.openInputStream(zipFile));
        while ((entry = zipInputStream.getNextEntry()) != null) {
            File outputFile = new File(outputFolder, entry.getName());

            if (entry.isDirectory()) {
                outputFile.mkdirs();
                continue;
            }

            OutputStream outputStream = null;
            try {
                outputStream = FileUtils.openOutputStream(outputFile);
                IOUtils.copy(zipInputStream, outputStream);
                outputStream.close();
            } catch (IOException exception) {
                outputFile.delete();
                throw new IOException(exception);
            } finally {
                IOUtils.closeQuietly(outputStream);
            }
        }
        zipInputStream.close();
    } finally {
        IOUtils.closeQuietly(zipInputStream);
    }
}

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

@GET
@Produces(MediaType.APPLICATION_JSON)/*from w  w w . jav a  2 s . co m*/
@Path("hash/")
public Response hashing() throws IOException {
    VolumeDAO volumeDAO = DAOFactory.getInstance().getVolumeDAO();
    List<Volume> findAll = volumeDAO.findAll();
    Transaction beginTransaction = volumeDAO.getSession().beginTransaction();
    for (Volume volume : findAll) {
        String fileSHA1 = DigestUtils.shaHex(FileUtils.openInputStream(new File(volume.getPath())));
        volume.setHashSH1(fileSHA1);
    }
    beginTransaction.commit();
    return Response.ok("hashed").build();
}

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

@Test
public void testReadFastBufferedInChunks() 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)));

    int expectedCount = 0;
    writer.setNumEntriesPerChunk(9);/*from  w  w  w .  j  a  va  2 s  . co m*/
    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)));
    writer.printStats(System.out);

    final MutableString sequence = new MutableString();
    int count = 0;

    ReadsReader reader = new ReadsReader(0, Long.MAX_VALUE, stream);

    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, entry.getReadIndex());
        count++;
    }

    assertEquals(expectedCount, count);

    stream.close();

    // now start at position 10, will skip the first collection.
    stream = new FastBufferedInputStream(FileUtils.openInputStream(new File(filename)));
    reader = new ReadsReader(10, Long.MAX_VALUE, stream);

    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());
        count++;
    }

    assertEquals(expectedCount - 9, count);

    // start at 150 is past the start of the second read collection, so this collection is not returned:
    reader = new ReadsReader(150, Long.MAX_VALUE, stream);

    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());
        count++;
    }
    // should have skipped 2:
    assertEquals(expectedCount - 9 * 2, count);

    // start at 0 and end at 150 should return only the second read collection, 9 sequences exactly.
    reader = new ReadsReader(10, 150, stream);

    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());
        count++;
    }

    // should have skipped 2:
    assertEquals(9, count);
}

From source file:com.isomorphic.maven.util.ArchiveUtils.java

/**
 * Steps common to archiving both zip and jar files, which include reading files from disk and using
 * their contents to create {@link ZipEntry ZipEntries} and writing them to a ZipOutputStream.
 * // w  ww. j a v a2 s. c om
 * @param root
 * @param source
 * @param target
 * @throws IOException
 */
private static void zip(File root, File source, ZipOutputStream target) throws IOException {
    String relativePath = root.toURI().relativize(source.toURI()).getPath().replace("\\", "/");

    BufferedInputStream in = null;
    try {
        if (source.isDirectory()) {

            if (!relativePath.endsWith("/")) {
                relativePath += "/";
            }
            ZipEntry entry = ZipEntryFactory.get(target, relativePath);
            entry.setTime(source.lastModified());
            target.putNextEntry(entry);
            target.closeEntry();

            for (File nestedFile : source.listFiles()) {
                zip(root, nestedFile, target);
            }
            return;
        }

        ZipEntry entry = ZipEntryFactory.get(target, relativePath);
        entry.setTime(source.lastModified());
        target.putNextEntry(entry);
        in = new BufferedInputStream(FileUtils.openInputStream(source));
        IOUtils.copy(in, target);
        target.closeEntry();

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

From source file:architecture.ee.web.attachment.DefaultAttachmentManager.java

public InputStream getAttachmentInputStream(Attachment attachment) {
    try {/*from  w w  w .j av  a2 s.co m*/
        File file = getAttachmentFromCacheIfExist(attachment);
        return FileUtils.openInputStream(file);
    } catch (IOException e) {
        throw new SystemException(e);
    }
}

From source file:com.github.cherimojava.orchidae.controller.PictureController.java

/**
 * actual method retrieving the picture from disk. Requested picture is only returned if the current user is allowed
 * to view it//from w  w  w  .j  a v a 2s. c  o m
 * 
 * @param id
 *            identification of picture
 * @param type
 *            type of the picture eg _t for thumbnail etc.
 * @return ResponseEntity containing the resource to the picture or NOT_FOUND
 * @throws IOException
 */
private ResponseEntity<Resource> _getPicture(String id, String type) throws IOException {
    File picture = fileUtil.getFileHandle(id + type);
    if (picture.exists()) {
        return new ResponseEntity<Resource>(new InputStreamResource(FileUtils.openInputStream(picture)),
                HttpStatus.OK);
    } else {
        LOG.debug("Could not find picture with id {}", id);
        // picture doesn't exist so return 404
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}

From source file:com.comcast.magicwand.spells.web.chrome.ChromePhoenixDriver.java

private void extractZip(File sourceZipFile, String destinationDir) throws IOException {
    LOG.debug("Extracting [{}] to dir [{}]", sourceZipFile, destinationDir);
    ZipInputStream zis = null;//from  www .j a  va2s .  c  om
    ZipEntry entry;

    try {
        zis = new ZipInputStream(FileUtils.openInputStream(sourceZipFile));

        while (null != (entry = zis.getNextEntry())) {
            File dst = Paths.get(destinationDir, entry.getName()).toFile();

            FileOutputStream output = FileUtils.openOutputStream(dst);
            try {
                IOUtils.copy(zis, output);
                output.close();
            } finally {
                IOUtils.closeQuietly(output);
            }
        }
        zis.close();
    } finally {
        IOUtils.closeQuietly(zis);
    }
}