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.silverpeas.core.workflow.engine.model.ProcessModelManagerImpl.java

/**
 * Saves a process model definition from java objects to an XML file
 * @param processFileName the xml file name that contains process model definition
 * @param process A processModel object to be saved
 * @throws WorkflowException when something goes wrong
 *//*from  w  w  w. jav  a 2  s . c  om*/
@Override
public void saveProcessModel(ProcessModel process, String processFileName) throws WorkflowException {
    Mapping mapping = new Mapping();
    // get configuration files url
    String mappingFileName = settings.getString("CastorXMLMappingFileURL", null);
    String schemaFileName = settings.getString("ProcessModesSchemaFileURL", null);
    String strProcessModelFileEncoding = settings.getString("ProcessModelFileEncoding");
    boolean runOnUnix = !FileUtil.isWindows();
    String processPath = getProcessPath(processFileName);
    try {
        if (runOnUnix) {
            mappingFileName = mappingFileName.replace('\\', '/');
        } else {
            mappingFileName = "file:///" + mappingFileName.replace('\\', '/');
        }
        mapping.loadMapping(mappingFileName);
        File file = new File(processPath);
        OutputStreamWriter writer = new OutputStreamWriter(FileUtils.openOutputStream(file),
                strProcessModelFileEncoding);
        Marshaller mar = new Marshaller(writer);
        mar.setMapping(mapping);
        mar.setNoNamespaceSchemaLocation(schemaFileName);
        mar.setSuppressXSIType(true);
        mar.setValidation(false);
        mar.setEncoding(strProcessModelFileEncoding);
        mar.marshal(process);
        writer.close();
        clearProcessModelCache();
    } catch (MappingException me) {
        throw new WorkflowException("ProcessModelManagerImpl.saveProcessModel",
                "workflowEngine.EX_ERR_CASTOR_LOAD_XML_MAPPING",
                "Mapping file name : " + (mappingFileName == null ? "<null>" : mappingFileName), me);
    } catch (MarshalException me) {
        throw new WorkflowException("ProcessModelManagerImpl.saveProcessModel",
                "workflowEngine.EX_ERR_CASTOR_MARSHALL_PROCESSMODEL",
                "Process file name : " + (processPath == null ? "<null>" : processPath), me);
    } catch (ValidationException ve) {
        throw new WorkflowException("ProcessModelManagerImpl.saveProcessModel",
                "workflowEngine.EX_ERR_CASTOR_INVALID_XML_PROCESSMODEL",
                "Process file name : " + (processPath == null ? "<null>" : processPath), ve);
    } catch (IOException ioe) {
        throw new WorkflowException("ProcessModelManagerImpl.saveProcessModel",
                "workflowEngine.EX_ERR_CASTOR_SAVE_PROCESSMODEL",
                "Process file name : " + (processPath == null ? "<null>" : processPath), ioe);
    }
}

From source file:org.silverpeas.file.ZipUtil.java

/**
 * ---------------------------------------------------------------------
 * @param zipFile/*from   w  w  w  .java  2 s  .c  om*/
 * @param zipEntry
 * @param toDir
 * @throws Exception
 * @see
 */
private static void extractFile(final ZipFile zipFile, final ZipEntry zipEntry, final File toDir)
        throws IOException {
    final File toFile = new File(toDir.getAbsolutePath(), zipEntry.getName());
    if (zipEntry.isDirectory()) {
        FileUtils.forceMkdir(toFile);
    } else if (!toFile.exists()) {
        toFile.getParentFile().mkdirs();
        final OutputStream out = FileUtils.openOutputStream(toFile);
        IOUtils.copy(zipFile.getInputStream(zipEntry), out);
        out.close();
    }
}

From source file:org.silverpeas.tools.dbBuilder.wysiwyg.adjustment.LogRewriter.java

/**
 * Executing treatments/*from  ww w .  ja  v a 2 s . c  o  m*/
 */
