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:com.walmart.gatling.commons.ReportExecutor.java

private void runJob(Master.GenerateReport job) {
    TaskEvent taskEvent = job.reportJob.taskEvent;
    CommandLine cmdLine = new CommandLine(agentConfig.getJob().getCommand());
    Map<String, Object> map = new HashMap<>();

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

    //parameters come from the task event
    for (Pair<String, String> pair : taskEvent.getParameters()) {
        cmdLine.addArgument(pair.getValue());
    }//from   w  w  w  . j av  a  2 s  .c  o m
    String dir = agentConfig.getJob().getLogDirectory() + "reports/" + job.reportJob.trackingId + "/";
    cmdLine.addArgument(dir);

    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;
    try {
        List<String> resultFiles = new ArrayList<>(job.results.size());
        //download all files adn
        /*int i=0;
        for (Worker.Result result : job.results) {
        String destFile = dir  + i++ + ".log";
        resultFiles.add(destFile);
        DownloadFile.downloadFile(result.metrics,destFile);
        }*/
        AtomicInteger index = new AtomicInteger();
        job.results.parallelStream().forEach(result -> {
            String destFile = dir + index.incrementAndGet() + ".log";
            resultFiles.add(destFile);
            DownloadFile.downloadFile(result.metrics, destFile);
        });
        String outPath = agentConfig.getJob().getOutPath(taskEvent.getJobName(), job.reportJob.trackingId);
        String errPath = agentConfig.getJob().getErrorPath(taskEvent.getJobName(), job.reportJob.trackingId);
        //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);
        System.out.println(cmdLine);
        int exitResult = executor.execute(cmdLine);
        ReportResult result;
        if (executor.isFailure(exitResult)) {
            result = new ReportResult(dir, job.reportJob, false);
            log.info("Report Executor Failed, result: " + job.toString());
        } else {
            result = new ReportResult(job.reportJob.getHtml(), job.reportJob, true);
            log.info("Report Executor Completed, result: " + result.toString());
        }
        for (String resultFile : resultFiles) {
            FileUtils.deleteQuietly(new File(resultFile));
        }
        getSender().tell(result, getSelf());

    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(outFile);
        IOUtils.closeQuietly(errorFile);
    }

}

From source file:dotaSoundEditor.Helpers.PortraitFinder.java

private void buildAnnouncerPortraits(VPKArchive vpk) {

    BufferedImage image = null;/*  w ww  . j a v a  2  s. c  o m*/
    for (VPKEntry entry : vpk.getEntriesForDir("resource/flash3/images/econ/announcer/")) {
        if (entry.getName().contains("large")) {
            continue; //don't grab the huge images, we won't use them.
        }

        File imageFile = new File(entry.getPath());

        try (FileChannel fc = FileUtils.openOutputStream(imageFile).getChannel()) {
            fc.write(entry.getData());
            image = ImageIO.read(imageFile);
            String announcer = entry.getName();
            portraitMap.put(announcer, image);
        } catch (IOException ex) {
            System.err.println("Can't write " + entry.getPath() + ": " + ex.getMessage());
        }
    }
}

From source file:com.buddycloud.mediaserver.download.DownloadAvatarTest.java

@Test
public void anonymousSuccessfulDownloadParamAuth() throws Exception {
    Base64 encoder = new Base64(true);
    String authStr = BASE_USER + ":" + BASE_TOKEN;

    ClientResource client = new ClientResource(URL + "?auth=" + new String(encoder.encode(authStr.getBytes())));

    File file = new File(TEST_OUTPUT_DIR + File.separator + "downloadedAvatar.jpg");
    FileOutputStream outputStream = FileUtils.openOutputStream(file);
    client.get().write(outputStream);/*from w  w w  .  ja  v a2 s. c  om*/

    Assert.assertTrue(file.exists());

    // Delete downloaded file
    FileUtils.deleteDirectory(new File(TEST_OUTPUT_DIR));
    outputStream.close();
}

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

