List of usage examples for com.google.common.io ByteStreams copy
public static long copy(ReadableByteChannel from, WritableByteChannel to) throws IOException
From source file:co.cask.cdap.internal.test.PluginJarHelper.java
public static Location createPluginJar(LocationFactory locationFactory, Manifest manifest, Class<?> clz, Class<?>... classes) 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 {//w w w . j ava 2 s . c o m bundler.createBundle(jarLocation, clz, classes); } 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"); // Create the program jar for deployment. It removes the "classes/" prefix as that's the convention taken // by the ApplicationBundler inside Twill. 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; } jarOutput.putNextEntry(jarEntry); if (!isDir) { ByteStreams.copy(jarInput, jarOutput); } } jarEntry = jarInput.getNextJarEntry(); } } return deployJar; }
From source file:org.gbif.registry.ws.client.DatasetWsClient.java
@Override public Metadata insertMetadata(UUID datasetKey, InputStream document) { // allow post through varnish (no chunked encoding needed) Metadata metadata;/*from w w w .jav a 2 s . c om*/ try { ByteArrayOutputStream os = new ByteArrayOutputStream(); ByteStreams.copy(document, os); metadata = getResource(datasetKey.toString(), "document").type(MediaType.APPLICATION_XML) .post(Metadata.class, os.toByteArray()); } catch (IOException e) { throw new IllegalStateException(e); } return metadata; }
From source file:com.android.sdklib.repositoryv2.LegacyDownloader.java
@Nullable @Override// w ww . j a v a 2 s .c o m public File downloadFully(@NonNull URL url, @Nullable SettingsController settings, @NonNull ProgressIndicator indicator) throws IOException { File result = File.createTempFile("LegacyDownloader", Long.toString(System.currentTimeMillis())); OutputStream out = mFileOp.newFileOutputStream(result); try { Pair<InputStream, Integer> downloadedResult = mDownloadCache.openDirectUrl(url.toString(), new LegacyTaskMonitor(indicator)); if (downloadedResult.getSecond() == 200) { ByteStreams.copy(downloadedResult.getFirst(), out); out.close(); return result; } } catch (CanceledByUserException e) { indicator.logInfo("The download was cancelled."); } return null; }
From source file:org.anarres.qemu.image.QEmuImage.java
/** * Creates this image./*from w ww . ja v a 2 s.c om*/ * <p> * The size of the new image is derived from the existing backing file. * <p> * backingFile is referenced by a relative path. If you want it referenced * absolutely, canonicalize the argument with {@link File#getAbsoluteFile()} * before calling this method. * * @param format The image format for the new image. * @param backingFile The backing file for the new image. */ public void create(@Nonnull QEmuImageFormat format, @Nonnull File backingFile) throws IOException { ProcessBuilder builder = new ProcessBuilder("qemu-img", "create", "-f", format.name(), "-b", backingFile.getPath(), file.getAbsolutePath()); Process process = builder.start(); ByteStreams.copy(process.getInputStream(), System.err); }
From source file:com.eclipsesource.connect.api.util.ZipUtil.java
private static void copyInputStream(InputStream in, OutputStream out) throws IOException { try {/*from w w w. j a v a 2 s . c o m*/ ByteStreams.copy(in, out); } finally { in.close(); out.close(); } }
From source file:org.apache.people.mreutegg.mhmp.zh.TileRepository.java
static void unzip(File zip) throws IOException { try (ZipFile file = new ZipFile(zip)) { file.stream().forEach(o -> {/* w ww. ja va 2s . co m*/ File tmp = new File(zip.getParent(), o.getName() + ".tmp"); try { try (InputStream in = file.getInputStream(o)) { try (OutputStream out = new FileOutputStream(tmp)) { ByteStreams.copy(in, out); } } if (!tmp.renameTo(new File(zip.getParent(), o.getName()))) { throw new IOException("Cannot rename file" + tmp.getAbsolutePath()); } } catch (IOException e) { throw new UncheckedIOException(e); } }); } }
From source file:com.planet57.gshell.commands.shell.WgetAction.java
@Override public Object execute(@Nonnull final CommandContext context) throws Exception { IO io = context.getIo();// ww w . j a va 2 s. c o m io.format("Downloading: %s%n", source); if (verbose) { io.format("Connecting to: %s:%s%n", source.getHost(), source.getPort() != -1 ? source.getPort() : source.getDefaultPort()); } URLConnection conn = source.openConnection(); if (verbose) { io.format("Length: %s [%s]%n", conn.getContentLength(), conn.getContentType()); } InputStream in = conn.getInputStream(); OutputStream out; if (outputFile != null) { if (verbose) { io.format("Saving to file: %s%n", outputFile); } out = new BufferedOutputStream(new FileOutputStream(outputFile)); } else { out = io.streams.out; } ByteStreams.copy(in, out); // if we write a file, close it then return the file if (outputFile != null) { Closeables.close(out); io.format("Saved %s [%s]%n", outputFile, outputFile.length()); return outputFile; } // else flush the stream and say we did good Flushables.flushQuietly(out); return null; }
From source file:co.cask.cdap.common.http.HttpRequests.java
/** * Executes an HTTP request to the url provided. * * @param request HTTP request to execute * @param requestConfig configuration for the HTTP request to execute * @return HTTP response/*from w ww . java 2 s . c o m*/ */ public static HttpResponse execute(HttpRequest request, HttpRequestConfig requestConfig) throws IOException { String requestMethod = request.getMethod().name(); URL url = request.getURL(); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(requestMethod); conn.setReadTimeout(requestConfig.getReadTimeout()); conn.setConnectTimeout(requestConfig.getConnectTimeout()); Multimap<String, String> headers = request.getHeaders(); if (headers != null) { for (Map.Entry<String, String> header : headers.entries()) { conn.setRequestProperty(header.getKey(), header.getValue()); } } InputSupplier<? extends InputStream> bodySrc = request.getBody(); if (bodySrc != null) { conn.setDoOutput(true); } if (conn instanceof HttpsURLConnection && !requestConfig.isVerifySSLCert()) { // Certificate checks are disabled for HTTPS connection. LOG.debug("Disabling SSL certificate check for {}", request.getURL()); try { disableCertCheck((HttpsURLConnection) conn); } catch (Exception e) { LOG.error("Got exception while disabling SSL certificate check for {}", request.getURL()); } } conn.connect(); try { if (bodySrc != null) { OutputStream os = conn.getOutputStream(); try { ByteStreams.copy(bodySrc, os); } finally { os.close(); } } try { if (isSuccessful(conn.getResponseCode())) { return new HttpResponse(conn.getResponseCode(), conn.getResponseMessage(), ByteStreams.toByteArray(conn.getInputStream())); } } catch (FileNotFoundException e) { // Server returns 404. Hence handle as error flow below. Intentional having empty catch block. } // Non 2xx response InputStream es = conn.getErrorStream(); byte[] content = (es == null) ? new byte[0] : ByteStreams.toByteArray(es); return new HttpResponse(conn.getResponseCode(), conn.getResponseMessage(), content); } finally { conn.disconnect(); } }
From source file:org.activityinfo.server.report.output.TempStorageServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String keyName = parseBlobKey(req.getRequestURI()); InputSupplier<? extends InputStream> inputSupplier; try {/*from w w w . ja v a 2s. com*/ inputSupplier = blobService.get("/temp/" + keyName); } catch (BlobNotFoundException e) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } resp.setHeader("Content-Type", mimeTypeFromUri(req.getRequestURI().toLowerCase())); resp.setHeader("Content-Disposition", "attachment"); ByteStreams.copy(inputSupplier, resp.getOutputStream()); }
From source file:com.google.gerrit.httpd.raw.RobotsServlet.java
@Override protected void doGet(final HttpServletRequest req, final HttpServletResponse rsp) throws IOException { rsp.setContentType("text/plain"); try (InputStream in = openRobotsFile(); OutputStream out = rsp.getOutputStream()) { ByteStreams.copy(in, out); }// w w w . ja v a 2 s . c o m }