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:io.airlift.http.server.ClassPathResourceHandler.java

@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    if (baseRequest.isHandled()) {
        return;//  w  ww .  j ava  2 s  .c  o  m
    }

    URL resource = getResourcePath(request);
    if (resource == null) {
        return;
    }

    // When a request hits this handler, it will serve something. Either data or an error.
    baseRequest.setHandled(true);

    String method = request.getMethod();
    boolean skipContent = false;
    if (!HttpMethod.GET.is(method)) {
        if (HttpMethod.HEAD.is(method)) {
            skipContent = true;
        } else {
            response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            return;
        }
    }

    InputStream resourceStream = null;
    try {
        resourceStream = resource.openStream();

        String contentType = MIME_TYPES.getMimeByExtension(resource.toString());
        response.setContentType(contentType);

        if (skipContent) {
            return;
        }

        // Send the content out. Lifted straight out of ResourceHandler.java
        OutputStream out;
        try {
            out = response.getOutputStream();
        } catch (IllegalStateException e) {
            out = new WriterOutputStream(response.getWriter());
        }

        ByteStreams.copy(resourceStream, out);
    } finally {
        closeQuietly(resourceStream);
    }
}

From source file:com.pamarin.income.controller.SuggestionCtrl.java

private File saveFile() {
    File attachFile = null;//from   ww  w . jav a2s .c o  m
    String errorMessage = "?";

    InputStream inputStream = null;
    OutputStream outputStream = null;

    try {
        String randomName = UUID.randomUUID().toString();
        String extension = FilenameUtils.getExtension(file.getFileName());
        inputStream = file.getInputstream();
        File parentDir = getTempDirectoryDateTime();
        attachFile = new File(parentDir, randomName + "." + extension);

        outputStream = new FileOutputStream(attachFile);
        ByteStreams.copy(inputStream, outputStream);
        getSuggestion().setImage("/" + parentDir.getName() + "/" + randomName + "." + extension);
    } catch (Exception ex) {
        LOG.warn(null, ex);
        attachFile = null;
        throw new UncheckedIOException(errorMessage);
    } finally {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException ex) {
                attachFile = null;
                throw new UncheckedIOException(errorMessage);
            }
        }

        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException ex) {
                attachFile = null;
                throw new UncheckedIOException(errorMessage);
            }
        }
    }

    return attachFile;
}

From source file:com.google.gerrit.server.tools.hooks.HookTestCase.java

protected File getHook(final String name) throws IOException {
    File hook = hooks.get(name);/*  w ww  . j a  v  a 2 s.  co  m*/
    if (hook != null) {
        return hook;
    }

    final String scproot = "com/google/gerrit/server/tools/root";
    final String path = scproot + "/hooks/" + name;
    URL url = cl().getResource(path);
    if (url == null) {
        fail("Cannot locate " + path + " in CLASSPATH");
    }

    if ("file".equals(url.getProtocol())) {
        hook = new File(url.getPath());
        if (!hook.isFile()) {
            fail("Cannot locate " + path + " in CLASSPATH");
        }
        long time = hook.lastModified();
        hook.setExecutable(true);
        hook.setLastModified(time);
        hooks.put(name, hook);
        return hook;
    } else if ("jar".equals(url.getProtocol())) {
        InputStream in = url.openStream();
        try {
            hook = File.createTempFile("hook_", ".sh");
            cleanup.add(hook);
            FileOutputStream out = new FileOutputStream(hook);
            try {
                ByteStreams.copy(in, out);
            } finally {
                out.close();
            }
        } finally {
            in.close();
        }
        hook.setExecutable(true);
        hooks.put(name, hook);
        return hook;
    } else {
        fail("Cannot invoke " + url);
        return null;
    }
}

From source file:com.broadwave.android.brut.androlib.res.AndrolibResources.java

public File getFrameworkApk(int id, String frameTag) throws AndrolibException {
    File dir = getFrameworkDir();
    File apk;/*from w w  w  . ja  v a 2 s  .  c  o m*/

    if (frameTag != null) {
        apk = new File(dir, String.valueOf(id) + '-' + frameTag + ".apk");
        if (apk.exists()) {
            return apk;
        }
    }

    apk = new File(dir, String.valueOf(id) + ".apk");
    if (apk.exists()) {
        return apk;
    }

    if (id == 1) {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = AndrolibResources.class.getResourceAsStream("/brut/androlib/android-framework.jar");
            out = new FileOutputStream(apk);
            ByteStreams.copy(in, out);
            return apk;
        } catch (IOException ex) {
            throw new AndrolibException(ex);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ex) {
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException ex) {
                }
            }
        }
    }

    throw new CantFindFrameworkResException(id);
}

