use of java.nio.channels.SeekableByteChannel in project graal by oracle.
the class SourceBuilderTest method testRelativeSourceWithContent.
@Test
public void testRelativeSourceWithContent() throws Exception {
setupEnv();
TruffleFile cwd = languageEnv.getCurrentWorkingDirectory();
String relativeName = "Test.java";
TruffleFile file = cwd.resolve(relativeName);
String content = "// Test";
try {
try (SeekableByteChannel c = file.newByteChannel(EnumSet.of(WRITE, CREATE))) {
c.write(ByteBuffer.wrap(content.getBytes("UTF-8")));
}
TruffleFile relativeFile = languageEnv.getPublicTruffleFile(relativeName);
Source source = Source.newBuilder("", relativeFile).build();
assertFalse(source.hasBytes());
assertTrue(source.hasCharacters());
// Constructed from relativeFile TruffleFile, but loads content and should be absolute
assertTrue(source.getURI().toString(), source.getURI().isAbsolute());
assertEquals(content, source.getCharacters().toString());
} finally {
file.delete();
}
}
use of java.nio.channels.SeekableByteChannel in project graal by oracle.
the class SystemUtils method computeFileDigest.
/**
* Computes file digest. The default algorithm is SHA-256
*
* @param localFile local file path
* @param digestAlgo the hash algorithm
* @return digest bytes
* @throws java.io.IOException in the case of I/O failure, or a digest failure/not found
*/
public static byte[] computeFileDigest(Path localFile, String digestAlgo) throws IOException {
try (SeekableByteChannel s = FileChannel.open(localFile, StandardOpenOption.READ)) {
ByteBuffer bb = ByteBuffer.allocate(4096);
long size = Files.size(localFile);
// NOI18N
MessageDigest dg = MessageDigest.getInstance("SHA-256");
while (size > 0) {
if (bb.limit() > size) {
bb.limit((int) size);
}
int r = s.read(bb);
if (r < 0) {
break;
}
bb.flip();
dg.update(bb);
bb.clear();
size -= r;
}
return dg.digest();
} catch (NoSuchAlgorithmException ex) {
throw new IOException(ex);
}
}
use of java.nio.channels.SeekableByteChannel in project sis by apache.
the class TestUtilities method createTemporaryFile.
/**
* Copies the full content of the given test resource in a temporary file and returns the channel for that file.
* The file is opened with {@link StandardOpenOption#DELETE_ON_CLOSE}, together with read and write options.
*
* @param caller defines the root from which to search for the {@code resource}.
* @param resource path (relative to the {@code caller}) of the test file to copy.
* @return a channel opened on a copy of the content of the given test resource.
* @throws IOException if an error occurred while copying the data.
*
* @since 0.8
*/
public static SeekableByteChannel createTemporaryFile(final Class<?> caller, final String resource) throws IOException {
final SeekableByteChannel channel;
try (ReadableByteChannel in = Channels.newChannel(caller.getResourceAsStream(resource))) {
final int s = resource.lastIndexOf('.');
final Path file = Files.createTempFile("SIS", (s >= 0) ? resource.substring(s) : null);
channel = Files.newByteChannel(file, StandardOpenOption.DELETE_ON_CLOSE, StandardOpenOption.READ, StandardOpenOption.WRITE);
final ByteBuffer buffer = ByteBuffer.allocate(4000);
while (in.read(buffer) >= 0) {
buffer.flip();
channel.write(buffer);
buffer.clear();
}
}
return channel.position(0);
}
use of java.nio.channels.SeekableByteChannel in project disunity by ata4.
the class BundleUtils method byteChannelForEntry.
public static SeekableByteChannel byteChannelForEntry(BundleEntry entry) throws IOException {
SeekableByteChannel chan;
// check if the entry is larger than 128 MiB
long size = entry.size();
if (size > 1 << 27) {
// copy entry to temporary file
Path tmpFile = Files.createTempFile("disunity", null);
Files.copy(entry.inputStream(), tmpFile, REPLACE_EXISTING);
chan = Files.newByteChannel(tmpFile, READ, DELETE_ON_CLOSE);
} else {
// copy entry to memory
ByteBuffer bb = ByteBuffer.allocateDirect((int) size);
IOUtils.copy(entry.inputStream(), new ByteBufferOutputStream(bb));
bb.flip();
chan = new ByteBufferChannel(bb);
}
return chan;
}
use of java.nio.channels.SeekableByteChannel in project elasticsearch by elastic.
the class SharedClusterSnapshotRestoreIT method testDeleteSnapshotWithCorruptedSnapshotFile.
public void testDeleteSnapshotWithCorruptedSnapshotFile() throws Exception {
Client client = client();
Path repo = randomRepoPath();
logger.info("--> creating repository at {}", repo.toAbsolutePath());
assertAcked(client.admin().cluster().preparePutRepository("test-repo").setType("fs").setSettings(Settings.builder().put("location", repo).put("compress", false).put("chunk_size", randomIntBetween(100, 1000), ByteSizeUnit.BYTES)));
createIndex("test-idx-1", "test-idx-2");
logger.info("--> indexing some data");
indexRandom(true, client().prepareIndex("test-idx-1", "doc").setSource("foo", "bar"), client().prepareIndex("test-idx-2", "doc").setSource("foo", "bar"));
logger.info("--> creating snapshot");
CreateSnapshotResponse createSnapshotResponse = client.admin().cluster().prepareCreateSnapshot("test-repo", "test-snap-1").setWaitForCompletion(true).setIndices("test-idx-*").get();
assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), greaterThan(0));
assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponse.getSnapshotInfo().totalShards()));
logger.info("--> truncate snapshot file to make it unreadable");
Path snapshotPath = repo.resolve("snap-" + createSnapshotResponse.getSnapshotInfo().snapshotId().getUUID() + ".dat");
try (SeekableByteChannel outChan = Files.newByteChannel(snapshotPath, StandardOpenOption.WRITE)) {
outChan.truncate(randomInt(10));
}
logger.info("--> delete snapshot");
client.admin().cluster().prepareDeleteSnapshot("test-repo", "test-snap-1").get();
logger.info("--> make sure snapshot doesn't exist");
assertThrows(client.admin().cluster().prepareGetSnapshots("test-repo").addSnapshots("test-snap-1"), SnapshotMissingException.class);
logger.info("--> make sure that we can create the snapshot again");
createSnapshotResponse = client.admin().cluster().prepareCreateSnapshot("test-repo", "test-snap-1").setWaitForCompletion(true).setIndices("test-idx-*").get();
assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), greaterThan(0));
assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponse.getSnapshotInfo().totalShards()));
}
Aggregations