List of usage examples for java.nio.channels ReadableByteChannel close
public void close() throws IOException;
From source file:org.alfresco.repo.transfer.HttpClientTransmitterImpl.java
/** * *///ww w . java 2s. c o m public void getTransferReport(Transfer transfer, OutputStream result) { TransferTarget target = transfer.getTransferTarget(); PostMethod getReportRequest = getPostMethod(); try { HostConfiguration hostConfig = getHostConfig(target); HttpState httpState = getHttpState(target); try { getReportRequest.setPath(target.getEndpointPath() + "/report"); //Put the transferId on the query string getReportRequest.setQueryString( new NameValuePair[] { new NameValuePair("transferId", transfer.getTransferId()) }); int responseStatus = httpClient.executeMethod(hostConfig, getReportRequest, httpState); checkResponseStatus("getReport", responseStatus, getReportRequest); InputStream is = getReportRequest.getResponseBodyAsStream(); // Now copy the response input stream to result. final ReadableByteChannel inputChannel = Channels.newChannel(is); final WritableByteChannel outputChannel = Channels.newChannel(result); try { // copy the channels channelCopy(inputChannel, outputChannel); } finally { // closing the channels inputChannel.close(); outputChannel.close(); } return; } catch (RuntimeException e) { throw e; } catch (Exception e) { String error = "Failed to execute HTTP request to target"; log.debug(error, e); throw new TransferException(MSG_HTTP_REQUEST_FAILED, new Object[] { "getTransferReport", target.toString(), e.toString() }, e); } } finally { getReportRequest.releaseConnection(); } }
From source file:org.alfresco.cacheserver.dropwizard.resources.CacheServerResource.java
@Path("/contentByNodeId/{nodeId}/{nodeVersion}") @GET/* ww w.ja va 2 s. co m*/ public Response contentByNodeId(@PathParam("nodeId") String nodeId, @PathParam("nodeVersion") String nodeVersion, @Auth UserDetails user, @Context final HttpServletResponse httpResponse) { try { if (LOGGER.isDebugEnabled()) LOGGER.debug("nodeId = " + nodeId); if (nodeId == null || nodeVersion == null) { throw new WebApplicationException(Response.Status.BAD_REQUEST); } else { UserContext.setUser(user); try { ContentReader content = localContentGetter.getContentByNodeId(nodeId, nodeVersion); if (content != null) { ReadableByteChannel inputChannel = content.getChannel(); String mimeType = content.getMimeType(); StreamingOutput streamer = new StreamingOutput() { @Override public void write(final OutputStream output) throws IOException, WebApplicationException { final WritableByteChannel outputChannel = Channels.newChannel(output); try { fastChannelCopy(inputChannel, outputChannel); // inputChannel.read(outputChannel); } finally { // closing the channels inputChannel.close(); outputChannel.close(); } } }; return Response.ok(streamer).type(mimeType).build(); } else { return Response.noContent().build(); } } finally { UserContext.setUser(null); } } } catch (Exception e) { LOGGER.error("caught", e); return Response.serverError().build(); } }
From source file:me.neatmonster.spacertk.actions.FileActions.java
/** * Sends a file to a URL//from w w w. j a v a 2 s .co m * @param url URL to send to * @param file File to send * @return If successful */ @Action(aliases = { "sendFile", "fileSend" }) public boolean sendFile(final String url, final String file) { FileOutputStream fileOutputStream = null; ReadableByteChannel readableByteChannel = null; try { File file_ = new File(file); if (file_.exists()) if (!deleteFile(file_.getPath())) return false; URL url_ = new URL(url); readableByteChannel = Channels.newChannel(url_.openStream()); fileOutputStream = new FileOutputStream(file_); fileOutputStream.getChannel().transferFrom(readableByteChannel, 0, 1 << 24); return true; } catch (IOException e) { e.printStackTrace(); } finally { try { if (fileOutputStream != null) fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } try { if (readableByteChannel != null) readableByteChannel.close(); } catch (IOException e) { e.printStackTrace(); } } return false; }
From source file:com.rogue.logore.update.UpdateHandler.java
/** * Downloads the latest jarfile for the {@link Plugin} * * @since 1.0.0// www. j a v a 2 s.c o m * @version 1.0.0 * * @TODO Add zip file support * @return The download result */ public Result download() { Result back = Result.UPDATED; File updateFolder = this.plugin.getServer().getUpdateFolderFile(); String url = (String) this.latest.get(this.DL_URL); ReadableByteChannel rbc = null; FileOutputStream fos = null; try { URL call = new URL(url); rbc = Channels.newChannel(call.openStream()); fos = new FileOutputStream(this.file); fos.getChannel().transferFrom(rbc, 0, 1 << 24); } catch (MalformedURLException ex) { this.plugin.getLogger().log(Level.SEVERE, "Error finding plugin update to download!", ex); back = Result.ERROR_FILENOTFOUND; } catch (IOException ex) { this.plugin.getLogger().log(Level.SEVERE, "Error transferring plugin data!", ex); back = Result.ERROR_DOWNLOAD_FAILED; } finally { try { if (fos != null) { fos.close(); } if (rbc != null) { rbc.close(); } } catch (IOException ex) { this.plugin.getLogger().log(Level.SEVERE, "Error closing streams/channels for download!", ex); } } return back; }
From source file:com.codelanx.playtime.update.UpdateHandler.java
/** * Downloads the latest jarfile for the {@link Plugin} * * @since 1.4.5/*www.j ava 2s.c om*/ * @version 1.4.5 * * @TODO Add zip file support * @return The download result */ public Result download() { Result back = Result.UPDATED; File updateLoc = this.plugin.getServer().getUpdateFolderFile(); updateLoc.mkdirs(); String url = (String) this.latest.get(this.DL_URL); File location = new File(updateLoc, this.file); ReadableByteChannel rbc = null; FileOutputStream fos = null; try { URL call = new URL(url); rbc = Channels.newChannel(call.openStream()); fos = new FileOutputStream(location); fos.getChannel().transferFrom(rbc, 0, 1 << 24); } catch (MalformedURLException ex) { this.plugin.getLogger().log(Level.SEVERE, "Error finding plugin update to download!", ex); back = Result.ERROR_FILENOTFOUND; } catch (IOException ex) { this.plugin.getLogger().log(Level.SEVERE, "Error transferring plugin data!", ex); back = Result.ERROR_DOWNLOAD_FAILED; } finally { try { if (fos != null) { fos.close(); } if (rbc != null) { rbc.close(); } } catch (IOException ex) { this.plugin.getLogger().log(Level.SEVERE, "Error closing streams/channels for download!", ex); } } return back; }
From source file:org.alfresco.cacheserver.TestEdgeServer.java
@Test public void test1() throws Exception { long nodeInternalId = 1l; String nodeId = GUID.generate(); String nodeVersion = "1"; String nodePath = "/1/2/3"; byte[] bytes = "test".getBytes("UTF-8"); String expectedMimeType = "text/plain"; Long expectedSize = new Long(bytes.length); InputStream nodeContent = new ByteArrayInputStream(bytes); ReadableByteChannel channel = null; try {/* w ww . jav a 2 s .co m*/ contentGetter.addTestContent(nodeInternalId, nodeId, nodeVersion, nodePath, "test", expectedMimeType); edgeServer.repoContentUpdated(Node.build().nodeId(nodeId).versionLabel(nodeVersion).nodePath(nodePath), expectedMimeType, expectedSize, true); UserDetails userDetails = new User("admin", null, null); UserContext.setUser(userDetails); ContentReader content = edgeServer.getByNodeId(nodeId, nodeVersion, true); channel = content.getChannel(); ByteBuffer bb = ByteBuffer.allocate(2048); channel.read(bb); assertNotNull(channel); assertEquals(expectedMimeType, content.getMimeType()); assertEquals(expectedSize, content.getSize()); ByteBuffer expectedNodeContent = ByteBuffer.wrap("test".getBytes("UTF-8")); compare(expectedNodeContent, bb); } finally { if (nodeContent != null) { nodeContent.close(); } if (channel != null) { channel.close(); } UserContext.setUser(null); } }
From source file:pl.psnc.synat.wrdz.zmd.download.adapters.HttpDownloadAdapter.java
@Override public String downloadFile(URI uri, String relativePath) throws DownloadAdapterException { String cachedFilePath = getResourceCachePath(relativePath); checkDestinationExistence(cachedFilePath); DefaultHttpClient httpclient = new DefaultHttpClient(); ReadableByteChannel rbc = null; FileOutputStream output = null; try {/*from w w w.ja v a 2s.com*/ if (usernamePasswordCredentials != null) { httpclient.getCredentialsProvider().setCredentials(authScope, usernamePasswordCredentials); } HttpResponse response = httpclient.execute(new HttpGet(uri)); HttpEntity entity = response.getEntity(); if (entity != null && response.getStatusLine().getStatusCode() == 200) { rbc = Channels.newChannel(entity.getContent()); output = new FileOutputStream(cachedFilePath); output.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); EntityUtils.consume(entity); } else { EntityUtils.consume(entity); throw new DownloadAdapterException( "Http error code or empty content was returned instead of resource."); } } catch (IOException e) { throw new DownloadAdapterException("Exception caught while downloading file contents to the cache.", e); } finally { httpclient.getConnectionManager().shutdown(); try { if (rbc != null) { rbc.close(); } if (output != null) { output.close(); } } catch (IOException e) { throw new DownloadAdapterException("Exception caught while closing input/output streams.", e); } } return cachedFilePath; }
From source file:com.chiorichan.updater.Download.java
@Override public void run() { ReadableByteChannel rbc = null; FileOutputStream fos = null;/*from ww w .j a va 2 s .c o m*/ try { HttpURLConnection conn = NetworkFunc.openHttpConnection(url); int response = conn.getResponseCode(); int responseFamily = response / 100; if (responseFamily == 3) throw new DownloadException( "The server issued a redirect response which the Updater failed to follow."); else if (responseFamily != 2) throw new DownloadException("The server issued a " + response + " response code."); InputStream in = getConnectionInputStream(conn); size = conn.getContentLength(); outFile = new File(outPath); outFile.delete(); rbc = Channels.newChannel(in); fos = new FileOutputStream(outFile); stateChanged(); Thread progress = new MonitorThread(Thread.currentThread(), rbc); progress.start(); fos.getChannel().transferFrom(rbc, 0, size > 0 ? size : Integer.MAX_VALUE); in.close(); rbc.close(); progress.interrupt(); if (size > 0) { if (size == outFile.length()) result = Result.SUCCESS; } else result = Result.SUCCESS; stateDone(); } catch (DownloadDeniedException e) { exception = e; result = Result.PERMISSION_DENIED; } catch (DownloadException e) { exception = e; result = Result.FAILURE; } catch (Exception e) { exception = e; e.printStackTrace(); } finally { IOUtils.closeQuietly(fos); IOUtils.closeQuietly(rbc); } if (exception != null) AutoUpdater.getLogger().severe("Download Resulted in an Exception", exception); }