Example usage for com.google.common.io ByteStreams copy

List of usage examples for com.google.common.io ByteStreams copy

Introduction

In this page you can find the example usage for com.google.common.io ByteStreams copy.

Prototype

public static long copy(ReadableByteChannel from, WritableByteChannel to) throws IOException 

Source Link

Document

Copies all bytes from the readable channel to the writable channel.

Usage

From source file:elw.web.CodeServlet.java

private void doGetOrHead(HttpServletRequest req, HttpServletResponse resp, final boolean doCopy)
        throws IOException {
    final String pathInfo = req.getPathInfo();

    if (pathInfo == null || !pathInfo.endsWith(".jar")) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;//from  w  w  w.  j  a va  2s .c o  m
    }

    final int lastSlashIdx = pathInfo.lastIndexOf("/");
    final String slashFileName = pathInfo.substring(lastSlashIdx);

    final String filePath = getServletContext().getRealPath(req.getServletPath() + slashFileName);
    final File codeFile = new File(filePath);
    if (!codeFile.exists()) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    resp.setContentType("application/java-archive");
    resp.setHeader("Cache-Control", "public");
    resp.setDateHeader("Expires", System.currentTimeMillis() + 1000 * 60 * 60 * 24);
    resp.setDateHeader("Last-Modified", codeFile.lastModified());
    resp.setHeader("Content-Length", String.valueOf(codeFile.length()));

    if (doCopy) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(codeFile);

            ByteStreams.copy(fis, resp.getOutputStream());
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    log.debug("failed on close", e);
                }
            }
        }
    }
}

From source file:de.siegmar.securetransfer.repository.memory.FileMemoryRepository.java

