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.buddycloud.mediaserver.download.DownloadAvatarTest.java

@Test
public void anonymousPreviewSuccessfulDownloadParamAuth() throws Exception {
    int height = 50;
    int width = 50;

    Base64 encoder = new Base64(true);
    String authStr = BASE_USER + ":" + BASE_TOKEN;

    String completeUrl = URL + "?maxheight=" + height + "&maxwidth=" + width + "?auth="
            + new String(encoder.encode(authStr.getBytes()));

    ClientResource client = new ClientResource(completeUrl);
    client.setChallengeResponse(ChallengeScheme.HTTP_BASIC, BASE_USER, BASE_TOKEN);

    File file = new File(TEST_OUTPUT_DIR + File.separator + "avatarPreview.jpg");
    FileOutputStream outputStream = FileUtils.openOutputStream(file);
    client.get().write(outputStream);/*from ww w  .  j av  a2 s .  co m*/

    Assert.assertTrue(file.exists());

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

    // Delete previews table row
    final String previewId = dataSource.getPreviewId(MEDIA_ID, height, width);
    dataSource.deletePreview(previewId);
}

From source file:com.github.lucapino.jira.GenerateReleaseNotesMojo.java

/**
 * Writes issues to output//  w w  w .  j  av  a 2s  .co m
 *
 * @param issues
 */
void output(List<JiraIssue> issues) throws IOException, MojoFailureException {

    Log log = getLog();
    if (targetFile == null) {
        log.warn("No targetFile specified. Ignoring");
        return;
    }
    if (issues == null) {
        log.warn("No issues found. File will not be generated.");
        return;
    }
    HashMap<Object, Object> parameters = new HashMap<>();
    HashMap<String, List<JiraIssue>> jiraIssues = processIssues(issues);
    List<JiraIssue> jiraIssuesList = new ArrayList<>();
    for (List<JiraIssue> list : jiraIssues.values()) {
        jiraIssuesList.addAll(list);
    }
    parameters.put("issues", jiraIssuesList);
    parameters.put("issuesMap", jiraIssues);
    parameters.put("jiraURL", jiraURL);
    parameters.put("jiraProjectKey", jiraProjectKey);
    parameters.put("releaseVersion", releaseVersion);
    if (announceParameters == null) {
        // empty Map to prevent NPE in velocity execution
        parameters.put("announceParameters", java.util.Collections.EMPTY_MAP);
    } else {
        parameters.put("announceParameters", announceParameters);
    }

    boolean useDefault = false;
    if (templateFile == null || !templateFile.exists()) {
        useDefault = true;
        // let's use the default one
        // it/peng/maven/jira/releaseNotes.vm
        InputStream defaultTemplate = this.getClass().getClassLoader().getResourceAsStream("releaseNotes.vm");
        templateFile = File.createTempFile("releaseNotes.vm", null);
        FileOutputStream fos = new FileOutputStream(templateFile);
        IOUtils.copy(defaultTemplate, fos);
        IOUtils.closeQuietly(defaultTemplate);
        IOUtils.closeQuietly(fos);
    }

    String content = getEvaluator().evaluate(templateFile, parameters);

    if (useDefault) {
        // remove the temp file
        templateFile.delete();
    }

    // this creates the parent folder and the file if they doesn't exist
    OutputStreamWriter writer = new OutputStreamWriter(FileUtils.openOutputStream(targetFile), "UTF-8");
    PrintWriter ps = new PrintWriter(writer);

    try {
        if (beforeText != null) {
            ps.println(beforeText);
        }
        ps.println(content);
        if (afterText != null) {
            ps.println(afterText);
        }
    } finally {
        ps.flush();
        IOUtils.closeQuietly(ps);
    }
}

From source file:gov.usgs.anss.query.MultiplexedMSOutputer.java

/**
 * This does the hard work of sorting - called as a shutdown hook.
 * TODO: consider recursion.//w  ww.j a va 2 s.  c  om
 * @param outputName name for the output file.
 * @param files list of MiniSEED files to multiplex.
 * @param cleanup flag indicating whether to cleanup after ourselves or not.
 * @throws IOException
 */
