Search in sources :

Example 21 with OpenOption

use of java.nio.file.OpenOption 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 22 with OpenOption

use of java.nio.file.OpenOption in project graal by oracle.

the class TruffleFileTest method testEmptyPath.

/**
 * Test checking that a {@link FileSystem} method for a non path operation is never called for
 * an empty path.
 */
@Test
public void testEmptyPath() throws Exception {
    setupEnv(Context.newBuilder().allowIO(true).fileSystem(new EmptyPathTestFs()).build());
    TruffleFile file = languageEnv.getInternalTruffleFile("");
    TruffleFile otherFile = languageEnv.getInternalTruffleFile("other");
    Map<Type, Object> defaultParameterValues = new HashMap<>();
    defaultParameterValues.put(int.class, 0);
    defaultParameterValues.put(String.class, "");
    defaultParameterValues.put(TruffleFile.class, otherFile);
    defaultParameterValues.put(Object.class, otherFile);
    defaultParameterValues.put(Set.class, Collections.emptySet());
    defaultParameterValues.put(Charset.class, UTF_8);
    defaultParameterValues.put(OpenOption[].class, new OpenOption[0]);
    defaultParameterValues.put(LinkOption[].class, new LinkOption[0]);
    defaultParameterValues.put(CopyOption[].class, new CopyOption[0]);
    defaultParameterValues.put(FileVisitOption[].class, new FileVisitOption[0]);
    defaultParameterValues.put(FileAttribute[].class, new FileAttribute<?>[0]);
    defaultParameterValues.put(FileTime.class, FileTime.fromMillis(System.currentTimeMillis()));
    defaultParameterValues.put(TruffleFile.AttributeDescriptor.class, TruffleFile.SIZE);
    defaultParameterValues.put(TruffleFile.class.getMethod("getAttributes", Collection.class, LinkOption[].class).getGenericParameterTypes()[0], Collections.singleton(TruffleFile.SIZE));
    defaultParameterValues.put(FileVisitor.class, new FileVisitor<TruffleFile>() {

        @Override
        public FileVisitResult preVisitDirectory(TruffleFile t, BasicFileAttributes bfa) throws IOException {
            return FileVisitResult.TERMINATE;
        }

        @Override
        public FileVisitResult visitFile(TruffleFile t, BasicFileAttributes bfa) throws IOException {
            return FileVisitResult.TERMINATE;
        }

        @Override
        public FileVisitResult visitFileFailed(TruffleFile t, IOException ioe) throws IOException {
            return FileVisitResult.TERMINATE;
        }

        @Override
        public FileVisitResult postVisitDirectory(TruffleFile t, IOException ioe) throws IOException {
            return FileVisitResult.TERMINATE;
        }
    });
    Set<Method> untestedMethods = new HashSet<>();
    for (Method m : EmptyPathTestFs.class.getMethods()) {
        if (m.isDefault()) {
            System.out.println(m.getName());
        }
    }
    nextMethod: for (Method m : TruffleFile.class.getDeclaredMethods()) {
        if ((m.getModifiers() & Modifier.PUBLIC) == Modifier.PUBLIC) {
            Type[] paramTypes = m.getGenericParameterTypes();
            Object[] params = new Object[paramTypes.length];
            for (int i = 0; i < paramTypes.length; i++) {
                Type paramType = paramTypes[i];
                Object param = defaultParameterValues.get(paramType);
                if (param == null) {
                    param = defaultParameterValues.get(erase(paramType));
                }
                if (param == null) {
                    untestedMethods.add(m);
                    continue nextMethod;
                }
                params[i] = param;
            }
            try {
                m.invoke(file, params);
            } catch (InvocationTargetException e) {
                if (!(e.getCause() instanceof NoSuchFileException)) {
                    throw new AssertionError("Unexpected exception.", e);
                }
            } catch (ReflectiveOperationException e) {
                throw new AssertionError("Unexpected exception.", e);
            }
        }
    }
    assertTrue("Failed to check methods: " + untestedMethods.stream().map(Method::getName).collect(Collectors.joining(", ")), untestedMethods.isEmpty());
}
Also used : CopyOption(java.nio.file.CopyOption) HashMap(java.util.HashMap) LinkOption(java.nio.file.LinkOption) FileVisitOption(java.nio.file.FileVisitOption) NoSuchFileException(java.nio.file.NoSuchFileException) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) StandardOpenOption(java.nio.file.StandardOpenOption) OpenOption(java.nio.file.OpenOption) GenericArrayType(java.lang.reflect.GenericArrayType) Type(java.lang.reflect.Type) ParameterizedType(java.lang.reflect.ParameterizedType) TruffleFile(com.oracle.truffle.api.TruffleFile) Collection(java.util.Collection) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) FileAttribute(java.nio.file.attribute.FileAttribute) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 23 with OpenOption

