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:co.cask.cdap.internal.test.AppJarHelper.java

public static Location createDeploymentJar(LocationFactory locationFactory, Class<?> clz, Manifest manifest,
        File... bundleEmbeddedJars) throws IOException {

    ApplicationBundler bundler = new ApplicationBundler(
            ImmutableList.of("co.cask.cdap.api", "org.apache.hadoop", "org.apache.hive", "org.apache.spark"),
            ImmutableList.of("org.apache.hadoop.hbase"));
    Location jarLocation = locationFactory.create(clz.getName()).getTempFile(".jar");
    ClassLoader oldClassLoader = ClassLoaders.setContextClassLoader(clz.getClassLoader());
    try {/*from   www .  j  a  v a2 s. c o m*/
        bundler.createBundle(jarLocation, clz);
    } finally {
        ClassLoaders.setContextClassLoader(oldClassLoader);
    }

    Location deployJar = locationFactory.create(clz.getName()).getTempFile(".jar");
    Manifest jarManifest = new Manifest(manifest);
    jarManifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    jarManifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, clz.getName());

    // Create the program jar for deployment. It removes the "classes/" prefix as that's the convention taken
    // by the ApplicationBundler inside Twill.
    Set<String> seenEntries = new HashSet<>();
    try (JarOutputStream jarOutput = new JarOutputStream(deployJar.getOutputStream(), jarManifest);
            JarInputStream jarInput = new JarInputStream(jarLocation.getInputStream())) {
        JarEntry jarEntry = jarInput.getNextJarEntry();
        while (jarEntry != null) {
            boolean isDir = jarEntry.isDirectory();
            String entryName = jarEntry.getName();
            if (!entryName.equals("classes/")) {
                if (entryName.startsWith("classes/")) {
                    jarEntry = new JarEntry(entryName.substring("classes/".length()));
                } else {
                    jarEntry = new JarEntry(entryName);
                }

                // TODO: this is due to manifest possibly already existing in the jar, but we also
                // create a manifest programatically so it's possible to have a duplicate entry here
                if ("META-INF/MANIFEST.MF".equalsIgnoreCase(jarEntry.getName())) {
                    jarEntry = jarInput.getNextJarEntry();
                    continue;
                }

                if (seenEntries.add(jarEntry.getName())) {
                    jarOutput.putNextEntry(jarEntry);
                    if (!isDir) {
                        ByteStreams.copy(jarInput, jarOutput);
                    }
                }
            }

            jarEntry = jarInput.getNextJarEntry();
        }

        for (File embeddedJar : bundleEmbeddedJars) {
            jarEntry = new JarEntry("lib/" + embeddedJar.getName());
            if (seenEntries.add(jarEntry.getName())) {
                jarOutput.putNextEntry(jarEntry);
                Files.copy(embeddedJar, jarOutput);
            }
        }
    }

    return deployJar;
}

From source file:org.impressivecode.depress.mr.astcompare.utils.Utils.java

private static void saveFile(InputStream is, OutputStream os) throws IOException {
    Closer closer = Closer.create();//  w  ww .j  a  v  a2 s. com
    try {
        InputStream in = closer.register(is);
        OutputStream out = closer.register(os);
        ByteStreams.copy(in, out);
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

From source file:net.minecrell.quartz.mappings.transformer.MappingsTransformer.java

public static void transform(ZipFile zip, ZipOutputStream out, TransformerContext context) throws IOException {
    ZipClassProvider provider = (ZipClassProvider) context.getClassProvider();

    Enumeration<? extends ZipEntry> entries = zip.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();

        if (entry.isDirectory() || !entry.getName().endsWith(".class")) {
            out.putNextEntry(new ZipEntry(entry));
            ByteStreams.copy(zip.getInputStream(entry), out);
            continue;
        }// w  w w  . java2  s . c  om

        ClassReader reader = provider.getClassFile(entry);
        reader = context.getTransformed(reader);

        ZipEntry entryOut = new ZipEntry(reader.getClassName() + ".class");
        entryOut.setSize(reader.b.length);
        entryOut.setCompressedSize(-1);
        out.putNextEntry(entryOut);
        out.write(reader.b);
    }
}

From source file:com.docdoku.server.postuploaders.ScormPostUploaderImpl.java

public void unzipScormArchive(BinaryResource archiveBinaryResource) {

    try (ZipInputStream zipInputStream = new ZipInputStream(
            dataManager.getBinaryResourceInputStream(archiveBinaryResource), Charset.forName("ISO-8859-1"))) {

        ZipEntry zipEntry;// w w  w  .j a  v  a 2  s  . c o  m
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            if (!zipEntry.isDirectory()) {
                OutputStream outputStream = null;
                try {
                    String entryName = zipEntry.getName();
                    String subResourceVirtualPath = ScormUtil.getScormSubResourceVirtualPath(entryName);
                    outputStream = dataManager.getBinarySubResourceOutputStream(archiveBinaryResource,
                            subResourceVirtualPath);
                    ByteStreams.copy(zipInputStream, outputStream);
                } finally {
                    if (outputStream != null) {
                        outputStream.flush();
                        outputStream.close();
                    }
                }
            }
        }
    } catch (StorageException | IOException e) {
        LOGGER.log(Level.SEVERE, null, e);
    }

}