private LogRewriter execute() throws Exception {
    dataWiring = DataWiring.execute(dbBuilderLogs);

    BufferedReader dbBuilderLogsReader = IOUtils.toBufferedReader(new FileReader(dbBuilderLogs));
    try {
        FileOutputStream dbBuilderLogsOS = FileUtils.openOutputStream(rewrittenDbBuilderLogs);
        try {

            dataWiring.writeStatistics(dbBuilderLogsOS);

            if (Boolean.valueOf(System.getProperty("statsOnly"))) {
                return this;
            }

            String line;
            do {

                // A line
                line = dbBuilderLogsReader.readLine();

                if (line == null) {
                    break;
                }

                String componentIdEnding = null;

                // New component ?
                Matcher matcher = DataWiring.REGEXP_NEW_COMPONENT_DETECTOR.matcher(line);
                if (matcher.find()) {
                    String componentId = matcher.group(1);
                    if (currents.containsKey(componentId)) {
                        throw new IllegalStateException(
                                "The componentId " + componentId + " has already been started !!!");
                    }
                    currents.put(componentId, new ComponentLogs(componentId));
                }

                // End component ?
                matcher = DataWiring.REGEXP_END_COMPONENT_DETECTOR.matcher(line);
                if (matcher.find()) {
                    String componentId = matcher.group(1);
                    if (!currents.containsKey(componentId)) {
                        throw new IllegalStateException(
                                "The componentId " + componentId + " has already been ending !!!");
                    }

                    componentIdEnding = componentId;
                }

                if (!currents.isEmpty()) {

                    String componentId = dataWiring.getComponentIdFromLine(line);
                    if (componentId == null) {
                        //  System.out.println("No component found in the line : " + line);
                        continue;
                    }

                    ComponentLogs componentLogs = currents.get(componentId);
                    if (componentLogs == null) {
                        System.out.println("No component logs found the line : " + line);
                        continue;
                    }

                    componentLogs.addLine(line);
                }

                if (componentIdEnding != null) {
                    ComponentLogs componentLogs = currents.remove(componentIdEnding);
                    dataWiring.clearComponentId(componentIdEnding);

                    IOUtils.writeLines(componentLogs.getLines(), "\n", dbBuilderLogsOS);
                }

            } while (true);
        } finally {
            IOUtils.closeQuietly(dbBuilderLogsOS);
        }
    } finally {
        IOUtils.closeQuietly(dbBuilderLogsReader);
    }
    return this;
}

From source file:org.silverpeas.tools.dbBuilder.wysiwyg.purge.LogRewriter.java

/**
 * Executing treatments/*w w  w.java2s .  c o  m*/
 */
private LogRewriter execute() throws Exception {
    dataWiring = DataWiring.execute(dbBuilderLogs);

    BufferedReader dbBuilderLogsReader = IOUtils.toBufferedReader(new FileReader(dbBuilderLogs));
    try {
        FileOutputStream dbBuilderLogsOS = FileUtils.openOutputStream(rewrittenDbBuilderLogs);
        try {

            if (Boolean.valueOf(System.getProperty("statsOnly"))) {
                return this;
            }

            String line;
            do {

                // A line
                line = dbBuilderLogsReader.readLine();

                if (line == null) {
                    break;
                }

                String componentIdEnding = null;

                // New component ?
                Matcher matcher = DataWiring.REGEXP_NEW_COMPONENT_DETECTOR.matcher(line);
                if (matcher.find()) {
                    String componentId = matcher.group(1);
                    if (currents.containsKey(componentId)) {
                        throw new IllegalStateException(
                                "The componentId " + componentId + " has already been started !!!");
                    }
                    currents.put(componentId, new ComponentLogs(componentId));
                }

                // End component ?
                matcher = DataWiring.REGEXP_END_COMPONENT_DETECTOR.matcher(line);
                if (matcher.find()) {
                    String componentId = matcher.group(1);
                    if (!currents.containsKey(componentId)) {
                        throw new IllegalStateException(
                                "The componentId " + componentId + " has already been ending !!!");
                    }

                    componentIdEnding = componentId;
                }

                if (!currents.isEmpty()) {

                    String componentId = dataWiring.getComponentIdFromLine(line);
                    if (componentId == null) {
                        //  System.out.println("No component found in the line : " + line);
                        continue;
                    }

                    ComponentLogs componentLogs = currents.get(componentId);
                    if (componentLogs == null) {
                        System.out.println("No component logs found the line : " + line);
                        continue;
                    }

                    componentLogs.addLine(line);
                }

                if (componentIdEnding != null) {
                    ComponentLogs componentLogs = currents.remove(componentIdEnding);
                    dataWiring.clearComponentId(componentIdEnding);

                    IOUtils.writeLines(componentLogs.getLines(), "\n", dbBuilderLogsOS);
                }

            } while (true);
        } finally {
            IOUtils.closeQuietly(dbBuilderLogsOS);
        }
    } finally {
        IOUtils.closeQuietly(dbBuilderLogsReader);
    }
    return this;
}

From source file:org.silverpeas.upload.web.FileUploadResource.java

/**
 * Saving the file./*  w  ww. jav  a 2s  .  co m*/
 * @param uploadedInputStream
 * @param uploadedFileLocation
 * @throws IOException
 */
private void saveToFile(InputStream uploadedInputStream, File uploadedFileLocation) throws IOException {
    try {
        FileOutputStream fOS = FileUtils.openOutputStream(uploadedFileLocation);
        try {
            IOUtils.copy(uploadedInputStream, fOS);
        } finally {
            IOUtils.closeQuietly(fOS);
        }
    } finally {
        IOUtils.closeQuietly(uploadedInputStream);
    }
}

From source file:org.silverpeas.util.PdfUtil.java