use of java.nio.file.OpenOption in project cryptofs by cryptomator.

the class CryptoFileSystemProviderTest method testNewByteChannelDelegatesToFileSystem.

@Test
public void testNewByteChannelDelegatesToFileSystem() throws IOException {
    @SuppressWarnings("unchecked") Set<OpenOption> options = mock(Set.class);
    FileChannel channel = mock(FileChannel.class);
    when(cryptoFileSystem.newFileChannel(cryptoPath, options)).thenReturn(channel);
    ByteChannel result = inTest.newByteChannel(cryptoPath, options);
    Assertions.assertSame(channel, result);
}
Also used : OpenOption(java.nio.file.OpenOption) ByteChannel(java.nio.channels.ByteChannel) AsynchronousFileChannel(java.nio.channels.AsynchronousFileChannel) AsyncDelegatingFileChannel(org.cryptomator.cryptofs.ch.AsyncDelegatingFileChannel) FileChannel(java.nio.channels.FileChannel) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 24 with OpenOption

use of java.nio.file.OpenOption in project sis by apache.

the class ChannelFactory method prepare.

/**
 * Returns a byte channel factory without wrappers, or {@code null} if unsupported.
 * This method performs the same work than {@linkplain #prepare(Object, boolean, String,
 * OpenOption[], UnaryOperator, UnaryOperator) above method}, but without wrappers.
 *
 * @param  storage         the stream or the file to open, or {@code null}.
 * @param  allowWriteOnly  whether to allow wrapping {@link WritableByteChannel} and {@link OutputStream}.
 * @param  encoding        if the input is an encoded URL, the character encoding (normally {@code "UTF-8"}).
 * @param  options         the options to use for creating a new byte channel. Can be null or empty for read-only.
 * @return the channel factory for the given input, or {@code null} if the given input is of unknown type.
 * @throws IOException if an error occurred while processing the given input.
 */
