Example usage for org.apache.commons.io FileUtils openOutputStream

List of usage examples for org.apache.commons.io FileUtils openOutputStream

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils openOutputStream.

Prototype

public static FileOutputStream openOutputStream(File file) throws IOException 

Source Link

Document

Opens a FileOutputStream for the specified file, checking and creating the parent directory if it does not exist.

Usage

From source file:gov.nih.nci.caarray.dataStorage.database.DatabaseMultipartBlobDataStorage.java

/**
 * {@inheritDoc}//from w  ww .j a v  a 2 s .c o m
 */
@Override
public File openFile(URI handle, boolean compressed) throws DataStoreException {
    checkScheme(handle);
    final String tempFileName = fileName(handle.getSchemeSpecificPart(), compressed);
    final TemporaryFileCache tempFileCache = this.tempFileCacheSource.get();
    File tempFile = tempFileCache.getFile(tempFileName);
    if (tempFile != null) {
        return tempFile;
    } else {
        tempFile = tempFileCache.createFile(tempFileName);
        final MultiPartBlob blob = this.searchDao.retrieve(MultiPartBlob.class,
                Long.valueOf(handle.getSchemeSpecificPart()));
        if (blob == null) {
            throw new DataStoreException("No data found for handle " + handle);
        }
        try {
            final OutputStream os = FileUtils.openOutputStream(tempFile);
            copyContentsToStream(blob, !compressed, os);
            IOUtils.closeQuietly(os);
        } catch (final IOException e) {
            throw new DataStoreException("Could not write out file ", e);
        }
        return tempFile;
    }
}

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 w w .  j a v a 2 s .  co 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.stefanbrenner.droplet.service.impl.XMPMetadataService.java

/**
 * A new raw file was created in the watched folder. A new xmp file with the
 * same filename as the raw file is created and the metadata gets added to
 * it. If an output folder is set, both files are finally moved to that
 * folder.//from ww  w  .  j  a v a  2 s.c o  m
 * 
 * @param rawFile
 *            the new raw file
 */
@Override
public void onFileCreate(final File rawFile) {

    dropletContext.addLoggingMessage(Messages.getString("ProcessingPanel.newRAWFileFound", rawFile.getName()));

    try {
        // create xmp file
        File xmpFile = com.stefanbrenner.droplet.utils.FileUtils.newFileBasedOn(rawFile, "xmp");

        // fill with metadata
        XMPMeta xmpMeta = XMPMetaFactory.create();

        /* Keywords */
        for (String tag : StringUtils.split(metadata.getTags(), ',')) {
            xmpMeta.appendArrayItem(SCHEMA_DC, "dc:subject", new PropertyOptions().setArray(true),
                    StringUtils.trim(tag), null);
        }

        /* Title and Description */
        // xmpMeta.setLocalizedText(schemaDc, "dc:title",
        // "x-default", "x-default", "Droplet Title");
        String description = StringUtils.trim(metadata.getDescription());
        description += "\n\n" + TITLE;
        description += "\n" + Configuration.getMessageProtocolProvider().getName();
        description += "\n" + dropletContext.getLastSetMessage();
        xmpMeta.setLocalizedText(SCHEMA_DC, "dc:description", "x-default", "x-default", description);

        // final String NS_DRP = "http://www.droplet.com/schema/1.0/";
        // REGISTRY.registerNamespace(NS_DRP, "drp");
        //
        // for (IActionDevice device :
        // dropletContext.getDroplet().getDevices(IActionDevice.class)) {
        // xmpMeta.appendArrayItem(NS_DRP, "device", new
        // PropertyOptions().setArray(true),
        // "Device " + device.getName(), null);
        // for (IAction action : device.getEnabledActions()) {
        // xmpMeta.appendArrayItem(NS_DRP, "action", new
        // PropertyOptions().setArray(true),
        // "Action " + action.getOffset(), null);
        // }
        // }

        /* UserComments */
        xmpMeta.setProperty(SCHEMA_EXIF, "exif:UserComment",
                "This picture was created with the help of Droplet - Toolkit for Liquid Art Photographer");

        // write to file
        FileOutputStream fos = FileUtils.openOutputStream(xmpFile);
        XMPMetaFactory.serialize(xmpMeta, fos, new SerializeOptions(SerializeOptions.OMIT_PACKET_WRAPPER));
        fos.close();

        dropletContext
                .addLoggingMessage(Messages.getString("ProcessingPanel.newXMPFileCreated", xmpFile.getName()));

        if (outputFolderURI != null) {
            File outputFolder = new File(outputFolderURI);
            FileUtils.moveFileToDirectory(xmpFile, outputFolder, false);
            FileUtils.moveFileToDirectory(rawFile, outputFolder, false);
        }

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

From source file:com.microsoft.applicationinsights.internal.perfcounter.JniPCConnector.java

private static void extractToLocalFolder(File dllOnDisk, String libraryToLoad) throws IOException {
    InputStream in = JniPCConnector.class.getClassLoader().getResourceAsStream(libraryToLoad);
    if (in == null) {
        throw new RuntimeException(String.format("Failed to find '%s' in jar", libraryToLoad));
    }// ww  w  .  ja va2 s . c om

    OutputStream out = null;
    try {
        out = FileUtils.openOutputStream(dllOnDisk);
        IOUtils.copy(in, out);

        InternalLogger.INSTANCE.trace("Successfully extracted '%s' to local folder", libraryToLoad);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                InternalLogger.INSTANCE.error("Failed to close input stream for dll extraction: %s",
                        e.getMessage());
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                InternalLogger.INSTANCE.error("Failed to close output stream for dll extraction: %s",
                        e.getMessage());
            }
        }
    }
}

