List of usage examples for java.nio.channels Channels newChannel
public static WritableByteChannel newChannel(OutputStream out)
From source file:org.restcomm.connect.http.filters.FileCacheServlet.java
/** * Stream the given input to the given output via NIO {@link Channels} and a * directly allocated NIO {@link ByteBuffer}. Both the input and output * streams will implicitly be closed after streaming, regardless of whether * an exception is been thrown or not./* w w w . j av a 2 s . c o m*/ * * @param input The input stream. * @param output The output stream. * @param bufferSize * @return The length of the written bytes. * @throws IOException When an I/O error occurs. */ public static long stream(InputStream input, OutputStream output, int bufferSize) throws IOException { try (ReadableByteChannel inputChannel = Channels.newChannel(input); WritableByteChannel outputChannel = Channels.newChannel(output)) { ByteBuffer buffer = ByteBuffer.allocateDirect(bufferSize); long size = 0; while (inputChannel.read(buffer) != -1) { buffer.flip(); size += outputChannel.write(buffer); buffer.clear(); } return size; } }
From source file:org.activiti.engine.test.api.repository.diagram.ProcessDiagramRetrievalTest.java
private static boolean isEqual(InputStream stream1, InputStream stream2) throws IOException { ReadableByteChannel channel1 = Channels.newChannel(stream1); ReadableByteChannel channel2 = Channels.newChannel(stream2); ByteBuffer buffer1 = ByteBuffer.allocateDirect(1024); ByteBuffer buffer2 = ByteBuffer.allocateDirect(1024); try {/*w w w . j a va 2 s . c o m*/ while (true) { int bytesReadFromStream1 = channel1.read(buffer1); int bytesReadFromStream2 = channel2.read(buffer2); if (bytesReadFromStream1 == -1 || bytesReadFromStream2 == -1) return bytesReadFromStream1 == bytesReadFromStream2; buffer1.flip(); buffer2.flip(); for (int i = 0; i < Math.min(bytesReadFromStream1, bytesReadFromStream2); i++) if (buffer1.get() != buffer2.get()) return false; buffer1.compact(); buffer2.compact(); } } finally { if (stream1 != null) stream1.close(); if (stream2 != null) stream2.close(); } }
From source file:org.apache.flex.utilities.converter.retrievers.download.DownloadRetriever.java
protected void performSafeDownload(URI sourceUri, File targetFile) throws IOException { HttpGet httpget = new HttpGet(sourceUri); HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(httpget); String reasonPhrase = response.getStatusLine().getReasonPhrase(); int statusCode = response.getStatusLine().getStatusCode(); System.out.println(String.format("statusCode: %d", statusCode)); System.out.println(String.format("reasonPhrase: %s", reasonPhrase)); HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); final ReadableByteChannel rbc = Channels.newChannel(content); final FileOutputStream fos = new FileOutputStream(targetFile); //////////////////////////////////////////////////////////////////////////////// // Do the downloading. //////////////////////////////////////////////////////////////////////////////// final long expectedSize = entity.getContentLength(); System.out.println("==========================================================="); System.out.println("Downloading " + sourceUri.toString()); if (expectedSize < 0) { try {//from w ww.java 2s . c o m System.out.println("Unknown size."); IOUtils.copy(content, fos); } finally { // close http network connection content.close(); } } else { long transferedSize = 0L; if (expectedSize > 1014 * 1024) { System.out.println("Expected size: " + (expectedSize / 1024 / 1024) + "MB"); } else { System.out.println("Expected size: " + (expectedSize / 1024) + "KB"); } final ProgressBar progressBar = new ProgressBar(expectedSize); while (transferedSize < expectedSize) { transferedSize += fos.getChannel().transferFrom(rbc, transferedSize, 1 << 20); progressBar.updateProgress(transferedSize); } fos.close(); System.out.println(); } System.out.println("Finished downloading."); System.out.println("==========================================================="); }
From source file:org.alfresco.repo.content.http.HttpAlfrescoContentReader.java
private ReadableByteChannel getDirectReadableChannelImpl() throws ContentIOException { String contentUrl = getContentUrl(); try {// ww w .ja va 2 s . co m if (!exists()) { throw new IOException("Content doesn't exist"); } String ticket = transactionService.getRetryingTransactionHelper().doInTransaction(ticketCallback, false, true); String url = HttpAlfrescoContentReader.generateURL(baseHttpUrl, contentUrl, ticket, false); GetMethod method = new GetMethod(url); int statusCode = httpClient.executeMethod(method); if (statusCode == HttpServletResponse.SC_OK) { // Get the stream from the request InputStream contentStream = method.getResponseBodyAsStream(); // Attach a listener to the stream to ensure that the HTTP request is cleaned up this.addListener(new StreamCloseListener(method)); // Done if (logger.isDebugEnabled()) { logger.debug("\n" + "HttpReader retrieve intput stream: \n" + " Reader: " + this + "\n" + " Server: " + baseHttpUrl); } return Channels.newChannel(contentStream); } else { // The content exists, but we failed to get it throw new IOException("Failed to get content remote content that supposedly exists."); } } catch (Throwable e) { throw new ContentIOException("Failed to open stream: \n" + " Reader: " + this + "\n" + " Remote server: " + baseHttpUrl, e); } }
From source file:io.github.microcks.service.ServiceService.java
/** Download a remote HTTP URL into a temporary local file. */ private String handleRemoteFileDownload(String remoteUrl) throws IOException { // Build remote Url and local file. URL website = new URL(remoteUrl); String localFile = System.getProperty("java.io.tmpdir") + "/microcks-" + System.currentTimeMillis() + ".project"; // Set authenticator instance. Authenticator.setDefault(new UsernamePasswordAuthenticator(username, password)); ReadableByteChannel rbc = null; FileOutputStream fos = null;/*w w w . j a v a2 s. c om*/ try { rbc = Channels.newChannel(website.openStream()); // Transfer file to local. fos = new FileOutputStream(localFile); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); } finally { if (fos != null) fos.close(); if (rbc != null) rbc.close(); } return localFile; }
From source file:it.doqui.index.ecmengine.business.personalization.encryption.content.DecryptingContentReaderDecorator.java
public ReadableByteChannel getReadableChannel() throws ContentIOException { logger.debug("[DecryptingContentReaderDecorator::getReadableChannel] BEGIN"); try {/*from w w w . j a va 2 s .co m*/ return Channels.newChannel(getContentInputStream()); } finally { logger.debug("[DecryptingContentReaderDecorator::getReadableChannel] END"); } }
From source file:com.bittorrent.mpetazzoni.tracker.TrackerService.java
/** * Write a {@link HTTPTrackerErrorMessage} to the response with the given * HTTP status code.//from www . j a va 2 s. c o m * * @param response The HTTP response object. * @param body The response output stream to write to. * @param status The HTTP status code to return. * @param error The error reported by the tracker. */ private void serveError(Response response, OutputStream body, Status status, HTTPTrackerErrorMessage error) throws IOException { response.setCode(status.getCode()); response.setText(status.getDescription()); logger.warn("Could not process announce request ({}) !", error.getReason()); WritableByteChannel channel = Channels.newChannel(body); channel.write(error.getData()); }
From source file:org.geowebcache.util.ResponseUtils.java
private static void loadBlankTile(Resource blankTile, URL source) throws IOException { InputStream inputStream = source.openStream(); ReadableByteChannel ch = Channels.newChannel(inputStream); try {/*from ww w. j ava 2s. c o m*/ blankTile.transferFrom(ch); } catch (IOException e) { e.printStackTrace(); } finally { ch.close(); } }
From source file:org.commoncrawl.hadoop.io.S3GetMetdataJob.java
@org.junit.Test public void testMapper() throws Exception { final ArcFileReader reader = new ArcFileReader(); Thread thread = new Thread(new Runnable() { public void run() { try { while (reader.hasMoreItems()) { ArcFileItem item = new ArcFileItem(); reader.getNextItem(item); map(new Text(item.getUri()), item, null, null); }/*from w w w .j a va 2 s .c o m*/ LOG.info("NO MORE ITEMS... BYE"); } catch (IOException e) { LOG.error(StringUtils.stringifyException(e)); } } }); // run the thread ... thread.start(); File file = new File("/Users/rana/Downloads/1213886083018_0.arc.gz"); ReadableByteChannel channel = Channels.newChannel(new FileInputStream(file)); try { int totalBytesRead = 0; for (;;) { ByteBuffer buffer = ByteBuffer.allocate(ArcFileReader.DEFAULT_BLOCK_SIZE); int bytesRead = channel.read(buffer); LOG.info("Read " + bytesRead + " From File"); if (bytesRead == -1) { reader.finished(); break; } else { buffer.flip(); totalBytesRead += buffer.remaining(); reader.available(buffer); } } } finally { channel.close(); } // now wait for thread to die ... LOG.info("Done Reading File.... Waiting for ArcFileThread to DIE"); thread.join(); LOG.info("Done Reading File.... ArcFileThread to DIED"); }