List of usage examples for java.nio.channels WritableByteChannel close
public void close() throws IOException;
From source file:com.cloud.maint.UpgradeManagerImpl.java
public String deployNewAgent(String url) { s_logger.info("Updating agent with binary from " + url); final HttpClient client = new HttpClient(s_httpClientManager); final GetMethod method = new GetMethod(url); int response; File file = null;/*from w ww. j ava 2s . co m*/ try { response = client.executeMethod(method); if (response != HttpURLConnection.HTTP_OK) { s_logger.warn("Retrieving the agent gives response code: " + response); return "Retrieving the file from " + url + " got response code: " + response; } final InputStream is = method.getResponseBodyAsStream(); file = File.createTempFile("agent-", "-" + Long.toString(new Date().getTime())); file.deleteOnExit(); s_logger.debug("Retrieving new agent into " + file.getAbsolutePath()); final FileOutputStream fos = new FileOutputStream(file); final ByteBuffer buffer = ByteBuffer.allocate(2048); final ReadableByteChannel in = Channels.newChannel(is); final WritableByteChannel out = fos.getChannel(); while (in.read(buffer) != -1) { buffer.flip(); out.write(buffer); buffer.clear(); } in.close(); out.close(); s_logger.debug("New Agent zip file is now retrieved"); } catch (final HttpException e) { return "Unable to retrieve the file from " + url; } catch (final IOException e) { return "Unable to retrieve the file from " + url; } finally { method.releaseConnection(); } file.delete(); return "File will be deployed."; }
From source file:backtype.storm.utils.Utils.java
public static void downloadFromMaster(Map conf, String file, String localFile) throws IOException, TException { WritableByteChannel out = null; NimbusClient client = null;/*from w w w .j a v a 2 s. c o m*/ try { client = NimbusClient.getConfiguredClient(conf, 10 * 1000); String id = client.getClient().beginFileDownload(file); out = Channels.newChannel(new FileOutputStream(localFile)); while (true) { ByteBuffer chunk = client.getClient().downloadChunk(id); int written = out.write(chunk); if (written == 0) { client.getClient().finishFileDownload(id); break; } } } finally { if (out != null) out.close(); if (client != null) client.close(); } }
From source file:com.msr.dnsdemo.network.DownloadFile.java
public DownloadFile(final Context ctxt, String url, FileOutputStream out) throws IOException, NullPointerException { String version = "0.3.x"; try {// w w w . j a v a 2 s .c o m version = ctxt.getPackageManager().getPackageInfo("com.msr.dnsdemo", 0).versionName; } catch (NameNotFoundException e) { } httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter("http.useragent", USERAGENT + version); InputStream in = openURL(url); if (in == null) { Log.e(TAG, "Unable to download: " + url); return; } final ReadableByteChannel inputChannel = Channels.newChannel(in); final WritableByteChannel outputChannel = Channels.newChannel(out); try { Log.i(TAG, "Downloading " + url); fastChannelCopy(inputChannel, outputChannel); } finally { try { if (inputChannel != null) { inputChannel.close(); } if (outputChannel != null) { outputChannel.close(); } if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (Exception e) { if (e != null && e.getMessage() != null) { Log.e(TAG, e.getMessage()); } else { Log.e(TAG, "fastChannelCopy() unknown error"); } } } }
From source file:info.lamatricexiste.network.Network.DownloadFile.java
public DownloadFile(final Context ctxt, String url, FileOutputStream out) throws IOException, NullPointerException { String version = "0.3.x"; try {//from ww w . j a va2s . c o m version = ctxt.getPackageManager().getPackageInfo(ActivityMain.TAG, 0).versionName; } catch (NameNotFoundException e) { } httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter("http.useragent", USERAGENT + version); InputStream in = openURL(url); if (in == null) { Log.e(TAG, "Unable to download: " + url); return; } final ReadableByteChannel inputChannel = Channels.newChannel(in); final WritableByteChannel outputChannel = Channels.newChannel(out); try { Log.i(TAG, "Downloading " + url); fastChannelCopy(inputChannel, outputChannel); } finally { try { if (inputChannel != null) { inputChannel.close(); } if (outputChannel != null) { outputChannel.close(); } if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (Exception e) { if (e != null && e.getMessage() != null) { Log.e(TAG, e.getMessage()); } else { Log.e(TAG, "fastChannelCopy() unknown error"); } } } }
From source file:org.apache.beam.sdk.io.FileBasedSinkTest.java
private File writeValuesWithWritableByteChannelFactory(final WritableByteChannelFactory factory, String... values) throws IOException { final File file = tmpFolder.newFile("test.gz"); final WritableByteChannel channel = factory.create(Channels.newChannel(new FileOutputStream(file))); for (String value : values) { channel.write(ByteBuffer.wrap((value + "\n").getBytes(StandardCharsets.UTF_8))); }/*from w ww.j av a2 s . c o m*/ channel.close(); return file; }
From source file:org.alfresco.cacheserver.dropwizard.resources.CacheServerResource.java
@Path("/contentByNodeId/{nodeId}/{nodeVersion}") @GET// www . j a v a 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:org.wso2.carbon.identity.common.testng.CarbonBasedTestListener.java
private void copyDefaultConfigsIfNotExists(Class callerClass) { URL carbonXmlUrl = callerClass.getClassLoader().getResource("repository/conf/carbon.xml"); boolean needToCopyCarbonXml = false; if (carbonXmlUrl == null) { needToCopyCarbonXml = true;//from w ww. j a va 2 s .com } else { File file = new File(carbonXmlUrl.getPath()); needToCopyCarbonXml = !file.exists(); } if (needToCopyCarbonXml) { try { //Copy default identity xml into temp location and use it. URL url = CarbonBasedTestListener.class.getClassLoader().getResource("repository/conf/carbon.xml"); InputStream inputStream = url.openStream(); ReadableByteChannel inputChannel = Channels.newChannel(inputStream); Path tmpDirPath = Paths.get(System.getProperty("java.io.tmpdir"), "tests", callerClass.getSimpleName()); Path repoConfPath = Paths.get(tmpDirPath.toUri().getPath(), "repository", "conf"); Path carbonXMLPath = repoConfPath.resolve("carbon.xml"); Path carbonXML = Files.createFile(carbonXMLPath); FileOutputStream fos = new FileOutputStream(carbonXML.toFile()); WritableByteChannel targetChannel = fos.getChannel(); //Transfer data from input channel to output channel ((FileChannel) targetChannel).transferFrom(inputChannel, 0, Short.MAX_VALUE); inputStream.close(); targetChannel.close(); fos.close(); System.setProperty(TestConstants.CARBON_CONFIG_DIR_PATH, tmpDirPath.toString()); } catch (IOException e) { log.error("Failed to copy carbon.xml", e); } } else { try { System.setProperty(TestConstants.CARBON_CONFIG_DIR_PATH, Paths.get(carbonXmlUrl.toURI()).getParent().toString()); } catch (URISyntaxException e) { log.error("Failed to copy path for carbon.xml", e); } } }
From source file:org.alfresco.repo.transfer.HttpClientTransmitterImpl.java
public void sendManifest(Transfer transfer, File manifest, OutputStream result) throws TransferException { TransferTarget target = transfer.getTransferTarget(); PostMethod postSnapshotRequest = getPostMethod(); MultipartRequestEntity requestEntity; if (log.isDebugEnabled()) { log.debug("does manifest exist? " + manifest.exists()); log.debug("sendManifest file : " + manifest.getAbsoluteFile()); }//from www . j a v a2 s . c om try { HostConfiguration hostConfig = getHostConfig(target); HttpState httpState = getHttpState(target); try { postSnapshotRequest.setPath(target.getEndpointPath() + "/post-snapshot"); //Put the transferId on the query string postSnapshotRequest.setQueryString( new NameValuePair[] { new NameValuePair("transferId", transfer.getTransferId()) }); //TODO encapsulate the name of the manifest part //And add the manifest file as a "part" Part file = new FilePart(TransferCommons.PART_NAME_MANIFEST, manifest); requestEntity = new MultipartRequestEntity(new Part[] { file }, postSnapshotRequest.getParams()); postSnapshotRequest.setRequestEntity(requestEntity); int responseStatus = httpClient.executeMethod(hostConfig, postSnapshotRequest, httpState); checkResponseStatus("sendManifest", responseStatus, postSnapshotRequest); InputStream is = postSnapshotRequest.getResponseBodyAsStream(); final ReadableByteChannel inputChannel = Channels.newChannel(is); final WritableByteChannel outputChannel = Channels.newChannel(result); try { // copy the channels channelCopy(inputChannel, outputChannel); } finally { 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[] { "sendManifest", target.toString(), e.toString() }, e); } } finally { postSnapshotRequest.releaseConnection(); } }
From source file:org.openhab.io.transport.cul.internal.network.CULNetworkHandlerImpl.java
private void processWrite(SelectionKey key) throws IOException { WritableByteChannel ch = (WritableByteChannel) key.channel(); synchronized (writeBuf) { writeBuf.flip();/*www. jav a 2 s . c o m*/ int bytesOp = 0, bytesTotal = 0; while (writeBuf.hasRemaining() && (bytesOp = ch.write(writeBuf)) > 0) { bytesTotal += bytesOp; } logger.debug("Written {} bytes to the network", bytesTotal); if (writeBuf.remaining() == 0) { key.interestOps(key.interestOps() ^ SelectionKey.OP_WRITE); } if (bytesTotal > 0) { writeBuf.notify(); } else if (bytesOp == -1) { logger.info("peer closed write channel"); ch.close(); } writeBuf.compact(); } }