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.pentaho.platform.repository2.unified.webservices.jaxws.SimpleRepositoryFileDataDto.java

/**
 * Converts SimpleRepositoryFileData to SimpleRepositoryFileDataDto. Does not use ByteArrayDataSource since that
 * implementation reads the entire stream into a byte array.
 *///from   w w  w  .ja  v  a2  s. c  o m
public static SimpleRepositoryFileDataDto convert(final SimpleRepositoryFileData simpleData) {
    FileOutputStream fout = null;
    boolean foutClosed = false;
    try {
        SimpleRepositoryFileDataDto simpleJaxWsData = new SimpleRepositoryFileDataDto();
        File tmpFile = File.createTempFile("pentaho-ws", null); //$NON-NLS-1$
        // TODO mlowery this might not delete files soon enough
        tmpFile.deleteOnExit();
        fout = FileUtils.openOutputStream(tmpFile);
        IOUtils.copy(simpleData.getStream(), fout);
        fout.close();
        foutClosed = true;
        simpleJaxWsData.dataHandler = new DataHandler(new FileDataSource(tmpFile));
        simpleJaxWsData.encoding = simpleData.getEncoding();
        simpleJaxWsData.mimeType = simpleData.getMimeType();
        return simpleJaxWsData;
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            if (fout != null && !foutClosed) {
                fout.close();
            }
        } catch (Exception e) {
            // CHECKSTYLES IGNORE
        }
    }
}

From source file:org.pentaho.platform.repository2.unified.webservices.jaxws.SimpleRepositoryFileDataDto.java

/**
 * Converts SimpleRepositoryFileDataDto to SimpleRepositoryFileData.
 *//*from   w  w  w.ja  v  a 2 s  . c  om*/
public static SimpleRepositoryFileData convert(final SimpleRepositoryFileDataDto simpleJaxWsData) {
    FileOutputStream fout = null;
    InputStream in = null;
    DataHandler dh = null;
    boolean foutClosed = false;
    try {
        File tmpFile = File.createTempFile("pentaho", null); //$NON-NLS-1$
        // TODO mlowery this might not delete files soon enough
        tmpFile.deleteOnExit();
        fout = FileUtils.openOutputStream(tmpFile);
        // used to cast to com.sun.xml.ws.developer.StreamingDataHandler here but that stopped working
        dh = simpleJaxWsData.dataHandler;
        // used to call dh.readOnce() (instead of dh.getInputStream()) here
        in = dh.getInputStream();
        IOUtils.copy(in, fout);
        fout.close();
        foutClosed = true;
        InputStream fin = new BufferedInputStream(FileUtils.openInputStream(tmpFile));
        return new SimpleRepositoryFileData(fin, simpleJaxWsData.encoding, simpleJaxWsData.mimeType);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        try {
            // close the streams
            if (in != null) {
                in.close();
            }
            // used to have to call dh.close() on the com.sun.xml.ws.developer.StreamingDataHandler here
            if (fout != null && !foutClosed) {
                fout.close();
            }
        } catch (Exception e) {
            // CHECKSTYLES IGNORE
        }
    }
}

From source file:org.sbs.util.ImageCompress.java

/**
 * gif//from  ww  w .j  av a 2s  .  c o  m
 * 
 * @param originalFile
 *            
 * @param resizedFile
 *            ?
 * @param newWidth
 *            
 * @param newHeight
 *             -1?
 * @param quality
 *             ()
 * @throws IOException
 */
