List of usage examples for com.google.common.io ByteStreams copy
public static long copy(ReadableByteChannel from, WritableByteChannel to) throws IOException
From source file:org.apache.s4.base.util.S4RLoaderFactory.java
/** * Explodes the s4r archive in a subdirectory of a user specified directory through "s4.tmp.dir" parameter, and * prepares a classloader that will load classes and resources from, first, the application classes, then the * dependencies./*w w w . j a v a2s .c o m*/ * * Uses a temporary directory if s4.tmp.dir is not provided. * * Inspired from Hadoop's application classloading implementation (RunJar class). * * @param s4rPath * path to s4r * @return classloader that loads resources from the s4r in a predefined order */ public S4RLoader createS4RLoader(String s4rPath) { File s4rDir = null; if (tmpDir == null) { s4rDir = Files.createTempDir(); s4rDir.deleteOnExit(); logger.warn( "s4.tmp.dir not specified, using temporary directory [{}] for unpacking S4R. You may want to specify a parent non-temporary directory.", s4rDir.getAbsolutePath()); } else { s4rDir = new File(tmpDir, s4rPath.substring(s4rPath.lastIndexOf(File.separator)) + "-" + System.currentTimeMillis()); if (!s4rDir.mkdir()) { throw new RuntimeException("Cannot create directory for unzipping S4R file in [" + s4rDir.getAbsolutePath() + "]. Aborting deployment."); } } logger.info("Unzipping S4R archive in [{}]", s4rDir.getAbsolutePath()); JarFile jar = null; try { jar = new JarFile(s4rPath); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (!entry.isDirectory()) { File to = new File(s4rDir, entry.getName()); Files.createParentDirs(to); InputStream is = jar.getInputStream(entry); OutputStream os = new FileOutputStream(to); try { ByteStreams.copy(is, os); } finally { Closeables.closeQuietly(is); Closeables.closeQuietly(os); } } } List<URL> classpath = new ArrayList<URL>(); addDirLibsToClassPath(classpath, s4rDir, "/app"); addDirLibsToClassPath(classpath, s4rDir, "/lib"); S4RLoader s4rLoader = new S4RLoader(classpath.toArray(new URL[] {})); return s4rLoader; } catch (IOException e) { logger.error("Cannot process S4R [{}]: {}", s4rPath, e.getClass().getName() + "/" + e.getMessage()); throw new RuntimeException("Cannot create S4R classloader", e); } }
From source file:com.cloudbees.demo.beesshop.service.MongoDbFileStorageService.java
public void serveFile(String photoId, String id, HttpServletResponse response) throws IOException { GridFSDBFile file = gridFS.findOne(new ObjectId(id)); response.setContentType(file.getContentType()); response.setHeader("cache-control", "public, max-age=" + TimeUnit.SECONDS.convert(365, TimeUnit.DAYS)); try (InputStream in = file.getInputStream()) { ByteStreams.copy(in, response.getOutputStream()); }/*from w ww . j ava 2s .co m*/ }
From source file:org.nickelproject.util.IoUtil.java
/** * Uncompress the given byte array using the delfate algorithm and return * the uncompressed byte array.// ww w . ja v a 2 s. c o m */ public static byte[] inflate(final byte[] pInput) throws IOException { final ByteArrayInputStream vByteArrayStream = new ByteArrayInputStream(pInput); final ByteArrayOutputStream vByteArrayOutputStream = new ByteArrayOutputStream(pInput.length); final InputStream vInflaterStream = new InflaterInputStream(vByteArrayStream); ByteStreams.copy(vInflaterStream, vByteArrayOutputStream); vInflaterStream.close(); final byte[] vUnCompressedBytes = vByteArrayOutputStream.toByteArray(); return vUnCompressedBytes; }
From source file:io.druid.segment.data.CompressedFloatsSupplierSerializer.java
public void closeAndConsolidate(OutputSupplier<? extends OutputStream> consolidatedOut) throws IOException { endBuffer.limit(endBuffer.position()); endBuffer.rewind();/*from ww w .j ava2s . c o m*/ flattener.write(StupidResourceHolder.create(endBuffer)); endBuffer = null; flattener.close(); try (OutputStream out = consolidatedOut.getOutput()) { out.write(CompressedFloatsIndexedSupplier.version); out.write(Ints.toByteArray(numInserted)); out.write(Ints.toByteArray(sizePer)); out.write(new byte[] { compression.getId() }); ByteStreams.copy(flattener.combineStreams(), out); } }
From source file:mn.le.farcek.jbw.code.servlet.JBWAssetHandlerServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try (ServletOutputStream out = response.getOutputStream()) { String resourcePath = request.getPathInfo(); if (resourcePath == null) throw new ServletException("path is null"); String[] split = resourcePath.split("/", 3); if (split.length == 3) { String bundleName = split[1]; String assetPath = split[2]; String ext = FFileUtils.getExtension(assetPath); if (ext != null) if (ext.equals("css")) response.setContentType("text/css"); else if (ext.equals("js")) response.setContentType("text/javascript"); else if (ext.equals("png")) response.setContentType("image/png"); else if (ext.equals("jpg")) response.setContentType("image/jpeg"); else if (ext.equals("gif")) response.setContentType("image/gif"); InputStream rs;/*from www. j a va 2 s . co m*/ try { rs = manager.getBundleManager(bundleName).getAssetReaderStream(assetPath); if (rs != null) { response.addHeader("Cache-Control", "public, max-age=90000"); response.setDateHeader("Expires", System.currentTimeMillis() + 5 * 24 * 60 * 60 * 1000); ByteStreams.copy(rs, out); } else throw new ServletException("not found asset. request path `" + assetPath + "` in the `" + bundleName + "` bundle."); } catch (MissingBundle ex) { throw new ServletException("not found asset. the `" + bundleName + "` bundle is not found"); } } else throw new ServletException( "not found asset. requared formar: `/{bundle name}/{asset path}`; called path:" + resourcePath); } }
From source file:com.facebook.buck.step.fs.XzStep.java
@Override public int execute(ExecutionContext context) { try (InputStream in = new BufferedInputStream(new FileInputStream(sourceFile.toFile())); OutputStream out = new BufferedOutputStream(new FileOutputStream(getDestinationFile().toFile())); XZOutputStream xzOut = new XZOutputStream(out, new LZMA2Options(compressionLevel), check)) { ByteStreams.copy(in, xzOut); xzOut.finish();//from w w w. ja va2 s . c o m } catch (IOException e) { e.printStackTrace(context.getStdErr()); return 1; } if (!keep && !context.getProjectFilesystem().deleteFileAtPath(sourceFile)) { return 1; } return 0; }
From source file:de.dentrassi.pm.aspect.common.eclipse.MavenSourceBundleVirtualizer.java
private void createSourceBundle(final Path tmp, final Context context, final BundleInformation bi) throws Exception { try (ZipInputStream zis = new ZipInputStream( new BufferedInputStream(new FileInputStream(context.getFile().toFile()))); ZipOutputStream zos = new ZipOutputStream( new BufferedOutputStream(new FileOutputStream(tmp.toFile())))) { ZipEntry entry;/* ww w. j a v a 2 s.co m*/ while ((entry = zis.getNextEntry()) != null) { if (entry.getName().equals("META-INF/MANIFEST.MF")) { continue; } zos.putNextEntry(entry); ByteStreams.copy(zis, zos); } entry = new ZipEntry("META-INF/MANIFEST.MF"); zos.putNextEntry(entry); final Manifest mf = new Manifest(); fillManifest(mf, bi); mf.write(zos); if (bi.getLocalization() != null && !bi.getLocalization().isEmpty()) { for (final Map.Entry<String, Properties> le : bi.getLocalization().entrySet()) { final String locale = le.getKey(); final String suffix = locale != null && !locale.isEmpty() ? "_" + locale : ""; entry = new ZipEntry(bi.getLocalization() + suffix); zos.putNextEntry(entry); le.getValue().store(zos, null); } } } }
From source file:com.android.builder.testing.MockableJarGenerator.java
public void createMockableJar(File input, File output) throws IOException { Preconditions.checkState(output.createNewFile(), "Output file [%s] already exists.", output.getAbsolutePath());/*from w w w . j a v a2 s. c o m*/ JarFile androidJar = null; JarOutputStream outputStream = null; try { androidJar = new JarFile(input); outputStream = new JarOutputStream(new FileOutputStream(output)); for (JarEntry entry : Collections.list(androidJar.entries())) { InputStream inputStream = androidJar.getInputStream(entry); if (entry.getName().endsWith(".class")) { if (!skipClass(entry.getName().replace("/", "."))) { rewriteClass(entry, inputStream, outputStream); } } else { outputStream.putNextEntry(entry); ByteStreams.copy(inputStream, outputStream); } inputStream.close(); } } finally { if (androidJar != null) { androidJar.close(); } if (outputStream != null) { outputStream.close(); } } }
From source file:org.apache.brooklyn.core.mgmt.persist.jclouds.JcloudsStoreObjectAccessor.java
@Override public byte[] getBytes() { try {//from www. j ava2s . c o m Blob blob = blobStore.getBlob(containerName, blobName); if (blob == null) return null; ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream in = blob.getPayload().openStream(); try { ByteStreams.copy(in, out); return out.toByteArray(); } finally { out.close(); } } catch (IOException e) { Exceptions.propagateIfFatal(e); throw new IllegalStateException("Error reading blobstore " + containerName + " " + blobName + ": " + e, e); } }
From source file:eu.esdihumboldt.hale.io.shp.ShapefileAdvisor.java
@Override public void copyResource(LocatableInputSupplier<? extends InputStream> resource, final Path target, IContentType resourceType, boolean includeRemote, IOReporter reporter) throws IOException { URI orgUri = resource.getLocation(); if (orgUri == null) { throw new IOException("URI for original resource must be known"); }//from w ww .j a va 2 s. c o m // copy if files can be resolved as a Path Path orgPath = null; try { orgPath = Paths.get(orgUri); } catch (Exception e) { // ignore } if (orgPath != null) { // determine the filename w/o extension String filemain = orgPath.getFileName().toString(); int extPos = filemain.lastIndexOf('.'); if (extPos > 0) { filemain = filemain.substring(0, extPos); } // matcher for associated files final PathMatcher auxfiles = orgPath.getFileSystem().getPathMatcher("glob:" + filemain + ".???"); // find all associated files Path orgDir = orgPath.getParent(); try (DirectoryStream<Path> files = Files.newDirectoryStream(orgDir, new DirectoryStream.Filter<Path>() { @Override public boolean accept(Path entry) throws IOException { return auxfiles.matches(entry.getFileName()); } })) { // copy the files for (Path orgFile : files) { Path targetFile = target.resolveSibling(orgFile.getFileName()); Files.copy(orgFile, targetFile); } } } else { // copy if not accessible through file system // copy the main file try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(target)); InputStream in = new DefaultInputSupplier(orgUri).getInput()) { ByteStreams.copy(in, out); } // determine base URI w/o dot and extension String base = orgUri.toASCIIString(); int extPos = base.lastIndexOf('.'); if (extPos > 0) { base = base.substring(0, extPos); } // determine file base name w/o dot and extension String filemain = target.getFileName().toString(); extPos = filemain.lastIndexOf('.'); if (extPos > 0) { filemain = filemain.substring(0, extPos); } for (ShpFileType type : ShpFileType.values()) { if (!type.equals(ShpFileType.SHP)) { try { URI source = URI.create(base + type.extensionWithPeriod); if (HaleIO.testStream(source, true)) { Path targetFile = target.resolveSibling(filemain + type.extensionWithPeriod); // copy the auxiliary file try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(targetFile)); InputStream in = new DefaultInputSupplier(source).getInput()) { ByteStreams.copy(in, out); } } } catch (Exception e) { log.debug("Failed to copy auxiliary file for Shapefile", e); } } } } }