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:ddf.catalog.resource.download.ReliableResourceDownloader.java

public ResourceResponse setupDownload(Metacard metacard, DownloadStatusInfo downloadStatusInfo) {
    Resource resource = resourceResponse.getResource();
    MimeType mimeType = resource.getMimeType();
    String resourceName = resource.getName();

    fbos = new FileBackedOutputStream(DEFAULT_FILE_BACKED_OUTPUT_STREAM_THRESHOLD);
    countingFbos = new CountingOutputStream(fbos);
    streamReadByClient = new ReliableResourceInputStream(fbos, countingFbos, downloadState, downloadIdentifier,
            resourceResponse);/*from  w ww  .jav a 2 s.c  o m*/

    this.metacard = metacard;

    // Create new ResourceResponse to return that will encapsulate the
    // ReliableResourceInputStream that will be read by the client simultaneously as the product
    // is cached to disk (if caching is enabled)
    ResourceImpl newResource = new ResourceImpl(streamReadByClient, mimeType, resourceName);
    resourceResponse = new ResourceResponseImpl(resourceResponse.getRequest(), resourceResponse.getProperties(),
            newResource);

    // Get handle to retrieved product's InputStream
    resourceInputStream = resource.getInputStream();

    eventListener.setDownloadMap(downloadIdentifier, resourceResponse);
    downloadStatusInfo.addDownloadInfo(downloadIdentifier, this, resourceResponse);

    if (downloaderConfig.isCacheEnabled()) {

        CacheKey keyMaker = null;
        String key = null;
        try {
            keyMaker = new CacheKey(metacard, resourceResponse.getRequest());
            key = keyMaker.generateKey();
        } catch (IllegalArgumentException e) {
            LOGGER.info("Cannot create cache key for resource with metacard ID = {}", metacard.getId());
            return resourceResponse;
        }

        if (!resourceCache.isPending(key)) {

            // Fully qualified path to cache file that will be written to.
            // Example:
            // <INSTALL-DIR>/data/product-cache/<source-id>-<metacard-id>
            // <INSTALL-DIR>/data/product-cache/ddf.distribution-abc123
            filePath = FilenameUtils.concat(resourceCache.getProductCacheDirectory(), key);
            reliableResource = new ReliableResource(key, filePath, mimeType, resourceName, metacard);
            resourceCache.addPendingCacheEntry(reliableResource);

            try {
                fos = FileUtils.openOutputStream(new File(filePath));
                doCaching = true;
                this.downloadState.setCacheEnabled(true);
            } catch (IOException e) {
                LOGGER.info("Unable to open cache file {} - no caching will be done.", filePath);
            }
        } else {
            LOGGER.debug("Cache key {} is already pending caching", key);
        }
    }

    return resourceResponse;
}

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

@Override
public void replaceContent(InputStream in, Long length)
        throws BadRequestException, ConflictException, NotAuthorizedException {
    LOGGER.debug("Replacing content of {}", this.file);

    OutputStream out = null;/*from  ww w .  jav  a2s  .c  om*/
    try {
        out = FileUtils.openOutputStream(this.file);
        IOUtils.copy(in, out);
    } catch (IOException e) {
        throw new RuntimeIoException(e);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                LOGGER.error("Error closing output stream to {}", this.file, e);
            }
        }
    }
}

From source file:gov.nih.nci.caarray.services.external.v1_0.grid.service.CaArraySvc_v1_0Impl.java

private TransferServiceContextReference stageFileContentsWithRmiStream(CaArrayEntityReference fileRef,
        boolean compressed) throws InvalidInputFault, DataStagingFault {
    OutputStream ostream = null;/* w  w w .j a v  a  2  s  .  c o  m*/
    try {
        java.io.File tempFile = java.io.File.createTempFile("stagedFile", null);
        FileStreamableContents fsContents = caArrayServer.getDataService().streamFileContents(fileRef,
                compressed);
        ostream = FileUtils.openOutputStream(tempFile);
        JavaDataApiUtils.readFully(fsContents.getContentStream(), ostream, false);
        return TransferServiceHelper.createTransferContext(tempFile,
                new DataDescriptor(false, fsContents.getMetadata().getName()), true);
    } catch (InvalidReferenceException e) {
        throw toFault(e);
    } catch (DataTransferException e) {
        throw mapExceptionToFault(e, DataStagingFault.class);
    } catch (IOException e) {
        throw mapExceptionToFault(e, DataStagingFault.class);
    } finally {
        if (ostream != null) {
            IOUtils.closeQuietly(ostream);
        }
    }
}

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);//from   w w  w .ja v a 2 s .c o m
        propsFile.putAll(props);
    }
    try (FileOutputStream conf = FileUtils
            .openOutputStream(new File(orchestrator.getServer().getHome(), CONF_FILE_PATH))) {
        propsFile.store(conf, "");
    }
}