public void resize(File originalFile, File resizedFile, int newWidth, int newHeight, float quality)
        throws IOException {
    if (quality < 0 || quality > 1) {
        throw new IllegalArgumentException("Quality has to be between 0 and 1");
    }
    ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath());
    Image i = ii.getImage();
    Image resizedImage = null;
    int iWidth = i.getWidth(null);
    int iHeight = i.getHeight(null);
    if (newHeight == -1) {
        if (iWidth > iHeight) {
            resizedImage = i.getScaledInstance(newWidth, (newWidth * iHeight) / iWidth, Image.SCALE_SMOOTH);
        } else {
            resizedImage = i.getScaledInstance((newWidth * iWidth) / iHeight, newWidth, Image.SCALE_SMOOTH);
        }
    } else {
        resizedImage = i.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
    }
    // This code ensures that all the pixels in the image are loaded.
    Image temp = new ImageIcon(resizedImage).getImage();
    // Create the buffered image.
    BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), temp.getHeight(null),
            BufferedImage.TYPE_INT_RGB);
    // Copy image to buffered image.
    Graphics g = bufferedImage.createGraphics();
    // Clear background and paint the image.
    g.setColor(Color.white);
    g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
    g.drawImage(temp, 0, 0, null);
    g.dispose();
    // Soften.
    float softenFactor = 0.05f;
    float[] softenArray = { 0, softenFactor, 0, softenFactor, 1 - (softenFactor * 4), softenFactor, 0,
            softenFactor, 0 };
    Kernel kernel = new Kernel(3, 3, softenArray);
    ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
    bufferedImage = cOp.filter(bufferedImage, null);
    // Write the jpeg to a file.
    FileOutputStream out = FileUtils.openOutputStream(resizedFile);
    // Encodes image as a JPEG data stream
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
    JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage);
    param.setQuality(quality, true);
    encoder.setJPEGEncodeParam(param);
    encoder.encode(bufferedImage);
}

From source file:org.schemaspy.util.ResourceWriter.java

/**
 * Copies resources from the jar file of the current thread and extract it
 * to the destination path.//from   w ww.  ja v  a  2s.com
 *
 * @param jarConnection
 * @param destPath destination file or directory
 */
private static void copyJarResourceToPath(JarURLConnection jarConnection, File destPath, FileFilter filter) {
    try {
        JarFile jarFile = jarConnection.getJarFile();
        String jarConnectionEntryName = jarConnection.getEntryName();

        /**
         * Iterate all entries in the jar file.
         */
        for (Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) {
            JarEntry jarEntry = e.nextElement();
            String jarEntryName = jarEntry.getName();

            /**
             * Extract files only if they match the path.
             */
            if (jarEntryName.startsWith(jarConnectionEntryName + "/")) {
                String filename = jarEntryName.substring(jarConnectionEntryName.length());
                File currentFile = new File(destPath, filename);

                if (jarEntry.isDirectory()) {
                    FileUtils.forceMkdir(currentFile);
                } else {
                    if (filter == null || filter.accept(currentFile)) {
                        InputStream is = jarFile.getInputStream(jarEntry);
                        OutputStream out = FileUtils.openOutputStream(currentFile);
                        IOUtils.copy(is, out);
                        is.close();
                        out.close();
                    }
                }
            }
        }
    } catch (IOException e) {
        LOGGER.warn(e.getMessage(), e);
    }
}

From source file:org.seadva.bagit.event.impl.SipGenerationHandler.java

