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:com.microsoft.intellij.components.MSToolsProject.java

private File getTemplatesZip() throws IOException {
    // we cache the templates zip for the current version of the plugin
    File cachedZip = new File(System.getProperty("java.io.tmpdir"), String.format(CACHED_TEMPLATE_ZIP_NAME,
            MSToolsApplication.getCurrent().getSettings().getPluginVersion()));

    BufferedReader reader = null;
    InputStream inputStream = null;
    ZipOutputStream outputStream = null;

    try {//w w  w  .  j a  v  a2  s  .c o m
        if (!cachedZip.exists()) {
            // read list of files to copy to zip and create the zip file
            outputStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(cachedZip)));

            reader = new BufferedReader(new InputStreamReader(
                    MSToolsProject.class.getResourceAsStream(TEMPLATES_RESOURCE_PATH + "fileList.txt")));
            String line = null;
            while ((line = reader.readLine()) != null) {
                inputStream = MSToolsProject.class.getResourceAsStream(TEMPLATES_RESOURCE_PATH + line);

                ZipEntry entry = new ZipEntry(line);
                outputStream.putNextEntry(entry);

                ByteStreams.copy(inputStream, outputStream);
                inputStream.close();
                inputStream = null;
            }
            reader.close();
            reader = null;
            outputStream.close();
            outputStream = null;
        }
    } catch (IOException e) {
        // if creation of the zip file fails and leaves a partially
        // created zip file in the file system then we delete it so
        // that we attempt creating it again the next time around
        // which we wouldn't if we discover that the file exists
        // already
        if (cachedZip.exists()) {
            cachedZip.delete();
        }

        throw e;
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException ignored) {
        }
    }

    return cachedZip;
}

From source file:net.nyvaria.openanalytics.bungee.client.ClientConfig.java

private Configuration loadPlayerConfig() {
    Configuration config = null;//  ww  w.  j a va  2  s  . c  om
    playerConfigFile = new File(getPlayerConfigPath());

    if (!playerConfigFile.getParentFile().exists()) {
        playerConfigFile.getParentFile().mkdirs();
    }

    if (playerConfigFile.isFile()) {
        // Attempt to load the player configuration file
        try {
            OpenAnalyticsBungee.getInstance().log(Level.FINE, "Loading player configuration file - %1$s",
                    playerConfigFile.getName());
            config = ConfigurationProvider.getProvider(YamlConfiguration.class).load(playerConfigFile);
        } catch (IOException e) {
            OpenAnalyticsBungee.getInstance().log(Level.WARNING, "Cannot read player configuration file - %1$s",
                    playerConfigFile.getName());
            e.printStackTrace();
        }

    } else if (!playerConfigFile.exists()) {
        // Attempt to create a new player configuration file
        try {
            OpenAnalyticsBungee.getInstance().log(Level.INFO, "Player configuration file not found");
            OpenAnalyticsBungee.getInstance().log(Level.INFO, "Creating new player configuration file - %1$s",
                    playerConfigFile.getName());

            // Create a default player config file
            playerConfigFile.createNewFile();
            InputStream in = OpenAnalyticsBungee.getInstance()
                    .getResourceAsStream(ClientConfig.DEFAULT_PLAYER_CONFIG_RESOURCE);
            OutputStream out = new FileOutputStream(playerConfigFile);
            ByteStreams.copy(in, out);

            // And then load it
            config = ConfigurationProvider.getProvider(YamlConfiguration.class).load(playerConfigFile);

        } catch (IOException e) {
            OpenAnalyticsBungee.getInstance().log(Level.WARNING,
                    "Cannot create new player configuration file - %1$s", playerConfigFile.getName());
            e.printStackTrace();
        }
    }

    return config;
}

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

protected void process(HttpServletRequest request, HttpServletResponse response) throws IOException {
    RequestHandler req = null;//w  w  w.  ja  v  a2 s . com
    SeleniumBasedRequest r = null;
    try {
        r = SeleniumBasedRequest.createFromRequest(request, getRegistry());
        req = new RequestHandler(r, response, getRegistry());
        req.process();

    } catch (Throwable e) {
        if (r instanceof WebDriverRequest && !response.isCommitted()) {
            // https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol#error-handling
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.setStatus(500);

            JsonObject resp = new JsonObject();

            final ExternalSessionKey serverSession = req.getServerSession();
            resp.addProperty("sessionId", serverSession != null ? serverSession.getKey() : null);
            resp.addProperty("status", ErrorCodes.UNHANDLED_ERROR);
            JsonObject value = new JsonObject();
            value.addProperty("message", e.getMessage());
            value.addProperty("class", e.getClass().getCanonicalName());

            JsonArray stacktrace = new JsonArray();
            for (StackTraceElement ste : e.getStackTrace()) {
                JsonObject st = new JsonObject();
                st.addProperty("fileName", ste.getFileName());
                st.addProperty("className", ste.getClassName());
                st.addProperty("methodName", ste.getMethodName());
                st.addProperty("lineNumber", ste.getLineNumber());
                stacktrace.add(st);
            }
            value.add("stackTrace", stacktrace);
            resp.add("value", value);

            String json = new Gson().toJson(resp);

            byte[] bytes = json.getBytes("UTF-8");
            InputStream in = new ByteArrayInputStream(bytes);
            try {
                response.setHeader("Content-Length", Integer.toString(bytes.length));
                ByteStreams.copy(in, response.getOutputStream());
            } finally {
                in.close();
                response.flushBuffer();
            }
        } else {
            throw (new IOException(e));
        }
    }

}

