Search in sources :

Example 66 with SeekableByteChannel

use of java.nio.channels.SeekableByteChannel in project graal by oracle.

the class NativeImageResourceFileSystemProviderTest method readingFileFileChannel.

/**
 * <p>
 * Reading from file using {@link java.nio.channels.FileChannel}.
 * </p>
 *
 * <p>
 * <b>Description: </b> We are doing next operations: </br>
 * <ol>
 * <li>Create new file system</li>
 * <li>Reading from file</li>
 * <li>Closing file system</li>
 * </ol>
 * </p>
 */
@Test
public void readingFileFileChannel() {
    // 1. Creating new file system.
    FileSystem fileSystem = createNewFileSystem();
    Path resourceDirectory = fileSystem.getPath(RESOURCE_DIR);
    Path resourceFile1 = resourceNameToPath(RESOURCE_FILE_1);
    // 2. Reading from file.
    Set<StandardOpenOption> permissions = Collections.singleton(StandardOpenOption.READ);
    try (SeekableByteChannel channel = fileSystem.provider().newFileChannel(resourceDirectory, permissions)) {
        ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
        channel.read(byteBuffer);
        Assert.fail("Trying to read from directory as a file!");
    } catch (IOException ignored) {
    }
    try (SeekableByteChannel channel = fileSystem.provider().newFileChannel(resourceFile1, permissions)) {
        ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
        channel.read(byteBuffer);
        String content = new String(byteBuffer.array());
        Assert.assertTrue("Nothing has been read from file!", content.length() > 0);
    } catch (IOException ioException) {
        Assert.fail("Exception occurs during reading from file!");
    }
    // 3. Closing file system.
    closeFileSystem(fileSystem);
}
Also used : Path(java.nio.file.Path) SeekableByteChannel(java.nio.channels.SeekableByteChannel) StandardOpenOption(java.nio.file.StandardOpenOption) FileSystem(java.nio.file.FileSystem) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) Test(org.junit.Test)

Example 67 with SeekableByteChannel

use of java.nio.channels.SeekableByteChannel in project graal by oracle.

the class NativeImageResourceFileSystemProviderTest method writingFileFileChannel.

/**
 * <p>
 * Writing into file using {@link java.nio.channels.FileChannel}.
 * </p>
 *
 * <p>
 * <b>Description: </b> We are doing next operations: </br>
 * <ol>
 * <li>Create new file system</li>
 * <li>Writing into file</li>
 * <li>Closing file system</li>
 * </ol>
 * </p>
 */
@Test
public void writingFileFileChannel() {
    // 1. Creating new file system.
    FileSystem fileSystem = createNewFileSystem();
    FileSystemProvider provider = fileSystem.provider();
    Path resourceDirectory = fileSystem.getPath(RESOURCE_DIR);
    Path resourceFile1 = resourceNameToPath(RESOURCE_FILE_1);
    Set<StandardOpenOption> readPermissions = Collections.singleton(StandardOpenOption.READ);
    Set<StandardOpenOption> writePermissions = Collections.singleton(StandardOpenOption.WRITE);
    Set<StandardOpenOption> readWritePermissions = new HashSet<>(Collections.emptySet());
    readWritePermissions.addAll(readPermissions);
    readWritePermissions.addAll(writePermissions);
    // 2. Writing into file.
    try {
        provider.newFileChannel(resourceDirectory, writePermissions);
        Assert.fail("Trying to write into directory as a file!");
    } catch (IOException ignored) {
    }
    try (SeekableByteChannel channel = provider.newFileChannel(resourceFile1, readPermissions)) {
        ByteBuffer byteBuffer = ByteBuffer.wrap("test string".getBytes());
        channel.write(byteBuffer);
        Assert.fail("Wrong write permissions!");
    } catch (IOException | NonWritableChannelException ignored) {
    }
    try (SeekableByteChannel channel = provider.newFileChannel(resourceFile1, readWritePermissions)) {
        ByteBuffer byteBuffer = ByteBuffer.wrap("test string#".getBytes());
        channel.write(byteBuffer);
        ByteBuffer byteBuffer2 = ByteBuffer.allocate((int) channel.size());
        channel.read(byteBuffer2);
        String content = new String(byteBuffer.array());
        Assert.assertTrue("Nothing has been writen into file!", content.length() > 0);
        Assert.assertTrue("Content has been writen into file improperly!", content.startsWith("test string#"));
    } catch (IOException ioException) {
        Assert.fail("Exception occurs during writing into file!");
    }
    // 3. Closing file system.
    closeFileSystem(fileSystem);
}
Also used : Path(java.nio.file.Path) SeekableByteChannel(java.nio.channels.SeekableByteChannel) StandardOpenOption(java.nio.file.StandardOpenOption) FileSystemProvider(java.nio.file.spi.FileSystemProvider) FileSystem(java.nio.file.FileSystem) IOException(java.io.IOException) NonWritableChannelException(java.nio.channels.NonWritableChannelException) ByteBuffer(java.nio.ByteBuffer) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 68 with SeekableByteChannel