@Override
public PackageDescriptor execute(PackageDescriptor packageDescriptor) {
    try {/*from   w w w  . ja v  a 2  s.com*/

        if (packageDescriptor.getAggregationId() == null)
            packageDescriptor.setAggregationId(packageDescriptor.getPackageId());

        generateSIP(packageDescriptor.getPackageId(), packageDescriptor.getAggregationId(), null,
                packageDescriptor.getUnzippedBagPath());
        String sipPath = packageDescriptor.getUnzippedBagPath() + "/" + packageDescriptor.getPackageId()
                + "_sip.xml";

        File sipFile = new File(sipPath);

        OutputStream out = FileUtils.openOutputStream(sipFile);
        new SeadXstreamStaxModelBuilder().buildSip(sip, out);
        out.close();
        packageDescriptor.setSipPath(sipPath);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return packageDescriptor;
}

From source file:org.sherlok.config.HttpConfigVariable.java

@Override
public String getProcessedValue() throws ProcessConfigVariableException {
    File file = getPath();/*from  w  w  w.j a  v a2s .com*/

    // if needed, download the file
    if (file == null || !file.exists()) {
        try {
            LOG.trace("Downloading file from " + url);

            // open an HTTP connection with the remote server
            URL remote = new URL(this.url);
            HttpURLConnection connection = (HttpURLConnection) remote.openConnection();
            int status = connection.getResponseCode();

            // make sure the request was successful
            if (status != HttpURLConnection.HTTP_OK) {
                throw new ProcessConfigVariableException("Status code from HTTP request is not 200: " + status);
            }

            // save the filename
            String disposition = connection.getHeaderField("Content-Disposition");
            file = extractFileName(disposition);

            // save the remote file
            InputStream input = connection.getInputStream();
            FileOutputStream output = FileUtils.openOutputStream(file);
            IOUtils.copy(input, output);

            output.close();
            input.close();
            connection.disconnect();
        } catch (IOException e) {
            String msg = "Failed to download " + url;
            throw new ProcessConfigVariableException(msg, e);
        }
    }

    if (rutaCompatible) {
        return FileBased.getRelativePathToResources(file.getAbsoluteFile());
    } else {
        return file.getAbsolutePath();
    }
}

From source file:org.silverpeas.attachment.webdav.impl.WebdavDocumentRepository.java

@Override
public void updateAttachmentBinaryContent(Session session, SimpleDocument attachment)
        throws RepositoryException, IOException {
    Node rootNode = session.getRootNode();
    Node webdavFileNode = rootNode.getNode(attachment.getWebdavJcrPath());
    Binary webdavBinary = webdavFileNode.getNode(JCR_CONTENT).getProperty(JCR_DATA).getBinary();
    InputStream in = webdavBinary.getStream();
    OutputStream out = null;/* w ww . j  a v  a 2  s  . c  o m*/
    try {
        out = FileUtils.openOutputStream(new File(attachment.getAttachmentPath()));
        IOUtils.copy(in, out);
    } finally {
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(in);
        webdavBinary.dispose();
    }
}

From source file:org.silverpeas.core.io.upload.UploadSessionFile.java

/**
 * Writes the given input stream into the physical file.<br>
 * Closes the input stream at the end.//  www . ja v a 2s  . c  o m
 * @param uploadedInputStream
 * @throws IOException
 */
public void write(InputStream uploadedInputStream) throws IOException {
    getUploadSession().markFileWritingInProgress(this);
    try {
        FileOutputStream fOS = FileUtils.openOutputStream(getServerFile());
        try {
            IOUtils.copy(uploadedInputStream, fOS);
        } finally {
            IOUtils.closeQuietly(fOS);
        }
    } finally {
        IOUtils.closeQuietly(uploadedInputStream);
        getUploadSession().markFileWritingDone(this);
    }
}

From source file:org.silverpeas.core.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 . ja v  a 2  s . c o  m
 * @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 SilverpeasRuntimeException(PDF_FILE_ERROR_MSG);
    } else if (!FileUtil.isPdf(pdfSource.getPath())) {
        throw new SilverpeasRuntimeException(NOT_PDF_FILE_ERROR_MSG);
    } else if (pdfDestination == null) {
        throw new SilverpeasRuntimeException(PDF_DESTINATION_ERROR_MSG);
    }

    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 SilverpeasRuntimeException(
                "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.silverpeas.core.webapi.attachment.SharedAttachmentResource.java

@GET
@Path("{ids}/zip")
@Produces(MediaType.APPLICATION_JSON)//from   ww w  .  j  a  v a  2  s  . 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 = AttachmentServiceProvider.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()));
            AttachmentServiceProvider.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 = getUri().getWebResourcePathBuilder().path(getToken()).path("zipcontent")
                .path(zipFile.getName()).build();
        long size = ZipUtil.compressPathToZip(folderToZip, zipFile);
        return new ZipEntity(getUri().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);
    }
}