Example usage for org.apache.commons.io IOUtils copyLarge

List of usage examples for org.apache.commons.io IOUtils copyLarge

Introduction

In this page you can find the example usage for org.apache.commons.io IOUtils copyLarge.

Prototype

public static long copyLarge(Reader input, Writer output) throws IOException 

Source Link

Document

Copy chars from a large (over 2GB) Reader to a Writer.

Usage

From source file:com.haulmont.cuba.core.app.filestorage.FileStorage.java

@Override
public long saveStream(final FileDescriptor fileDescr, final InputStream inputStream)
        throws FileStorageException {
    checkFileDescriptor(fileDescr);/*from  w  ww .ja  v  a2s  .  com*/

    File[] roots = getStorageRoots();

    // Store to primary storage

    checkStorageDefined(roots, fileDescr);
    checkPrimaryStorageAccessible(roots, fileDescr);

    File dir = getStorageDir(roots[0], fileDescr);
    dir.mkdirs();
    checkDirectoryExists(dir);

    final File file = new File(dir, getFileName(fileDescr));
    checkFileExists(file);

    long size = 0;
    OutputStream os = null;
    try {
        os = FileUtils.openOutputStream(file);
        size = IOUtils.copyLarge(inputStream, os);
        os.flush();
        writeLog(file, false);
    } catch (IOException e) {
        IOUtils.closeQuietly(os);
        FileUtils.deleteQuietly(file);

        throw new FileStorageException(FileStorageException.Type.IO_EXCEPTION, file.getAbsolutePath(), e);
    } finally {
        IOUtils.closeQuietly(os);
    }

    // Copy file to secondary storages asynchronously

    final SecurityContext securityContext = AppContext.getSecurityContext();
    for (int i = 1; i < roots.length; i++) {
        if (!roots[i].exists()) {
            log.error("Error saving {} into {} : directory doesn't exist", fileDescr, roots[i]);
            continue;
        }

        File copyDir = getStorageDir(roots[i], fileDescr);
        final File fileCopy = new File(copyDir, getFileName(fileDescr));

        writeExecutor.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    AppContext.setSecurityContext(securityContext);
                    FileUtils.copyFile(file, fileCopy, true);
                    writeLog(fileCopy, false);
                } catch (Exception e) {
                    log.error("Error saving {} into {} : {}", fileDescr, fileCopy.getAbsolutePath(),
                            e.getMessage());
                } finally {
                    AppContext.setSecurityContext(null);
                }
            }
        });
    }

    return size;
}

From source file:cz.zcu.kiv.eegdatabase.wui.core.file.FileServiceImpl.java

@Override
@Transactional/*from  ww w  .j a  v a  2  s .  c o m*/
public FileDTO getFile(int fileId) {
    FileOutputStream out = null;
    try {
        DataFile dataFileEntity = fileDAO.read(fileId);
        FileDTO dto = new FileDTO();

        File tmpFile;
        tmpFile = File.createTempFile("dataFile", ".tmp");
        tmpFile.deleteOnExit();
        out = new FileOutputStream(tmpFile);
        IOUtils.copyLarge(dataFileEntity.getFileContent().getBinaryStream(), out);
        dto.setFile(tmpFile);
        dto.setFileName(dataFileEntity.getFilename());
        dto.setMimetype(dataFileEntity.getMimetype());

        return dto;
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        return null;
    } catch (SQLException e) {
        log.error(e.getMessage(), e);
        return null;
    } finally {
        IOUtils.closeQuietly(out);
    }

}

From source file:edu.umn.msi.tropix.common.io.FileUtilsImpl.java

