Search in sources :

Example 46 with OpenOption

use of java.nio.file.OpenOption in project j2objc by google.

the class DefaultFileSystemProviderTest method test_newByteChannel.

@Test
public void test_newByteChannel() throws IOException {
    Set<OpenOption> set = new HashSet<OpenOption>();
    // When file doesn't exist
    try (SeekableByteChannel sbc = provider.newByteChannel(filesSetup.getTestPath(), set)) {
        fail();
    } catch (NoSuchFileException expected) {
        assertTrue(expected.getMessage().contains(filesSetup.getTestPath().toString()));
    }
    // File opens in READ mode by default. The channel is non writable by default.
    try (SeekableByteChannel sbc = provider.newByteChannel(filesSetup.getDataFilePath(), set)) {
        sbc.write(ByteBuffer.allocate(10));
        fail();
    } catch (NonWritableChannelException expected) {
    }
    // Read a file.
    try (SeekableByteChannel sbc = provider.newByteChannel(filesSetup.getDataFilePath(), set)) {
        ByteBuffer readBuffer = ByteBuffer.allocate(10);
        int bytesReadCount = sbc.read(readBuffer);
        String readData = new String(Arrays.copyOf(readBuffer.array(), bytesReadCount), "UTF-8");
        assertEquals(TEST_FILE_DATA, readData);
    }
}
Also used : SeekableByteChannel(java.nio.channels.SeekableByteChannel) OpenOption(java.nio.file.OpenOption) NoSuchFileException(java.nio.file.NoSuchFileException) NonWritableChannelException(java.nio.channels.NonWritableChannelException) ByteBuffer(java.nio.ByteBuffer) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 47 with OpenOption

use of java.nio.file.OpenOption in project j2objc by google.

the class DefaultFileSystemProvider2Test method test_newFileChannel_withFileAttributes.

/* J2ObjC changed: junitparams not supported
    @SuppressWarnings("unused")
    private Object[] parameters_test_newFileChannel_NoSuchFileException() {
        return new Object[] {
                new Object[] { EnumSet.noneOf(StandardOpenOption.class) },
                new Object[] { EnumSet.of(READ) },
                new Object[] { EnumSet.of(WRITE) },
                new Object[] { EnumSet.of(TRUNCATE_EXISTING) },
                new Object[] { EnumSet.of(APPEND) },
                new Object[] { EnumSet.of(CREATE, READ) },
                new Object[] { EnumSet.of(CREATE, TRUNCATE_EXISTING) },
                new Object[] { EnumSet.of(CREATE, READ) },
        };
    }
     */
@Test
public void test_newFileChannel_withFileAttributes() throws IOException {
    Set<OpenOption> openOptions = new HashSet<>();
    FileTime fileTime = FileTime.fromMillis(System.currentTimeMillis());
    Files.setAttribute(filesSetup.getDataFilePath(), "basic:lastModifiedTime", fileTime);
    FileAttribute<FileTime> unsupportedAttr = new MockFileAttribute<>("basic:lastModifiedTime", fileTime);
    Set<PosixFilePermission> perm = PosixFilePermissions.fromString("rwx------");
    FileAttribute<Set<PosixFilePermission>> supportedAttr = PosixFilePermissions.asFileAttribute(perm);
    try {
        // When file doesn't exists and with OpenOption CREATE & WRITE.
        openOptions.clear();
        openOptions.add(CREATE);
        openOptions.add(WRITE);
        provider.newFileChannel(filesSetup.getTestPath(), openOptions, unsupportedAttr);
        fail();
    } catch (UnsupportedOperationException expected) {
    } finally {
        filesSetup.reset();
        openOptions.clear();
    }
    try {
        // With OpenOption CREATE & WRITE.
        openOptions.clear();
        openOptions.add(CREATE);
        openOptions.add(WRITE);
        provider.newFileChannel(filesSetup.getTestPath(), openOptions, supportedAttr);
        assertEquals(supportedAttr.value(), Files.getAttribute(filesSetup.getTestPath(), supportedAttr.name()));
    } finally {
        filesSetup.reset();
        openOptions.clear();
    }
    // When file exists.
    try {
        provider.newFileChannel(filesSetup.getDataFilePath(), openOptions, unsupportedAttr);
        fail();
    } catch (UnsupportedOperationException expected) {
    } finally {
        filesSetup.reset();
        openOptions.clear();
    }
    // When file exists. No change in permissions.
    try {
        Set<PosixFilePermission> originalPermissions = (Set<PosixFilePermission>) Files.getAttribute(filesSetup.getDataFilePath(), supportedAttr.name());
        FileChannel fc = provider.newFileChannel(filesSetup.getDataFilePath(), openOptions, supportedAttr);
        assertEquals(originalPermissions, Files.getAttribute(filesSetup.getDataFilePath(), supportedAttr.name()));
    } finally {
        filesSetup.reset();
        openOptions.clear();
    }
}
Also used : StandardOpenOption(java.nio.file.StandardOpenOption) OpenOption(java.nio.file.OpenOption) EnumSet(java.util.EnumSet) Set(java.util.Set) HashSet(java.util.HashSet) FileChannel(java.nio.channels.FileChannel) FileTime(java.nio.file.attribute.FileTime) PosixFilePermission(java.nio.file.attribute.PosixFilePermission) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 48 with OpenOption