From source file:hu.akarnokd.utils.io.ByteArrayStream.java

/**
 * Reads the conents of the supplied input stream.
 * @param in the input stream to read from
 * @throws IOException if the copy throws this exception
 *///w w w.  j  ava 2s .  c  om
public synchronized void readFrom(InputStream in) throws IOException {
    ByteStreams.copy(in, this);
}

From source file:com.facebook.buck.util.zip.CustomZipOutputStream.java

public void writeEntry(String name, InputStream contents) throws IOException {
    try {//  w  w w.j  a  va  2 s  .  co  m
        putNextEntry(new CustomZipEntry(name));
        ByteStreams.copy(contents, this);
        closeEntry();
    } finally {
        contents.close();
    }
}

From source file:eu.itesla_project.iidm.datasource.ZipFileDataSource.java

@Override
public OutputStream newOutputStream(String suffix, String ext, boolean append) throws IOException {
    if (append) {
        throw new UnsupportedOperationException("append not supported in zip file data source");
    }/*from w ww.jav  a2  s  . c  o  m*/
    Path tmpZipFilePath = Files.createTempFile(directory, null, null);
    ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(tmpZipFilePath));
    Path zipFilePath = getZipFilePath();
    String entryName = DataSourceUtil.getFileName(baseName, suffix, ext);
    zos.putNextEntry(new ZipEntry(entryName));
    return new ForwardingOutputStream<ZipOutputStream>(zos) {
        @Override
        public void close() throws IOException {
            os.closeEntry();
            if (Files.exists(zipFilePath)) {
                try (ZipFile zipFile = new ZipFile(getZipFilePath().toFile())) {
                    for (Enumeration<? extends ZipEntry> e = zipFile.entries(); e.hasMoreElements();) {
                        ZipEntry entry = e.nextElement();
                        if (!entry.getName().equals(entryName)) {
                            zos.putNextEntry(entry);
                            ByteStreams.copy(zipFile.getInputStream(entry), zos);
                            zos.closeEntry();
                        }
                    }
                }
            }
            super.close();
            Files.copy(tmpZipFilePath, zipFilePath, StandardCopyOption.REPLACE_EXISTING);
            Files.delete(tmpZipFilePath);
        }
    };
}

From source file:com.splicemachine.pipeline.SnappyPipelineCompressor.java

@Override
public <T> T decompress(byte[] bytes, Class<T> clazz) throws IOException {
    byte[] d = bytes;
    if (supportsNative) {
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        ByteArrayOutputStream baos = new ByteArrayOutputStream(d.length);

        Decompressor snappyDecompressor = CodecPool.getDecompressor(snappy);
        try {//  w w w  .  j a  v  a 2  s  .com
            InputStream is = snappy.createInputStream(bais, snappyDecompressor);
            ByteStreams.copy(is, baos);
            baos.flush();
            d = baos.toByteArray();
            baos.close();
            is.close();
        } finally {
            CodecPool.returnDecompressor(snappyDecompressor);
        }
    }
    return delegate.decompress(d, clazz);
}

From source file:de.dentrassi.pm.storage.service.jpa.blob.BlobStore.java

public void doStreamed(final EntityManager em, final ArtifactEntity ae,
        final ThrowingConsumer<Path> fileConsumer) throws IOException {
    final Path tmp = StreamServiceHelper.createTempFile(ae.getName());

    try {//from   w w  w  .j  a va2s  .  c om
        try (OutputStream os = new BufferedOutputStream(new FileOutputStream(tmp.toFile()))) {
            streamArtifact(em, ae, (ai, in) -> {
                ByteStreams.copy(in, os);
            });
        }

        try {
            fileConsumer.accept(tmp);
        } catch (final IOException e) {
            throw e;
        } catch (final Exception e) {
            throw new RuntimeException(e);
        }
    } finally {
        Files.deleteIfExists(tmp);
    }
}

From source file:io.druid.segment.data.BlockLayoutLongSupplierSerializer.java

@Override
public void writeToChannel(WritableByteChannel channel) throws IOException {
    try (InputStream meta = ioPeon.makeInputStream(metaFile);
            InputStream input = flattener.combineStreams().getInput()) {
        ByteStreams.copy(Channels.newChannel(meta), channel);
        final ReadableByteChannel from = Channels.newChannel(input);
        ByteStreams.copy(from, channel);
    }/* w w w.  j  av  a2s.  co m*/
}