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.textocat.textokit.commons.consumer.XmiFileWriter.java

@Override
protected OutputStream getOutputStream(DocumentMetadata meta) throws IOException {
    Path outRelativePath = outPathFunc.apply(meta);
    Path resultPath = outBasePath.resolve(outRelativePath);
    resultPath = IoUtils.addExtension(resultPath, XMI_FILE_EXTENSION);
    // does not create missing parents
    // return Files.newOutputStream(resultPath);
    return FileUtils.openOutputStream(resultPath.toFile());
}

From source file:com.textocat.textokit.morph.ruscorpora.DictionaryAligningTagMapper2.java

@Override
public void initialize(UimaContext ctx) throws ResourceInitializationException {
    ExternalResourceInitializer.initialize(this, ctx);
    ConfigurationParameterInitializer.initialize(this, ctx);
    dict = dictHolder.getDictionary();//w ww  . j a  v  a2 s.com
    gm = dict.getGramModel();
    try {
        FileOutputStream os = FileUtils.openOutputStream(outFile);
        Writer bw = new BufferedWriter(new OutputStreamWriter(os, "utf-8"));
        out = new PrintWriter(bw);
    } catch (IOException e) {
        throw new ResourceInitializationException(e);
    }
    //
    rncDistortionsMask = new BitSet();
    rncDistortionsMask.set(gm.getGrammemNumId(Dist));
    rncDistortionsMask.set(gm.getGrammemNumId(RNCMorphConstants.RNC_Abbr));
    //
    rncTrimmer = new PosTrimmer(gm, POST, Anum, Apro, Prnt, GNdr, ANim, NMbr, CAse, Supr, ASpc, TRns, VOic,
            MOod, TEns, PErs, INvl, Name, Patr, Surn, Fixd, Dist, RNCMorphConstants.RNC_Abbr,
            RNCMorphConstants.RNC_INIT);
}

From source file:de.burlov.amazon.s3.dirsync.test.TestDirSync.java

private void createTestData(File baseDir, int fileAmount, int medianSize) throws IOException {
    if (baseDir.exists()) {
        FileUtils.cleanDirectory(baseDir);
    }// w  ww  . ja  va 2s  .c o m
    for (int i = 0; i < fileAmount; i++) {
        int count = RandomUtils.nextInt(512);
        String filename = RandomStringUtils.random(count, "1234567890/");
        count = RandomUtils.nextInt(medianSize);
        byte[] data = new byte[count];
        new Random().nextBytes(data);
        File file = new File(baseDir, filename);
        file.getParentFile().mkdirs();

        OutputStream out = FileUtils.openOutputStream(file);
        out.write(data);
        out.close();
    }
}

From source file:com.silverpeas.attachment.web.SharedAttachmentResource.java