From source file:com.walmart.gatling.commons.ScriptExecutor.java

private Object runJob(Object message) {
    Master.Job job = (Master.Job) message;
    TaskEvent taskEvent = (TaskEvent) job.taskEvent;

    CommandLine cmdLine = new CommandLine(agentConfig.getJob().getCommand());
    log.info("Verified Script worker received task: {}", message);
    Map<String, Object> map = new HashMap<>();

    if (StringUtils.isNotEmpty(agentConfig.getJob().getMainClass()))
        cmdLine.addArgument(agentConfig.getJob().getCpOrJar());

    map.put("path", new File(agentConfig.getJob().getJobArtifact(taskEvent.getJobName())));
    cmdLine.addArgument("${path}");

    if (!StringUtils.isEmpty(agentConfig.getJob().getMainClass())) {
        cmdLine.addArgument(agentConfig.getJob().getMainClass());
    }//w  w  w.  j  a  va  2  s .  co  m
    //parameters come from the task event
    for (Pair<String, String> pair : taskEvent.getParameters()) {
        cmdLine.addArgument(pair.getValue());
    }
    cmdLine.addArgument("-rf").addArgument(agentConfig.getJob().getResultPath(job.roleId, job.jobId));

    cmdLine.setSubstitutionMap(map);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(agentConfig.getJob().getExitValues());
    ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    executor.setWatchdog(watchdog);
    executor.setWorkingDirectory(new File(agentConfig.getJob().getPath()));
    FileOutputStream outFile = null;
    FileOutputStream errorFile = null;
    String outPath = "", errPath = "";
    try {
        outPath = agentConfig.getJob().getOutPath(taskEvent.getJobName(), job.jobId);
        errPath = agentConfig.getJob().getErrorPath(taskEvent.getJobName(), job.jobId);
        //create the std and err files
        outFile = FileUtils.openOutputStream(new File(outPath));
        errorFile = FileUtils.openOutputStream(new File(errPath));

        PumpStreamHandler psh = new PumpStreamHandler(new ExecLogHandler(outFile),
                new ExecLogHandler(errorFile));
        executor.setStreamHandler(psh);
        log.info("command: {}", cmdLine);
        int exitResult = executor.execute(cmdLine);
        //executor.getWatchdog().destroyProcess().
        Worker.Result result = new Worker.Result(exitResult, agentConfig.getUrl(errPath),
                agentConfig.getUrl(outPath), null, job);
        log.info("Exit code: {}", exitResult);
        if (executor.isFailure(exitResult) || exitResult == 1) {
            log.info("Script Executor Failed, job: " + job.jobId);
            //getSender().tell(new Worker.WorkFailed(result), getSelf());
            return new Worker.WorkFailed(result);
        } else {
            result = new Worker.Result(exitResult, agentConfig.getUrl(errPath), agentConfig.getUrl(outPath),
                    agentConfig.getUrl(getMetricsPath(job)), job);
            log.info("Script Executor Completed, job: " + result);
            //getSender().tell(new Worker.WorkComplete(result), getSelf());
            return new Worker.WorkComplete(result);
        }

    } catch (IOException e) {
        log.error(e.toString());
        Worker.Result result = new Worker.Result(-1, agentConfig.getUrl(errPath), agentConfig.getUrl(outPath),
                null, job);
        log.info("Executor Encountered run time exception, result: " + result.toString());
        //getSender().tell(new Worker.WorkFailed(result), getSelf());
        return new Worker.WorkFailed(result);
    } finally {
        IOUtils.closeQuietly(outFile);
        IOUtils.closeQuietly(errorFile);
    }
}

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

/**
 * Extracts folders/files from a zip archive using zip-optimized code from commons-compress.
 *///from  w ww  . ja  va2 s. com
private static void extractZipArchive(File archiveFile, File destinationFolder) throws CompressException {
    ZipFile zipFile = null;

    try {
        zipFile = new ZipFile(archiveFile);
        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
        ZipArchiveEntry entry = null;
        byte[] buffer = new byte[BUFFER_SIZE];

        for (; entries.hasMoreElements(); entry = entries.nextElement()) {
            File outputFile = new File(
                    destinationFolder.getAbsolutePath() + IOUtils.DIR_SEPARATOR + entry.getName());

            if (entry.isDirectory()) {
                FileUtils.forceMkdir(outputFile);
            } else {
                InputStream inputStream = zipFile.getInputStream(entry);
                OutputStream outputStream = FileUtils.openOutputStream(outputFile);

                try {
                    IOUtils.copyLarge(inputStream, outputStream, buffer);
                } finally {
                    IOUtils.closeQuietly(inputStream);
                    IOUtils.closeQuietly(outputStream);
                }
            }
        }
    } catch (Exception e) {
        throw new CompressException(e);
    } finally {
        ZipFile.closeQuietly(zipFile);
    }
}

