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.streamsets.pipeline.stage.destination.hdfs.TestHdfsTarget.java

@Test
public void testOnlyConfDirectory() throws Exception {
    // Create custom core-site.xml
    Configuration configuration = new Configuration();
    configuration.clear();// w w w. j  ava  2 s.c o  m
    configuration.set(CommonConfigurationKeys.FS_DEFAULT_NAME_KEY, "file:///");
    FileOutputStream configOut = FileUtils.openOutputStream(new File(getTestDir() + "/conf-dir/core-site.xml"));
    configuration.writeXml(configOut);
    configOut.close();

    HdfsTarget hdfsTarget = HdfsTargetUtil.newBuilder().hdfsUri("").hdfsConfDir(getTestDir() + "/conf-dir/")
            .build();

    TargetRunner runner = new TargetRunner.Builder(HdfsDTarget.class, hdfsTarget)
            .setOnRecordError(OnRecordError.STOP_PIPELINE).build();

    runner.runInit();

    // The configuration object should have the FS config from core-site.xml
    Assert.assertEquals("file:///",
            hdfsTarget.getHdfsConfiguration().get(CommonConfigurationKeys.FS_DEFAULT_NAME_KEY));

    runner.runDestroy();
}

From source file:com.silverpeas.util.web.servlet.FileUploadUtil.java