@GET
@Path("{ids}/zip")
@Produces(MediaType.APPLICATION_JSON)// w  ww .j a v a  2s .c o m
public ZipEntity zipFiles(@PathParam("ids") String attachmentIds) {
    StringTokenizer tokenizer = new StringTokenizer(attachmentIds, ",");
    File folderToZip = FileUtils.getFile(FileRepositoryManager.getTemporaryPath(),
            UUID.randomUUID().toString());
    while (tokenizer.hasMoreTokens()) {
        SimpleDocument attachment = AttachmentServiceFactory.getAttachmentService()
                .searchDocumentById(new SimpleDocumentPK(tokenizer.nextToken()), null).getLastPublicVersion();
        if (!isFileReadable(attachment)) {
            throw new WebApplicationException(Status.UNAUTHORIZED);
        }
        OutputStream out = null;
        try {
            out = FileUtils.openOutputStream(FileUtils.getFile(folderToZip, attachment.getFilename()));
            AttachmentServiceFactory.getAttachmentService().getBinaryContent(out, attachment.getPk(), null);
        } 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("sharing").path("attachments").path(componentId)
                .path(getToken()).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:ddf.security.pdp.xacml.SampleXACML.java

public boolean copyPolicies() {
    boolean allSuccessful = true;

    if (StringUtils.isEmpty(karafHomeDir)) {
        LOGGER.info("Could not determine Karaf Home directory!");
        return false;
    }//from   w w  w  .  jav  a 2s  . c o  m

    BufferedInputStream inStream;
    FileOutputStream outStream;
    for (int i = 0; i < copyStreams.length; i++) {
        // Write policy file to policies directory
        inStream = null;
        outStream = null;
        try {
            // Retrieve an input stream to the XACML policy file in the resource directory
            inStream = copyStreams[i];
            final File karafHomeDirFile = new File(karafHomeDir);
            if (karafHomeDirFile.exists()) {
                String policyDirStr = karafHomeDir + POLICY_DIR;
                File outputDir = new File(policyDirStr);
                outputDir.mkdir();
                File outputFile = new File(policyDirStr + copyFileNames[i]);
                outStream = FileUtils.openOutputStream(outputFile);
                if (null != outStream) {
                    IOUtils.copy(inStream, outStream);
                    LOGGER.info("Copying file to {}{}", policyDirStr, copyFileNames[i]);
                } else {
                    LOGGER.info("Could not create policy file output stream! File: {}", copyFileNames[i]);
                    allSuccessful = false;
                }
            } else {
                LOGGER.info("Karaf home directory does not exist! File: {}", copyFileNames[i]);
                allSuccessful = false;
            }
        } catch (IOException ex) {
            LOGGER.info("Unable to write out policy file! File: {}", copyFileNames[i], ex);
            allSuccessful = false;
        } finally {
            IOUtils.closeQuietly(inStream);
            IOUtils.closeQuietly(outStream);
        }
    }

    if (allSuccessful) {
        LOGGER.info("All policies successfully copied.");
        return true;
    } else {
        LOGGER.info("One or more policy files failed to copy!");
        return false;
    }
}

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

@Test
public void downloadImageParamAuth() throws Exception {
    Base64 encoder = new Base64(true);
    String authStr = BASE_USER + ":" + BASE_TOKEN;

    ClientResource client = new ClientResource(URL + "?auth=" + new String(encoder.encode(authStr.getBytes())));

    File file = new File(TEST_OUTPUT_DIR + File.separator + "downloaded.jpg");
    FileOutputStream outputStream = FileUtils.openOutputStream(file);
    client.get().write(outputStream);/*  www.  ja va  2s .  c  o m*/

    Assert.assertTrue(file.exists());

    // Delete downloaded file
    FileUtils.deleteDirectory(new File(TEST_OUTPUT_DIR));
    outputStream.close();
}

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

@Test
public void downloadVideoParamAuth() throws Exception {
    Base64 encoder = new Base64(true);
    String authStr = BASE_USER + ":" + BASE_TOKEN;

    ClientResource client = new ClientResource(URL + "?auth=" + new String(encoder.encode(authStr.getBytes())));

    File file = new File(TEST_OUTPUT_DIR + File.separator + "downloaded.avi");
    FileOutputStream outputStream = FileUtils.openOutputStream(file);
    client.get().write(outputStream);//from w w  w  .  j av  a  2s.co m

    Assert.assertTrue(file.exists());

    // Delete downloaded file
    FileUtils.deleteDirectory(new File(TEST_OUTPUT_DIR));
    outputStream.close();
}

From source file:net.ostis.scpdev.builder.scg.SCgFileBuilder.java

@Override
public void buildImpl(IFolder binroot) throws CoreException {
    // 1. Parse scg file
    if (parseSCgFile() == false)
        return;//from  www  .  jav  a 2s  .  c o  m

    File converted = null;

    try {
        try {
            if (log.isDebugEnabled()) {
                IFolder folder = source.getProject().getFolder("converted_scs");
                if (folder.exists() == false)
                    folder.create(true, true, null);

                IFile convertedFile = folder.getFile(source.getName() + ".scs");
                converted = convertedFile.getRawLocation().toFile();
            } else {
                converted = File.createTempFile("scg", "builder");
            }

            FileOutputStream out = FileUtils.openOutputStream(converted);
            SCsWriter writer = new SCsWriter(out);
            try {
                // Write includes from SCg-file.
                writer.write("\n");
                for (String include : includes) {
                    writer.write(include);
                    writer.write("\n");
                }

                for (IFile gwfFile : gwfs) {
                    // 2. Parse each gwf file
                    if (parseGwfFile(gwfFile.getRawLocation().toFile()) == false) {
                        // If parsing for one fails then skip other gwfs
                        return;
                    }

                    writer.comment("////////////////////////////////////////////////");
                    writer.comment(String.format("File '%s'", gwfFile.getFullPath().toString()));
                    writer.write("\n");

                    // 3. Use list 'objects' encode all not writed
                    // scg-objects
                    encodeToSCs(writer);
                }
            } finally {
                writer.close();
            }

            InputStream errorStream = convertSCsSource(converted.getAbsolutePath(), binroot);
            if (errorStream != null)
                applySCsErrors(source, errorStream);
        } finally {
            if (log.isDebugEnabled()) {
                source.getProject().getFolder("converted_scs").refreshLocal(IResource.DEPTH_INFINITE, null);
            } else {
                if (converted != null) {
                    FileUtils.forceDelete(converted);
                }
            }
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new CoreException(StatusUtils.makeStatus(IStatus.ERROR, e.getMessage(), e));
    }
}

From source file:bjerne.gallery.service.impl.ImageResizeServiceImpl.java

@Override
public void resizeImage(File origImage, File newImage, int width, int height) throws IOException {
    LOG.debug("Entering resizeImage(origImage={}, width={}, height={})", origImage, width, height);
    long startTime = System.currentTimeMillis();
    InputStream is = new BufferedInputStream(new FileInputStream(origImage));
    BufferedImage i = ImageIO.read(is);
    IOUtils.closeQuietly(is);/*  ww w. j  a va  2s.  co  m*/
    BufferedImage scaledImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    int origWidth = i.getWidth();
    int origHeight = i.getHeight();
    LOG.debug("Original size of image - width: {}, height={}", origWidth, height);
    float widthFactor = ((float) origWidth) / ((float) width);
    float heightFactor = ((float) origHeight) / ((float) height);
    float maxFactor = Math.max(widthFactor, heightFactor);
    int newHeight, newWidth;
    if (maxFactor > 1) {
        newHeight = (int) (((float) origHeight) / maxFactor);
        newWidth = (int) (((float) origWidth) / maxFactor);
    } else {
        newHeight = origHeight;
        newWidth = origWidth;
    }
    LOG.debug("Size of scaled image will be: width={}, height={}", newWidth, newHeight);
    int startX = Math.max((width - newWidth) / 2, 0);
    int startY = Math.max((height - newHeight) / 2, 0);
    Graphics2D scaledGraphics = scaledImage.createGraphics();
    scaledGraphics.setColor(backgroundColor);
    scaledGraphics.fillRect(0, 0, width, height);
    scaledGraphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
            RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    scaledGraphics.drawImage(i, startX, startY, newWidth, newHeight, null);
    OutputStream resultImageOutputStream = new BufferedOutputStream(FileUtils.openOutputStream(newImage));
    String extension = FilenameUtils.getExtension(origImage.getName());
    ImageIO.write(scaledImage, extension, resultImageOutputStream);
    IOUtils.closeQuietly(resultImageOutputStream);
    long duration = System.currentTimeMillis() - startTime;
    LOG.debug("Time in milliseconds to scale {}: {}", newImage.toString(), duration);
}

From source file:com.intuit.tank.standalone.agent.StandaloneAgentStartup.java

public void startTest(final StandaloneAgentRequest request) {
    Thread t = new Thread(new Runnable() {
        public void run() {
            try {
                currentAvailability.setAvailabilityStatus(AgentAvailabilityStatus.DELEGATING);
                sendAvailability();//from   w w w. j  a  va2 s. c  o  m
                LOG.info("Starting up: ControllerBaseUrl=" + controllerBase);
                URL url = new URL(controllerBase + SERVICE_RELATIVE_PATH + METHOD_SETTINGS);
                LOG.info("Starting up: making call to tank service url to get settings.xml "
                        + url.toExternalForm());
                InputStream settingsStream = url.openStream();
                try {
                    String settings = IOUtils.toString(settingsStream);
                    FileUtils.writeStringToFile(new File("settings.xml"), settings);
                    LOG.info("got settings file...");
                } finally {
                    IOUtils.closeQuietly(settingsStream);
                }
                url = new URL(controllerBase + SERVICE_RELATIVE_PATH + METHOD_SUPPORT);
                LOG.info("Making call to tank service url to get support files " + url.toExternalForm());
                ZipInputStream zip = new ZipInputStream(url.openStream());
                try {
                    ZipEntry entry = zip.getNextEntry();
                    while (entry != null) {
                        String name = entry.getName();
                        LOG.info("Got file from controller: " + name);
                        File f = new File(name);
                        FileOutputStream fout = FileUtils.openOutputStream(f);
                        try {
                            IOUtils.copy(zip, fout);
                        } finally {
                            IOUtils.closeQuietly(fout);
                        }
                        entry = zip.getNextEntry();
                    }
                } finally {
                    IOUtils.closeQuietly(zip);
                }
                // now start the harness
                String cmd = API_HARNESS_COMMAND + " -http=" + controllerBase + " -jobId=" + request.getJobId()
                        + " -stopBehavior=" + request.getStopBehavior();
                LOG.info("Starting apiharness with command: " + cmd);
                currentAvailability.setAvailabilityStatus(AgentAvailabilityStatus.RUNNING_JOB);
                sendAvailability();
                Process exec = Runtime.getRuntime().exec(cmd);
                exec.waitFor();
                currentAvailability.setAvailabilityStatus(AgentAvailabilityStatus.AVAILABLE);
                sendAvailability();
                //
            } catch (Exception e) {
                LOG.error("Error in AgentStartup " + e, e);
                currentAvailability.setAvailabilityStatus(AgentAvailabilityStatus.AVAILABLE);
                sendAvailability();
            }
        }
    });
    t.start();
}