@Override
public SecretFile storeFile(final String id, final CryptedData originalName, final InputStream in,
        final KeyIv key, final Instant expiration) {

    LOG.info("Store file {}", id);

    final ByteArrayOutputStream dataOut = new ByteArrayOutputStream();

    try {//  www. j  av a 2s. c o  m
        final long originalFileSize;

        try (final OutputStream cryptOut = cryptor.getCryptOut(dataOut, key)) {
            originalFileSize = ByteStreams.copy(in, cryptOut);
        }

        final SecretFile secretFile = new SecretFile(id, originalName, originalFileSize, dataOut.size(), key,
                expiration);

        meta.put(id, secretFile);
        data.put(id, dataOut.toByteArray());

        return secretFile;
    } catch (final IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:org.isisaddons.module.docx.dom.IoHelper.java

public void write(byte[] bytes, File file) throws IOException {
    final FileOutputStream targetFos = new FileOutputStream(file);
    ByteStreams.copy(new ByteArrayInputStream(bytes), targetFos);
}

From source file:tachyon.util.CommonUtils.java

/**
 * Blocking operation that copies the processes stdout/stderr to this JVM's stdout/stderr.
 *//*from  w  w  w .ja va2 s.  c  om*/
private static void redirectIO(final Process process) throws IOException {
    // Because chmod doesn't have a lot of error or output messages, its safe to process the output
    // after the process is done. As of java 7, you can have the process redirect to System.out
    // and System.err without forking a process.
    // TODO when java 6 support is dropped, switch to
    // http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html#inheritIO()
    Closer closer = Closer.create();
    try {
        ByteStreams.copy(closer.register(process.getInputStream()), System.out);
        ByteStreams.copy(closer.register(process.getErrorStream()), System.err);
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

From source file:org.apache.nifi.processors.pcap.SplitPcap.java

@Override
public void onTrigger(ProcessContext processContext, ProcessSession processSession) throws ProcessException {
    final FlowFile flowFile = processSession.get();

    final ComponentLog logger = getLogger();

    if (flowFile != null) {
        final String vfsFilename = String.format("ram:/%s",
                flowFile.getAttribute(CoreAttributes.FILENAME.key()));
        final FileObject fileObject;
        try {/*from   ww w. j  a  v a2  s  .c  om*/
            fileObject = vfsManager.resolveFile(vfsFilename);
        } catch (FileSystemException e) {
            throw new ProcessException(String.format("Unable to resolve file in VFS: %s", vfsFilename));
        }
        processSession.read(flowFile, inputStream -> {
            final OutputStream vfsOutputStream = fileObject.getContent().getOutputStream();
            ByteStreams.copy(inputStream, vfsOutputStream);
        });

        final StringBuilder errorStringBuilder = new StringBuilder();
        final Pcap pcap = Pcap.openOffline(vfsFilename, errorStringBuilder);
        if (pcap == null) {
            throw new ProcessException(String.format("Unable to open pcap %s, error: %s", vfsFilename,
                    errorStringBuilder.toString()));
        }
        try {
            pcap.loop(-1, (PcapPacketHandler<String>) (pcapPacket, s) -> logger.info("got packet {}",
                    new Object[] { pcapPacket.getTotalSize() }), "offline capture");
        } finally {
            pcap.close();
        }
    }
}

From source file:org.diqube.ui.WebServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String path = req.getPathInfo();
    if (path == null || "".equals(path)) {
        resp.sendRedirect("/");
        return;//from   w ww . ja  v a 2  s . c o  m
    }

    if ("/".equals(path))
        path = DEFAULT_RESOURCE;

    try {
        path = new URI(path).normalize().toString();
        if (path.startsWith(".") || path.startsWith(".."))
            path = DEFAULT_RESOURCE;
        if (!path.startsWith("/"))
            path = "/" + path;
    } catch (URISyntaxException e) {
        path = DEFAULT_RESOURCE;
    }

    InputStream is = getClass().getResourceAsStream(WAR_STATIC_ROOT + path);

    if (path.equals("/index.html") || is == null || !path.contains(".")) {
        if (cachedIndexHtmlBytes == null) {
            synchronized (cachedIndexHtmlSync) {
                if (cachedIndexHtmlBytes == null) {
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    try (InputStream is2 = getClass().getResourceAsStream(WAR_STATIC_ROOT + "/index.html")) {
                        ByteStreams.copy(is2, baos);
                    }
                    String indexHtmlString = baos.toString("UTF-8");
                    indexHtmlString = indexHtmlString.replace("{{globalContextPath}}",
                            getServletContext().getContextPath());
                    cachedIndexHtmlBytes = indexHtmlString.getBytes("UTF-8");
                }
            }
        }

        is = new ByteArrayInputStream(cachedIndexHtmlBytes);
    }

    if (path.endsWith(".css"))
        resp.setContentType("text/css");

    ByteStreams.copy(is, resp.getOutputStream());
    is.close();
}

From source file:ca.ualberta.physics.cssdp.file.service.CacheService.java

public ServiceResponse<String> put(final String filename, final String externalKey,
        final InputStream fileData) {

    final ServiceResponse<String> sr = new ServiceResponse<String>();

    File tempDir = Files.createTempDir();
    final File tempFile = new File(tempDir, UUID.randomUUID().toString());
    FileOutputStream fos = null;/* w w  w.jav a  2 s.  co m*/
    try {
        Files.touch(tempFile);
        fos = new FileOutputStream(tempFile);
        logger.debug("Shuffling bytes from input stream into " + tempFile.getAbsolutePath());
        ByteStreams.copy(fileData, fos);
    } catch (IOException e) {
        sr.error("Could not copy file data into temp file because " + e.getMessage());

    } finally {
        if (fos != null) {
            try {
                fos.flush();
                fos.close();
            } catch (IOException ignore) {
            }
        }
    }

    final String md5 = getMD5(tempFile);
    new ManualTransaction(sr, emp.get()) {

        @Override
        public void onError(Exception e, ServiceResponse<?> sr) {
            Throwable t = Throwables.getRootCause(e);
            sr.error(t.getMessage());
        }

        @Override
        public void doInTransaction() {

            CachedFile existing = cachedFileDao.get(md5);
            if (existing != null) {
                if (existing.getExternalKeys().contains(externalKey)) {
                    sr.info("File with signature " + md5 + " already in cache with key " + externalKey);
                } else {
                    existing.getExternalKeys().add(externalKey);
                    cachedFileDao.update(existing);
                }
            } else {

                StringBuffer path = new StringBuffer();
                for (String subdir : Splitter.fixedLength(4).split(md5)) {
                    path.append("/" + subdir);
                }
                path.append("/");

                File cachePath = new File(cacheRoot, path.toString());
                cachePath.mkdirs();
                File cacheFile = new File(cachePath, "" + (cachePath.list().length + 1));

                try {
                    Files.touch(cacheFile);
                    Files.copy(tempFile, cacheFile);
                    logger.debug("Shuffling bytes from " + tempFile.getAbsolutePath() + " into "
                            + cacheFile.getAbsolutePath());
                } catch (IOException e) {
                    sr.error("Could not copy temp file into cache because " + e.getMessage());

                }

                // sanity check
                if (cacheFile.length() == 0) {
                    cacheFile.delete();
                    sr.error("Zero byte file, not caching.");
                }

                CachedFile cachedFile = new CachedFile(filename, md5, cacheFile);
                cachedFile.getExternalKeys().add(externalKey);

                cachedFileDao.save(cachedFile);

            }

        }
    };

    tempFile.delete();
    tempDir.delete();
    logger.debug("temp files and dirs cleared");

    if (sr.isRequestOk()) {
        sr.setPayload(md5);
    }
    logger.info("File with MD5 " + md5 + " is now in cache");
    return sr;
}

From source file:com.chiorichan.util.FileUtil.java

public static void putResource(String resource, File file) throws IOException {
    try {//from w  w  w.  ja v a2s  . c om
        InputStream is = Loader.class.getClassLoader().getResourceAsStream(resource);
        FileOutputStream os = new FileOutputStream(file);
        ByteStreams.copy(is, os);
        is.close();
        os.close();
    } catch (FileNotFoundException e) {
        throw new IOException(e);
    }
}

From source file:com.indeed.iupload.core.filesystem.HDFSProxy.java

@Override
public void createFile(String path, String name, InputStream inputStream) throws IOException {
    final Path pathObj = new Path(path, name);
    if (!getFileSystem(path).exists(pathObj)) {
        mkdirs(path);//w w w  .ja v  a 2 s.  com
    }
    OutputStream outputStream = getFileSystem(path).create(pathObj);
    ByteStreams.copy(inputStream, outputStream);
    outputStream.close();
}

From source file:de.nx42.maps4cim.util.Compression.java

/**
 * Compresses the input file using the zip file format and stores the
 * resulting zip file in the desired location
 * @param input the file to compress/*from ww  w.  j  a  v a  2 s  .co m*/
 * @param zipOutput the resulting zip file
 * @return the resulting zip file
 * @throws IOException if there is an error accessing the input file or
 * writing the output zip file
 */
public static File storeAsZip(File input, File zipOutput) throws IOException {
    // create new zip output stream
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipOutput));
    ZipEntry ze = new ZipEntry(input.getName());
    zos.putNextEntry(ze);

    // use file as input stream and copy bytes
    InputStream in = new FileInputStream(input);
    ByteStreams.copy(in, zos);

    // close current zip entry and all streams
    zos.closeEntry();
    in.close();
    zos.close();
    return zipOutput;
}