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:org.deeplearning4j.util.SerializationUtils.java

public static void saveObject(Object toSave, File saveTo) {
    try {/*from  w  w w .  j a v a 2  s. c  o  m*/
        OutputStream os1 = FileUtils.openOutputStream(saveTo);
        ObjectOutputStream os = new ObjectOutputStream(os1);
        os.writeObject(toSave);
        os.flush();
        os.close();
        os1.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

From source file:org.duracloud.common.util.IOUtil.java

public static File writeStreamToFile(InputStream inStream, boolean gzip) {

    File file = null;//w ww  .j  av a2 s .  co  m
    OutputStream outStream = null;
    try {
        file = File.createTempFile("file", ".tmp");
        outStream = FileUtils.openOutputStream(file);
        if (gzip) {
            outStream = new GZIPOutputStream(outStream);
        }
        IOUtils.copy(inStream, outStream);
    } catch (IOException e) {
        String err = "Error writing stream to file: " + e.getMessage();

        //close the outputstream if possible
        //so that file can be deleted.
        if (null != outStream) {
            IOUtils.closeQuietly(outStream);
        }

        if (file != null && file.exists()) {
            file.delete();
        }

        throw new DuraCloudRuntimeException(err, e);
    } finally {
        if (null != inStream) {
            IOUtils.closeQuietly(inStream);
        }
        if (null != outStream) {
            IOUtils.closeQuietly(outStream);
        }
    }
    return file;
}

From source file:org.duracloud.mill.dup.DuplicationTaskProcessor.java

private File cacheContent(InputStream inStream) throws TaskExecutionFailedException {
    File localFile = null;//w ww .  j  a v  a 2s  .com
    try {
        localFile = File.createTempFile("content-item", ".tmp", workDir);
        try (OutputStream outStream = FileUtils.openOutputStream(localFile)) {
            IOUtils.copy(inStream, outStream);
        }
        inStream.close();
    } catch (IOException e) {
        String msg = "Unable to cache content file due to: " + e.getMessage();
        throw new DuplicationTaskExecutionFailedException(buildFailureMessage(msg), e);
    }
    return localFile;
}

From source file:org.duracloud.services.duplication.impl.ContentDuplicatorImpl.java

private File cacheStreamToFile(InputStream inputStream) {
    File file = null;/*w w w . j ava 2s  .  c om*/
    OutputStream outStream = null;
    try {
        file = File.createTempFile("content-create", ".tmp");
        outStream = FileUtils.openOutputStream(file);
        IOUtils.copy(inputStream, outStream);

    } catch (IOException e) {
        throw new DuraCloudRuntimeException("Error caching stream.", e);

    } finally {
        IOUtils.closeQuietly(outStream);
        IOUtils.closeQuietly(inputStream);
    }
    return file;
}

From source file:org.eclipse.ebr.maven.AboutFilesUtil.java

private String downloadLicenseFile(final File licenseOutputDir, final License license, final URL licenseUrl)
        throws IOException {
    String licenseFileName = "about_files/" + sanitizeFileName(license.getName()).toUpperCase();
    final String existingLicense = findExistingLicenseFile(licenseOutputDir, licenseFileName);
    if (existingLicense != null) {
        if (!forceDownload) {
            getLog().info(format("Found existing license file at '%s'. %s", existingLicense,
                    REQUIRES_FORCE_DOWNLOAD_MESSAGE));
            return existingLicense;
        } else if (getMavenSession().isOffline()) {
            getLog().warn(format("Re-using existing license file at '%s'. Maven is offline.", existingLicense));
            return existingLicense;
        }//from www . ja v  a2  s .  co m
    } else if (getMavenSession().isOffline())
        throw new IOException("Maven is offline.");
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        final HttpGet get = new HttpGet(licenseUrl.toExternalForm());
        get.setHeader("Accept", "text/plain,text/html");
        try (final CloseableHttpResponse response = client.execute(get)) {
            if (response.getStatusLine().getStatusCode() != 200)
                throw new IOException(format("Download failed: %s", response.getStatusLine().toString()));
            final HttpEntity entity = response.getEntity();
            if (entity == null)
                throw new IOException("Download faild. Empty respose.");

            try (final InputStream is = entity.getContent()) {
                final ContentType contentType = ContentType.getOrDefault(entity);
                if (StringUtils.equalsIgnoreCase(contentType.getMimeType(), "text/plain")) {
                    licenseFileName = licenseFileName + ".txt";
                } else if (StringUtils.equalsIgnoreCase(contentType.getMimeType(), "text/html")) {
                    licenseFileName = licenseFileName + ".html";
                } else {
                    getLog().warn(format(
                            "Unexpected content type (%s) returned by remote server. Falling back to text/plain.",
                            contentType));
                    licenseFileName = licenseFileName + ".txt";
                }

                final FileOutputStream os = FileUtils
                        .openOutputStream(new File(licenseOutputDir, licenseFileName));
                try {
                    IOUtils.copy(is, os);
                } finally {
                    IOUtils.closeQuietly(os);
                }
            }
        }
    }
    return licenseFileName;
}

From source file:org.eclipse.gyrex.logback.config.internal.LogbackConfigGenerator.java

public File generateConfig() {
    // get state location
    if (!parentFolder.isDirectory() && !parentFolder.mkdirs()) {
        throw new IllegalStateException(
                String.format("Unable to create configs directory (%s).", parentFolder));
    }// w  ww .j  a v a 2s. com

    // save file
    final File configFile = new File(parentFolder,
            String.format("logback.%s.xml", DateFormatUtils.format(lastModified, "yyyyMMdd-HHmmssSSS")));
    OutputStream outputStream = null;
    XMLStreamWriter xmlStreamWriter = null;
    try {
        outputStream = new BufferedOutputStream(FileUtils.openOutputStream(configFile));
        final XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
        xmlStreamWriter = outputFactory.createXMLStreamWriter(outputStream, CharEncoding.UTF_8);
        // try to format the output
        try {
            final Class<?> clazz = getClass().getClassLoader()
                    .loadClass("com.sun.xml.internal.txw2.output.IndentingXMLStreamWriter");
            xmlStreamWriter = (XMLStreamWriter) clazz.getConstructor(XMLStreamWriter.class)
                    .newInstance(xmlStreamWriter);
        } catch (final Exception e) {
            // ignore
        }
        config.toXml(xmlStreamWriter);
        xmlStreamWriter.flush();
    } catch (final IOException e) {
        throw new IllegalStateException(
                String.format("Unable to create config file (%s).", ExceptionUtils.getRootCauseMessage(e)), e);
    } catch (final XMLStreamException e) {
        throw new IllegalStateException(
                String.format("Error writing config (%s).", ExceptionUtils.getRootCauseMessage(e)), e);
    } finally {
        if (null != xmlStreamWriter) {
            try {
                xmlStreamWriter.close();
            } catch (final Exception e) {
                // ignore
            }
        }
        IOUtils.closeQuietly(outputStream);
    }

    // cleanup directory
    removeOldFiles(parentFolder);

    return configFile;
}

From source file:org.eclipse.gyrex.preferences.internal.console.ExportCmd.java

@Override
protected void doExecute() throws Exception {
    final IPreferencesService preferencesService = EclipsePreferencesUtil.getPreferencesService();

    if (!StringUtils.endsWithIgnoreCase(file.getName(), FILE_EXT_EPF)) {
        file = new File(file.getParentFile(), file.getName().concat(FILE_EXT_EPF));
    }//from www.jav a2 s  .c  om

    IEclipsePreferences node = preferencesService.getRootNode();

    if (StringUtils.isNotBlank(path)) {
        node = (IEclipsePreferences) node.node(path);
    }

    final FileOutputStream output = FileUtils.openOutputStream(file);
    try {
        preferencesService.exportPreferences(node, output, null);
        printf("Successfully exported %s to %s.", node.absolutePath(), file.getAbsolutePath());
    } finally {
        IOUtils.closeQuietly(output);
    }
}

From source file:org.eclipse.gyrex.server.internal.opsmode.OpsMode.java

/**
 * Writes the instance state/*from w w w  .jav a 2 s.  c  o m*/
 * 
 * @param mode
 */
private void persistInstanceState(final OperationMode mode) {
    if (null == mode) {
        return;
    }
    final File instanceState = getInstanceStateFile();
    if ((null == instanceState) || instanceState.exists()) {
        // never overwrite existing file
        return;
    }

    // make sure the folders exists
    instanceState.getParentFile().mkdirs();

    FileOutputStream stream = null;
    try {
        stream = FileUtils.openOutputStream(instanceState);
        switch (mode) {
        case PRODUCTION:
            stream.write('p');
            break;

        case DEVELOPMENT:
        default:
            stream.write('d');
            break;
        }
    } catch (final IOException e) {
        LOG.warn("Error saving operation mode. {}", e.getMessage());
    } finally {
        IOUtils.closeQuietly(stream);
    }

}

From source file:org.eclipse.lyo.client.oslc.samples.automation.WriteThroughProperties.java

@Override
public synchronized Object setProperty(String key, String value) {

    Object property = super.setProperty(key, value);

    try {/*from  w w w .  j  av  a  2  s.  com*/

        FileOutputStream fos = FileUtils.openOutputStream(adapterPropertiesFile);

        store(fos, "Write through save for property : " + key);

        fos.close();

    } catch (IOException e) {

        throw new RuntimeException(e);

    }

    return property;
}

From source file:org.eclipse.smila.binarystorage.persistence.io.BssIOUtils.java

/**
 * Writes input stream to file./* ww w .ja va2 s.  c  om*/
 * 
 * @param path
 * @param stream
 * @throws BinaryStorageException
 */
public static void writeInputStreamToFile(final String path, final InputStream stream)
        throws BinaryStorageException {

    final File record = mkdirForFileRecord(path);
    if (stream instanceof FileInputStream) {
        try {
            writeCopyByChannels(record.getCanonicalPath(), stream);
        } catch (final IOException ioe) {
            throw new BinaryStorageException(ioe, "Could not write from input stream to record :" + path);
        }
    } else {
        FileOutputStream output = null;
        try {
            output = FileUtils.openOutputStream(record);
            IOUtils.copy(stream, output);
        } catch (final IOException ioe) {
            throw new BinaryStorageException(ioe, "Could not write from input stream to record :" + path);
        } finally {
            IOUtils.closeQuietly(output);
        }
    }
}