public static void multiplexFiles(String outputName, List<File> files, boolean cleanup, boolean allowEmpty)
        throws IOException {
    ArrayList<File> cleanupFiles = new ArrayList<File>(files);
    ArrayList<File> moreFiles = new ArrayList<File>();

    File outputFile = new File(outputName);
    File tempOutputFile = new File(outputName + ".tmp");

    do {
        // This checks if we're in a subsequent (i.e. not the first) iteration and if there are any more files to process...?
        if (!moreFiles.isEmpty()) {
            logger.info("more files left to multiplex...");
            FileUtils.deleteQuietly(tempOutputFile);
            FileUtils.moveFile(outputFile, tempOutputFile);

            cleanupFiles.add(tempOutputFile);
            moreFiles.add(tempOutputFile);
            files = moreFiles;
            moreFiles = new ArrayList<File>();
        }

        logger.log(Level.FINE, "Multiplexing blocks from {0} temp files to {1}",
                new Object[] { files.size(), outputName });
        BufferedOutputStream out = new BufferedOutputStream(FileUtils.openOutputStream(outputFile));

        // The hard part, sorting the temp files...
        TreeMap<MiniSeed, FileInputStream> blks = new TreeMap<MiniSeed, FileInputStream>(
                new MiniSeedTimeOnlyComparator());
        // Prime the TreeMap
        logger.log(Level.FINEST, "Priming the TreeMap with files: {0}", files);
        for (File file : files) {
            logger.log(Level.INFO, "Reading first block from {0}", file.toString());
            try {
                FileInputStream fs = FileUtils.openInputStream(file);
                MiniSeed ms = getNextValidMiniSeed(fs, allowEmpty);
                if (ms != null) {
                    blks.put(ms, fs);
                } else {
                    logger.log(Level.WARNING, "Failed to read valid MiniSEED block from {0}", file.toString());
                }
            } catch (IOException ex) {
                // Catch "Too many open files" i.e. hitting ulimit, throw anything else.
                if (ex.getMessage().contains("Too many open files")) {
                    logger.log(Level.INFO, "Too many open files - {0} deferred.", file.toString());
                    moreFiles.add(file);
                } else
                    throw ex;
            }
        }

        while (!blks.isEmpty()) {
            MiniSeed next = blks.firstKey();
            out.write(next.getBuf(), 0, next.getBlockSize());

            FileInputStream fs = blks.remove(next);
            next = getNextValidMiniSeed(fs, allowEmpty);
            if (next != null) {
                blks.put(next, fs);
            } else {
                fs.close();
            }
        }

        out.close();
    } while (!moreFiles.isEmpty());

    if (cleanup) {
        logger.log(Level.INFO, "Cleaning up...");
        for (File file : cleanupFiles) {
            FileUtils.deleteQuietly(file);
        }
    }
}

From source file:com.dv.util.DataViewerZipUtil.java

/**
 *
 * @param zipInput/*  w ww.  ja va2  s.  c o  m*/
 * @param dest
 * @throws IOException
 */
private static void doUnzipFile(ZipInputStream zipInput, File dest) throws IOException {
    if (!dest.exists()) {
        FileUtils.forceMkdir(dest);
    }
    for (ZipEntry entry; (entry = zipInput.getNextEntry()) != null;) {
        String entryName = entry.getName();

        File file = new File(dest, entry.getName());
        if (entryName.endsWith(File.separator)) {
            FileUtils.forceMkdir(file);
        } else {
            OutputStream out = FileUtils.openOutputStream(file);
            try {
                IOUtils.copy(zipInput, out);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                IOUtils.closeQuietly(out);
            }
        }
        zipInput.closeEntry();
    }
}

From source file:ctrus.pa.bow.DefaultBagOfWords.java

public void printVocabulary() throws IOException {
    if (_options.hasOption(DefaultOptions.PRINT_VOCABULARY)) {
        String outputFileString;//  w  ww  .ja va 2  s.  c  o  m
        try {
            outputFileString = _options.getOption(DefaultOptions.OUTPUT_DIR);
            if (!outputFileString.endsWith(File.separator))
                outputFileString = outputFileString + File.separator;
        } catch (MissingOptionException ex) {
            outputFileString = "." + File.separator;
        }
        String outputFileString1 = outputFileString + File.separator + DEFAULT_TERM_VOCAB_FILE;
        String outputFileString2 = outputFileString + File.separator + DEFAULT_TERM_FREQ_FILE;
        String outputFileString3 = outputFileString + File.separator + DEFAULT_DOC_VOCAB_FILE;

        CtrusHelper.printToConsole("Writing vocabulary to " + outputFileString + " ...");

        // Write terms
        FileOutputStream fos1 = FileUtils.openOutputStream(new File(outputFileString1));
        Vocabulary.getInstance(_options).writeTermVocabularyTo(fos1);
        fos1.close();

        // Write frequency
        FileOutputStream fos2 = FileUtils.openOutputStream(new File(outputFileString2));
        Vocabulary.getInstance(_options).writeTermFrequencyTo(fos2);
        fos2.close();

        // Write doc
        FileOutputStream fos3 = FileUtils.openOutputStream(new File(outputFileString3));
        Vocabulary.getInstance(_options).writeDocVocabularyTo(fos3);
        fos3.close();
    }
}