From source file:com.asakusafw.dmdl.thundergate.GenerateTask.java

private void generateRecordLockDdl(ModelRepository repository) {
    File output = configuration.getRecordLockDdlOutput();
    if (output == null) {
        return;//from  w  w  w. ja v  a 2s. c o m
    }
    int count = 0;
    RecordLockDdlEmitter generator = new RecordLockDdlEmitter();
    for (TableModelDescription model : repository.allTables()) {
        generator.addTable(model.getReference().getSimpleName());
        count++;
    }
    if (count == 0) {
        LOG.warn(
                "?DDL????????: {}",
                output);
        return;
    }
    LOG.info("?DDL??????: {}", output);
    try {
        FileOutputStream stream = FileUtils.openOutputStream(output);
        try {
            generator.appendTo(stream);
        } finally {
            stream.close();
        }
    } catch (IOException e) {
        LOG.error("?DDL??????", e);
    }
}

From source file:de.bitinsomnia.webdav.server.MiltonFolderResource.java

@Override
public Resource createNew(String newName, InputStream inputStream, Long length, String contentType)
        throws IOException, ConflictException, NotAuthorizedException, BadRequestException {
    File newFile = new File(this.file, newName);
    OutputStream out = null;/*from  ww w.j  a  va2 s .  c  om*/
    try {
        out = FileUtils.openOutputStream(newFile);
        IOUtils.copy(inputStream, out);

        return new MiltonFileResource(newFile, resourceFactory);
    } catch (Exception e) {
        LOGGER.error("Error creating file {}", newFile, e);
        throw new RuntimeIoException(e);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                LOGGER.warn("Error closing new file output stream for file {}", newFile, e);
            }
        }
    }
}

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   w  w  w  .ja  v  a 2  s .c o  m
    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);
    }
}

From source file:com.googlecode.dex2jar.v3.Dex2jar.java

public void to(File file) throws IOException {
    if (file.exists() && file.isDirectory()) {
        doTranslate(file);//from   w  w  w .j  ava 2s. c  om
    } else {
        OutputStream fos = FileUtils.openOutputStream(file);
        try {
            to(fos);
        } finally {
            IOUtils.closeQuietly(fos);
        }
    }
}

From source file:gov.nih.nci.firebird.commons.selenium2.util.FileDownloadUtils.java

/**
 * Downloads and returns a file from the given uri.
 *
 * @param driver the driver/*ww  w . j  a v a2  s.com*/
 * @param uri the uri to use to download the file
 * @return the response including the file and the response headers.
 */
public static FileDownloadResponse downloadFromUri(WebDriver driver, String uri) throws IOException {
    File file = getDestinationFile();
    OutputStream out = FileUtils.openOutputStream(file);
    InputStream inputStream = null;
    try {
        DefaultHttpClient client = new DefaultHttpClient();
        setupCookies(client, driver);
        HttpGet get = new HttpGet(uri);
        HttpResponse response = client.execute(get);
        inputStream = response.getEntity().getContent();
        IOUtils.copy(inputStream, out);
        return new FileDownloadResponse(file, response.getAllHeaders());
    } finally {
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(inputStream);
    }
}

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

/**
 * Extracts an archive using generic stream factories provided by commons-compress.
 *//* www. java  2s  .  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);
    }
}