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.dv.util.DataViewerZipUtil.java

public static void doUnzipFile(ZipFile zipFile, File dest) throws IOException {
    if (!dest.exists()) {
        FileUtils.forceMkdir(dest);//w  w  w  . j  a  v a  2  s. com
    }
    Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        File file = new File(dest, entry.getName());
        if (entry.getName().endsWith(File.separator)) {
            FileUtils.forceMkdir(file);
        } else {
            OutputStream out = FileUtils.openOutputStream(file);
            InputStream in = zipFile.getInputStream(entry);
            try {
                IOUtils.copy(in, out);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                IOUtils.closeQuietly(out);
            }
        }
    }
    zipFile.close();
}

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

@Test
public void downloadImagePreview() throws Exception {
    int height = 50;
    int width = 50;
    String completeUrl = URL + "?maxheight=" + height + "&maxwidth=" + width;

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

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

@Test
public void downloadVideoPreview() throws Exception {
    int height = 50;
    int width = 50;
    String completeUrl = URL + "?maxheight=" + height + "&maxwidth=" + width;

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

    File file = new File(TEST_OUTPUT_DIR + File.separator + "preview.jpg");
    FileOutputStream outputStream = FileUtils.openOutputStream(file);
    client.get().write(outputStream);// ww  w . j ava 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.silverpeas.attachment.web.AttachmentRessource.java

@GET
@Path("{ids}/zip")
@Produces(MediaType.APPLICATION_JSON)/* www.j  a  va  2  s.  c om*/
public ZipEntity zipFiles(@PathParam("ids") String attachmentIds) {
    StringTokenizer tokenizer = new StringTokenizer(attachmentIds, ",");
    File folderToZip = FileUtils.getFile(FileRepositoryManager.getTemporaryPath(),
            UUID.randomUUID().toString());
    while (tokenizer.hasMoreTokens()) {
        SimpleDocumentPK pk = new SimpleDocumentPK(tokenizer.nextToken());
        SimpleDocument attachment = AttachmentServiceFactory.getAttachmentService().searchDocumentById(pk,
                null);
        if (!isFileReadable(attachment)) {
            throw new WebApplicationException(Status.UNAUTHORIZED);
        }
        OutputStream out = null;
        try {
            out = FileUtils.openOutputStream(FileUtils.getFile(folderToZip, attachment.getFilename()));
            AttachmentServiceFactory.getAttachmentService().getBinaryContent(out, pk, token);
        } catch (IOException e) {
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        } finally {
            IOUtils.closeQuietly(out);
        }
    }
    try {
        File zipFile = FileUtils.getFile(folderToZip.getPath() + ".zip");
        URI downloadUri = getUriInfo().getBaseUriBuilder().path("attachments").path(componentId).path(token)
                .path("zipcontent").path(zipFile.getName()).build();
        long size = ZipManager.compressPathToZip(folderToZip, zipFile);
        return new ZipEntity(getUriInfo().getRequestUri(), downloadUri.toString(), size);
    } catch (IllegalArgumentException e) {
        throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
    } catch (UriBuilderException e) {
        throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
    } catch (IOException e) {
        throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
    } finally {
        FileUtils.deleteQuietly(folderToZip);
    }
}

From source file:de.hybris.platform.atddimpex.keywords.ImpexKeywordLibrary.java

private OutputStream getImpExLogOutputStream(final String resourceName) throws IOException {
    if (impExLogOutputStream == null) {
        final RobotTest robotTest = robotTestContext.getCurrentRobotTest();

        if (robotTest == null) {
            throw new IllegalStateException(
                    "KeywordMethods must only be called within a valid RobotTestContext");
        } else {//from  w  w w.ja  v  a 2s .  c o m
            final String testSuiteName = robotTest.getTestSuite().getName().replaceAll(Pattern.quote(" "), "_");

            final String impExLogPath = String.format("%s/%s/%s-data.impex", robotTestContext.getProjectName(),
                    testSuiteName, robotTest.getName());
            final File impExLogFile = new File(Config.getParameter(PROP_REPORT_PATH), impExLogPath);

            impExLogOutputStream = FileUtils.openOutputStream(impExLogFile);
        }
    } else {
        IOUtils.write(IMPEX_LOG_LINE_SEPERATOR, impExLogOutputStream, DEFAULT_ENCODING);
    }

    IOUtils.write(IMPEX_LOG_RESOURCE_BANNER, impExLogOutputStream, DEFAULT_ENCODING);
    IOUtils.write(String.format("# Import from %s %s", resourceName, IMPEX_LOG_LINE_SEPERATOR),
            impExLogOutputStream, DEFAULT_ENCODING);
    IOUtils.write(IMPEX_LOG_RESOURCE_BANNER, impExLogOutputStream, DEFAULT_ENCODING);

    impExLogOutputStream.flush();

    return impExLogOutputStream;
}

From source file:com.badlogicgames.packr.Packr.java

public void pack(Config config) throws IOException {
    // create output dir
    File out = new File(config.outDir);
    File target = out;/*from   www. j  a va2 s.c  om*/
    if (out.exists()) {
        if (new File(".").equals(out)) {
            System.out.println("Output directory equals working directory, aborting");
            System.exit(-1);
        }

        System.out.println("Output directory '" + out.getAbsolutePath() + "' exists, deleting");
        FileUtils.deleteDirectory(out);
    }
    out.mkdirs();

    Map<String, String> values = new HashMap<String, String>();
    values.put("${executable}", config.executable);
    values.put("${bundleIdentifier}", "com.yourcompany.identifier"); // FIXME add as a param

    // if this is a mac build, let's create the app bundle structure
    if (config.platform == Platform.mac) {
        new File(out, "Contents").mkdirs();
        FileUtils.writeStringToFile(new File(out, "Contents/Info.plist"),
                readResourceAsString("/Info.plist", values));
        target = new File(out, "Contents/MacOS");
        target.mkdirs();
        new File(out, "Contents/Resources").mkdirs();
        // FIXME copy icons
    }

    // write jar, exe and config to target folder
    byte[] exe = null;
    String extension = "";
    switch (config.platform) {
    case windows:
        exe = readResource("/packr-windows.exe");
        extension = ".exe";
        break;
    case linux32:
        exe = readResource("/packr-linux");
        break;
    case linux64:
        exe = readResource("/packr-linux-x64");
        break;
    case mac:
        exe = readResource("/packr-mac");
        break;
    }
    FileUtils.writeByteArrayToFile(new File(target, config.executable + extension), exe);
    new File(target, config.executable + extension).setExecutable(true);
    FileUtils.copyFile(new File(config.jar), new File(target, new File(config.jar).getName()));
    writeConfig(config, new File(target, "config.json"));

    // add JRE from local or remote zip file
    File jdkFile = null;
    if (config.jdk.startsWith("http://") || config.jdk.startsWith("https://")) {
        System.out.println("Downloading JDK from '" + config.jdk + "'");
        jdkFile = new File(target, "jdk.zip");
        InputStream in = new URL(config.jdk).openStream();
        OutputStream outJdk = FileUtils.openOutputStream(jdkFile);
        IOUtils.copy(in, outJdk);
        in.close();
        outJdk.close();
    } else {
        jdkFile = new File(config.jdk);
    }
    File tmp = new File(target, "tmp");
    tmp.mkdirs();
    System.out.println("Unpacking JRE");
    ZipUtil.unpack(jdkFile, tmp);
    File jre = searchJre(tmp);
    if (jre == null) {
        System.out.println("Couldn't find JRE in JDK, see '" + tmp.getAbsolutePath() + "'");
        System.exit(-1);
    }
    FileUtils.copyDirectory(jre, new File(target, "jre"));
    FileUtils.deleteDirectory(tmp);
    if (config.jdk.startsWith("http://") || config.jdk.startsWith("https://")) {
        jdkFile.delete();
    }

    // copy resources
    System.out.println("copying resources");
    copyResources(target, config.resources);

    // perform tree shaking      
    if (config.minimizeJre != null) {
        minimizeJre(config, target);
    }

    System.out.println("Done!");
}

From source file:com.adobe.acs.commons.dam.AbstractRenditionModifyingProcess.java

void saveImage(Asset asset, Rendition toReplace, Layer layer, String mimetype, double quality,
        WorkflowHelper workflowHelper) throws IOException {
    File tmpFile = File.createTempFile(getTempFileSpecifier(), "." + workflowHelper.getExtension(mimetype));
    OutputStream out = FileUtils.openOutputStream(tmpFile);
    InputStream is = null;/*from w ww. ja  v a2  s. c  o m*/
    try {
        layer.write(mimetype, quality, out);
        is = FileUtils.openInputStream(tmpFile);
        asset.addRendition(toReplace.getName(), is, mimetype);
    } finally {
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(is);
        FileUtils.deleteQuietly(tmpFile);
    }
}

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

@Test
public void anonymousPreviewSuccessfulDownload() throws Exception {
    int height = 50;
    int width = 50;
    String completeUrl = URL + "?maxheight=" + height + "&maxwidth=" + width;

    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);// w ww .  j  ava 2s. 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.splunk.shuttl.server.mbeans.OverrideWithOldArchiverRootURIConfiguration.java

private void writeToPropertiesFile(Properties props, File file) throws IOException {
    logger.warn("Writing properties: " + props + ", to properties file: " + file
            + ", overriding any previous configuration.");
    props.store(FileUtils.openOutputStream(file), overrideReason);
}

From source file:com.sillelien.dollar.DocTestingVisitor.java

@Override
public void visit(@NotNull VerbatimNode node) {
    if ("java".equals(node.getType())) {
        try {/* w ww .  j  a  va  2s .  c o  m*/
            String name = "DocTemp" + System.currentTimeMillis();
            File javaFile = new File("/tmp/" + name + ".java");
            File clazzFile = new File("/tmp/" + name + ".class");
            clazzFile.getParentFile().mkdirs();
            FileUtils.write(javaFile,
                    "import com.sillelien.dollar.api.*;\n"
                            + "import static com.sillelien.dollar.api.DollarStatic.*;\n" + "public class "
                            + name + " implements java.lang.Runnable{\n" + "    public void run() {\n"
                            + "        " + node.getText() + "\n" + "    }\n" + "}");
            final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
            final StandardJavaFileManager jfm = javac.getStandardFileManager(null, null, null);
            JavaCompiler.CompilationTask task;
            DiagnosticListener<JavaFileObject> diagnosticListener = new DiagnosticListener<JavaFileObject>() {

                @Override
                public void report(Diagnostic diagnostic) {
                    System.out.println(diagnostic);
                    throw new RuntimeException(diagnostic.getMessage(Locale.getDefault()));
                }
            };

            try (FileOutputStream fileOutputStream = FileUtils.openOutputStream(clazzFile)) {
                task = javac.getTask(new OutputStreamWriter(fileOutputStream), jfm, diagnosticListener, null,
                        null, jfm.getJavaFileObjects(javaFile));
            }
            task.call();

            try {
                // Convert File to a URL
                URL url = clazzFile.getParentFile().toURL();
                URL[] urls = new URL[] { url };
                ClassLoader cl = new URLClassLoader(urls);
                Class cls = cl.loadClass(name);
                ((Runnable) cls.newInstance()).run();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            System.out.println("Parsed: " + node.getText());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}