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.jitsi.meet.test.FailureListener.java

/**
 * Saves the html source of the supplied page.
 * @param driver the driver controlling the page.
 * @param fileName the destination html file name.
 *//*from   w  ww  .  j a  va 2  s.c  o  m*/
private void saveHtmlSource(WebDriver driver, String fileName) {
    try {
        FileUtils.openOutputStream(new File(outputHtmlSourceParentFolder, fileName))
                .write(driver.getPageSource().getBytes());
    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:org.kaaproject.kaa.sandbox.web.services.SandboxServiceImpl.java

@Override
public void buildProjectData(String uuid, BuildOutputData outputData, String projectId,
        ProjectDataType dataType) throws SandboxServiceException {
    PrintStream outPrint = null;//w  w w  .  j a va 2s.c o m
    ClientMessageOutputStream outStream = null;
    ByteArrayOutputStream byteOutStream = null;
    if (outputData != null) {
        byteOutStream = new ByteArrayOutputStream();
        outPrint = new PrintStream(byteOutStream);
    }
    try {
        outStream = new ClientMessageOutputStream(uuid, outPrint);
        Project project = projectsMap.get(projectId);
        if (project != null) {
            String sdkProfileId = project.getSdkProfileId();
            outStream.println("SDK profile id of project: " + sdkProfileId);
            outStream.println("Getting SDK for requested project...");
            FileData sdkFileData = cacheService.getSdk(project.getId());
            if (sdkFileData != null) {
                outStream.println("Successfuly got SDK.");
                File rootDir = createTempDirectory("demo-project");
                try {
                    outStream.println("Processing project archive...");
                    String sourceArchiveFile = Environment.getServerHomeDir() + "/" + DEMO_PROJECTS_FOLDER + "/"
                            + project.getSourceArchive();
                    String rootProjectDir = rootDir.getAbsolutePath();

                    executeCommand(outStream,
                            new String[] { "tar", "-C", rootProjectDir, "-xzvf", sourceArchiveFile }, null);

                    File sdkFile = new File(
                            rootProjectDir + "/" + project.getSdkLibDir() + "/" + sdkFileData.getFileName());
                    FileOutputStream fos = FileUtils.openOutputStream(sdkFile);
                    fos.write(sdkFileData.getFileData());
                    fos.flush();
                    fos.close();

                    ProjectDataKey dataKey = new ProjectDataKey(projectId, dataType);
                    if (dataType == ProjectDataType.SOURCE) {
                        String sourceArchiveName = FilenameUtils.getName(sourceArchiveFile);
                        outStream.println("Compressing source project archive...");

                        File sourceFile = new File(rootDir, sourceArchiveName);

                        String[] files = rootDir.list();
                        String[] command = (String[]) ArrayUtils.addAll(new String[] { "tar", "-czvf",
                                sourceFile.getAbsolutePath(), "-C", rootProjectDir }, files);

                        executeCommand(outStream, command, null);

                        outStream.println("Source project archive compressed.");
                        byte[] sourceFileBytes = FileUtils.readFileToByteArray(sourceFile);
                        FileData sourceFileData = new FileData();
                        sourceFileData.setFileName(sourceArchiveName);
                        sourceFileData.setFileData(sourceFileBytes);
                        sourceFileData.setContentType("application/x-compressed");
                        cacheService.putProjectFile(dataKey, sourceFileData);
                    } else {
                        outStream.println("Building binary file...");
                        File projectFolder = rootDir;
                        if (project.getProjectFolder() != null
                                && !project.getProjectFolder().trim().isEmpty()) {
                            projectFolder = new File(rootDir, project.getProjectFolder());
                        }

                        executeCommand(outStream, new String[] { "ant" }, projectFolder);

                        outStream.println("Build finished.");

                        File binaryFile = new File(rootDir, project.getDestBinaryFile());
                        byte[] binaryFileBytes = FileUtils.readFileToByteArray(binaryFile);
                        FileData binaryFileData = new FileData();

                        String binaryFileName = FilenameUtils.getName(binaryFile.getAbsolutePath());

                        binaryFileData.setFileName(binaryFileName);
                        binaryFileData.setFileData(binaryFileBytes);
                        if (project.getSdkLanguage() == SdkLanguage.JAVA) {
                            if (project.getPlatforms().contains(Platform.ANDROID)) {
                                binaryFileData.setContentType("application/vnd.android.package-archive");
                            } else {
                                binaryFileData.setContentType("application/java-archive");
                            }
                        }
                        cacheService.putProjectFile(dataKey, binaryFileData);
                    }
                } finally {
                    FileUtils.deleteDirectory(rootDir);
                }
            } else {
                outStream.println("Unable to get/create SDK for requested project!");
            }
        } else {
            outStream.println("No project configuration found!");
        }
    } catch (Exception e) {
        if (outStream != null) {
            outStream.println("Unexpected error occurred: " + e.getMessage());
        }
        throw Utils.handleException(e);
    } finally {
        if (uuid != null) {
            broadcastMessage(uuid, uuid + " finished");
        }
        if (outPrint != null) {
            outPrint.flush();
            outPrint.close();
            outputData.setOutputData(byteOutStream.toByteArray());
        }
    }
}

From source file:org.kalypso.ogc.sensor.zml.ObservationMarshaller.java

private OutputStream openOutputStream(final File file) throws IOException {
    final OutputStream fileStream = new BufferedOutputStream(FileUtils.openOutputStream(file));

    /* Handle compressed zml */
    final String extension = FilenameUtils.getExtension(file.getName());
    if ("zmlz".equalsIgnoreCase(extension)) //$NON-NLS-1$
    {/*from ww  w .  j  a v a 2s  .c o  m*/
        final short bufferSize = Short.MAX_VALUE; // 32KB
        return new GZIPOutputStream(fileStream, bufferSize);
    }

    return fileStream;
}

From source file:org.kuali.maven.plugins.graph.dot.DotGeneratorTest.java

@Test
public void testHelloWorld() {
    try {//from w ww . j av a  2s.com
        Graph g = dg.getHelloWorld();
        String s = sg.getString(g);
        File file = new File("./target/test-classes/hellworld.dot");
        OutputStream out = FileUtils.openOutputStream(file);
        IOUtils.write(s.getBytes(), out);
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.liveSense.service.apacheds.configurationLoader.Loader.java

public void install(Bundle bundle, String path) throws Exception {
    String apacheDSConfigurationName = new File(bundle.getEntry(path).getFile()).getName();
    String apacheDSRelativePath = path;
    String bundleRoot = bundle.getEntry(apacheDSRelativePath).toString();

    String apacheDSHome = getDsHome(bundle.getBundleContext());
    File apacheDSConfigurationHome = new File(apacheDSHome, bundle.getSymbolicName());
    Enumeration<?> entries = bundle.findEntries(apacheDSRelativePath, "*", true);
    boolean firstEntry = true;
    while (entries != null && entries.hasMoreElements()) {
        URL confPath = (URL) entries.nextElement();
        if (!confPath.toString().endsWith("/") && confPath.toString().endsWith(".ldif")) {
            // Make the path realative
            // Put the file to DS instance 
            if (!apacheDSConfigurationHome.exists()) {
                apacheDSConfigurationHome.mkdirs();
            }/*w  w  w .  j a  v a 2  s. c o m*/

            File con = new File(apacheDSConfigurationHome, confPath.toString().substring(bundleRoot.length()));
            if (!con.exists()) {
                FileOutputStream output = null;
                try {
                    output = FileUtils.openOutputStream(con);
                    IOUtils.copy(confPath.openStream(), output);
                    output.close(); // don't swallow close Exception if copy completes normally
                } catch (Throwable th) {
                    log.error("Could not write ldif: " + con.getAbsolutePath());
                } finally {
                    if (output != null)
                        IOUtils.closeQuietly(output);
                }
                try {
                    LdifFileLoader ldifLoader = new LdifFileLoader(
                            apacheDsService.getDirectoryService().getAdminSession(), con.getAbsolutePath());
                    ldifLoader.execute();
                } catch (Throwable th) {
                    log.error("Could not load ldif: " + con.getAbsolutePath(), th);
                }
            }
        }
    }
}

From source file:org.localmatters.lesscss4j.cli.CompilerMain.java

protected OutputStream createOutputStream(String outputFilename) throws IOException {
    if (outputFilename == null || "-".equals(outputFilename)) {
        return System.out;
    } else {/*w w w  . ja v  a 2s  .  c  om*/
        return FileUtils.openOutputStream(new File(outputFilename));
    }
}

From source file:org.mule.devkit.maven.MashapeGeneratorMojo.java

public MashapeGeneratorMojo() {
    codeModel = new CodeModel(new CodeWriter() {
        @Override//from  w  ww. j a v  a  2 s .co m
        public OutputStream openBinary(org.mule.devkit.model.code.Package pkg, String fileName)
                throws IOException {
            File file = new File(defaultOutputDirectory, pkg.name().replace(".", "/") + "/" + fileName);
            return FileUtils.openOutputStream(file);
        }

        @Override
        public void close() throws IOException {
        }
    });
}

From source file:org.n52.sos.XmlToExiConverter.java

protected void encode(String fileName) {
    try (InputStream exiIS = FileUtils.openInputStream(getFile(fileName, XML_EXTENSION));
            OutputStream exiOS = FileUtils.openOutputStream(getFile(fileName, EXI_EXTENSION))) {
        EXIResult exiResult = new EXIResult();
        exiResult.setOutputStream(exiOS);
        XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        xmlReader.setContentHandler(exiResult.getHandler());
        xmlReader.parse(new InputSource(exiIS));
    } catch (Exception e) {
        // TODO: handle exception
    }//from ww  w  .j  a  v  a 2 s . com
}

From source file:org.n52.sos.XmlToExiConverter.java

protected void decode(String fileName) {
    try (InputStream exiIS = FileUtils.openInputStream(getFile(fileName, EXI_EXTENSION));
            OutputStream os = FileUtils.openOutputStream(getFile(fileName, XML_EXTENSION_2))) {

        Reader reader = new InputStreamReader(exiIS, "ISO-8859-1");
        InputSource is = new InputSource(reader);
        is.setEncoding("ISO-8859-1");

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();

        EXISource exiSource = new EXISource();
        XMLReader exiReader = exiSource.getXMLReader();
        SAXSource saxSource = new SAXSource(is);
        //            SAXSource saxSource = new SAXSource(new InputSource(exiIS));
        exiSource.setXMLReader(exiReader);
        transformer.transform(saxSource, new StreamResult(os));
    } catch (Exception e) {
        System.out.println(e.getStackTrace());
    }//  w ww .  ja v a  2 s .c o m
}

From source file:org.nd4j.util.ArchiveUtils.java

/**
 * Extracts files to the specified destination
 *
 * @param file the file to extract to//from ww  w . ja  v a2 s . c o  m
 * @param dest the destination directory
 * @throws IOException
 */
public static void unzipFileTo(String file, String dest) throws IOException {
    File target = new File(file);
    if (!target.exists())
        throw new IllegalArgumentException("Archive doesnt exist");
    FileInputStream fin = new FileInputStream(target);
    int BUFFER = 2048;
    byte data[] = new byte[BUFFER];

    if (file.endsWith(".zip") || file.endsWith(".jar")) {
        try (ZipInputStream zis = new ZipInputStream(fin)) {
            //get the zipped file list entry
            ZipEntry ze = zis.getNextEntry();

            while (ze != null) {
                String fileName = ze.getName();
                File newFile = new File(dest + File.separator + fileName);

                if (ze.isDirectory()) {
                    newFile.mkdirs();
                    zis.closeEntry();
                    ze = zis.getNextEntry();
                    continue;
                }

                FileOutputStream fos = new FileOutputStream(newFile);

                int len;
                while ((len = zis.read(data)) > 0) {
                    fos.write(data, 0, len);
                }

                fos.close();
                ze = zis.getNextEntry();
                log.debug("File extracted: " + newFile.getAbsoluteFile());
            }

            zis.closeEntry();
        }
    } else if (file.endsWith(".tar.gz") || file.endsWith(".tgz")) {

        BufferedInputStream in = new BufferedInputStream(fin);
        GzipCompressorInputStream gzIn = new GzipCompressorInputStream(in);
        TarArchiveInputStream tarIn = new TarArchiveInputStream(gzIn);

        TarArchiveEntry entry;
        /* Read the tar entries using the getNextEntry method **/
        while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null) {
            log.info("Extracting: " + entry.getName());
            /* If the entry is a directory, create the directory. */

            if (entry.isDirectory()) {
                File f = new File(dest + File.separator + entry.getName());
                f.mkdirs();
            }
            /*
             * If the entry is a file,write the decompressed file to the disk
             * and close destination stream.
             */
            else {
                int count;
                try (FileOutputStream fos = new FileOutputStream(dest + File.separator + entry.getName());
                        BufferedOutputStream destStream = new BufferedOutputStream(fos, BUFFER);) {
                    while ((count = tarIn.read(data, 0, BUFFER)) != -1) {
                        destStream.write(data, 0, count);
                    }

                    destStream.flush();
                    IOUtils.closeQuietly(destStream);
                }
            }
        }

        // Close the input stream
        tarIn.close();
    } else if (file.endsWith(".gz")) {
        File extracted = new File(target.getParent(), target.getName().replace(".gz", ""));
        if (extracted.exists())
            extracted.delete();
        extracted.createNewFile();
        try (GZIPInputStream is2 = new GZIPInputStream(fin);
                OutputStream fos = FileUtils.openOutputStream(extracted)) {
            IOUtils.copyLarge(is2, fos);
            fos.flush();
        }
    } else {
        throw new IllegalStateException(
                "Unable to infer file type (compression format) from source file name: " + file);
    }
    target.delete();
}