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.eclipse.packagedrone.repo.channel.web.channel.TransferController.java
protected ModelAndView performExport(final HttpServletResponse response, final String filename, final IOConsumer<OutputStream> exporter) { try {//from w w w.j a v a 2 s.c om final Path tmp = Files.createTempFile("export-", null); try { try (OutputStream tmpStream = new BufferedOutputStream(new FileOutputStream(tmp.toFile()))) { // first we spool this out to temp file, so that we don't block the channel for too long exporter.accept(tmpStream); } response.setContentLengthLong(tmp.toFile().length()); response.setContentType("application/zip"); response.setHeader("Content-Disposition", String.format("attachment; filename=%s", filename)); try (InputStream inStream = new BufferedInputStream(new FileInputStream(tmp.toFile()))) { ByteStreams.copy(inStream, response.getOutputStream()); } return null; } finally { Files.deleteIfExists(tmp); } } catch (final IOException e) { return CommonController.createError("Failed to export", null, e); } }
From source file:de.dentrassi.pm.storage.service.jpa.blob.DatabaseBlobStoreProcessor.java
protected void writeBlobAsStream(final EntityManager em, final InputStream stream, final Function<Long, String> idFunction) throws SQLException, IOException { final Connection c = em.unwrap(Connection.class); final long size; final Path tmp = Files.createTempFile("blob-", null); try {//from w ww. java 2s .com try (OutputStream os = new FileOutputStream(tmp.toFile())) { size = ByteStreams.copy(stream, os); } final String id = idFunction.apply(size); try (InputStream in = new FileInputStream(tmp.toFile())) { try (PreparedStatement ps = c.prepareStatement("update ARTIFACTS set data=? where id=?")) { ps.setBinaryStream(1, in, size); ps.setString(2, id); ps.executeUpdate(); } } } finally { Files.deleteIfExists(tmp); } }
From source file:com.linecorp.armeria.internal.grpc.GrpcMessageMarshaller.java
public ByteBuf serializeResponse(O message) throws IOException { switch (responseType) { case PROTOBUF: return serializeProto((Message) message); default://from w w w .j av a2s. c o m CompositeByteBuf out = alloc.compositeBuffer(); try (ByteBufOutputStream os = new ByteBufOutputStream(out)) { ByteStreams.copy(method.streamResponse(message), os); } return out; } }
From source file:com.google.api.client.http.AbstractInputStreamContent.java
/** * Writes the content provided by the given source input stream into the given destination output * stream./* ww w . j a v a2s.c o m*/ * * <p> * Sample use: * </p> * * <pre> static void downloadMedia(HttpResponse response, File file) throws IOException { FileOutputStream out = new FileOutputStream(file); try { AbstractInputStreamContent.copy(response.getContent(), out, true); } finally { out.close(); } } * </pre> * * @param inputStream source input stream * @param outputStream destination output stream * @param closeInputStream whether the input stream should be closed at the end of this method * @since 1.7 */ public static void copy(InputStream inputStream, OutputStream outputStream, boolean closeInputStream) throws IOException { try { ByteStreams.copy(inputStream, outputStream); } finally { if (closeInputStream) { inputStream.close(); } } }
From source file:org.eclipse.xtend.core.parser.JFlexLoader.java
protected void copyIntoFileAndCloseStream(InputStream content, final File file) throws FileNotFoundException, IOException { BufferedInputStream inputStream = new BufferedInputStream(content); try {//from w w w.java 2 s . c om BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file)); try { ByteStreams.copy(inputStream, outputStream); } finally { outputStream.close(); } } finally { inputStream.close(); } }
From source file:com.codeminders.socketio.sample.chat.ChatSocketServlet.java
@Override @SuppressWarnings("unchecked") public void init(ServletConfig config) throws ServletException { super.init(config); of("/chat").on(new ConnectionListener() { @Override/*w w w . j a v a2 s .c om*/ public void onConnect(final Socket socket) { try { socket.emit(WELCOME, "Welcome to Socket.IO Chat, " + socket.getId() + "!"); socket.join("room"); } catch (SocketIOException e) { e.printStackTrace(); socket.disconnect(true); } socket.on(new DisconnectListener() { @Override public void onDisconnect(Socket socket, DisconnectReason reason, String errorMessage) { of("/chat").emit(ANNOUNCEMENT, socket.getSession().getSessionId() + " disconnected"); } }); socket.on(CHAT_MESSAGE, new EventListener() { @Override public Object onEvent(String name, Object[] args, boolean ackRequested) { LOGGER.log(Level.FINE, "Received chat message: " + args[0]); try { socket.broadcast("room", CHAT_MESSAGE, socket.getId(), args[0]); } catch (SocketIOException e) { e.printStackTrace(); } return "OK"; //this object will be sent back to the client in ACK packet } }); socket.on(FORCE_DISCONNECT, new EventListener() { @Override public Object onEvent(String name, Object[] args, boolean ackRequested) { socket.disconnect(false); return null; } }); socket.on(CLIENT_BINARY, new EventListener() { @Override public Object onEvent(String name, Object[] args, boolean ackRequested) { Map map = (Map<Object, Object>) args[0]; InputStream is = (InputStream) map.get("buffer"); ByteArrayOutputStream os = new ByteArrayOutputStream(); try { ByteStreams.copy(is, os); byte[] array = os.toByteArray(); String s = "["; for (byte b : array) s += " " + b; s += " ]"; LOGGER.log(Level.FINE, "Binary received: " + s); } catch (IOException e) { e.printStackTrace(); } return "OK"; } }); socket.on(SERVER_BINARY, new EventListener() { @Override public Object onEvent(String name, Object[] args, boolean ackRequested) { try { socket.emit(SERVER_BINARY, new ByteArrayInputStream(new byte[] { 1, 2, 3, 4 }), new ACKListener() { @Override public void onACK(Object[] args) { System.out.println("ACK received: " + args[0]); } }); } catch (SocketIOException e) { socket.disconnect(true); } return null; } }); } }); // Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(new Runnable() // { // @Override // public void run() // { // try // { // of("/chat").in("room").emit("time", new Date().toString()); // } // catch (SocketIOException e) // { // e.printStackTrace(); // } // } // }, 0, 20, TimeUnit.SECONDS); // of("/news").on(new ConnectionListener() // { // @Override // public void onConnect(Socket socket) // { // socket.on(); // } // }); }
From source file:org.puder.trs80.io.FileManager.java
/** * Reads a file within the base path of this manager. * * @param filename the filename to read// ww w. jav a 2s . c o m * @return The contents of the file, if it could be read. */ public Optional<byte[]> readFile(String filename) { try { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); FileInputStream file = new FileInputStream(new File(baseDir, filename)); ByteStreams.copy(file, bytes); return Optional.of(bytes.toByteArray()); } catch (IOException e) { return Optional.absent(); } }
From source file:abs.backend.erlang.ErlApp.java
private void copyRuntime() throws IOException { InputStream is = null;/*ww w . j a va 2s . c o m*/ // TODO: this only works when the erlang compiler is invoked // from a jar file. See http://stackoverflow.com/a/2993908 on // how to handle the other case. URLConnection resource = getClass().getResource("").openConnection(); try { for (String f : RUNTIME_FILES) { if (f.endsWith("/*")) { String dirname = f.substring(0, f.length() - 2); String inname = RUNTIME_PATH + dirname; String outname = destDir + "/" + dirname; new File(outname).mkdirs(); if (resource instanceof JarURLConnection) { copyJarDirectory(((JarURLConnection) resource).getJarFile(), inname, outname); } else if (resource instanceof FileURLConnection) { /* stolz: This at least works for the unit tests from within Eclipse */ File file = new File("src"); assert file.exists(); FileUtils.copyDirectory(new File("src/" + RUNTIME_PATH), destDir); } else { throw new UnsupportedOperationException("File type: " + resource); } } else { is = ClassLoader.getSystemResourceAsStream(RUNTIME_PATH + f); if (is == null) throw new RuntimeException("Could not locate Runtime file:" + f); String outputFile = f.replace('/', File.separatorChar); File file = new File(destDir, outputFile); file.getParentFile().mkdirs(); ByteStreams.copy(is, Files.newOutputStreamSupplier(file)); } } } finally { if (is != null) is.close(); } for (String f : EXEC_FILES) { new File(destDir, f).setExecutable(true, false); } }
From source file:eu.esdihumboldt.hale.ui.common.components.URILink.java
private SelectionAdapter createDefaultSelectionAdapter(final URI uri) { return new SelectionAdapter() { private URI removeFragment(URI uri) throws URISyntaxException { String uristring = uri.toString(); uristring = uristring.substring(0, uristring.indexOf("#")); return new URI(uristring); }/*from w ww . j a v a2s .c om*/ // the URI has to be an existing file on the local drive or on a // server @Override public void widgetSelected(SelectionEvent e) { URI newuri = uri; try { // online resource if (uri.getScheme().equals("http") || uri.getScheme().equals("https")) { try { Desktop.getDesktop().browse(uri); } catch (IOException e1) { MessageDialog.openWarning(Display.getCurrent().getActiveShell(), "Opening Error", "No default application set!"); } return; } if (uri.toString().contains("#")) { newuri = removeFragment(uri); } // local resource or bundle resource if (DefaultInputSupplier.SCHEME_LOCAL.equals(newuri.getScheme()) || "bundleentry".equals(newuri.getScheme())) { // cannot be opened by system // so copy resource to temporary file String name = newuri.getPath(); int index = name.lastIndexOf('/'); if (index >= 0) { name = name.substring(index + 1); } if (!name.isEmpty()) { File tmpFile = Files.createTempFile("resource", name).toFile(); try (OutputStream out = new FileIOSupplier(tmpFile).getOutput(); InputStream in = new DefaultInputSupplier(newuri).getInput()) { ByteStreams.copy(in, out); } tmpFile.deleteOnExit(); newuri = tmpFile.toURI(); } } // try creating a file File file = new File(newuri); if (file.exists()) { try { Desktop.getDesktop().open(file); } catch (IOException e2) { try { Desktop.getDesktop().browse(newuri); } catch (IOException e1) { MessageDialog.openWarning(Display.getCurrent().getActiveShell(), "Opening Error", "No default application set!"); } } } else { try { Desktop.getDesktop().browse(newuri); } catch (IOException e1) { MessageDialog.openWarning(Display.getCurrent().getActiveShell(), "Opening Error", "No default application set!"); } } } catch (Exception e1) { // ignore } } }; }
From source file:com.proofpoint.http.server.ClassPathResourceHandler.java
@Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (baseRequest.isHandled()) { return;/* www. j av a2 s . c o m*/ } URL resource = getResourcePath(request); if (resource == null) { return; } // When a request hits this handler, it will serve something. Either data or an error. baseRequest.setHandled(true); String method = request.getMethod(); boolean skipContent = false; if (!HttpMethods.GET.equals(method)) { if (HttpMethods.HEAD.equals(method)) { skipContent = true; } else { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } } try (InputStream resourceStream = resource.openStream()) { Buffer contentTypeBytes = MIME_TYPES.getMimeByExtension(resource.toString()); if (contentTypeBytes != null) { // convert the content type bytes to a string using the specified character set String contentTypeHeaderValue = contentTypeBytes.toString(Charsets.US_ASCII); response.setContentType(contentTypeHeaderValue); } if (skipContent) { return; } // Send the content out. Lifted straight out of ResourceHandler.java OutputStream out; try { out = response.getOutputStream(); } catch (IllegalStateException e) { out = new WriterOutputStream(response.getWriter()); } if (out instanceof AbstractHttpConnection.Output) { ((AbstractHttpConnection.Output) out).sendContent(resourceStream); } else { ByteStreams.copy(resourceStream, out); } } }