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:org.celeria.minecraft.backup.Archive.java

private void writeToEntry(final FileContent content) throws IOException {
    final InputStream input = inputStreamFrom(content);
    boolean threw = true;
    try {/*from   ww w  . ja  va 2 s.c o  m*/
        ByteStreams.copy(input, output);
        threw = false;
    } finally {
        Closeables.close(input, threw);
    }
}

From source file:com.facebook.buck.jvm.java.abi.JavaFileManagerStubJarWriter.java

@Override
public void writeClass(Path relativePath, Consumer<ClassWriter> stubber) throws IOException {
    String relativePathString = MorePaths.pathWithUnixSeparators(relativePath);
    String className = relativePathString.replace('/', '.').substring(0, relativePathString.length() - 6); // Strip .class off the end

    ClassWriter writer = new ClassWriter(0);
    stubber.accept(writer);//  w  ww. ja  v  a2  s  . c o  m
    try (InputStream inputStream = new ByteArrayInputStream(writer.toByteArray());
            OutputStream outputStream = fileManager.getJavaFileForOutput(StandardLocation.CLASS_OUTPUT,
                    className, JavaFileObject.Kind.CLASS, null).openOutputStream()) {
        ByteStreams.copy(inputStream, outputStream);
    }
}

From source file:com.ibm.og.client.CustomHttpEntity.java

@Override
public void writeTo(final OutputStream outstream) throws IOException {
    final InputStream in = getContent();
    OutputStream out = outstream;

    if (this.writeThroughput > 0) {
        out = Streams.throttle(outstream, this.writeThroughput);
    }/*from   w ww  . j  a va2  s .  c o  m*/

    this.requestContentStart = System.nanoTime();
    ByteStreams.copy(in, out);
    this.requestContentFinish = System.nanoTime();
    in.close();
}

From source file:net.awairo.favdler.downloader.DownloadTask.java

@VisibleForTesting
static boolean download(FromSpec fromSpec, File outDir) {
    URLConnection connection = fromSpec.openConnection();
    connection.setConnectTimeout(5000);// ww  w  .jav  a2s .c  o m
    connection.setReadTimeout(5000);

    File snDir = new File(outDir, fromSpec.screenName());
    if (!snDir.exists()) {
        snDir.mkdir();
    }
    if (!snDir.isDirectory()) {
        log.warn("??????({})", snDir);
        throw new AppException("downloaddir_was_not_a_directory", snDir);
    }

    try (InputStream from = connection.getInputStream();
            OutputStream to = new FileOutputStream(
                    new File(snDir, fromSpec.statusId() + "_" + fromSpec.name()))) {
        ByteStreams.copy(from, to);
    } catch (IOException e) {
        log.warn("?????", e);
        return false;
    }

    return true;
}

From source file:org.fenixedu.academic.domain.phd.PhdProgramDocumentUploadBean.java

public void setFile(InputStream file) {
    this.file = file;

    if (file != null) {
        final ByteArrayOutputStream result = new ByteArrayOutputStream();
        try {/*from www.ja v a2  s . co  m*/
            ByteStreams.copy(this.file, result);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        this.fileContent = result.toByteArray();
    } else {
        this.fileContent = null;
    }
}

From source file:org.openqa.grid.web.servlet.ResourceServlet.java

protected void process(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String resource = request.getPathInfo().replace(request.getServletPath(), "");
    if (resource.startsWith("/"))
        resource = resource.replaceFirst("/", "");
    InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource);
    if (in == null) {
        throw new Error("Cannot find resource " + resource);
    }/*  w ww  . j a  v  a2 s . c o m*/

    try {
        ByteStreams.copy(in, response.getOutputStream());
    } finally {
        in.close();
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.DATE, 10);
        response.setDateHeader("Expires", c.getTime().getTime());
        response.setHeader("Cache-Control", "max-age=864000");
        response.flushBuffer();
    }

}

From source file:com.facebook.buck.jvm.java.testutil.ClassesImpl.java

@Override
public void createJar(Path jarPath) throws IOException {
    try (JarOutputStream jar = new JarOutputStream(Files.newOutputStream(jarPath))) {
        List<Path> files = Files.walk(root.getRoot().toPath()).filter(path -> path.toFile().isFile())
                .collect(Collectors.toList());

        for (Path file : files) {
            ZipEntry entry = new ZipEntry(
                    MorePaths.pathWithUnixSeparators(root.getRoot().toPath().relativize(file)));
            jar.putNextEntry(entry);//from ww  w. j  av a 2 s .  c o m
            ByteStreams.copy(Files.newInputStream(file), jar);
            jar.closeEntry();
        }
    }
}

From source file:uk.org.iay.mdq.server.CertificateController.java

/**
 * Returns the certificate being used for signing responses.
 * /*  ww  w  . j a v a 2  s  .  com*/
 * @param response {@link HttpServletResponse} in which to build the response
 * 
 * @throws Exception if anything goes wrong
 */
@RequestMapping("")
void getCertificate(@Nonnull final HttpServletResponse response) throws Exception {
    log.debug("queried for certificate");
    final InputStream in = certificateResource.getInputStream();
    final OutputStream out = response.getOutputStream();
    response.setContentType("text/plain");
    ByteStreams.copy(in, out);
}

From source file:org.stjs.testing.driver.StreamUtils.java

public static boolean copy(ClassLoader classLoader, String url, HttpExchange exchange)
        throws IOException, URISyntaxException {
    URI uri = new URI(url);

    if (uri.getPath() == null) {
        throw new IllegalArgumentException("Wrong path in uri:" + url);
    }/* w ww .  j  av  a  2  s .  c  om*/

    InputStream is = classLoader.getResourceAsStream(uri.getPath().substring(1));
    if (is == null) {
        exchange.sendResponseHeaders(HttpURLConnection.HTTP_NOT_FOUND, 0);
        return false;
    }
    try {
        exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK,
                getResourceSize(classLoader, uri.getPath().substring(1)));
        OutputStream out = exchange.getResponseBody();
        ByteStreams.copy(is, out);
        out.flush();
    } finally {
        is.close();
    }

    // TODO handle remote urls too
    return true;
}

From source file:com.bennavetta.aeneas.cli.mesos.RunMesosSlave.java

@Override
protected int execute() {
    String containerId = dockerClient.createContainerCmd(imageName).withEnv("MESOS_port=" + port).exec()
            .getId();/*from   w ww  .  j a va  2s  .c om*/

    StartContainerCmd start = dockerClient.startContainerCmd(containerId).withNetworkMode("host");

    if (!disableDocker) {
        start = start.withBinds(new Bind("/var/run/docker.sock", new Volume("/var/run/docker.sock")),
                new Bind("/sys", new Volume("/sys"))).withPrivileged(true);
    }
    start.exec();

    try (InputStream log = dockerClient.logContainerCmd(containerId).withFollowStream().withStdErr()
            .withStdOut().exec()) {
        ByteStreams.copy(log, System.out);
    } catch (IOException e) {
        if (!(e instanceof EOFException)) {
            System.err.println("Error reading container logs: " + e);
            return 1;
        }
    } finally {
        dockerClient.removeContainerCmd(containerId).withForce().exec();
    }

    return 0;
}