private static ChannelFactory prepare(Object storage, final boolean allowWriteOnly, final String encoding, OpenOption[] options) throws IOException {
    /*
         * Unconditionally verify the options (unless 'allowWriteOnly' is true),
         * even if we may not use them.
         */
    final Set<OpenOption> optionSet;
    if (options == null || options.length == 0) {
        optionSet = Collections.singleton(StandardOpenOption.READ);
    } else {
        optionSet = new HashSet<>(Arrays.asList(options));
        optionSet.add(StandardOpenOption.READ);
        if (!allowWriteOnly && optionSet.removeAll(ILLEGAL_OPTIONS)) {
            throw new IllegalArgumentException(Errors.format(Errors.Keys.IllegalArgumentValue_2, "options", Arrays.toString(options)));
        }
    }
    /*
         * Check for inputs that are already readable channels or input streams.
         * Note that Channels.newChannel(InputStream) checks for instances of FileInputStream in order to delegate
         * to its getChannel() method, but only if the input stream type is exactly FileInputStream, not a subtype.
         * If Apache SIS defines its own FileInputStream subclass someday, we may need to add a special case here.
         */
    if (storage instanceof ReadableByteChannel || (allowWriteOnly && storage instanceof WritableByteChannel)) {
        return new Stream((Channel) storage);
    } else if (storage instanceof InputStream) {
        return new Stream(Channels.newChannel((InputStream) storage));
    } else if (allowWriteOnly && storage instanceof OutputStream) {
        return new Stream(Channels.newChannel((OutputStream) storage));
    }
    /*
         * In the following cases, we will try hard to convert to Path objects before to fallback
         * on File, URL or URI, because only Path instances allow us to use the given OpenOptions.
         */
    if (storage instanceof URL) {
        try {
            storage = IOUtilities.toPath((URL) storage, encoding);
        } catch (IOException e) {
            /*
                 * This is normal if the URL uses HTTP or FTP protocol for instance. Log the exception at FINE
                 * level without stack trace. We will open the channel later using the URL instead of the Path.
                 */
            recoverableException(e);
        }
    } else if (storage instanceof URI) {
        /*
             * If the user gave us a URI, try to convert to a Path before to fallback to URL, in order to be
             * able to use the given OpenOptions.  Note that the conversion to Path is likely to fail if the
             * URL uses HTTP or FTP protocols, because JDK7 does not provide file systems for them by default.
             */
        final URI uri = (URI) storage;
        if (!uri.isAbsolute()) {
            /*
                 * All methods invoked in this block throws IllegalArgumentException if the URI has no scheme,
                 * so we are better to check now and provide a more appropriate exception for this method.
                 */
            throw new IOException(Resources.format(Resources.Keys.MissingSchemeInURI_1, uri));
        } else
            try {
                storage = Paths.get(uri);
            } catch (IllegalArgumentException | FileSystemNotFoundException e) {
                try {
                    storage = uri.toURL();
                } catch (MalformedURLException ioe) {
                    ioe.addSuppressed(e);
                    throw ioe;
                }
                /*
                 * We have been able to convert to URL, but the given OpenOptions may not be used.
                 * Log the exception at FINE level without stack trace, because the exception is
                 * probably a normal behavior in this context.
                 */
                recoverableException(e);
            }
    } else {
        if (storage instanceof CharSequence) {
            // Needs to be before the check for File or URL.
            storage = IOUtilities.toFileOrURL(storage.toString(), encoding);
        }
        /*
             * If the input is a File or a CharSequence that we have been able to convert to a File,
             * try to convert to a Path in order to be able to use the OpenOptions. Only if we fail
             * to convert to a Path (which is unlikely), we will use directly the File.
             */
        if (storage instanceof File) {
            final File file = (File) storage;
            try {
                storage = file.toPath();
            } catch (final InvalidPathException e) {
                /*
                     * Unlikely to happen. But if it happens anyway, try to open the channel in a
                     * way less surprising for the user (closer to the object he has specified).
                     */
                if (file.isFile()) {
                    return new Fallback(file, e);
                }
            }
        }
    }
    /*
         * One last check for URL. The URL may be either the given input if we have not been able
         * to convert it to a Path, or a URI, File or CharSequence input converted to URL. Do not
         * try to convert the URL to a Path, because this has already been tried before this point.
         */
    if (storage instanceof URL) {
        final URL file = (URL) storage;
        return new ChannelFactory() {

            @Override
            public ReadableByteChannel readable(String filename, StoreListeners listeners) throws IOException {
                return Channels.newChannel(file.openStream());
            }

            @Override
            public WritableByteChannel writable(String filename, StoreListeners listeners) throws IOException {
                return Channels.newChannel(file.openConnection().getOutputStream());
            }
        };
    }
    /*
         * Handle path to directory as an unsupported input. Attempts to read bytes from that channel would cause an
         * IOException to be thrown. On Java 10, that IOException does not occur at channel openning time but rather
         * at reading time. See https://bugs.openjdk.java.net/browse/JDK-8080629 for more information.
         *
         * If the file does not exist, we let NoSuchFileException to be thrown by the code below because non-existant
         * file is probably an error. This is not the same situation than a directory, which can not be opened by this
         * class but may be opened by some specialized DataStore implementations.
         */
    if (storage instanceof Path) {
        final Path path = (Path) storage;
        if (!Files.isDirectory(path)) {
            return new ChannelFactory() {

                @Override
                public ReadableByteChannel readable(String filename, StoreListeners listeners) throws IOException {
                    return Files.newByteChannel(path, optionSet);
                }

                @Override
                public WritableByteChannel writable(String filename, StoreListeners listeners) throws IOException {
                    return Files.newByteChannel(path, optionSet);
                }
            };
        }
    }
    return null;
}
Also used : Path(java.nio.file.Path) ReadableByteChannel(java.nio.channels.ReadableByteChannel) MalformedURLException(java.net.MalformedURLException) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) WritableByteChannel(java.nio.channels.WritableByteChannel) IOException(java.io.IOException) URI(java.net.URI) URL(java.net.URL) InvalidPathException(java.nio.file.InvalidPathException) OpenOption(java.nio.file.OpenOption) StandardOpenOption(java.nio.file.StandardOpenOption) StoreListeners(org.apache.sis.storage.event.StoreListeners) FileSystemNotFoundException(java.nio.file.FileSystemNotFoundException) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) File(java.io.File)