public void writeStreamToFile(final File file, @WillClose final InputStream inputStream) {
    final FileOutputStream outputStream = getFileOutputStream(file);
    try {//from  w w  w  .j  a v  a 2s. com
        IOUtils.copyLarge(inputStream, outputStream);
    } catch (final IOException e) {
        throw new IORuntimeException(e);
    } finally {
        IOUtils.closeQuietly(outputStream);
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:com.manydesigns.elements.blobs.SimpleBlobManager.java

@Override
public void save(Blob blob) throws IOException {
    ensureValidCode(blob.getCode());//ww w .j a  v  a  2  s . c  o  m
    File dataFile = getDataFile(blob.getCode());
    if (!dataFile.getParentFile().isDirectory()) {
        dataFile.getParentFile().mkdirs();
    }
    FileOutputStream out = new FileOutputStream(dataFile);
    try {
        blob.setSize(IOUtils.copyLarge(blob.getInputStream(), out));
    } finally {
        IOUtils.closeQuietly(out);
    }
    File metaFile = getMetaFile(blob.getCode());
    if (!metaFile.getParentFile().isDirectory()) {
        metaFile.getParentFile().mkdirs();
    }
    out = new FileOutputStream(metaFile);
    try {
        blob.getMetaProperties().store(out, "Blob code #" + blob.getCode());
    } finally {
        IOUtils.closeQuietly(out);
    }
    blob.dispose();
}

From source file:com.springsource.html5expense.controllers.ExpenseReportingApiController.java

@RequestMapping(value = "/receipts/{expenseId}")
public void renderMedia(HttpServletResponse httpServletResponse, OutputStream os,
        @PathVariable("expenseId") Integer expenseId) {

    Expense expense = service.getExpense(expenseId);
    httpServletResponse.setContentType(buildMimeTypeForExpense(expense));

    File f = service.retreiveReceipt(expenseId);
    InputStream is = null;//from ww w.  j av  a2s  .co m
    try {
        is = new FileInputStream(f);
        httpServletResponse.setContentLength((int) f.length());
        IOUtils.copyLarge(is, os);
    } catch (Exception e1) {
        log.error(e1);
    } finally {
        if (is != null)
            IOUtils.closeQuietly(is);
        if (os != null)
            IOUtils.closeQuietly(os);
    }
}

From source file:gov.nih.nci.calims2.ui.common.document.DocumentController.java

/**
 * /*from  w  w  w .j av  a  2  s  .c  o m*/
 * @param response The servlet response.
 * @param id The id of the filledreport to view.
 */
@RequestMapping("/download.do")
public void download(HttpServletResponse response, @RequestParam("id") Long id) {
    try {
        Document document = getMainService().findById(Document.class, id);
        ServletOutputStream servletOutputStream = response.getOutputStream();
        File downloadedFile = storageService.get(document, new File(tempfiledir));
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + document.getName());
        FileInputStream fileInputStream = new FileInputStream(downloadedFile);
        IOUtils.copyLarge(fileInputStream, servletOutputStream);
        IOUtils.closeQuietly(fileInputStream);
        servletOutputStream.flush();
        servletOutputStream.close();
        downloadedFile.delete();
    } catch (IOException e1) {
        throw new RuntimeException("IOException in download", e1);
    } catch (StorageServiceException e) {
        throw new RuntimeException("StorageServiceException in download", e);
    }
}

From source file:de.tudarmstadt.ukp.dkpro.core.api.resources.ResourceUtils.java

/**
 * Make a given classpath location available as a folder. A temporary folder is created and
 * deleted upon a regular shutdown of the JVM. This method must not be used for creating
 * executable binaries. For this purpose, getUrlAsExecutable should be used.
 *
 * @param aClasspathBase/*from www  . j a v  a 2 s  .c  o m*/
 *            a classpath location as used by
 *            {@link PathMatchingResourcePatternResolver#getResources(String)}
 * @param aCache
 *            use the cache or not.
 * @see PathMatchingResourcePatternResolver
 */
public static File getClasspathAsFolder(String aClasspathBase, boolean aCache) throws IOException {
    synchronized (classpathFolderCache) {
        File folder = classpathFolderCache.get(aClasspathBase);

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        if (!aCache || (folder == null) || !folder.exists()) {
            folder = File.createTempFile("dkpro-package", "");
            folder.delete();
            FileUtils.forceMkdir(folder);

            Resource[] roots = resolver.getResources(aClasspathBase);
            for (Resource root : roots) {
                String base = root.getURL().toString();
                Resource[] resources = resolver.getResources(base + "/**/*");
                for (Resource resource : resources) {
                    if (!resource.isReadable()) {
                        // This is true for folders/packages
                        continue;
                    }

                    // Relativize
                    String res = resource.getURL().toString();
                    if (!res.startsWith(base)) {
                        throw new IOException("Resource location does not start with base location");
                    }
                    String relative = resource.getURL().toString().substring(base.length());

                    // Make sure the target folder exists
                    File target = new File(folder, relative).getAbsoluteFile();
                    if (target.getParentFile() != null) {
                        FileUtils.forceMkdir(target.getParentFile());
                    }

                    // Copy data
                    InputStream is = null;
                    OutputStream os = null;
                    try {
                        is = resource.getInputStream();
                        os = new FileOutputStream(target);
                        IOUtils.copyLarge(is, os);
                    } finally {
                        IOUtils.closeQuietly(is);
                        IOUtils.closeQuietly(os);
                    }

                    // WORKAROUND: folders get written as files if inside jars
                    // delete files of size zero
                    if (target.length() == 0) {
                        FileUtils.deleteQuietly(target);
                    }
                }
            }

            if (aCache) {
                classpathFolderCache.put(aClasspathBase, folder);
            }
        }

        return folder;
    }
}

From source file:com.manydesigns.elements.blobs.BlobManager.java

public Blob saveBlob(String code, InputStream sourceStream, String fileName, String contentType,
        @Nullable String characterEncoding) throws IOException {
    ensureValidCode(code);//from ww  w.  j  a  va 2  s  . c  om

    File metaFile = RandomUtil.getCodeFile(blobsDir, metaFileNamePattern, code);
    File dataFile = RandomUtil.getCodeFile(blobsDir, dataFileNamePattern, code);
    Blob blob = new Blob(metaFile, dataFile);

    // copy the data
    long size = IOUtils.copyLarge(sourceStream, new FileOutputStream(dataFile));

    // set and save the metadata
    blob.setCode(code);
    blob.setFilename(fileName);
    blob.setContentType(contentType);
    blob.setSize(size);
    blob.saveMetaProperties();

    return blob;
}

From source file:com.amalto.core.servlet.LogViewerServlet.java

private void downloadLogFile(HttpServletResponse response) throws IOException {
    String filename = file.getAbsolutePath();
    filename = FilenameUtils.getName(filename);
    response.setContentType("text/x-log; name=\"" + filename + '"'); //$NON-NLS-1$
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + '"'); //$NON-NLS-1$ //$NON-NLS-2$
    FileInputStream fis = new FileInputStream(file);
    try {/*from  w  ww .ja v  a 2s.c o m*/
        OutputStream responseOutputStream = response.getOutputStream();
        IOUtils.copyLarge(fis, responseOutputStream);
        responseOutputStream.close();
    } finally {
        try {
            fis.close();
        } catch (Exception e) {
            // ignore it
        }
    }
}

From source file:com.rapleaf.hank.storage.HdfsPartitionRemoteFileOps.java

@Override
public void copyToLocalRoot(String remoteSourceRelativePath, String localDestinationRoot) throws IOException {
    Path source = new Path(getAbsoluteRemotePath(remoteSourceRelativePath));
    File destination = new File(localDestinationRoot + "/" + new Path(remoteSourceRelativePath).getName());
    LOG.info("Copying remote file " + source + " to local file " + destination);
    InputStream inputStream = getInputStream(remoteSourceRelativePath);
    FileOutputStream fileOutputStream = new FileOutputStream(destination);
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
    // Use copyLarge (over 2GB)
    try {// w  ww .  j av  a 2  s .c  o m
        IOUtils.copyLarge(inputStream, bufferedOutputStream);
        bufferedOutputStream.flush();
        fileOutputStream.flush();
    } finally {
        inputStream.close();
        bufferedOutputStream.close();
        fileOutputStream.close();
    }
}