/**
 * Add a image under or over content on each page of a PDF file.
 * @param pdfSource the source pdf file, this content is not modified by this method
 * @param image the image file//from  w ww.  j ava2 s . com
 * @param pdfDestination the destination pdf file, with the image under or over content
 * @param isBackground indicates if image is addes under or over the content of the pdf source
 * file
 */
private static void addImageOnEachPage(File pdfSource, File image, File pdfDestination,
        final boolean isBackground) {
    if (pdfSource == null || !pdfSource.isFile()) {
        throw new RuntimeException("The pdf source file doesn't exist");
    } else if (!FileUtil.isPdf(pdfSource.getPath())) {
        throw new RuntimeException("The source is not a pdf file");
    } else if (pdfDestination == null) {
        throw new RuntimeException("The pdf destination file is unknown");
    }

    FileInputStream pdfSourceIS = null;
    FileOutputStream pdfDestinationIS = null;
    try {
        pdfSourceIS = FileUtils.openInputStream(pdfSource);
        pdfDestinationIS = FileUtils.openOutputStream(pdfDestination);
        addImageOnEachPage(pdfSourceIS, image, pdfDestinationIS, isBackground);
    } catch (IOException e) {
        throw new RuntimeException("Pdf source file cannot be opened or pdf destination file cannot be created",
                e);
    } finally {
        IOUtils.closeQuietly(pdfSourceIS);
        IOUtils.closeQuietly(pdfDestinationIS);
    }
}

From source file:org.sipfoundry.sipxconfig.admin.localization.LocalizationContextImpl.java

private File createLocalizationPackage(InputStream stream, String name) {
    File uploadDirectory = new File(m_regionDir, "localization_packages");
    File fileToApply = new File(uploadDirectory.getPath(), name);
    OutputStream os = null;//from w w w .  j a  v a  2 s.c  om
    try {
        os = FileUtils.openOutputStream(fileToApply);
        IOUtils.copy(stream, os);
    } catch (IOException ex) {
        LOG.warn("Cannot upload file", ex);
        throw new UserException("message.upload.failed");
    } finally {
        IOUtils.closeQuietly(os);
    }
    return fileToApply;
}

From source file:org.sonar.api.utils.ZipUtils.java

public static void zipDir(File dir, File zip) throws IOException {
    OutputStream out = null;/*ww w. j a va  2 s.  c  o  m*/
    ZipOutputStream zout = null;
    try {
        out = FileUtils.openOutputStream(zip);
        zout = new ZipOutputStream(out);
        zip(dir, zout, null);

    } finally {
        IOUtils.closeQuietly(zout);
        IOUtils.closeQuietly(out);
    }
}

From source file:org.sonar.batch.EmbeddedSonarPlugin.java

@Override
public void start(BundleContext context) throws Exception {
    super.start(context);

    File stateDir = getStateLocation().toFile();
    File workDir = new File(stateDir, "sonar-plugins");
    pluginsManager = PluginsManagerFactory.newPluginsManager(workDir);

    Bundle bundle = context.getBundle();
    Enumeration<String> e = bundle.getEntryPaths("/plugins/");
    while (e.hasMoreElements()) {
        String entry = e.nextElement();
        URL url = bundle.getEntry(entry);
        InputStream input = url.openStream();
        File file = new File(workDir, entry);
        OutputStream output = FileUtils.openOutputStream(file);
        IOUtil.copy(input, output);/*from w  ww  .j ava 2s. co  m*/
        IOUtil.close(input);
        pluginsManager.install(file);
    }

    pluginsManager.start();
}

From source file:org.sonar.plugins.checkstyle.CheckstyleExecutor.java

/**
 * Execute Checkstyle and return the generated XML report.
 *//*  w ww  .  j a v  a 2  s  . co m*/
public void execute() {
    TimeProfiler profiler = new TimeProfiler().start("Execute Checkstyle " + CheckstyleVersion.getVersion());
    ClassLoader initialClassLoader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(PackageNamesLoader.class.getClassLoader());

    Checker checker = null;
    OutputStream xmlOutput = null;
    try {

        checker = new Checker();
        checker.setClassloader(projectClassloader);
        checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());
        checker.addListener(listener);

        File xmlReport = configuration.getTargetXMLReport();
        if (xmlReport != null) {
            LOG.info("Checkstyle output report: " + xmlReport.getAbsolutePath());
            xmlOutput = FileUtils.openOutputStream(xmlReport);
            checker.addListener(new XMLLogger(xmlOutput, true));
        }

        checker.setCharset(configuration.getCharset().name());
        checker.configure(configuration.getCheckstyleConfiguration());
        checker.process(configuration.getSourceFiles());

        profiler.stop();

    } catch (Exception e) {
        throw new SonarException("Can not execute Checkstyle", e);

    } finally {
        if (checker != null) {
            checker.destroy();
        }
        IOUtils.closeQuietly(xmlOutput);
        Thread.currentThread().setContextClassLoader(initialClassLoader);
    }
}