Java Code Examples for java.nio.channels.WritableByteChannel#close()
The following examples show how to use
java.nio.channels.WritableByteChannel#close() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DataBufferUtilsTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void writeWritableByteChannelCancel() throws Exception { DataBuffer foo = stringBuffer("foo"); DataBuffer bar = stringBuffer("bar"); Flux<DataBuffer> flux = Flux.just(foo, bar); WritableByteChannel channel = Files.newByteChannel(tempFile, StandardOpenOption.WRITE); Flux<DataBuffer> writeResult = DataBufferUtils.write(flux, channel); StepVerifier.create(writeResult, 1) .consumeNextWith(stringConsumer("foo")) .thenCancel() .verify(Duration.ofSeconds(5)); String result = String.join("", Files.readAllLines(tempFile)); assertEquals("foo", result); channel.close(); flux.subscribe(DataBufferUtils::release); }
Example 2
Source File: ServiceHandler.java From jstorm with Apache License 2.0 | 6 votes |
@Override public void finishFileUpload(String location) throws TException { TimeCacheMap<Object, Object> uploaders = data.getUploaders(); Object obj = uploaders.get(location); if (obj == null) { throw new TException("File for that location does not exist (or timed out)"); } try { if (obj instanceof WritableByteChannel) { WritableByteChannel channel = (WritableByteChannel) obj; channel.close(); uploaders.remove(location); LOG.info("Finished uploading file from client: " + location); } else { throw new TException("Object isn't WritableByteChannel for " + location); } } catch (IOException e) { LOG.error(" WritableByteChannel close failed when finishFileUpload " + location); } }
Example 3
Source File: Utils.java From jstorm with Apache License 2.0 | 6 votes |
public static void downloadFromMaster(Map conf, String file, String localFile) throws IOException, TException { WritableByteChannel out = null; NimbusClient client = null; 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(); } }
Example 4
Source File: MockInitialContextFactory.java From carbon-identity-framework with Apache License 2.0 | 6 votes |
/** * Copies a resource inside a jar to external file within a directory. * Then returns the created file. * * @param relativeFilePath * @param clazz * @return * @throws TestCreationException */ private static File copyTempFile(String relativeFilePath, Class clazz) throws TestCreationException { URL url = clazz.getClassLoader().getResource(relativeFilePath); if(url == null) { throw new TestCreationException("Could not find a resource on the classpath : " + relativeFilePath); } InputStream inputStream; try { inputStream = url.openStream(); ReadableByteChannel inputChannel = Channels.newChannel(inputStream); File tempFile = File.createTempFile("tmp_", "_registry.sql"); FileOutputStream fos = new FileOutputStream(tempFile); 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(); return tempFile; } catch (IOException e) { throw new TestCreationException("Could not copy the file content to temp file from : " + relativeFilePath); } }
Example 5
Source File: DownloadSample.java From huaweicloud-sdk-java-obs with Apache License 2.0 | 6 votes |
private void downloadToLocalFile() throws ObsException, IOException { ObsObject obsObject = obsClient.getObject(bucketName, objectKey, null); ReadableByteChannel rchannel = Channels.newChannel(obsObject.getObjectContent()); ByteBuffer buffer = ByteBuffer.allocate(4096); WritableByteChannel wchannel = Channels.newChannel(new FileOutputStream(new File(localFilePath))); while (rchannel.read(buffer) != -1) { buffer.flip(); wchannel.write(buffer); buffer.clear(); } rchannel.close(); wchannel.close(); }
Example 6
Source File: MuxMp4.java From dashencrypt with Mozilla Public License 2.0 | 6 votes |
private void writeMp4(List<Track> tracks) throws IOException { Movie m = new Movie(); m.setTracks(tracks); Mp4Builder mp4Builder = getFileBuilder(m); Container isoFile = mp4Builder.build(m); System.out.print("Writing t "); WritableByteChannel wbc = new FileOutputStream(outputFile).getChannel(); try { isoFile.writeContainer(wbc); } finally { wbc.close(); } System.out.println("Done."); }
Example 7
Source File: DataBufferUtilsTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void writeWritableByteChannelErrorInWrite() throws Exception { DataBuffer foo = stringBuffer("foo"); DataBuffer bar = stringBuffer("bar"); Flux<DataBuffer> flux = Flux.just(foo, bar); WritableByteChannel channel = mock(WritableByteChannel.class); when(channel.write(any())) .thenAnswer(invocation -> { ByteBuffer buffer = invocation.getArgument(0); int written = buffer.remaining(); buffer.position(buffer.limit()); return written; }) .thenThrow(new IOException()); Flux<DataBuffer> writeResult = DataBufferUtils.write(flux, channel); StepVerifier.create(writeResult) .consumeNextWith(stringConsumer("foo")) .consumeNextWith(stringConsumer("bar")) .expectError(IOException.class) .verify(Duration.ofSeconds(3)); channel.close(); }
Example 8
Source File: DataBufferUtilsTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void writeWritableByteChannelErrorInFlux() throws Exception { DataBuffer foo = stringBuffer("foo"); DataBuffer bar = stringBuffer("bar"); Flux<DataBuffer> flux = Flux.just(foo, bar).concatWith(Flux.error(new RuntimeException())); WritableByteChannel channel = Files.newByteChannel(tempFile, StandardOpenOption.WRITE); Flux<DataBuffer> writeResult = DataBufferUtils.write(flux, channel); StepVerifier.create(writeResult) .consumeNextWith(stringConsumer("foo")) .consumeNextWith(stringConsumer("bar")) .expectError() .verify(Duration.ofSeconds(5)); String result = String.join("", Files.readAllLines(tempFile)); assertEquals("foobar", result); channel.close(); }
Example 9
Source File: PathResourceTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void getWritableChannel() throws IOException { PathResource resource = new PathResource(temporaryFolder.newFile("test").toPath()); ByteBuffer buffer = ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8)); WritableByteChannel channel = null; try { channel = resource.writableChannel(); channel.write(buffer); } finally { if (channel != null) { channel.close(); } } assertThat(resource.contentLength(), equalTo(4L)); }
Example 10
Source File: DataBufferUtilsTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void writeWritableByteChannelCancel() throws Exception { DataBuffer foo = stringBuffer("foo"); DataBuffer bar = stringBuffer("bar"); Flux<DataBuffer> flux = Flux.just(foo, bar); WritableByteChannel channel = Files.newByteChannel(tempFile, StandardOpenOption.WRITE); Flux<DataBuffer> writeResult = DataBufferUtils.write(flux, channel); StepVerifier.create(writeResult, 1) .consumeNextWith(stringConsumer("foo")) .thenCancel() .verify(Duration.ofSeconds(5)); String result = String.join("", Files.readAllLines(tempFile)); assertEquals("foo", result); channel.close(); flux.subscribe(DataBufferUtils::release); }
Example 11
Source File: ChannelsTest.java From j2objc with Apache License 2.0 | 6 votes |
public void testNewOutputStreamWritableByteChannel() throws Exception { byte[] writebuf = new byte[this.testNum]; ByteBuffer writebcbuf = ByteBuffer.allocateDirect(this.testNum); this.fouts = new FileOutputStream(tmpFile); WritableByteChannel writebc = this.fouts.getChannel(); assertTrue(writebc.isOpen()); OutputStream testouts = Channels.newOutputStream(writebc); // read in testins and fins use the same pointer testouts.write(writebuf); this.assertFileSizeSame(tmpFile, this.testNum); writebc.write(writebcbuf); this.assertFileSizeSame(tmpFile, this.testNum * 2); testouts.write(writebuf); this.assertFileSizeSame(tmpFile, this.testNum * 3); // readbc.close() affect testins writebc.close(); assertFalse(writebc.isOpen()); try { testouts.write(writebuf); fail(); } catch (ClosedChannelException e) { // correct } }
Example 12
Source File: CULNetworkHandlerImpl.java From openhab1-addons with Eclipse Public License 2.0 | 6 votes |
private void processWrite(SelectionKey key) throws IOException { WritableByteChannel ch = (WritableByteChannel) key.channel(); synchronized (writeBuf) { writeBuf.flip(); 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(); } }
Example 13
Source File: DXTImage.java From tribaltrouble with GNU General Public License v2.0 | 5 votes |
public void write(File file) throws IOException { WritableByteChannel out = new FileOutputStream(file).getChannel(); ByteBuffer header = ByteBuffer.allocate(2 + 2 + 4); header.putShort(width).putShort(height).putInt(internal_format); header.flip(); writeContents(out, header); int old_position = mipmaps.position(); int old_limit = mipmaps.limit(); mipmaps.clear(); writeContents(out, mipmaps); mipmaps.position(old_position); mipmaps.limit(old_limit); out.close(); }
Example 14
Source File: FileBasedSink.java From beam with Apache License 2.0 | 5 votes |
private static void closeChannelAndThrow( WritableByteChannel channel, ResourceId filename, Exception prior) throws Exception { try { channel.close(); } catch (Exception e) { LOG.error("Closing channel for {} failed.", filename, e); prior.addSuppressed(e); } // We should fail here regardless of whether above channel.close() call failed or not. throw prior; }
Example 15
Source File: GoogleCloudStorage.java From tutorials with MIT License | 5 votes |
private void updateString(BlobId blobId, String newString) throws IOException { Blob blob = storage.get(blobId); if (blob != null) { WritableByteChannel channel = blob.writer(); channel.write(ByteBuffer.wrap(newString.getBytes(UTF_8))); channel.close(); } }
Example 16
Source File: FileUtils.java From workcraft with MIT License | 5 votes |
public static void copyFileToStream(File inFile, OutputStream os) throws IOException { FileInputStream is = new FileInputStream(inFile); FileChannel inChannel = is.getChannel(); WritableByteChannel outChannel = Channels.newChannel(os); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (is != null) is.close(); if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
Example 17
Source File: OutputsMaterializer.java From buck with Apache License 2.0 | 5 votes |
private static void tryCloseChannel(WritableByteChannel channel) { try { channel.close(); } catch (IOException e) { throw new UncheckedExecutionException(e); } }
Example 18
Source File: FileChannelUtil.java From common-utils with GNU General Public License v2.0 | 5 votes |
public static void copyAndClose(String src, Socket socket) throws IOException { FileChannel srcChannel = (FileChannel) Channels.newChannel(new FileOutputStream(src)); WritableByteChannel destChannel = Channels.newChannel(socket.getOutputStream()); try { srcChannel.transferTo(0, srcChannel.size(), destChannel); } finally { srcChannel.close(); destChannel.close(); } }
Example 19
Source File: FileBasedSinkTest.java From beam with Apache License 2.0 | 5 votes |
private File writeValuesWithCompression(Compression compression, String... values) throws IOException { final File file = tmpFolder.newFile("test.gz"); final WritableByteChannel channel = compression.writeCompressed(Channels.newChannel(new FileOutputStream(file))); for (String value : values) { channel.write(ByteBuffer.wrap((value + "\n").getBytes(StandardCharsets.UTF_8))); } channel.close(); return file; }
Example 20
Source File: BrotliEncoderChannelTest.java From ShizuruNotes with Apache License 2.0 | 4 votes |
private static void run(String entryName, TestMode mode) throws Throwable { InputStream bundle = getBundle(); byte[] original; try { original = BundleHelper.readEntry(bundle, entryName); } finally { bundle.close(); } if (original == null) { throw new RuntimeException("Can't read bundle entry: " + entryName); } if ((mode == TestMode.WRITE_CHUNKS) && (original.length <= CHUNK_SIZE)) { return; } ByteArrayOutputStream dst = new ByteArrayOutputStream(); WritableByteChannel encoder = new BrotliEncoderChannel(Channels.newChannel(dst)); ByteBuffer src = ByteBuffer.wrap(original); try { switch (mode) { case WRITE_ALL: encoder.write(src); break; case WRITE_CHUNKS: while (src.hasRemaining()) { int limit = Math.min(CHUNK_SIZE, src.remaining()); ByteBuffer slice = src.slice(); ((Buffer) slice).limit(limit); ((Buffer) src).position(src.position() + limit); encoder.write(slice); } break; } } finally { encoder.close(); } InputStream decoder = new BrotliInputStream(new ByteArrayInputStream(dst.toByteArray())); try { long originalCrc = BundleHelper.fingerprintStream(new ByteArrayInputStream(original)); long crc = BundleHelper.fingerprintStream(decoder); assertEquals(originalCrc, crc); } finally { decoder.close(); } }