From source file:com.textocat.textokit.commons.consumer.XmiWriter.java

/**
 * Serialize a CAS to a file in XMI format
 *
 * @param aCas CAS to serialize/*w w w.  j  ava  2  s. c  o m*/
 * @param name output file
 * @throws SAXException
 * @throws Exception
 * @throws ResourceProcessException
 */
private void writeXmi(CAS aCas, File name) throws IOException, SAXException {
    OutputStream out = null;

    try {
        // write XMI
        out = FileUtils.openOutputStream(name);
        // seems like it is not necessary to buffer outputStream for SAX TransformationHandler
        // out = new BufferedOutputStream(out);
        XmiCasSerializer ser = new XmiCasSerializer(aCas.getTypeSystem());
        XMLSerializer xmlSer = new XMLSerializer(out, xmlFormatted);
        ser.serialize(aCas, xmlSer.getContentHandler());
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:gov.nih.nci.caarray.services.external.v1_0.grid.client.GridDataApiUtils.java

private static void downloadToDir(TransferServiceContextReference transferRef, File dir)
        throws IOException, DataTransferException {
    TransferServiceContextClient tclient = null;
    try {/*  w w w. ja v a 2s  .c om*/
        tclient = new TransferServiceContextClient(transferRef.getEndpointReference());
        DataTransferDescriptor dd = tclient.getDataTransferDescriptor();
        FileOutputStream fos = FileUtils.openOutputStream(new File(dir, dd.getDataDescriptor().getName()));
        readFully(dd, fos, true);
        IOUtils.closeQuietly(fos);
    } finally {
        if (tclient != null) {
            tclient.destroy();
        }
    }
}

From source file:com.izforge.izpack.installer.unpacker.FileUnpacker.java

/**
 * Returns a stream to the target file.//from   w  w w.  j  a va 2s .c  o m
 * <p/>
 * If the target file is blockable, then a temporary file will be created, and a stream to this returned instead.
 *
 * @param file   the pack file meta-data
 * @param target the requested target
 * @return a stream to the actual target
 * @throws IOException an I/O error occurred
 */
protected OutputStream getTarget(PackFile file, File target) throws IOException {
    this.target = target;
    OutputStream result;
    if (isBlockable(file)) {
        // If target file might be blocked the output file must first refer to a temporary file, because
        // Windows Setup API doesn't work on streams but only on physical files
        tmpTarget = File.createTempFile("__FQ__", null, target.getParentFile());
        result = FileUtils.openOutputStream(tmpTarget);
    } else {
        result = FileUtils.openOutputStream(target);
    }
    return result;
}

From source file:ddf.catalog.backup.CatalogBackupPlugin.java

private void createFile(Metacard metacard) throws IOException {

    // Metacards written to temp files. Each temp file is renamed when the write is
    // complete. This makes it easy to find and remove failed files.
    File tempFile = getFile(metacard.getId(), TEMP_FILE_EXTENSION);

    try (ObjectOutputStream oos = new ObjectOutputStream(FileUtils.openOutputStream(tempFile))) {
        oos.writeObject(new MetacardImpl(metacard));
    }/* w  w w .  ja v  a2  s. c  o  m*/

    renameTempFile(tempFile);
}

From source file:de.smartics.maven.plugin.jboss.modules.JandexMojo.java

private void writeIndex(final Indexer indexer) throws MojoExecutionException {
    final File indexFile = new File(outputDirectory, "META-INF/jandex.idx");
    indexFile.getParentFile().mkdirs();/*  w  w  w.j av  a 2  s . c o  m*/

    FileOutputStream indexOutput = null;
    try {
        indexOutput = FileUtils.openOutputStream(indexFile);
        final IndexWriter writer = new IndexWriter(indexOutput);
        final Index index = indexer.complete();
        writer.write(index);
    } catch (final IOException e) {
        throw new MojoExecutionException(
                String.format("Cannot write index file '%s'.", indexFile.getAbsoluteFile()), e);
    } finally {
        IOUtils.closeQuietly(indexOutput);
    }
}