use of java.nio.file.OpenOption in project winery by eclipse.

the class Generator method updateFilesRecursively.

/**
 * Iterates recursively through all the files in the project working directory and tries to replace the global
 * placeholders.
 *
 * @param folderOrFile to start with
 */
private void updateFilesRecursively(File folderOrFile) {
    if (folderOrFile.isFile()) {
        if (folderOrFile.getAbsolutePath().endsWith(".jar")) {
            return;
        }
        Generator.LOGGER.trace("Updating file " + folderOrFile);
        try {
            // Read file and replace placeholders
            Charset cs = Charset.defaultCharset();
            List<String> lines = new ArrayList<>();
            for (String line : Files.readAllLines(folderOrFile.toPath(), cs)) {
                line = line.replaceAll(Generator.PLACEHOLDER_CLASS_NAME, this.name);
                line = line.replaceAll(Generator.PLACEHOLDER_JAVA_PACKAGE, this.javaPackage);
                line = line.replaceAll(Generator.PLACEHOLDER_NAMESPACE, this.namespace);
                line = line.replaceAll(Generator.PLACEHOLDER_IA_ARTIFACT_TEMPLATE_UPLOAD_URL, this.iaArtifactTemplateUploadUrl.toString());
                lines.add(line);
            }
            // Write file
            OpenOption[] options = new OpenOption[] { StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING };
            Files.write(folderOrFile.toPath(), lines, cs, options);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        Generator.LOGGER.trace("Updating folder " + folderOrFile);
        for (File childFile : folderOrFile.listFiles()) {
            this.updateFilesRecursively(childFile);
        }
    }
}
Also used : OpenOption(java.nio.file.OpenOption) StandardOpenOption(java.nio.file.StandardOpenOption) ArrayList(java.util.ArrayList) Charset(java.nio.charset.Charset) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) File(java.io.File)

Example 49 with OpenOption

use of java.nio.file.OpenOption in project n2a by frothga.

the class SshFileSystemProvider method newOutputStream.