use of java.nio.channels.SeekableByteChannel in project graal by oracle.

the class NativeImageResourceFileSystemProviderTest method readingFileByteChannel.

/**
 * <p>
 * Reading from file using {@link java.nio.channels.ByteChannel}.
 * </p>
 *
 * <p>
 * <b>Description: </b> We are doing next operations: </br>
 * <ol>
 * <li>Create new file system</li>
 * <li>Reading from file</li>
 * <li>Closing file system</li>
 * </ol>
 * </p>
 */
@Test
public void readingFileByteChannel() {
    // 1. Creating new file system.
    FileSystem fileSystem = createNewFileSystem();
    Path resourceDirectory = fileSystem.getPath(RESOURCE_DIR);
    Path resourceFile1 = resourceNameToPath(RESOURCE_FILE_1);
    // 2. Reading from file.
    try (SeekableByteChannel channel = Files.newByteChannel(resourceDirectory, StandardOpenOption.READ)) {
        ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
        channel.read(byteBuffer);
        Assert.fail("Trying to read from directory as a file!");
    } catch (IOException ignored) {
    }
    try (SeekableByteChannel channel = Files.newByteChannel(resourceFile1, StandardOpenOption.READ)) {
        ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
        channel.read(byteBuffer);
        String content = new String(byteBuffer.array());
        Assert.assertTrue("Nothing has been read from file!", content.length() > 0);
    } catch (IOException ioException) {
        Assert.fail("Exception occurs during reading from file!");
    }
    // 3. Closing file system.
    closeFileSystem(fileSystem);
}
Also used : Path(java.nio.file.Path) SeekableByteChannel(java.nio.channels.SeekableByteChannel) FileSystem(java.nio.file.FileSystem) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) Test(org.junit.Test)

Example 69 with SeekableByteChannel

use of java.nio.channels.SeekableByteChannel in project graal by oracle.

the class LSPFileSystem method newByteChannel.

@Override
public SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException {
    for (OpenOption option : options) {
        if (!(option instanceof StandardOpenOption && StandardOpenOption.READ.equals(option))) {
            throw new AccessDeniedException(path.toString(), null, "Read-only file-system");
        }
    }
    final String text = fileProvider.getSourceText(path);
    if (text != null) {
        final byte[] bytes = text.getBytes();
        return new SeekableByteChannel() {

            int position = 0;

            @Override
            public boolean isOpen() {
                return true;
            }

            @Override
            public void close() throws IOException {
            }

            @Override
            public int write(ByteBuffer src) throws IOException {
                throw new AccessDeniedException(path.toString(), null, "Read-only file-system");
            }

            @Override
            public SeekableByteChannel truncate(long size) throws IOException {
                throw new AccessDeniedException(path.toString(), null, "Read-only file-system");
            }

            @Override
            public long size() throws IOException {
                return bytes.length;
            }

            @Override
            public int read(ByteBuffer dst) throws IOException {
                int len = Math.min(dst.remaining(), bytes.length - position);
                dst.put(bytes, position, len);
                position += len;
                return len;
            }

            @Override
            public SeekableByteChannel position(long newPosition) throws IOException {
                if (newPosition > Integer.MAX_VALUE) {
                    throw new IllegalArgumentException("> Integer.MAX_VALUE");
                }
                position = (int) newPosition;
                return this;
            }

            @Override
            public long position() throws IOException {
                return position;
            }
        };
    }
    try {
        return delegate.newFileChannel(path, options, attrs);
    } catch (UnsupportedOperationException uoe) {
        return delegate.newByteChannel(path, options, attrs);
    }
}
Also used : SeekableByteChannel(java.nio.channels.SeekableByteChannel) OpenOption(java.nio.file.OpenOption) StandardOpenOption(java.nio.file.StandardOpenOption) AccessDeniedException(java.nio.file.AccessDeniedException) StandardOpenOption(java.nio.file.StandardOpenOption) ByteBuffer(java.nio.ByteBuffer)

Example 70 with SeekableByteChannel

use of java.nio.channels.SeekableByteChannel in project graal by oracle.

the class IOHelper method copy.