From source file:org.waveprotocol.box.server.rpc.atmosphere.AtmosphereClientInterceptor.java

@Override
public Action inspect(AtmosphereResource resource) {

    AtmosphereRequest request = resource.getRequest();

    try {/* w w w  .  j a v  a 2s.  c om*/
        // Find the first context parameter
        String path = request.getPathInfo();

        if (path == null || path.isEmpty())
            return Action.CONTINUE;

        if (path.startsWith("/")) {
            path = path.substring(1);
        }
        String[] parts = path.split("/");

        // Serve the file
        if (parts.length > 0 && "GET".equals(resource.getRequest().getMethod())
                && "atmosphere.js".equals(parts[0])) {
            resource.getResponse().setContentType("text/javascript");
            InputStream is = this.getClass().getClassLoader()
                    .getResourceAsStream("org/waveprotocol/box/server/rpc/atmosphere/atmosphere.js");
            OutputStream os = resource.getResponse().getOutputStream();
            ByteStreams.copy(is, os);
            return Action.CANCELLED;

        }

    } catch (IOException e) {
        LOG.severe("Error sending atmosphere.js", e);
    }

    return Action.CONTINUE;
}

From source file:com.foundationdb.sql.pg.PostgresServerFilesITBase.java

/** Copy a resource from the test jar into a temp file so that it
 * can be read by things that do not take a URL.
 *///w w  w.  ja  va  2s.  c  o  m
protected File copyResourceToTempFile(String resource) throws IOException {
    File tempFile = File.createTempFile(getClass().getSimpleName(), null);
    tempFile.deleteOnExit();
    try (InputStream istr = getClass().getResourceAsStream(resource);
            OutputStream ostr = new FileOutputStream(tempFile)) {
        ByteStreams.copy(istr, ostr);
    }
    return tempFile;
}

From source file:io.bazel.rules.closure.http.filter.GzipFilter.java

public void apply() throws IOException {
    if (!response.getHeader("Content-Encoding").isEmpty()
            || !COMPRESSIBLE.contains(response.getContentType().withoutParameters())
            || !ALLOWS_GZIP.matcher(request.getHeader("Accept-Encoding")).find()) {
        return;//w w w  .j av a2 s  . co  m
    }
    try (ByteArrayOutputStream buffer = new ByteArrayOutputStream()) {
        try (InputStream input = response.getPayload();
                OutputStream output = new GZIPOutputStream(buffer, 8192)) {
            ByteStreams.copy(input, output);
        }
        response.setHeader("Content-Encoding", "gzip");
        response.setContentLength(buffer.size());
        response.setPayload(new ByteArrayInputStream(buffer.toByteArray()));
    }
}

From source file:com.complexible.common.io.ByteStreams2.java

public static byte[] gzip(final byte[] theBytes) throws IOException {
    final ByteArrayOutputStream aOut = new ByteArrayOutputStream(theBytes.length);

    final GZIPOutputStream aZipped = new GZIPOutputStream(aOut);
    final ByteArrayInputStream aIn = new ByteArrayInputStream(theBytes);

    Closer aCloser = Closer.create();/*from ww  w  . jav  a  2  s.  c om*/
    aCloser.register(aZipped);
    aCloser.register(aIn);

    try {
        ByteStreams.copy(aIn, aZipped);
    } finally {
        aCloser.close();
    }

    return aOut.toByteArray();
}

From source file:org.jclouds.blobstore.GetPath.java

private static void copyDirectoryToDestination(BlobStoreContext context, String container, String directory,
        File destinationDir) throws FileNotFoundException, IOException {
    InputStream input = null;/*from   w  w w.j a  v  a  2s . co  m*/

    try {
        checkState(context.getBlobStore().containerExists(container),
                String.format("source container %s does not exist", directory, container));
        checkState(context.getBlobStore().directoryExists(container, directory),
                String.format("source directory %s does not exist in container %s", directory, container));

        String path = container + "/" + directory;
        InputStreamMap map = context.createInputStreamMap(path);
        System.out.printf("fetching %d entries from %s %s%n", map.size(),
                context.getProviderSpecificContext().getIdentity(), path);
        for (Entry<String, InputStream> entry : map.entrySet()) {
            System.out.printf("getting file: %s/%s%n", path, entry.getKey());
            input = entry.getValue();
            File file = new File(destinationDir, entry.getKey());
            OutputStream out = new FileOutputStream(file);
            ByteStreams.copy(input, out);
            out.flush();
            out.close();
        }

    } finally {
        // Close connection
        Closeables.closeQuietly(input);
    }
}

From source file:com.metamx.druid.utils.CompressionUtils.java

public static void unzip(InputStream in, File outDir) throws IOException {
    ZipInputStream zipIn = new ZipInputStream(in);

    ZipEntry entry;//  www  .  j a v  a2s  .c om
    while ((entry = zipIn.getNextEntry()) != null) {
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(new File(outDir, entry.getName()));
            ByteStreams.copy(zipIn, out);
            zipIn.closeEntry();
            out.close();
        } finally {
            Closeables.closeQuietly(out);
        }
    }
}