public OutputStream newOutputStream(Path path, OpenOption... options) throws IOException {
    boolean create = true;
    boolean createNew = false;
    boolean truncate = true;
    boolean append = false;
    if (options != null && options.length > 0) {
        Set<OpenOption> optionSet = new HashSet<OpenOption>(Arrays.asList(options));
        create = optionSet.contains(StandardOpenOption.CREATE);
        createNew = optionSet.contains(StandardOpenOption.CREATE_NEW);
        truncate = optionSet.contains(StandardOpenOption.TRUNCATE_EXISTING);
        append = optionSet.contains(StandardOpenOption.APPEND);
        if (optionSet.contains(StandardOpenOption.READ))
            throw new IllegalArgumentException();
        if (optionSet.contains(StandardOpenOption.DELETE_ON_CLOSE))
            throw new UnsupportedOperationException();
    }
    SshPath A = (SshPath) path;
    if (!create || createNew) {
        try {
            checkAccess(A);
            if (createNew)
                throw new FileAlreadyExistsException(A.toString());
        } catch (NoSuchFileException e) {
            if (!create && !createNew)
                throw e;
            checkAccess(A.getParent());
        }
    } else {
        checkAccess(A.getParent());
    }
    try {
        // cat performs as well or better than sftp put on files up to 1M.
        // For small files cat is even better, because it has almost no protocol setup.
        List<String> args = new ArrayList<String>();
        args.add("cat");
        if (append && !truncate)
            args.add(">>");
        else
            args.add(">");
        args.add(A.quote());
        AnyProcess proc = A.fileSystem.connection.build(args).start();
        OutputStream stream = proc.getOutputStream();
        return new // Wrap the stream, so that when it is closed the channel is closed as well.
        OutputStream() {

            public void close() throws IOException {
                // Causes cat command to exit.
                stream.close();
                try {
                    proc.waitFor(1, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                }
                proc.close();
            }

            public void write(int b) throws IOException {
                stream.write(b);
            }

            public void write(byte[] b, int off, int len) throws IOException {
                stream.write(b, off, len);
            }

            public void flush() throws IOException {
                stream.flush();
            }
        };
    } catch (Exception e) {
        throw new IOException(e);
    }
}
Also used : FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) AnyProcess(gov.sandia.n2a.host.Host.AnyProcess) OutputStream(java.io.OutputStream) NoSuchFileException(java.nio.file.NoSuchFileException) ArrayList(java.util.ArrayList) IOException(java.io.IOException) NoSuchFileException(java.nio.file.NoSuchFileException) SftpException(com.jcraft.jsch.SftpException) NonWritableChannelException(java.nio.channels.NonWritableChannelException) NonReadableChannelException(java.nio.channels.NonReadableChannelException) FileSystemAlreadyExistsException(java.nio.file.FileSystemAlreadyExistsException) JSchException(com.jcraft.jsch.JSchException) AccessDeniedException(java.nio.file.AccessDeniedException) NoSuchElementException(java.util.NoSuchElementException) FileSystemNotFoundException(java.nio.file.FileSystemNotFoundException) IOException(java.io.IOException) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) StandardOpenOption(java.nio.file.StandardOpenOption) OpenOption(java.nio.file.OpenOption) HashSet(java.util.HashSet)

Aggregations

OpenOption (java.nio.file.OpenOption)49 StandardOpenOption (java.nio.file.StandardOpenOption)30 IOException (java.io.IOException)19 HashSet (java.util.HashSet)17 Test (org.junit.Test)17 Path (java.nio.file.Path)15 File (java.io.File)13 FileChannel (java.nio.channels.FileChannel)9 FileIO (org.apache.ignite.internal.processors.cache.persistence.file.FileIO)8 FileIODecorator (org.apache.ignite.internal.processors.cache.persistence.file.FileIODecorator)8 ByteBuffer (java.nio.ByteBuffer)7 SeekableByteChannel (java.nio.channels.SeekableByteChannel)7 NoSuchFileException (java.nio.file.NoSuchFileException)7 FileIOFactory (org.apache.ignite.internal.processors.cache.persistence.file.FileIOFactory)7 RandomAccessFileIOFactory (org.apache.ignite.internal.processors.cache.persistence.file.RandomAccessFileIOFactory)7 GridCommonAbstractTest (org.apache.ignite.testframework.junits.common.GridCommonAbstractTest)7 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)6 InputStream (java.io.InputStream)5 RandomAccessFile (java.io.RandomAccessFile)5 WritableByteChannel (java.nio.channels.WritableByteChannel)5