public void dumpException(DexFileReader reader, File errorFile) throws IOException {
    for (Map.Entry<Method, Exception> e : exceptions.entrySet()) {
        System.err.println("Error:" + e.getKey().toString() + "->" + e.getValue().getMessage());
    }/*from   w ww.  j  a va  2 s  . c  om*/

    final ZipOutputStream errorZipOutputStream = new ZipOutputStream(FileUtils.openOutputStream(errorFile));
    errorZipOutputStream.putNextEntry(new ZipEntry("summary.txt"));
    final PrintWriter fw = new PrintWriter(new OutputStreamWriter(errorZipOutputStream, "UTF-8"));
    fw.println(getVersionString());
    fw.println("there are " + exceptions.size() + " error methods");
    fw.print("options: ");
    if ((readerConfig & DexFileReader.SKIP_DEBUG) == 0) {
        fw.print(" -d");
    }
    fw.println();
    fw.flush();
    errorZipOutputStream.closeEntry();
    final Out out = new Out() {

        @Override
        public void pop() {

        }

        @Override
        public void push() {

        }

        @Override
        public void s(String s) {
            fw.println(s);
        }

        @Override
        public void s(String format, Object... arg) {
            fw.println(String.format(format, arg));
        }
    };
    final int[] count = new int[] { 0 };
    reader.accept(new EmptyVisitor() {

        @Override
        public DexClassVisitor visit(int accessFlags, String className, String superClass,
                String[] interfaceNames) {
            return new EmptyVisitor() {

                @Override
                public DexMethodVisitor visitMethod(final int accessFlags, final Method method) {
                    if (exceptions.containsKey(method)) {
                        return new EmptyVisitor() {

                            @Override
                            public DexCodeVisitor visitCode() {
                                try {
                                    errorZipOutputStream.putNextEntry(new ZipEntry("t" + count[0]++ + ".txt"));
                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                }
                                Exception exception = exceptions.get(method);
                                exception.printStackTrace(fw);
                                out.s("");
                                out.s("DexMethodVisitor mv=cv.visitMethod(%s, %s);",
                                        Escape.methodAcc(accessFlags), Escape.v(method));
                                out.s("DexCodeVisitor code = mv.visitCode();");
                                return new ASMifierCodeV(out);
                            }

                            @Override
                            public void visitEnd() {
                                out.s("mv.visitEnd();");
                                fw.flush();
                                try {
                                    errorZipOutputStream.closeEntry();
                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        };
                    }
                    return null;
                }

            };
        }

    }, readerConfig);
    errorZipOutputStream.close();

}

From source file:edu.ku.brc.util.AttachmentUtils.java

/**
 * @param attachmentLocation/*from w  w w  . j av  a 2  s . c o  m*/
 * @return
 */
public static boolean isAttachmentDirMounted(final File attachmentLocation) {
    String fullPath = "";
    String statsMsg = "The test to write to the AttachmentLocation [%s] %s.";
    try {
        fullPath = attachmentLocation.getCanonicalPath();

        if (attachmentLocation.exists()) {
            if (attachmentLocation.isDirectory()) {
                File tmpFile = new File(attachmentLocation.getAbsoluteFile() + File.separator
                        + System.currentTimeMillis() + System.getProperty("user.name"));
                //log.debug(String.format("Trying to write a file to AttachmentLocation [%s]", tmpFile.getCanonicalPath()));
                if (tmpFile.createNewFile()) {
                    // I don't think I need this anymore
                    FileOutputStream fos = FileUtils.openOutputStream(tmpFile);
                    fos.write(1);
                    fos.close();
                    tmpFile.delete();

                    //log.debug(String.format(statsMsg, fullPath, "succeeded"));

                    return true;

                } else {
                    log.error(String.format("The Attachment Location [%s] atachment file couldn't be created",
                            fullPath));
                }
            } else {
                log.error(String.format("The Attachment Location [%s] is not a directory.", fullPath));
            }
        } else {
            log.error(String.format("The Attachment Location [%s] doesn't exist.", fullPath));
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    log.debug(String.format(statsMsg, fullPath, "failed"));

    return false;
}

From source file:com.haulmont.cuba.core.app.filestorage.FileStorage.java

@Override
public long saveStream(final FileDescriptor fileDescr, final InputStream inputStream)
        throws FileStorageException {
    checkFileDescriptor(fileDescr);/*from w  w w  .  j  av  a  2  s .  co m*/

    File[] roots = getStorageRoots();

    // Store to primary storage

    checkStorageDefined(roots, fileDescr);
    checkPrimaryStorageAccessible(roots, fileDescr);

    File dir = getStorageDir(roots[0], fileDescr);
    dir.mkdirs();
    checkDirectoryExists(dir);

    final File file = new File(dir, getFileName(fileDescr));
    checkFileExists(file);

    long size = 0;
    OutputStream os = null;
    try {
        os = FileUtils.openOutputStream(file);
        size = IOUtils.copyLarge(inputStream, os);
        os.flush();
        writeLog(file, false);
    } catch (IOException e) {
        IOUtils.closeQuietly(os);
        FileUtils.deleteQuietly(file);

        throw new FileStorageException(FileStorageException.Type.IO_EXCEPTION, file.getAbsolutePath(), e);
    } finally {
        IOUtils.closeQuietly(os);
    }

    // Copy file to secondary storages asynchronously

    final SecurityContext securityContext = AppContext.getSecurityContext();
    for (int i = 1; i < roots.length; i++) {
        if (!roots[i].exists()) {
            log.error("Error saving {} into {} : directory doesn't exist", fileDescr, roots[i]);
            continue;
        }

        File copyDir = getStorageDir(roots[i], fileDescr);
        final File fileCopy = new File(copyDir, getFileName(fileDescr));

        writeExecutor.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    AppContext.setSecurityContext(securityContext);
                    FileUtils.copyFile(file, fileCopy, true);
                    writeLog(fileCopy, false);
                } catch (Exception e) {
                    log.error("Error saving {} into {} : {}", fileDescr, fileCopy.getAbsolutePath(),
                            e.getMessage());
                } finally {
                    AppContext.setSecurityContext(null);
                }
            }
        });
    }

    return size;
}

