List of usage examples for java.nio.channels ReadableByteChannel close
public void close() throws IOException;
From source file:org.polago.deployconf.DeployConfRunner.java
/** * Gets a DeploymentConfig instance from a Path. * * @param path the file to use//from w w w . j a v a 2 s . c om * @return a DeploymentConfig representation of the ReadableByteChannel * @throws Exception indicating error */ private DeploymentConfig getDeploymentConfigFromPath(Path path) throws Exception { ReadableByteChannel ch = FileChannel.open(path, StandardOpenOption.READ); InputStream is = Channels.newInputStream(ch); DeploymentReader reader = new DeploymentReader(is, getGroupManager()); DeploymentConfig result = reader.parse(); ch.close(); return result; }
From source file:com.doplgangr.secrecy.FileSystem.File.java
public java.io.File readFile(CryptStateListener listener) { decrypting = true;// www.j a v a 2 s . c o m InputStream is = null; OutputStream out = null; java.io.File outputFile = null; try { outputFile = java.io.File.createTempFile("tmp" + name, "." + FileType, storage.getTempFolder()); outputFile.mkdirs(); outputFile.createNewFile(); AES_Encryptor enc = new AES_Encryptor(key); is = new CipherInputStream(new FileInputStream(file), enc.decryptstream()); listener.setMax((int) file.length()); ReadableByteChannel inChannel = Channels.newChannel(is); FileChannel outChannel = new FileOutputStream(outputFile).getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate(Config.bufferSize); while (inChannel.read(byteBuffer) >= 0 || byteBuffer.position() > 0) { byteBuffer.flip(); outChannel.write(byteBuffer); byteBuffer.compact(); listener.updateProgress((int) outChannel.size()); } inChannel.close(); outChannel.close(); Util.log(outputFile.getName(), outputFile.length()); return outputFile; } catch (FileNotFoundException e) { listener.onFailed(2); Util.log("Encrypted File is missing", e.getMessage()); } catch (IOException e) { Util.log("IO Exception while decrypting", e.getMessage()); if (e.getMessage().contains("pad block corrupted")) listener.onFailed(1); else e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { listener.Finished(); decrypting = false; try { if (is != null) { is.close(); } if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } // An error occured. Too Bad if (outputFile != null) storage.purgeFile(outputFile); return null; }
From source file:org.openhab.io.transport.cul.internal.network.CULNetworkHandlerImpl.java
private void processRead(SelectionKey key) throws Exception { ReadableByteChannel ch = (ReadableByteChannel) key.channel(); int bytesOp = 0, bytesTotal = 0; while (readBuf.hasRemaining() && (bytesOp = ch.read(readBuf)) > 0) { bytesTotal += bytesOp;//w w w . j a v a 2 s.c o m } logger.debug("Read {} bytes from network", bytesTotal); if (bytesTotal > 0) { readBuf.flip(); onRead(readBuf); readBuf.compact(); } else if (bytesOp == -1) { logger.info("peer closed read channel"); ch.close(); } }
From source file:io.spring.initializr.generator.ProjectGenerator.java
private File downloadExternalStructure(String urlStr, File file) throws IOException { URL url = new URL(urlStr); String filename = FilenameUtils.getBaseName(urlStr) + "." + FilenameUtils.getExtension(urlStr); log.info("Filename: " + filename); ReadableByteChannel rbc = Channels.newChannel(url.openStream()); File f = new File(file, filename); FileOutputStream fos = new FileOutputStream(f); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close();//from w w w. ja v a 2 s.com rbc.close(); return f; }
From source file:org.darkware.wpman.security.ChecksumDatabase.java
/** * Perform a checksum calculation on the given {@link ReadableByteChannel}. Other code should not create * implementations which are dependant on any particular characteristics of the checksum, but the checksum * is very likely to be based on a cryptographic-strength hash. The results of the checksum are encoded as * a base64 {@code String}./*from ww w .j ava2 s .co m*/ * * @param channel The {@code ReadableByteChannel} to read data from. * @return A Base64 encoded {@code String} representing the checksum. * @throws IOException If there was an error while reading data from the channel. * @see Base64#encodeBase64String(byte[]) */ protected String doChecksum(ReadableByteChannel channel) throws IOException { Hasher hasher = Hashing.sha256().newHasher(); final ByteBuffer block = ByteBuffer.allocate(4096); while (channel.isOpen()) { int bytesRead = channel.read(block); if (bytesRead > 0) { block.flip(); hasher.putBytes(block.array(), 0, block.limit()); block.clear(); } else if (bytesRead == -1) { channel.close(); } } return Base64.encodeBase64String(hasher.hash().asBytes()); }
From source file:org.geowebcache.GeoWebCacheDispatcher.java
private void loadBlankTile(Resource blankTile, URL source) throws IOException { InputStream inputStream = source.openStream(); ReadableByteChannel ch = Channels.newChannel(inputStream); try {// w w w. j a va2 s . 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 2s .com*/ 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"); }
From source file:com.quanticate.opensource.compressingcontentstore.DecompressingContentReader.java
@Override protected ReadableByteChannel getDirectReadableChannel() throws ContentIOException { // Get a Channel onto the real data ReadableByteChannel rawChannel = getRawChannel(); // Wrap this as an InputStream - Commons Compress is Stream not Channel based // Note that Commons Compress needs to mark/reset a bit to identify InputStream rawInp = new BufferedInputStream(Channels.newInputStream(rawChannel), 32); // Try to process it as a compressed stream try {// www . j a v a 2 s . c o m CompressorInputStream decompressed = new CompressorStreamFactory().createCompressorInputStream(rawInp); logger.debug("Detected compressed data as " + decompressed.getClass().getName()); return Channels.newChannel(decompressed); } catch (CompressorException e) { logger.info("Unable to decompress " + realContentReader, e); } // Tidy up that channel, and re-fetch the real one try { rawInp.close(); rawChannel.close(); } catch (IOException e) { logger.warn("Error tidying up", e); } logger.debug("Using raw form for " + getContentUrl()); return getRawChannel(); }
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 ww w. jav a 2 s. c o m*/ 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(); } }