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.overlord.sramp.atom.archive.SrampArchive.java

/**
 * Packs up the current contents of the S-RAMP archive into a single (.zip) file and
 * returns a reference to it.  This method is guaranteed to either throw an Exception
 * or return a valid {@link File}.  It will never throw and leave a temporary file
 * behind./*w  w  w.j a v  a  2  s  .co m*/
 * @throws SrampArchiveException
 */
public File pack() throws SrampArchiveException {
    try {
        File archiveFile = null;
        try {
            archiveFile = File.createTempFile("s-ramp-archive", ".sramp"); //$NON-NLS-1$ //$NON-NLS-2$
            FileOutputStream outputStream = FileUtils.openOutputStream(archiveFile);
            ZipOutputStream zipOutputStream = null;
            try {
                zipOutputStream = new ZipOutputStream(outputStream);
                Collection<SrampArchiveEntry> entries = getEntries();
                for (SrampArchiveEntry entry : entries) {
                    packEntry(entry, zipOutputStream);
                }
            } finally {
                IOUtils.closeQuietly(zipOutputStream);
            }
        } catch (Throwable t) {
            // If anything goes wrong, make sure the File is cleaned up, as
            // we won't have another chance to do so.
            if (archiveFile != null && archiveFile.isFile())
                archiveFile.delete();
            throw t;
        }
        return archiveFile;
    } catch (Throwable t) {
        throw new SrampArchiveException(Messages.i18n.format("ERROR_PACKING_ARCHIVE"), t); //$NON-NLS-1$
    }
}

From source file:org.overlord.sramp.ui.server.ArtifactUploadServlet.java

/**
 * Make a temporary copy of the resource by saving the content to a temp file.
 * @param resourceInputStream//from   ww w . j av a2 s . co m
 * @throws IOException
 */
private File stashResourceContent(InputStream resourceInputStream) throws IOException {
    File resourceTempFile = null;
    OutputStream oStream = null;
    try {
        resourceTempFile = File.createTempFile("s-ramp-ui-upload", ".tmp");
        oStream = FileUtils.openOutputStream(resourceTempFile);
    } catch (IOException e) {
        FileUtils.deleteQuietly(resourceTempFile);
        throw e;
    } finally {
        IOUtils.copy(resourceInputStream, oStream);
        IOUtils.closeQuietly(resourceInputStream);
        IOUtils.closeQuietly(oStream);
    }
    return resourceTempFile;
}

From source file:org.overlord.sramp.ui.server.servlets.AbstractUploadServlet.java

/**
 * Make a temporary copy of the resource by saving the content to a temp file.
 * @param resourceInputStream/*from   w w  w. ja  va  2 s.co  m*/
 * @throws IOException
 */
protected File stashResourceContent(InputStream resourceInputStream) throws IOException {
    File resourceTempFile = null;
    OutputStream oStream = null;
    try {
        resourceTempFile = File.createTempFile("s-ramp-ui-upload", ".tmp"); //$NON-NLS-1$ //$NON-NLS-2$
        oStream = FileUtils.openOutputStream(resourceTempFile);
        IOUtils.copy(resourceInputStream, oStream);
        return resourceTempFile;
    } catch (IOException e) {
        FileUtils.deleteQuietly(resourceTempFile);
        throw e;
    } finally {
        IOUtils.closeQuietly(resourceInputStream);
        IOUtils.closeQuietly(oStream);
    }
}

From source file:org.overlord.sramp.wagon.SrampWagon.java

/**
 * Make a temporary copy of the resource by saving the content to a temp file.
 * @param resourceInputStream/*ww w  .  j  a va2  s. com*/
 * @throws IOException
 */
private File stashResourceContent(InputStream resourceInputStream) throws IOException {
    File resourceTempFile = null;
    OutputStream oStream = null;
    try {
        resourceTempFile = File.createTempFile("s-ramp-wagon-resource", ".tmp"); //$NON-NLS-1$ //$NON-NLS-2$
        oStream = FileUtils.openOutputStream(resourceTempFile);
    } finally {
        IOUtils.copy(resourceInputStream, oStream);
        IOUtils.closeQuietly(resourceInputStream);
        IOUtils.closeQuietly(oStream);
    }
    return resourceTempFile;
}