From source file:com.topclouders.releaseplugin.helper.FileHelper.java

private void copyJarEntry(final JarEntry jarEntry, File destinationDirectory) {
    final String fileName = this.getFileName(jarEntry);
    final File currentFile = new File(destinationDirectory, fileName);

    if (jarEntry.isDirectory()) {
        currentFile.mkdirs();/*w w  w.j  a  v  a2s  . co  m*/
    } else {
        try (OutputStream out = FileUtils.openOutputStream(currentFile);
                InputStream is = this.jarFile.getInputStream(jarEntry)) {
            IOUtils.copy(is, out);
        } catch (Exception e) {

        }
    }

}

From source file:gov.nih.nci.caarray.services.external.v1_0.data.AbstractDataApiUtils.java

/**
 * {@inheritDoc}//from   w  w w.ja va  2  s  .co  m
 */
public void downloadMageTabZipToFile(CaArrayEntityReference experimentRef, File toFile)
        throws InvalidReferenceException, DataTransferException, IOException {
    OutputStream ostream = FileUtils.openOutputStream(toFile);
    try {
        copyMageTabZipToOutputStream(experimentRef, ostream);
    } finally {
        if (ostream != null) {
            ostream.close();
        }
    }
}

From source file:com.norconex.collector.http.fetch.impl.DefaultDocumentFetcher.java

@Override
public CrawlStatus fetchDocument(DefaultHttpClient httpClient, HttpDocument doc) {
    //TODO replace signature with Writer class.
    LOG.debug("Fetching document: " + doc.getUrl());
    HttpGet method = null;/*ww  w.  j av a  2 s .com*/
    try {
        method = new HttpGet(doc.getUrl());

        // Execute the method.
        HttpResponse response = httpClient.execute(method);
        int statusCode = response.getStatusLine().getStatusCode();

        InputStream is = response.getEntity().getContent();
        if (ArrayUtils.contains(validStatusCodes, statusCode)) {
            //--- Fetch headers ---
            Header[] headers = response.getAllHeaders();
            for (int i = 0; i < headers.length; i++) {
                Header header = headers[i];
                String name = header.getName();
                if (StringUtils.isNotBlank(headersPrefix)) {
                    name = headersPrefix + name;
                }
                if (doc.getMetadata().getString(name) == null) {
                    doc.getMetadata().addString(name, header.getValue());
                }
            }

            //--- Fetch body
            FileOutputStream os = FileUtils.openOutputStream(doc.getLocalFile());
            IOUtils.copy(is, os);
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
            return CrawlStatus.OK;
        }
        // read response anyway to be safer, but ignore content
        BufferedInputStream bis = new BufferedInputStream(is);
        int result = bis.read();
        while (result != -1) {
            result = bis.read();
        }
        IOUtils.closeQuietly(bis);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return CrawlStatus.NOT_FOUND;
        }
        LOG.debug("Unsupported HTTP Response: " + response.getStatusLine());
        return CrawlStatus.BAD_STATUS;
    } catch (Exception e) {
        if (LOG.isDebugEnabled()) {
            LOG.error("Cannot fetch document: " + doc.getUrl() + " (" + e.getMessage() + ")", e);
        } else {
            LOG.error("Cannot fetch document: " + doc.getUrl() + " (" + e.getMessage() + ")");
        }
        throw new HttpCollectorException(e);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:net.sourceforge.lept4j.util.LoadLibs.java

/**
 * Copies resources from the jar file of the current thread and extract it
 * to the destination directory.//from   w ww.ja v a2 s .c o  m
 *
 * @param jarConnection
 * @param destDir
 */
static void copyJarResourceToDirectory(JarURLConnection jarConnection, File destDir) {
    try {
        JarFile jarFile = jarConnection.getJarFile();
        String jarConnectionEntryName = jarConnection.getEntryName() + "/";

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

            /**
             * Extract files only if they match the path.
             */
            if (jarEntryName.startsWith(jarConnectionEntryName)) {
                String filename = jarEntryName.substring(jarConnectionEntryName.length());
                File currentFile = new File(destDir, filename);

                if (jarEntry.isDirectory()) {
                    currentFile.mkdirs();
                } else {
                    currentFile.deleteOnExit();
                    InputStream is = jarFile.getInputStream(jarEntry);
                    OutputStream out = FileUtils.openOutputStream(currentFile);
                    IOUtils.copy(is, out);
                    is.close();
                    out.close();
                }
            }
        }
    } catch (IOException e) {
        logger.log(Level.WARNING, e.getMessage(), e);
    }
}