Example 25 with OpenOption

use of java.nio.file.OpenOption in project activemq-artemis by apache.

the class FileBasedNodeManager method useActivationSequenceChannel.

/**
 * If {@code createIfNotExists} and activation sequence file doesn't exist yet, it returns {@code null},
 * otherwise it opens it.<br>
 * if {@code !createIfNotExists} it just open to create it.
 */
private FileChannel useActivationSequenceChannel(final boolean createIfNotExists) throws IOException {
    FileChannel channel = this.activationSequenceChannel;
    if (channel != null) {
        return channel;
    }
    final OpenOption[] openOptions;
    if (!createIfNotExists) {
        if (!Files.exists(activationSequencePath)) {
            return null;
        }
        openOptions = new OpenOption[] { READ, WRITE };
    } else {
        openOptions = new OpenOption[] { READ, WRITE, CREATE };
    }
    channel = FileChannel.open(activationSequencePath, openOptions);
    activationSequenceChannel = channel;
    return channel;
}
Also used : OpenOption(java.nio.file.OpenOption) FileChannel(java.nio.channels.FileChannel)

Aggregations

OpenOption (java.nio.file.OpenOption)99 StandardOpenOption (java.nio.file.StandardOpenOption)73 IOException (java.io.IOException)40 HashSet (java.util.HashSet)32 Path (java.nio.file.Path)30 File (java.io.File)19 FileChannel (java.nio.channels.FileChannel)18 Test (org.junit.Test)18 NoSuchFileException (java.nio.file.NoSuchFileException)16 OutputStream (java.io.OutputStream)12 ArrayList (java.util.ArrayList)11 InputStream (java.io.InputStream)10 SeekableByteChannel (java.nio.channels.SeekableByteChannel)10 FileIO (org.apache.ignite.internal.processors.cache.persistence.file.FileIO)10 FileIODecorator (org.apache.ignite.internal.processors.cache.persistence.file.FileIODecorator)10 ByteBuffer (java.nio.ByteBuffer)9 GridCommonAbstractTest (org.apache.ignite.testframework.junits.common.GridCommonAbstractTest)9 FileIOFactory (org.apache.ignite.internal.processors.cache.persistence.file.FileIOFactory)8 RandomAccessFileIOFactory (org.apache.ignite.internal.processors.cache.persistence.file.RandomAccessFileIOFactory)8 Set (java.util.Set)7