From source file:svnserver.repository.git.GitDeltaConsumer.java

public boolean migrateFilter(@NotNull GitFilter filter) throws IOException, SVNException {
    if (newFilter == null || objectId == null) {
        throw new IllegalStateException("Original object ID defined, but original Filter is not defined");
    }/*from   ww w .j a v a  2  s. c  o m*/
    final GitObject<ObjectId> beforeId = objectId;
    if (!newFilter.equals(filter)) {
        final Repository repo = writer.getRepository().getRepository();

        try (final TemporaryOutputStream content = new TemporaryOutputStream();
                final TemporaryOutputStream.Holder holder = content.holder()) {
            try (InputStream inputStream = newFilter.inputStream(objectId);
                    OutputStream outputStream = filter.outputStream(content, user)) {
                ByteStreams.copy(inputStream, outputStream);
            }
            try (InputStream inputStream = content.toInputStream()) {
                objectId = new GitObject<>(repo,
                        writer.getInserter().insert(Constants.OBJ_BLOB, content.size(), inputStream));
                newFilter = filter;
            }
        }
    }
    return !beforeId.equals(objectId);
}

From source file:org.diqube.file.DiqubeFileWriter.java

/**
 * Write data of already serialized table shards to the file.
 * /*  w w w . ja v a2s  .  c  o m*/
 * @param serializedTableShards
 *          The serialized data of one or multiple table shards
 * @param totalNumberOfRows
 *          The total number of rows all the TableShards contain
 * @param numberOfTableShards
 *          The number of table shards that are provided
 * @throws IOException
 *           If anything cannot be written.
 */
public void writeSerializedTableShards(InputStream serializedTableShards, long totalNumberOfRows,
        int numberOfTableShards) throws IOException {
    ByteStreams.copy(serializedTableShards, outputStream);
    outputStream.flush();
    this.numberOfTableShards += numberOfTableShards;
    this.numberOfRows += totalNumberOfRows;
}

From source file:com.cloudera.kitten.util.LocalDataHelper.java

private void copyToHdfs(String key, String localDataName) throws IOException {
    if (!localToHdfs.containsKey(localDataName)) {
        FileSystem fs = FileSystem.get(conf);
        Path src = new Path(localDataName);
        Path dst = getPath(fs, src.getName());
        InputStream data = getFileOrResource(localDataName);
        FSDataOutputStream os = fs.create(dst, true);
        ByteStreams.copy(data, os);
        os.close();// w ww.j  a v  a 2  s. com
        URI uri = dst.toUri();
        localToHdfs.put(key, uri);
    }
}

From source file:org.eclipse.packagedrone.repo.channel.util.DownloadHelper.java

public static void streamArtifact(final HttpServletResponse response, final ArtifactInformation artifact,
        final InputStream stream, final Optional<String> mimetype, final boolean download,
        final Function<ArtifactInformation, String> nameFunc) throws IOException {
    final String mt = mimetype.orElseGet(() -> evalMimeType(artifact));

    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType(mt);/* w  w w.j a  v  a  2 s.  c o m*/
    response.setDateHeader("Last-Modified", artifact.getCreationInstant().toEpochMilli());
    response.setContentLengthLong(artifact.getSize());

    if (download) {
        if (nameFunc != null) {
            response.setHeader("Content-Disposition",
                    String.format("attachment; filename=%s", nameFunc.apply(artifact)));
        } else {
            response.setHeader("Content-Disposition",
                    String.format("attachment; filename=%s", artifact.getName()));
        }
    }

    final long size = ByteStreams.copy(stream, response.getOutputStream());
    logger.debug("Copyied {} bytes", size);
}

From source file:co.cask.tigon.sql.internal.StreamBinaryGenerator.java

private void copyResourceFileToDir(String fileName, File libZip) throws IOException {
    InputStream ifres = getClass().getResourceAsStream("/" + fileName);
    ByteStreams.copy(ifres, Files.newOutputStreamSupplier(libZip));
    ifres.close();//from  ww  w .j  a  v a2 s . c o m
}

From source file:org.ambraproject.rhino.util.Archive.java

public final void write(OutputStream stream) throws IOException {
    try (ZipOutputStream zipOutputStream = new ZipOutputStream(stream)) {
        for (Map.Entry<String, ?> entry : files.entrySet()) {
            zipOutputStream.putNextEntry(new ZipEntry(entry.getKey()));
            try (InputStream entryFile = openFileFrom(entry.getValue())) {
                ByteStreams.copy(entryFile, zipOutputStream);
            }//from  w w w  .jav a  2s.  co m
        }
    } finally {
        stream.close();
    }
}

From source file:org.openqa.selenium.server.browserlaunchers.ResourceExtractor.java

private static void copyStream(InputStream in, OutputStream out) throws IOException {
    try {//from   w  w  w  .j  av a  2s  .c o m
        ByteStreams.copy(in, out);
    } finally {
        out.close();
        in.close();
    }
}