static void copy(final Path source, final Path target, final FileSystem sourceFileSystem, final FileSystem targetFileSystem, CopyOption... options) throws IOException {
    if (source.equals(target)) {
        return;
    }
    final Path sourceReal = sourceFileSystem.toRealPath(source, LinkOption.NOFOLLOW_LINKS);
    final Path targetReal = targetFileSystem.toRealPath(target, LinkOption.NOFOLLOW_LINKS);
    if (sourceReal.equals(targetReal)) {
        return;
    }
    final Set<LinkOption> linkOptions = new HashSet<>();
    final Set<StandardCopyOption> copyOptions = EnumSet.noneOf(StandardCopyOption.class);
    for (CopyOption option : options) {
        if (option instanceof StandardCopyOption) {
            copyOptions.add((StandardCopyOption) option);
        } else if (option instanceof LinkOption) {
            linkOptions.add((LinkOption) option);
        }
    }
    if (copyOptions.contains(StandardCopyOption.ATOMIC_MOVE)) {
        throw new AtomicMoveNotSupportedException(source.toString(), target.toString(), "Atomic move not supported");
    }
    final Map<String, Object> sourceAttributes = sourceFileSystem.readAttributes(sourceReal, "basic:isSymbolicLink,isDirectory,lastModifiedTime,lastAccessTime,creationTime", linkOptions.toArray(new LinkOption[linkOptions.size()]));
    if ((Boolean) sourceAttributes.getOrDefault("isSymbolicLink", false)) {
        throw new IOException("Copying of symbolic links is not supported.");
    }
    if (copyOptions.contains(StandardCopyOption.REPLACE_EXISTING)) {
        try {
            targetFileSystem.delete(targetReal);
        } catch (NoSuchFileException notFound) {
        // Does not exist - nothing to delete
        }
    } else {
        boolean exists;
        try {
            targetFileSystem.checkAccess(targetReal, EnumSet.noneOf(AccessMode.class));
            exists = true;
        } catch (IOException ioe) {
            exists = false;
        }
        if (exists) {
            throw new FileAlreadyExistsException(target.toString());
        }
    }
    if ((Boolean) sourceAttributes.getOrDefault("isDirectory", false)) {
        targetFileSystem.createDirectory(targetReal);
    } else {
        final Set<StandardOpenOption> readOptions = EnumSet.of(StandardOpenOption.READ);
        final Set<StandardOpenOption> writeOptions = EnumSet.of(StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW);
        try (SeekableByteChannel sourceChannel = sourceFileSystem.newByteChannel(sourceReal, readOptions);
            SeekableByteChannel targetChannel = targetFileSystem.newByteChannel(targetReal, writeOptions)) {
            final ByteBuffer buffer = ByteBuffer.allocateDirect(1 << 16);
            while (sourceChannel.read(buffer) != -1) {
                buffer.flip();
                while (buffer.hasRemaining()) {
                    targetChannel.write(buffer);
                }
                buffer.clear();
            }
        }
    }
    if (copyOptions.contains(StandardCopyOption.COPY_ATTRIBUTES)) {
        String[] basicMutableAttributes = { "lastModifiedTime", "lastAccessTime", "creationTime" };
        try {
            for (String key : basicMutableAttributes) {
                final Object value = sourceAttributes.get(key);
                if (value != null) {
                    targetFileSystem.setAttribute(targetReal, key, value);
                }
            }
        } catch (Throwable rootCause) {
            try {
                targetFileSystem.delete(targetReal);
            } catch (Throwable suppressed) {
                rootCause.addSuppressed(suppressed);
            }
            throw rootCause;
        }
    }
}
Also used : Path(java.nio.file.Path) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) StandardCopyOption(java.nio.file.StandardCopyOption) CopyOption(java.nio.file.CopyOption) LinkOption(java.nio.file.LinkOption) StandardOpenOption(java.nio.file.StandardOpenOption) NoSuchFileException(java.nio.file.NoSuchFileException) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) SeekableByteChannel(java.nio.channels.SeekableByteChannel) StandardCopyOption(java.nio.file.StandardCopyOption) AtomicMoveNotSupportedException(java.nio.file.AtomicMoveNotSupportedException) AccessMode(java.nio.file.AccessMode) HashSet(java.util.HashSet)

Aggregations

SeekableByteChannel (java.nio.channels.SeekableByteChannel)151 ByteBuffer (java.nio.ByteBuffer)72 Path (java.nio.file.Path)56 IOException (java.io.IOException)52 Test (org.junit.Test)41 InputStream (java.io.InputStream)17 ReadableByteChannel (java.nio.channels.ReadableByteChannel)13 NoSuchFileException (java.nio.file.NoSuchFileException)13 FileSystem (java.nio.file.FileSystem)12 StandardOpenOption (java.nio.file.StandardOpenOption)11 Test (org.testng.annotations.Test)9 WritableByteChannel (java.nio.channels.WritableByteChannel)8 OpenOption (java.nio.file.OpenOption)8 HashSet (java.util.HashSet)8 OutputStream (java.io.OutputStream)7 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6 File (java.io.File)6 CloudStorageFileSystem (com.google.cloud.storage.contrib.nio.CloudStorageFileSystem)5 ByteArrayInputStream (java.io.ByteArrayInputStream)5 URI (java.net.URI)5