From source file:io.tempra.AppServer.java

public static void copyJarResourceToFolder(JarURLConnection jarConnection, File destDir) {

    try {/*from   w  w w  .j  av a  2 s .c  o m*/
        JarFile jarFile = jarConnection.getJarFile();

        /**
         * Iterate all entries in the jar file.
         */
        for (Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) {

            JarEntry jarEntry = e.nextElement();
            String jarEntryName = jarEntry.getName();
            String jarConnectionEntryName = jarConnection.getEntryName();

            /**
             * Extract files only if they match the path.
             */
            if (jarEntryName.startsWith(jarConnectionEntryName)) {

                String filename = jarEntryName.startsWith(jarConnectionEntryName)
                        ? jarEntryName.substring(jarConnectionEntryName.length())
                        : jarEntryName;
                File currentFile = new File(destDir, filename);

                if (jarEntry.isDirectory()) {
                    currentFile.mkdirs();
                } else {
                    InputStream is = jarFile.getInputStream(jarEntry);
                    OutputStream out = FileUtils.openOutputStream(currentFile);
                    IOUtils.copy(is, out);
                    is.close();
                    out.close();
                }
            }
        }
    } catch (IOException e) {
        // TODO add logger
        e.printStackTrace();
    }

}

From source file:gov.nih.nci.caarray.upgrade.FixHybridizationsWithMissingArraysMigrator.java

private File getFile(Long fileId) throws SQLException, IOException {
    MultiPartBlob mpb = dao.getFileBlob(fileId);

    File f = File.createTempFile("datafile", null);
    InputStream is = mpb.readUncompressedContents();
    FileOutputStream fos = FileUtils.openOutputStream(f);
    IOUtils.copy(is, fos);/* w  w  w .ja  va2 s  . c  om*/
    IOUtils.closeQuietly(is);
    IOUtils.closeQuietly(fos);

    return f;
}

From source file:com.stacksync.desktop.Environment.java

public void copyResourcesFromJar(JarURLConnection jarConnection, File destDir) {

    try {//  w  ww  .  j a  v a  2 s.c  o m
        JarFile jarFile = jarConnection.getJarFile();

        /**
         * Iterate all entries in the jar file.
         */
        for (Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) {

            JarEntry jarEntry = e.nextElement();
            String jarEntryName = jarEntry.getName();
            String jarConnectionEntryName = jarConnection.getEntryName();

            /**
             * Extract files only if they match the path.
             */
            if (jarEntryName.startsWith(jarConnectionEntryName)) {

                String filename = jarEntryName.startsWith(jarConnectionEntryName)
                        ? jarEntryName.substring(jarConnectionEntryName.length())
                        : jarEntryName;
                File currentFile = new File(destDir, filename);

                if (jarEntry.isDirectory()) {
                    currentFile.mkdirs();
                } else {
                    InputStream is = jarFile.getInputStream(jarEntry);
                    OutputStream out = FileUtils.openOutputStream(currentFile);
                    IOUtils.copy(is, out);
                    is.close();
                    out.close();
                }
            }
        }
    } catch (IOException e) {
        // TODO add logger
        e.printStackTrace();
    }

}

From source file:net.sf.logsaw.ui.impl.LogResourceManagerImpl.java

@Override
public synchronized void saveState() throws CoreException {
    XMLMemento rootElem = XMLMemento.createWriteRoot(ELEM_ROOT);
    rootElem.putInteger(ATTRIB_COMPAT, COMPAT_VERSION);
    for (ILogResource log : logSet) {
        IMemento logElem = rootElem.createChild(ELEM_LOG_RESOURCE);
        logElem.createChild(ELEM_NAME).putTextData(log.getName());
        IMemento dialectElem = logElem.createChild(ELEM_DIALECT);
        dialectElem.putString(ATTRIB_FACTORY, log.getDialect().getFactory().getId());
        // Save config options of dialect
        saveConfigOptions(dialectElem,/*  w  w  w  .  j av a 2 s. c  o m*/
                (IConfigurableObject) log.getDialect().getAdapter(IConfigurableObject.class));
        logElem.createChild(ELEM_PK).putTextData(log.getPK());
        // Save config options of resource
        saveConfigOptions(logElem, (IConfigurableObject) log.getAdapter(IConfigurableObject.class));
    }
    try {
        // Save to state file
        rootElem.save(new BufferedWriter(
                new OutputStreamWriter(FileUtils.openOutputStream(stateFile.toFile()), "UTF-8"))); //$NON-NLS-1$
    } catch (IOException e) {
        // Unexpected exception; wrap with CoreException
        throw new CoreException(new Status(IStatus.ERROR, UIPlugin.PLUGIN_ID,
                NLS.bind(Messages.LogResourceManager_error_failedToUpdateState,
                        new Object[] { e.getLocalizedMessage() }),
                e));
    }
}