public static void saveToFile(File file, FileItem item) throws IOException {
    OutputStream out = FileUtils.openOutputStream(file);
    InputStream in = item.getInputStream();
    try {// w  w w  . ja  va2 s . c  o m
        IOUtils.copy(in, out);
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
}

From source file:com.textocat.textokit.corpus.statistics.dao.corpus.XmiFileTreeCorpusDAO.java

static private void serializeCAS(CAS cas, File outFile) throws IOException, SAXException {
    OutputStream out = null;//from  w  w  w .  j  a v  a  2 s  . co  m
    try {
        out = FileUtils.openOutputStream(outFile);
        XmiCasSerializer xcs = new XmiCasSerializer(cas.getTypeSystem());
        XMLSerializer ser = new XMLSerializer(out, true);
        xcs.serialize(cas, ser.getContentHandler());
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:com.tascape.qa.th.SuiteRunner.java

private void logAppProperties(File dir) throws IOException {
    File props = new File(dir, "execution.properties");
    SYS_CONFIG.getProperties().store(FileUtils.openOutputStream(props), "Testharness");
}

From source file:com.cloudant.sync.datastore.AttachmentStreamFactory.java

/**
 * Get stream for writing attachment data to disk.
 *
 * Opens the output stream using {@see FileUtils#openOutputStream(File)}.
 *
 * Data should be written to the stream unencoded, unencrypted.
 *
 * @param file File to write to./*w ww. j a  v  a2  s  . c o  m*/
 * @param encoding Encoding to use.
 * @return Stream for writing.
 * @throws IOException if there's a problem writing to disk, including issues with
 *      encryption (bad key length and other key issues).
 */
public OutputStream getOutputStream(File file, Attachment.Encoding encoding) throws IOException {

    // First, open a stream to the raw bytes on disk.
    // Then, if we have a key assume the file should be encrypted before writing,
    // so wrap the file stream in a stream which encrypts during writing.
    // If the attachment needs encoding, we need to encode the data before it
    // is encrypted, so wrap a stream which will encode (gzip) before passing
    // to encryption stream, or directly to file stream if not encrypting.
    //
    //  User writes [-> Encoding Stream] [-> Encryption Stream] -> write to disk

    OutputStream os = FileUtils.openOutputStream(file);

    if (key != null) {

        try {

            // Create IV
            byte[] iv = new byte[16];
            new SecureRandom().nextBytes(iv);

            os = new EncryptedAttachmentOutputStream(os, key, iv);

        } catch (InvalidKeyException ex) {
            // Replace with an IOException as we validate the key when opening
            // the databases and the key should be the same -- it's therefore
            // not worth forcing the developer to catch something they can't
            // fix during file read; generic IOException works better.
            throw new IOException("Bad key used to write file; check encryption key.", ex);
        } catch (InvalidAlgorithmParameterException ex) {
            // We are creating what should be a valid IV for AES, 16-bytes.
            // Therefore this shouldn't happen. Again, the developer cannot
            // fix it, so wrap in an IOException as we can't write the file.
            throw new IOException("Bad key used to write file; check encryption key.", ex);
        }

    }

    switch (encoding) {
    case Plain:
        break; // nothing to do
    case Gzip:
        os = new GZIPOutputStream(os);
    }

    return os;
}

From source file:de.uni_siegen.wineme.come_in.thumbnailer.Main.java

protected static void initLogging() throws IOException {
    System.setProperty("log4j.configuration", LOG4J_CONFIG_FILE);

    File logConfigFile = new File(LOG4J_CONFIG_FILE);
    if (!logConfigFile.exists()) {
        // Extract config properties from jar
        InputStream in = Main.class.getResourceAsStream("/" + LOG4J_CONFIG_FILE);
        if (in == null) {
            System.err.println(/*from  w  ww . ja  v a  2  s.c o  m*/
                    "Packaging error: can't find logging configuration inside jar. (Neither can I find the config file on the file system: "
                            + logConfigFile.getAbsolutePath() + ")");
            System.exit(1);
        }

        OutputStream out = null;
        try {
            out = FileUtils.openOutputStream(logConfigFile);
            IOUtils.copy(in, out);
        } finally {
            try {
                if (in != null)
                    in.close();
            } finally {
                if (out != null)
                    out.close();
            }
        }
    }

    PropertyConfigurator.configureAndWatch(logConfigFile.getAbsolutePath(), 10 * 1000);
    mLog.info("Logging initialized");
}

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

@Test
public void downloadImagePreviewParamAuth() 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);

    File file = new File(TEST_OUTPUT_DIR + File.separator + "preview.jpg");
    FileOutputStream outputStream = FileUtils.openOutputStream(file);
    client.get().write(outputStream);//from   w  ww .  ja v a  2 s .c  o  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.buddycloud.mediaserver.download.DownloadVideoTest.java

@Test
public void downloadVideoPreviewParamAuth() 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);

    File file = new File(TEST_OUTPUT_DIR + File.separator + "preview.jpg");
    FileOutputStream outputStream = FileUtils.openOutputStream(file);
    client.get().write(outputStream);//from w  w w.  j  a v a2s. c o 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.nateyolles.sling.publick.utils.VltUtils.java

public static VaultPackage readPackage(PackageManager packageManager, InputStream stream, File tempFolder)
        throws IOException {
    File file = File.createTempFile("distr-vault-read-" + System.nanoTime(), ".zip", tempFolder);
    OutputStream out = FileUtils.openOutputStream(file);
    try {// w  w w  .  j a v  a 2s  .  c  om
        IOUtils.copy(stream, out);
        return packageManager.open(file);
    } catch (IOException e) {
        FileUtils.deleteQuietly(file);
        throw e;
    } finally {
        IOUtils.closeQuietly(stream);
        IOUtils.closeQuietly(out);
    }
}

From source file:com.orange.ocara.model.export.docx.AuditDocxExporter.java

/**
 * Create OleObject using a sample./*from w  w  w . j  a v a 2  s. c  o m*/
 *
 * @param from File to embed
 * @param to   Destination file
 */
private void createOleObject(File from, File to) throws IOException, Ole10NativeException {
    File existingOleObject = new File(templateDirectory, "word/embeddings/oleObject.bin");

    OutputStream os = null;
    try {
        // When
        POIFSFileSystem fs = new POIFSFileSystem(FileUtils.openInputStream(existingOleObject));

        fs.getRoot().getEntry(Ole10Native.OLE10_NATIVE).delete();

        Ole10Native ole = new Ole10Native(from.getName(), from.getName(), from.getName(),
                IOUtils.toByteArray(FileUtils.openInputStream(from)));

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ole.writeOut(stream);

        fs.getRoot().createDocument(Ole10Native.OLE10_NATIVE, new ByteArrayInputStream(stream.toByteArray()));

        os = FileUtils.openOutputStream(to);
        fs.writeFilesystem(os);

    } finally {
        IOUtils.closeQuietly(os);
    }
}