From source file:org.panthercode.arctic.core.settings.Configuration.java

/**
 * Store the configuration to file.//from   w  ww .j a va  2 s .  c om
 *
 * @param path path to file
 * @throws IOException Is thrown if an error occurs while writing in file.
 */
public void store(final String path) throws IOException {
    try (FileOutputStream stream = FileUtils.openOutputStream(new File(path))) {
        store(stream, this.comment);
    }
}

From source file:org.pentaho.di.trans.steps.teradatabulkloader.TeraDataBulkLoaderRoutines.java

/**
 * Creates the script file./* w  w  w  .  j  a v a 2  s .  c  o m*/
 *
 * @return the string
 * @throws Exception the exception
 */
public String createScriptFile() throws Exception {
    File tempScriptFile;

    if (meta.getGenerateScript()) {
        tempScriptFile = File.createTempFile(FilenameUtils.getBaseName(meta.getScriptFileName()), "");
    } else {
        tempScriptFile = File.createTempFile(FilenameUtils.getBaseName(meta.getExistingScriptFile()), "");
    }
    tempScriptFile.deleteOnExit();

    try {
        scriptFile = FileUtils.openOutputStream(tempScriptFile);
        scriptFilePrintStream = new PrintStream(scriptFile);
    } catch (IOException e) {
        throw new KettleException(
                BaseMessages.getString(PKG, "TeraDataBulkLoaderMeta.Exception.OpenScriptFile", scriptFile), e);
    }

    if (meta.getGenerateScript()) {
        createGeneratedScriptFile();
    } else {
        createFromExistingScriptFile();
    }
    scriptFilePrintStream.close();
    IOUtils.closeQuietly(scriptFile);
    return tempScriptFile.getAbsolutePath();
}

From source file:org.pentaho.di.trans.steps.terafast.TeraFast.java

/**
 * {@inheritDoc}/*from ww  w. j a va2s.  co m*/
 *
 * @see org.pentaho.di.trans.step.BaseStep#processRow(org.pentaho.di.trans.step.StepMetaInterface,
 *      org.pentaho.di.trans.step.StepDataInterface)
 */
@Override
public boolean processRow(final StepMetaInterface smi, final StepDataInterface sdi) throws KettleException {
    this.meta = (TeraFastMeta) smi;
    // this.data = (GenericStepData) sdi;

    Object[] row = getRow();
    if (row == null) {

        this.dataFilePrintStream.close();

        IOUtils.closeQuietly(this.dataFile);

        this.execute();

        setOutputDone();

        try {
            logBasic(BaseMessages.getString(PKG, "TeraFast.Log.WatingForFastload"));
            if (this.process != null) {
                final int exitVal = this.process.waitFor();
                if (exitVal != 0) {
                    setErrors(DEFAULT_ERROR_CODE);
                }
                logBasic(BaseMessages.getString(PKG, "TeraFast.Log.ExitValueFastloadPath", "" + exitVal));
            }
        } catch (Exception e) {
            logError(BaseMessages.getString(PKG, "TeraFast.Log.ErrorInStep"), e);
            this.setDefaultError();
            stopAll();
        }

        return false;
    }

    if (this.first) {
        this.first = false;
        try {
            final File tempDataFile = new File(resolveFileName(this.meta.getDataFile().getValue()));
            this.dataFile = FileUtils.openOutputStream(tempDataFile);
            this.dataFilePrintStream = new PrintStream(dataFile);
        } catch (IOException e) {
            throw new KettleException("Cannot open data file [path=" + this.dataFile + "]", e);
        }

        // determine column sort order according to field mapping
        // thus the columns in the generated datafile are always in the same order and have the same size as in the
        // targetTable
        this.tableRowMeta = this.meta.getRequiredFields(this.getTransMeta());
        RowMetaInterface streamRowMeta = this.getTransMeta().getPrevStepFields(this.getStepMeta());
        this.columnSortOrder = new ArrayList<Integer>(this.tableRowMeta.size());
        for (int i = 0; i < this.tableRowMeta.size(); i++) {
            ValueMetaInterface column = this.tableRowMeta.getValueMeta(i);
            int tableIndex = this.meta.getTableFieldList().getValue().indexOf(column.getName());
            if (tableIndex >= 0) {
                String streamField = this.meta.getStreamFieldList().getValue().get(tableIndex);
                this.columnSortOrder.add(streamRowMeta.indexOfValue(streamField));
            }
        }
    }

    writeToDataFile(getInputRowMeta(), row);
    return true;
}

From source file:org.pentaho.platform.plugin.services.importexport.CommandLineProcessor.java

/**
 * internal helper to write output file/*  w  ww  .j  a va2s  .  c o m*/
 * 
 * @param message
 * @param logFile
 */
private void writeFile(String message, String logFile) {
    try {
        File file = new File(logFile);
        FileOutputStream fout = FileUtils.openOutputStream(file);
        IOUtils.copy(IOUtils.toInputStream(message), fout);
        fout.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

From source file:org.pentaho.platform.repository2.unified.jcr.DumpToFilePentahoSystemListener.java

@Override
public boolean startup(IPentahoSession pentahoSession) {
    Mode tmpMode = null;//w ww.j a v  a2 s . c om
    if (!StringUtils.hasText(fileName)) {
        fileName = System.getProperty(PROP_DUMP_TO_FILE);
        tmpMode = Mode.CUSTOM;
        if (fileName == null) {
            fileName = System.getProperty(PROP_DUMP_TO_FILE_SYSTEM_VIEW);
            tmpMode = Mode.SYS;
        }
        if (fileName == null) {
            fileName = System.getProperty(PROP_DUMP_TO_FILE_DOCUMENT_VIEW);
            tmpMode = Mode.DOC;
        }
    } else {
        tmpMode = Mode.CUSTOM;
    }
    final Mode mode = tmpMode;
    if (fileName != null) {
        final JcrTemplate jcrTemplate = PentahoSystem.get(JcrTemplate.class, "jcrTemplate", pentahoSession); //$NON-NLS-1$
        TransactionTemplate txnTemplate = PentahoSystem.get(TransactionTemplate.class, "jcrTransactionTemplate", //$NON-NLS-1$
                pentahoSession);
        String repositoryAdminUsername = PentahoSystem.get(String.class, "repositoryAdminUsername", //$NON-NLS-1$
                pentahoSession);

        final String ZIP_EXTENSION = ".zip"; //$NON-NLS-1$
        // let the user know this is a zip
        if (!fileName.endsWith(ZIP_EXTENSION)) {
            fileName = fileName + ZIP_EXTENSION;
        }
        logger.debug(String.format("dumping repository to file \"%s\"", fileName)); //$NON-NLS-1$
        ZipOutputStream tmpOut = null;
        try {
            tmpOut = new ZipOutputStream(
                    new BufferedOutputStream(FileUtils.openOutputStream(new File(fileName))));
        } catch (IOException e) {
            IOUtils.closeQuietly(tmpOut);
            throw new RuntimeException(e);
        }
        final ZipOutputStream out = tmpOut;
        // stash existing session
        IPentahoSession origPentahoSession = PentahoSessionHolder.getSession();
        // run as repo super user
        PentahoSessionHolder.setSession(createRepositoryAdminPentahoSession(repositoryAdminUsername));
        try {
            txnTemplate.execute(new TransactionCallbackWithoutResult() {
                public void doInTransactionWithoutResult(final TransactionStatus status) {
                    jcrTemplate.execute(new JcrCallback() {
                        public Object doInJcr(final Session session) throws RepositoryException, IOException {
                            switch (mode) {
                            case SYS: {
                                final boolean SKIP_BINARY = false;
                                final boolean NO_RECURSE = false;
                                out.putNextEntry(new ZipEntry("repository.xml")); //$NON-NLS-1$
                                session.exportSystemView("/", out, SKIP_BINARY, NO_RECURSE); //$NON-NLS-1$
                                return null;
                            }
                            case DOC: {
                                final boolean SKIP_BINARY = false;
                                final boolean NO_RECURSE = false;
                                out.putNextEntry(new ZipEntry("repository.xml")); //$NON-NLS-1$
                                session.exportDocumentView("/", out, SKIP_BINARY, NO_RECURSE); //$NON-NLS-1$
                                return null;
                            }
                            default: {
                                out.putNextEntry(new ZipEntry("repository.txt")); //$NON-NLS-1$
                                session.getRootNode().accept(new DumpToFileTraversingItemVisitor(out));
                                return null;
                            }
                            }
                        }
                    });
                }
            });
        } finally {
            // restore original session
            PentahoSessionHolder.setSession(origPentahoSession);
            IOUtils.closeQuietly(out);
        }
        logger.debug(String.format("dumped repository to file \"%s\"", fileName)); //$NON-NLS-1$
    }
    return true;
}

From source file:org.pentaho.platform.repository2.unified.jcr.JcrRepositoryDumpToFile.java

public void execute() {
    if (filename != null) {
        final String ZIP_EXTENSION = ".zip"; //$NON-NLS-1$
        // let the user know this is a zip
        if (!filename.endsWith(ZIP_EXTENSION)) {
            filename = filename + ZIP_EXTENSION;
        }//from ww  w.ja  v a  2  s  .  c om
        logger.debug(String.format("dumping repository to file \"%s\"", filename)); //$NON-NLS-1$
        ZipOutputStream tmpOut = null;
        try {
            tmpOut = new ZipOutputStream(
                    new BufferedOutputStream(FileUtils.openOutputStream(new File(filename))));
        } catch (IOException e) {
            IOUtils.closeQuietly(tmpOut);
            throw new RuntimeException(e);
        }
        final ZipOutputStream out = tmpOut;
        // stash existing session
        IPentahoSession origPentahoSession = PentahoSessionHolder.getSession();
        // run as repo super user
        PentahoSessionHolder.setSession(createRepositoryAdminPentahoSession(repositoryAdminUsername));
        try {
            txnTemplate.execute(new TransactionCallbackWithoutResult() {
                public void doInTransactionWithoutResult(final TransactionStatus status) {
                    jcrTemplate.execute(new JcrCallback() {
                        public Object doInJcr(final Session session) throws RepositoryException, IOException {
                            switch (mode) {
                            case SYS: {
                                final boolean SKIP_BINARY = false;
                                final boolean NO_RECURSE = false;
                                out.putNextEntry(new ZipEntry("repository.xml")); //$NON-NLS-1$
                                session.exportSystemView("/", out, SKIP_BINARY, NO_RECURSE); //$NON-NLS-1$
                                return null;
                            }
                            case DOC: {
                                final boolean SKIP_BINARY = false;
                                final boolean NO_RECURSE = false;
                                out.putNextEntry(new ZipEntry("repository.xml")); //$NON-NLS-1$
                                session.exportDocumentView("/", out, SKIP_BINARY, NO_RECURSE); //$NON-NLS-1$
                                return null;
                            }
                            default: {
                                out.putNextEntry(new ZipEntry("repository.txt")); //$NON-NLS-1$
                                session.getRootNode().accept(new DumpToFileTraversingItemVisitor(out));
                                return null;
                            }
                            }
                        }
                    });
                }
            });
        } finally {
            // restore original session
            PentahoSessionHolder.setSession(origPentahoSession);
            IOUtils.closeQuietly(out);
        }
        logger.debug(String.format("dumped repository to file \"%s\"", filename)); //$NON-NLS-1$
    }
}