Java Examples for java.nio.file.OpenOption

The following java examples will help you to understand the usage of java.nio.file.OpenOption. These source code samples are taken from different open source projects.

Example 1
Project: Advanced-Logon-Editor-master  File: FileWriter.java View source code
protected static boolean writeFile(Path file, List<String> lines, boolean append) {
    assert (file != null) && (lines != null) && (lines.size() > 0);
    OpenOption[] options;
    Charset charset = Charset.defaultCharset();
    if (append) {
        options = new OpenOption[] { StandardOpenOption.WRITE, StandardOpenOption.APPEND, StandardOpenOption.CREATE };
    } else {
        options = new OpenOption[] { StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING };
    }
    try (BufferedWriter writer = Files.newBufferedWriter(file, charset, options)) {
        String separator = System.getProperty("line.separator");
        if ((lines == null) || (lines.size() <= 0)) {
            writer.write("");
        } else {
            for (String line : lines) {
                writer.write(line + separator);
            }
        }
        writer.flush();
        writer.close();
    } catch (IOException e) {
        return false;
    }
    assert FileUtil.control(file);
    return true;
}
Example 2
Project: datakernel-master  File: AsyncFile.java View source code
/**
	 * Reads all sequence of bytes from this channel into the given buffer.
	 *
	 * @param eventloop event loop in which a file will be used
	 * @param executor  @param path     the  path of the file to read
	 * @param callback  which will be called after complete
	 */
public static void readFile(Eventloop eventloop, ExecutorService executor, Path path, final ResultCallback<ByteBuf> callback) {
    open(eventloop, executor, path, new OpenOption[] { READ }, new ForwardingResultCallback<AsyncFile>(callback) {

        @Override
        public void onResult(final AsyncFile file) {
            file.readFully(new ResultCallback<ByteBuf>() {

                @Override
                public void onResult(ByteBuf buf) {
                    file.close(IgnoreCompletionCallback.create());
                    callback.setResult(buf);
                }

                @Override
                public void onException(Exception e) {
                    file.close(IgnoreCompletionCallback.create());
                    callback.setException(e);
                }
            });
        }
    });
}
Example 3
Project: drools-wb-master  File: DRLTextEditorServiceImplTest.java View source code
@Test
public void testCreateAlreadyExisting() throws URISyntaxException {
    when(ioService.exists(any(org.uberfire.java.nio.file.Path.class))).thenReturn(true);
    try {
        drlService.create(path2, filename, "", "");
        fail("FileAlreadyExistsException was not thrown when expected!");
    } catch (FileAlreadyExistsException faee) {
    }
    verify(ioService, never()).write(any(org.uberfire.java.nio.file.Path.class), anyString(), any(OpenOption.class));
}
Example 4
Project: neembuu-uploader-master  File: ClassRus.java View source code
@Override
public SeekableByteChannel p(String name, OpenOption... openOptions) throws IOException {
    //create is ignored
    OpenOption[] whiteList = { READ };
    for (OpenOption openOption : openOptions) {
        boolean clean = false;
        INNER: for (OpenOption whiteOpt : whiteList) {
            if (openOption == whiteOpt) {
                clean = true;
                break INNER;
            }
        }
        if (!clean)
            throw new IOException("Not supported " + openOption);
    }
    final String v = v(name);
    SeekableByteChannel_wrap sbc = new SeekableByteChannel_wrap(v);
    return sbc;
}
Example 5
Project: wb-master  File: DRLTextEditorServiceImplTest.java View source code
@Test
public void testCreateAlreadyExisting() throws URISyntaxException {
    when(ioService.exists(any(org.uberfire.java.nio.file.Path.class))).thenReturn(true);
    try {
        drlService.create(path2, filename, "", "");
        fail("FileAlreadyExistsException was not thrown when expected!");
    } catch (FileAlreadyExistsException faee) {
    }
    verify(ioService, never()).write(any(org.uberfire.java.nio.file.Path.class), anyString(), any(OpenOption.class));
}
Example 6
Project: divconq-master  File: AsyncHashWork.java View source code
@Override
public void run(final TaskRun run) {
    run.info(0, "AsyncHashTask at running in thread: " + Thread.currentThread().getName());
    RecordStruct params = run.getTask().getParams();
    if (params == null) {
        run.error(1, "Unable to Greet, missing params structure.");
        run.complete();
        return;
    }
    String name = params.getFieldAsString("Path");
    if (StringUtil.isEmpty(name)) {
        run.error(1, "Unable to Greet, missing Path param.");
        run.complete();
        return;
    }
    final Path path = Paths.get(name);
    final ByteBuffer buf = ByteBuffer.allocate(64 * 1024);
    AsynchronousFileChannel sbc = null;
    try {
        Set<OpenOption> opts = new HashSet<>();
        opts.add(StandardOpenOption.READ);
        sbc = AsynchronousFileChannel.open(path, opts, Hub.instance.getWorkPool());
    } catch (IOException x) {
        run.error(1, "Unable to open file: " + x);
    }
    sbc.read(buf, 0, sbc, new CompletionHandler<Integer, AsynchronousFileChannel>() {

        protected MessageDigest md = null;

        protected int pos = 0;

        @Override
        public void completed(Integer result, AsynchronousFileChannel sbc) {
            run.info(0, "A) AsyncHashTask completed after read in context: " + OperationContext.get().getOpId());
            // TODO review what is intended and rework
            //run.thawContext();
            run.info(0, "B) AsyncHashTask completed after read in context: " + OperationContext.get().getOpId());
            run.info(0, "C) AsyncHashTask completed after read in thread: " + Thread.currentThread().getName());
            if (this.md == null) {
                try {
                    this.md = MessageDigest.getInstance("SHA-256");
                } catch (NoSuchAlgorithmException x) {
                    run.error(1, "Unable to create digest object: " + x);
                    try {
                        sbc.close();
                    } catch (IOException x2) {
                    }
                    run.complete();
                    return;
                }
            }
            if (result == -1) {
                try {
                    sbc.close();
                } catch (IOException x) {
                }
                String sha256 = HexUtil.bufferToHex(this.md.digest());
                run.info(0, "Hash of " + path + " is " + sha256);
                run.setResult(new RecordStruct(new FieldStruct("Hash", sha256)));
                run.complete();
                return;
            }
            if (result > 0) {
                buf.flip();
                this.md.update(buf);
                this.pos += result;
            }
            buf.clear();
            sbc.read(buf, this.pos, sbc, this);
        }

        @Override
        public void failed(Throwable x, AsynchronousFileChannel sbc) {
            run.info(0, "A) AsyncHashTask failed after read in context: " + OperationContext.get().getOpId());
            // TODO review what is intended and rework
            //run.thawContext();
            run.info(0, "B) AsyncHashTask failed after read in context: " + OperationContext.get().getOpId());
            run.info(0, "C) AsyncHashTask failed after read in thread: " + Thread.currentThread().getName());
            run.error(1, "Async hash task failed to read file: " + x);
            try {
                sbc.close();
            } catch (IOException x2) {
            }
            run.complete();
        }
    });
}
Example 7
Project: Giraffe-master  File: FileSystemCRUDTest.java View source code
@Test
public void createsDeleteOnClose() throws IOException {
    OpenOption[] options = { StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE };
    Path file = generateUnusedPath(getTestPath("delete_on_close.txt"));
    try (SeekableByteChannel ch = Files.newByteChannel(file, options)) {
        assertTrue(msg(file, "does not exist"), Files.exists(file));
    }
    assertTrue(msg(file, "exists"), Files.notExists(file));
}
Example 8
Project: guvnor-master  File: ArchiverTest.java View source code
@Before
public void setUp() throws Exception {
    final SimpleFileSystemProvider simpleFileSystemProvider = new SimpleFileSystemProvider();
    simpleFileSystemProvider.forceAsDefault();
    ioService = spy(new MockIOService() {

        @Override
        public Path get(URI uri) throws IllegalArgumentException, FileSystemNotFoundException, SecurityException {
            return simpleFileSystemProvider.getPath(uri);
        }

        @Override
        public InputStream newInputStream(Path path, OpenOption... openOptions) throws IllegalArgumentException, NoSuchFileException, UnsupportedOperationException, IOException, SecurityException {
            return getClass().getResourceAsStream(path.toString().substring(path.toString().indexOf("test-classes") + "test-classes".length()));
        }
    });
    archiver = new Archiver(ioService);
}
Example 9
Project: javafs-master  File: FuseFileSystemProvider.java View source code
@Override
protected int create(String path, long mode, StructFuseFileInfo info) {
    try {
        final Set<OpenOption> options = fileInfoToOpenOptions(info);
        options.add(StandardOpenOption.CREATE);
        final SeekableByteChannel channel = fsp.newByteChannel(path(path), options);
        final long fh = fileHandle.incrementAndGet();
        openFiles.put(fh, channel);
        info.fh(fh);
        return 0;
    } catch (Exception e) {
        return -errno(e);
    }
}
Example 10
Project: niolex-common-utils-master  File: FileChannelUtilTest.java View source code
@Test
public void testReadFromPosition() throws Exception {
    Set<OpenOption> set = new HashSet<OpenOption>();
    set.add(StandardOpenOption.CREATE);
    set.add(StandardOpenOption.TRUNCATE_EXISTING);
    set.add(StandardOpenOption.READ);
    set.add(StandardOpenOption.WRITE);
    set.add(StandardOpenOption.DSYNC);
    set.add(StandardOpenOption.DELETE_ON_CLOSE);
    FileAttribute<?>[] NO_ATTRIBUTES = new FileAttribute[0];
    Path path = FileSystems.getDefault().getPath(PREX, "tmp.f");
    FileChannel channel = FileChannel.open(path, set, NO_ATTRIBUTES);
    String txt = "This is used to test text writing.";
    int s = writeToPosition(channel, ByteBuffer.wrap(txt.getBytes()), 0);
    assertEquals(34, s);
    ByteBuffer buf = ByteBuffer.allocate(34);
    int m = readFromPosition(channel, buf, 0);
    assertEquals(34, m);
    String ret = new String(buf.array());
    assertEquals(txt, ret);
    buf.clear();
    int l = readFromPosition(channel, buf, 3);
    assertEquals(31, l);
    String tic = new String(buf.array(), 0, buf.position());
    assertEquals(txt.substring(3), tic);
}
Example 11
Project: ReloadablePropertiesAnnotation-master  File: UpdatingReloadablePropertyPostProcessorIntTest.java View source code
@After
public void cleanUp() throws Exception {
    this.loadedProperties.setProperty("dynamicProperty.stringValue", "Injected String Value");
    this.loadedProperties.setProperty("dynamicProperty.baseStringValue", "World");
    this.loadedProperties.setProperty("dynamicProperty.compoiteStringValue", "Hello, ${dynamicProperty.baseStringValue}!");
    final OutputStream newOutputStream = Files.newOutputStream(new File(DIR + PROPERTIES).toPath(), new OpenOption[] {});
    this.loadedProperties.store(newOutputStream, null);
    // this is a hack -> I need to find an alternative
    Thread.sleep(500);
    assertThat(this.bean.getStringProperty(), is("Injected String Value"));
    assertThat(this.bean.getCompositeStringProperty(), is("Hello, World!"));
}
Example 12
Project: sft-master  File: ReadOnlyRootedFileSystemProvider.java View source code
@Override
public AsynchronousFileChannel newAsynchronousFileChannel(final Path path, final Set<? extends OpenOption> options, final ExecutorService executor, final FileAttribute<?>... attrs) throws IOException {
    for (final OpenOption o : options) {
        if (!StandardOpenOption.READ.equals(o)) {
            throw new IOException("ReadOnly FileSystem");
        }
    }
    final AsynchronousFileChannel chan = super.newAsynchronousFileChannel(path, options, executor, attrs);
    return new ReadOnlyAsynchronousFileChannel(chan);
}
Example 13
Project: sftpserver-master  File: ReadOnlyRootedFileSystemProvider.java View source code
@Override
public AsynchronousFileChannel newAsynchronousFileChannel(final Path path, final Set<? extends OpenOption> options, final ExecutorService executor, final FileAttribute<?>... attrs) throws IOException {
    for (final OpenOption o : options) {
        if (!StandardOpenOption.READ.equals(o)) {
            throw new IOException("ReadOnly FileSystem");
        }
    }
    final AsynchronousFileChannel chan = super.newAsynchronousFileChannel(path, options, executor, attrs);
    return new ReadOnlyAsynchronousFileChannel(chan);
}
Example 14
Project: uberfire-master  File: JGitFileSystemProvider.java View source code
@Override
public OutputStream newOutputStream(final Path path, final OpenOption... options) throws IllegalArgumentException, UnsupportedOperationException, IOException, SecurityException {
    checkNotNull("path", path);
    final JGitPathImpl gPath = toPathImpl(path);
    final Pair<PathType, ObjectId> result = checkPath(gPath.getFileSystem().gitRepo(), gPath.getRefTree(), gPath.getPath());
    if (result.getK1().equals(PathType.DIRECTORY)) {
        throw new NotDirectoryException(path.toString());
    }
    try {
        final File file = File.createTempFile("gitz", "woot");
        return new FilterOutputStream(new FileOutputStream(file)) {

            @Override
            public void close() throws java.io.IOException {
                super.close();
                commit(gPath, buildCommitInfo("{" + toPathImpl(path).getPath() + "}", Arrays.asList(options)), new DefaultCommitContent(new HashMap<String, File>() {

                    {
                        put(gPath.getPath(), file);
                    }
                }));
            }
        };
    } catch (java.io.IOException e) {
        throw new IOException("Could not create file or output stream.", e);
    }
}
Example 15
Project: heron-master  File: FileUtils.java View source code
public static boolean writeToFile(String filename, byte[] contents, boolean overwrite) {
    // default Files behavior is to overwrite. If we specify no overwrite then CREATE_NEW fails
    // if the file exist. This operation is atomic.
    OpenOption[] options = overwrite ? new OpenOption[] {} : new OpenOption[] { StandardOpenOption.CREATE_NEW };
    try {
        Files.write(new File(filename).toPath(), contents, options);
    } catch (IOException e) {
        LOG.log(Level.SEVERE, "Failed to write content to file. ", e);
        return false;
    }
    return true;
}
Example 16
Project: jimfs-master  File: FileSystemView.java View source code
/**
   * Gets the regular file at the given path, creating it if it doesn't exist and the given options
   * specify that it should be created.
   */
public RegularFile getOrCreateRegularFile(JimfsPath path, Set<OpenOption> options, FileAttribute<?>... attrs) throws IOException {
    checkNotNull(path);
    if (!options.contains(CREATE_NEW)) {
        // assume file exists unless we're explicitly trying to create a new file
        RegularFile file = lookUpRegularFile(path, options);
        if (file != null) {
            return file;
        }
    }
    if (options.contains(CREATE) || options.contains(CREATE_NEW)) {
        return getOrCreateRegularFileWithWriteLock(path, options, attrs);
    } else {
        throw new NoSuchFileException(path.toString());
    }
}
Example 17
Project: jReto-master  File: SimpleChatUI.java View source code
public FileChannel getSaveFileChannel(String fileName) {
    FileDialog fd = new FileDialog(shlSimpleChatExample, SWT.SAVE);
    fd.setText("Choose a file for the incoming file transfer");
    fd.setFileName(fileName);
    String selected = fd.open();
    Path path = FileSystems.getDefault().getPath(selected);
    OpenOption[] read = { StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW };
    try {
        System.out.println("File will be saved to: " + path);
        FileChannel fileChannel = FileChannel.open(path, read);
        return fileChannel;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
Example 18
Project: kie-wb-common-master  File: ProjectDiagramServiceController.java View source code
public Path save(final Path path, final ProjectDiagram diagram, final Map<String, ?> attributes, final OpenOption... comment) {
    try {
        String[] raw = serizalize(diagram);
        getIoService().write(Paths.convert(path), raw[0], attributes, comment);
    } catch (Exception e) {
        LOG.error("Error while saving diagram with UUID [" + diagram.getName() + "].", e);
        throw new RuntimeException(e);
    }
    return path;
}
Example 19
Project: mina-sshd-master  File: SftpTest.java View source code
@Test
public void testSftpFileSystemAccessor() throws Exception {
    List<NamedFactory<Command>> factories = sshd.getSubsystemFactories();
    assertEquals("Mismatched subsystem factories count", 1, GenericUtils.size(factories));
    NamedFactory<Command> f = factories.get(0);
    assertObjectInstanceOf("Not an SFTP subsystem factory", SftpSubsystemFactory.class, f);
    SftpSubsystemFactory factory = (SftpSubsystemFactory) f;
    SftpFileSystemAccessor accessor = factory.getFileSystemAccessor();
    try {
        AtomicReference<Path> fileHolder = new AtomicReference<>();
        AtomicReference<Path> dirHolder = new AtomicReference<>();
        factory.setFileSystemAccessor(new SftpFileSystemAccessor() {

            @Override
            public SeekableByteChannel openFile(ServerSession session, SftpEventListenerManager subsystem, Path file, String handle, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException {
                fileHolder.set(file);
                return SftpFileSystemAccessor.super.openFile(session, subsystem, file, handle, options, attrs);
            }

            @Override
            public DirectoryStream<Path> openDirectory(ServerSession session, SftpEventListenerManager subsystem, Path dir, String handle) throws IOException {
                dirHolder.set(dir);
                return SftpFileSystemAccessor.super.openDirectory(session, subsystem, dir, handle);
            }

            @Override
            public String toString() {
                return SftpFileSystemAccessor.class.getSimpleName() + "[" + getCurrentTestName() + "]";
            }
        });
        Path targetPath = detectTargetFolder();
        Path parentPath = targetPath.getParent();
        Path localFile = Utils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), getCurrentTestName());
        Files.createDirectories(localFile.getParent());
        byte[] expected = (getClass().getName() + "#" + getCurrentTestName() + "[" + localFile + "]").getBytes(StandardCharsets.UTF_8);
        Files.write(localFile, expected, StandardOpenOption.CREATE);
        try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
            session.addPasswordIdentity(getCurrentTestName());
            session.auth().verify(5L, TimeUnit.SECONDS);
            try (SftpClient sftp = session.createSftpClient()) {
                byte[] actual = new byte[expected.length];
                try (InputStream stream = sftp.read(Utils.resolveRelativeRemotePath(parentPath, localFile), OpenMode.Read)) {
                    IoUtils.readFully(stream, actual);
                }
                Path remoteFile = fileHolder.getAndSet(null);
                assertNotNull("No remote file holder value", remoteFile);
                assertEquals("Mismatched opened local files", localFile.toFile(), remoteFile.toFile());
                assertArrayEquals("Mismatched retrieved file contents", expected, actual);
                Path localParent = localFile.getParent();
                String localName = Objects.toString(localFile.getFileName(), null);
                try (CloseableHandle handle = sftp.openDir(Utils.resolveRelativeRemotePath(parentPath, localParent))) {
                    List<DirEntry> entries = sftp.readDir(handle);
                    Path remoteParent = dirHolder.getAndSet(null);
                    assertNotNull("No remote folder holder value", remoteParent);
                    assertEquals("Mismatched opened folder", localParent.toFile(), remoteParent.toFile());
                    assertFalse("No dir entries", GenericUtils.isEmpty(entries));
                    for (DirEntry de : entries) {
                        Attributes attrs = de.getAttributes();
                        if (!attrs.isRegularFile()) {
                            continue;
                        }
                        if (localName.equals(de.getFilename())) {
                            return;
                        }
                    }
                    fail("Cannot find listing of " + localName);
                }
            }
        }
    } finally {
        // restore original
        factory.setFileSystemAccessor(accessor);
    }
}
Example 20
Project: resourcefs-master  File: ResourceFileSystemProvider.java View source code
@Override
public InputStream newInputStream(Path path, OpenOption... options) throws IOException {
    if (!path.isAbsolute()) {
        throw new IllegalArgumentException("Only absolute paths allowed: " + path.toUri().toString());
    }
    if (getClass().getResource(path.toUri().toString()) == null) {
        throw new FileNotFoundException(path.toUri().toString());
    }
    return getClass().getResourceAsStream(path.toUri().toString());
}
Example 21
Project: sfs-master  File: MultiWriteStreamTest.java View source code
@Test
public void test(TestContext context) throws IOException {
    SfsVertx sfsVertx = new SfsVertxImpl(rule.vertx(), backgroundPool, ioPool);
    final byte[] dataBuffer = new byte[1024 * 1024 * 2];
    Arrays.fill(dataBuffer, (byte) 1);
    Path tmpFile = Files.createTempFile("", "");
    Files.write(tmpFile, dataBuffer, StandardOpenOption.WRITE, StandardOpenOption.SYNC);
    Async async = context.async();
    Observable.range(0, 5).doOnNext( integer -> {
        LOGGER.debug("Attempt " + integer);
    }).flatMap( integer -> {
        try {
            final Path out1 = Files.createTempFile("", "");
            final Path out2 = Files.createTempFile("", "");
            final Path out3 = Files.createTempFile("", "");
            WriteQueueSupport q1 = new WriteQueueSupport(8192);
            WriteQueueSupport q2 = new WriteQueueSupport(8192);
            WriteQueueSupport q3 = new WriteQueueSupport(8192);
            Set<OpenOption> options = Sets.newHashSet(StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE);
            AsynchronousFileChannel ain = AsynchronousFileChannel.open(tmpFile, options, ioPool);
            AsynchronousFileChannel aout1 = AsynchronousFileChannel.open(out1, options, ioPool);
            AsynchronousFileChannel aout2 = AsynchronousFileChannel.open(out2, options, ioPool);
            AsynchronousFileChannel aout3 = AsynchronousFileChannel.open(out3, options, ioPool);
            AsyncFileReaderImpl r1 = new AsyncFileReaderImpl(sfsVertx.getOrCreateContext(), 0, 8192, dataBuffer.length, ain, LOGGER);
            AsyncFileWriterImpl w1 = new AsyncFileWriterImpl(0, q1, sfsVertx.getOrCreateContext(), aout1, LOGGER);
            AsyncFileWriterImpl w2 = new AsyncFileWriterImpl(0, q2, sfsVertx.getOrCreateContext(), aout2, LOGGER);
            AsyncFileWriterImpl w3 = new AsyncFileWriterImpl(0, q3, sfsVertx.getOrCreateContext(), aout3, LOGGER);
            LOGGER.debug("Start Attempt " + integer + ", w1=" + w1 + ", w2=" + w2 + ", w3=" + w3);
            MultiEndableWriteStream multiWriteStreamConsumer = new MultiEndableWriteStream(w1, w2, w3);
            return AsyncIO.pump(r1, multiWriteStreamConsumer).doOnNext( aVoid1 -> {
                try {
                    ain.close();
                    aout1.close();
                    aout2.close();
                    aout3.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                LOGGER.debug("Complete Attempt " + integer + ", w1=" + w1 + ", w2=" + w2 + ", w3=" + w3);
            }).doOnNext( aVoid1 -> {
                try {
                    byte[] buffer1 = Files.readAllBytes(out1);
                    byte[] buffer2 = Files.readAllBytes(out2);
                    byte[] buffer3 = Files.readAllBytes(out3);
                    VertxAssert.assertArrayEquals(context, dataBuffer, buffer1);
                    VertxAssert.assertArrayEquals(context, dataBuffer, buffer2);
                    VertxAssert.assertArrayEquals(context, dataBuffer, buffer3);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }).map(new ToVoid<>()).subscribe(new TestSubscriber(context, async) {

        @Override
        public void onNext(Void aVoid) {
            request(1);
        }

        @Override
        public void onStart() {
            request(1);
        }
    });
}
Example 22
Project: wonderdb-master  File: FilePointerFactory.java View source code
public void create(FileBlockEntry entry) {
    Path path = Paths.get(entry.getFileName());
    AsynchronousFileChannel afc = null;
    try {
        Set<OpenOption> set = new HashSet<OpenOption>();
        set.add(StandardOpenOption.READ);
        set.add(StandardOpenOption.WRITE);
        set.add(StandardOpenOption.CREATE);
        //			afc = AsynchronousFileChannel.open(path, StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
        afc = AsynchronousFileChannel.open(path, set, executor);
        asyncChannelMap.put(entry.getFileId(), afc);
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
    BlockingQueue<FileChannel> q1 = new ArrayBlockingQueue<FileChannel>(5);
    syncChannelMap.put(entry.getFileId(), q1);
    for (int i = 0; i < 5; i++) {
        path = Paths.get(entry.getFileName());
        FileChannel fc = null;
        try {
            fc = FileChannel.open(path, StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        q1.add(fc);
    }
    try {
        RandomAccessFile raf = new RandomAccessFile(entry.getFileName(), "rw");
        if (raf.length() < entry.getBlockSize() * 10000) {
            raf.setLength(entry.getBlockSize() * 10000);
        }
        fileMap.put(entry.getFileId(), raf);
    } catch (FileNotFoundException e) {
    } catch (IOException e1) {
    }
}
Example 23
Project: cnctools-master  File: CNCToolsController.java View source code
private void saveGCode(String gCode, final File filename) {
    if (gCode == null) {
        throw new IllegalArgumentException("gCode most not be null");
    }
    if (filename == null) {
        throw new IllegalArgumentException("filename most not be null");
    }
    try (BufferedWriter br = Files.newBufferedWriter(filename.toPath(), Charset.forName("UTF-8"), new OpenOption[] { StandardOpenOption.CREATE_NEW })) {
        // We do this currently in memory because we don't expect large files anyways
        while (gCode.lastIndexOf(SEPERATOR + SEPERATOR) != -1) {
            gCode = gCode.replaceAll(SEPERATOR + SEPERATOR, SEPERATOR);
        }
        br.write(gCode.trim());
        br.flush();
        br.close();
    } catch (IOException ex) {
        System.out.println(ex.getMessage());
    }
}
Example 24
Project: elasticsearch-master  File: Checkpoint.java View source code
public static void write(ChannelFactory factory, Path checkpointFile, Checkpoint checkpoint, OpenOption... options) throws IOException {
    final ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(FILE_SIZE) {

        @Override
        public synchronized byte[] toByteArray() {
            // don't clone
            return buf;
        }
    };
    final String resourceDesc = "checkpoint(path=\"" + checkpointFile + "\", gen=" + checkpoint + ")";
    try (OutputStreamIndexOutput indexOutput = new OutputStreamIndexOutput(resourceDesc, checkpointFile.toString(), byteOutputStream, FILE_SIZE)) {
        CodecUtil.writeHeader(indexOutput, CHECKPOINT_CODEC, CURRENT_VERSION);
        checkpoint.write(indexOutput);
        CodecUtil.writeFooter(indexOutput);
        assert indexOutput.getFilePointer() == FILE_SIZE : "get you numbers straight; bytes written: " + indexOutput.getFilePointer() + ", buffer size: " + FILE_SIZE;
        assert indexOutput.getFilePointer() < 512 : "checkpoint files have to be smaller than 512 bytes for atomic writes; size: " + indexOutput.getFilePointer();
    }
    // now go and write to the channel, in one go.
    try (FileChannel channel = factory.open(checkpointFile, options)) {
        Channels.writeToChannel(byteOutputStream.toByteArray(), channel);
        // no need to force metadata, file size stays the same and we did the full fsync
        // when we first created the file, so the directory entry doesn't change as well
        channel.force(false);
    }
}
Example 25
Project: inspectIT-master  File: CustomAsyncChannel.java View source code
/**
	 * Opens the channel creating the file in the given path to the directory. The
	 * {@link AsynchronousFileChannel} will work with provided {@link ExecutorService}.
	 *
	 * @param executorService
	 *            Executor service that has threads that will work on
	 *            {@link AsynchronousFileChannel}.
	 * @return True if the channel is opened, false if the channel is already opened and thus
	 *         operation is skipped.
	 * @throws IOException
	 *             When {@link IOException} occurs during opening.
	 */
public boolean openChannel(ExecutorService executorService) throws IOException {
    openCloseLock.lock();
    try {
        if (!this.isOpened()) {
            Set<OpenOption> optionsSet = new HashSet<>();
            optionsSet.add(StandardOpenOption.CREATE);
            optionsSet.add(StandardOpenOption.WRITE);
            optionsSet.add(StandardOpenOption.READ);
            fileChannel = AsynchronousFileChannel.open(path, optionsSet, executorService, new FileAttribute<?>[0]);
            if (log.isDebugEnabled()) {
                log.info("Channel opened for path " + path + ". Next write position is " + nextWritingPosition.get() + ".");
            }
            return true;
        } else {
            if (log.isDebugEnabled()) {
                log.info("Tried to open already opened channel for path " + path + ".");
            }
            return false;
        }
    } finally {
        openCloseLock.unlock();
    }
}
Example 26
Project: lucene-solr-master  File: VerboseFS.java View source code
@Override
public OutputStream newOutputStream(Path path, OpenOption... options) throws IOException {
    Throwable exception = null;
    try {
        return super.newOutputStream(path, options);
    } catch (Throwable t) {
        exception = t;
    } finally {
        sop("newOutputStream" + Arrays.toString(options) + ": " + path(path), exception);
    }
    throw new AssertionError();
}
Example 27
Project: memoryfilesystem-master  File: MemoryFileSystem.java View source code
InputStream newInputStream(AbstractPath path, OpenOption... options) throws IOException {
    this.checker.check();
    Set<OpenOption> optionsSet;
    if (options == null || options.length == 0) {
        optionsSet = Collections.emptySet();
    } else {
        optionsSet = new HashSet<>(options.length);
        for (OpenOption option : options) {
            optionsSet.add(option);
        }
    }
    MemoryFile file = this.getFile(path, optionsSet);
    return file.newInputStream(optionsSet, path);
}
Example 28
Project: nshmp-haz-master  File: HazardExport.java View source code
/*
   * Write the current list of {@code Hazard}s to file.
   */
private void writeHazards() throws IOException {
    Hazard demo = hazards.get(0);
    Set<Gmm> gmms = gmmSet(demo.model);
    OpenOption[] options = firstBatch ? WRITE : APPEND;
    Function<Double, String> formatter = Parsing.formatDoubleFunction(RATE_FMT);
    if (demo.config.hazard.valueFormat == ValueFormat.POISSON_PROBABILITY) {
        formatter = Functions.compose(formatter, Mfds.annualRateToProbabilityConverter());
    }
    /* Line maps for ascii output; may or may not be used */
    Map<Imt, List<String>> totalLines = Maps.newEnumMap(Imt.class);
    Map<Imt, Map<SourceType, List<String>>> typeLines = Maps.newEnumMap(Imt.class);
    Map<Imt, Map<Gmm, List<String>>> gmmLines = Maps.newEnumMap(Imt.class);
    /* Curve maps for binary output; may or may not be used */
    Map<Imt, Map<Integer, XySequence>> totalCurves = Maps.newEnumMap(Imt.class);
    Map<Imt, Map<SourceType, Map<Integer, XySequence>>> typeCurves = Maps.newEnumMap(Imt.class);
    Map<Imt, Map<Gmm, Map<Integer, XySequence>>> gmmCurves = Maps.newEnumMap(Imt.class);
    /* Initialize line maps. */
    for (Imt imt : demo.totalCurves.keySet()) {
        List<String> lines = new ArrayList<>();
        totalLines.put(imt, lines);
        if (firstBatch) {
            Iterable<?> header = Iterables.concat(Lists.newArrayList(namedSites ? "name" : null, "lon", "lat"), demo.config.hazard.modelCurves().get(imt).xValues());
            lines.add(Parsing.join(header, Delimiter.COMMA));
        }
        if (exportSource) {
            Map<SourceType, List<String>> typeMap = new EnumMap<>(SourceType.class);
            typeLines.put(imt, typeMap);
            for (SourceType type : demo.model.types()) {
                typeMap.put(type, Lists.newArrayList(lines));
            }
        }
        if (exportGmm) {
            Map<Gmm, List<String>> gmmMap = new EnumMap<>(Gmm.class);
            gmmLines.put(imt, gmmMap);
            for (Gmm gmm : gmms) {
                gmmMap.put(gmm, Lists.newArrayList(lines));
            }
        }
    }
    /* Initialize curve maps and binary output files. */
    if (exportBinary) {
        for (Imt imt : demo.totalCurves.keySet()) {
            totalCurves.put(imt, new HashMap<Integer, XySequence>());
            if (exportSource) {
                Map<SourceType, Map<Integer, XySequence>> typeMap = new EnumMap<>(SourceType.class);
                typeCurves.put(imt, typeMap);
                for (SourceType type : demo.model.types()) {
                    typeMap.put(type, new HashMap<Integer, XySequence>());
                }
            }
            if (exportGmm) {
                Map<Gmm, Map<Integer, XySequence>> gmmMap = new EnumMap<>(Gmm.class);
                gmmCurves.put(imt, gmmMap);
                for (Gmm gmm : gmms) {
                    gmmMap.put(gmm, new HashMap<Integer, XySequence>());
                }
            }
        }
    }
    /* Process batch */
    for (Hazard hazard : hazards) {
        String name = namedSites ? hazard.site.name : null;
        Location location = hazard.site.location;
        List<String> locData = Lists.newArrayList(name, String.format("%.5f", location.lon()), String.format("%.5f", location.lat()));
        Map<Imt, Map<SourceType, XySequence>> curvesBySource = exportSource ? curvesBySource(hazard) : null;
        Map<Imt, Map<Gmm, XySequence>> curvesByGmm = exportGmm ? curvesByGmm(hazard) : null;
        for (Entry<Imt, XySequence> imtEntry : hazard.totalCurves.entrySet()) {
            Imt imt = imtEntry.getKey();
            XySequence totalCurve = imtEntry.getValue();
            Iterable<Double> emptyValues = Doubles.asList(new double[totalCurve.size()]);
            String emptyLine = toLine(locData, emptyValues, formatter);
            totalLines.get(imt).add(toLine(locData, imtEntry.getValue().yValues(), formatter));
            Metadata meta = null;
            int binIndex = -1;
            if (exportBinary) {
                meta = metaMap.get(imt);
                binIndex = curveIndex(meta.bounds, meta.spacing, location);
                totalCurves.get(imt).put(binIndex, totalCurve);
            }
            if (exportSource) {
                Map<SourceType, XySequence> sourceCurveMap = curvesBySource.get(imt);
                for (Entry<SourceType, List<String>> typeEntry : typeLines.get(imt).entrySet()) {
                    SourceType type = typeEntry.getKey();
                    String typeLine = emptyLine;
                    if (sourceCurveMap.containsKey(type)) {
                        XySequence typeCurve = sourceCurveMap.get(type);
                        typeLine = toLine(locData, typeCurve.yValues(), formatter);
                        if (exportBinary) {
                            typeCurves.get(imt).get(type).put(binIndex, typeCurve);
                        }
                    }
                    typeEntry.getValue().add(typeLine);
                }
            }
            if (exportGmm) {
                Map<Gmm, XySequence> gmmCurveMap = curvesByGmm.get(imt);
                for (Entry<Gmm, List<String>> gmmEntry : gmmLines.get(imt).entrySet()) {
                    Gmm gmm = gmmEntry.getKey();
                    String gmmLine = emptyLine;
                    if (gmmCurveMap.containsKey(gmm)) {
                        XySequence gmmCurve = gmmCurveMap.get(gmm);
                        gmmLine = toLine(locData, gmmCurveMap.get(gmm).yValues(), formatter);
                        if (exportBinary) {
                            gmmCurves.get(imt).get(gmm).put(binIndex, gmmCurve);
                        }
                    }
                    gmmEntry.getValue().add(gmmLine);
                }
            }
        }
    }
    /* write/append */
    for (Entry<Imt, List<String>> totalEntry : totalLines.entrySet()) {
        Imt imt = totalEntry.getKey();
        Path imtDir = dir.resolve(imt.name());
        Files.createDirectories(imtDir);
        Path totalFile = imtDir.resolve("total" + TEXT_SUFFIX);
        Files.write(totalFile, totalEntry.getValue(), US_ASCII, options);
        Metadata meta = null;
        if (exportBinary) {
            meta = metaMap.get(imt);
            Path totalBinFile = imtDir.resolve("total" + BINARY_SUFFIX);
            writeBinaryBatch(totalBinFile, meta, totalCurves.get(imt));
        }
        if (exportSource) {
            Path typeDir = imtDir.resolve("source");
            Files.createDirectories(typeDir);
            for (Entry<SourceType, List<String>> typeEntry : typeLines.get(imt).entrySet()) {
                SourceType type = typeEntry.getKey();
                String filename = type.toString();
                Path typeFile = typeDir.resolve(filename + TEXT_SUFFIX);
                Files.write(typeFile, typeEntry.getValue(), US_ASCII, options);
                if (exportBinary) {
                    Path typeBinFile = typeDir.resolve(filename + BINARY_SUFFIX);
                    writeBinaryBatch(typeBinFile, meta, typeCurves.get(imt).get(type));
                }
            }
        }
        if (exportGmm) {
            Path gmmDir = imtDir.resolve("gmm");
            Files.createDirectories(gmmDir);
            for (Entry<Gmm, List<String>> gmmEntry : gmmLines.get(imt).entrySet()) {
                Gmm gmm = gmmEntry.getKey();
                String filename = gmm.name();
                Path gmmFile = gmmDir.resolve(filename + TEXT_SUFFIX);
                Files.write(gmmFile, gmmEntry.getValue(), US_ASCII, options);
                if (exportBinary) {
                    Path gmmBinFile = gmmDir.resolve(filename + BINARY_SUFFIX);
                    writeBinaryBatch(gmmBinFile, meta, gmmCurves.get(imt).get(gmm));
                }
            }
        }
    }
}
Example 29
Project: openjdk-master  File: ZipFSTester.java View source code
private static void fchCopy(Path src, Path dst) throws IOException {
    Set<OpenOption> read = new HashSet<>();
    read.add(READ);
    Set<OpenOption> openwrite = new HashSet<>();
    openwrite.add(CREATE_NEW);
    openwrite.add(WRITE);
    try (FileChannel srcFc = src.getFileSystem().provider().newFileChannel(src, read);
        FileChannel dstFc = dst.getFileSystem().provider().newFileChannel(dst, openwrite)) {
        ByteBuffer bb = ByteBuffer.allocate(8192);
        while (srcFc.read(bb) >= 0) {
            bb.flip();
            dstFc.write(bb);
            bb.clear();
        }
    }
}
Example 30
Project: package-drone-master  File: GodModeService.java View source code
/**
     * Write out the announce file <br>
     * Writing a file like this seems a little bit strange from a Java
     * perspective. However, there seems to be no other way to create a file
     * with a provided set of initial file attributes other than
     * {@link Files#newByteChannel(java.nio.file.Path, Set, FileAttribute...)}.
     * All other methods don't access file attributes.
     *
     * @param adminToken
     *            The admin token to write out
     */
protected void writeAnnounceFile(final String adminToken) {
    final Path path = ANNOUNCE_FILE.toPath();
    /*
         * Try to delete the file first. We don't care about the result
         * since the next operation will try to create a new file anyway.
         *
         * However by deleting it first, we try to ensure that the initial
         * file permissions are set. If the file exists these would not be
         * changed.
         */
    ANNOUNCE_FILE.delete();
    // posix
    final FileAttribute<?>[] attrs;
    if (ANNOUNCE_FILE_POSIX) {
        final Set<PosixFilePermission> perms = EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE);
        attrs = new FileAttribute<?>[] { PosixFilePermissions.asFileAttribute(perms) };
    } else {
        attrs = new FileAttribute<?>[0];
    }
    final Set<? extends OpenOption> options = EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
    try (SeekableByteChannel sbc = Files.newByteChannel(path, options, attrs)) {
        final StringWriter sw = new StringWriter();
        final PrintWriter writer = new PrintWriter(sw);
        writer.format("user=%s%n", NAME);
        writer.format("password=%s%n", adminToken);
        writer.close();
        final ByteBuffer data = ByteBuffer.wrap(sw.toString().getBytes(StandardCharsets.UTF_8));
        while (data.hasRemaining()) {
            sbc.write(data);
        }
    } catch (final UnsupportedOperationException e) {
        System.err.format("WARNING: Failed to write out announce file with secured posix permissions. If you are on a non-posix platform (e.g. Windows), you might need to set the system property '%s' to 'true'%n", PROP_NOT_POSIX);
    } catch (final IOException e) {
        System.err.println("WARNING: Unable to write announce file: " + ExceptionHelper.getMessage(e));
    }
}
Example 31
Project: structr-master  File: StructrSSHFileSystem.java View source code
@Override
public OutputStream newOutputStream(Path path, OpenOption... options) throws IOException {
    logger.info("x");
    OutputStream os = null;
    FileBase actualFile = (FileBase) ((StructrSSHFile) path).getActualFile();
    try (final Tx tx = StructrApp.getInstance(securityContext).tx()) {
        if (actualFile == null) {
            actualFile = (FileBase) create(path);
        }
        if (actualFile != null) {
            os = ((FileBase) actualFile).getOutputStream();
        }
        tx.success();
    } catch (FrameworkException fex) {
        logger.warn("", fex);
        throw new IOException(fex);
    }
    return os;
}
Example 32
Project: fabric8-master  File: FabricProfileFileSystem.java View source code
public <A extends BasicFileAttributes> SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>[] attrs) throws IOException {
    final byte[] data = getFile(path);
    return new SeekableByteChannel() {

        long position;

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

        @Override
        public int write(ByteBuffer src) throws IOException {
            throw new UnsupportedOperationException();
        }

        @Override
        public long position() throws IOException {
            return position;
        }

        @Override
        public SeekableByteChannel position(long newPosition) throws IOException {
            position = newPosition;
            return this;
        }

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

        @Override
        public SeekableByteChannel truncate(long size) throws IOException {
            throw new UnsupportedOperationException();
        }

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

        @Override
        public void close() throws IOException {
        }
    };
}
Example 33
Project: test-fs-master  File: TestFileSystemProvider.java View source code
/** {@inheritDoc} */
@Override
public SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException {
    path = ((TestPath) path).unwrap();
    checkIfRemoved(path);
    checkPermissions(path, true, toAccessModes(options));
    Path target = addedPathTargets.get(path.toAbsolutePath());
    if (target != null) {
        return provider.newByteChannel(target, options, attrs);
    }
    return provider.newByteChannel(path, options, attrs);
}
Example 34
Project: liferay-portal-master  File: FileHelperUtilTest.java View source code
@Test
public void testUnzipImpossibleScenario() throws IOException {
    FileSystem fileSystem = FileSystems.getDefault();
    FileSystemProvider fileSystemProvider = new FileSystemProviderWrapper(fileSystem.provider()) {

        @Override
        public InputStream newInputStream(Path path, OpenOption... options) {
            return null;
        }
    };
    Path impossiableSourceFilePath = Paths.get("ImpossibleSourceFilePath");
    impossiableSourceFilePath = fileSystemProvider.getPath(impossiableSourceFilePath.toUri());
    try {
        FileHelperUtil.unzip(impossiableSourceFilePath, FileHelperUtil.TEMP_DIR_PATH);
        Assert.fail();
    } catch (NullPointerException npe) {
    }
}
Example 35
Project: felix-master  File: Builtin.java View source code
/*
     * the following methods depend on the internals of the runtime implementation.
     * ideally, they should be available via some API.
     */
public Object tac(CommandSession session, String[] argv) throws IOException {
    final String[] usage = { "tac - capture stdin as String or List and optionally write to file.", "Usage: tac [-al] [FILE]", "  -a --append              append to FILE", "  -l --list                return List<String>", "  -? --help                show help" };
    Process process = Process.Utils.current();
    Options opt = Options.compile(usage).parse(argv);
    if (opt.isSet("help")) {
        opt.usage(process.err());
        return null;
    }
    List<String> args = opt.args();
    BufferedWriter fw = null;
    if (args.size() == 1) {
        Path path = session.currentDir().resolve(args.get(0));
        Set<OpenOption> options = new HashSet<>();
        options.add(StandardOpenOption.WRITE);
        options.add(StandardOpenOption.CREATE);
        if (opt.isSet("append")) {
            options.add(StandardOpenOption.APPEND);
        } else {
            options.add(StandardOpenOption.TRUNCATE_EXISTING);
        }
        fw = Files.newBufferedWriter(path, StandardCharsets.UTF_8, options.toArray(new OpenOption[options.size()]));
    }
    StringWriter sw = new StringWriter();
    BufferedReader rdr = new BufferedReader(new InputStreamReader(process.in()));
    ArrayList<String> list = null;
    if (opt.isSet("list")) {
        list = new ArrayList<String>();
    }
    boolean first = true;
    String s;
    while ((s = rdr.readLine()) != null) {
        if (list != null) {
            list.add(s);
        } else {
            if (!first) {
                sw.write(' ');
            }
            first = false;
            sw.write(s);
        }
        if (fw != null) {
            fw.write(s);
            fw.newLine();
        }
    }
    if (fw != null) {
        fw.close();
    }
    return list != null ? list : sw.toString();
}
Example 36
Project: incubator-taverna-language-master  File: BundleFileSystemProvider.java View source code
@Override
public SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException {
    final BundleFileSystem fs = (BundleFileSystem) path.getFileSystem();
    Path zipPath = fs.unwrap(path);
    if (options.contains(StandardOpenOption.WRITE) || options.contains(StandardOpenOption.APPEND)) {
        if (Files.isDirectory(zipPath)) {
            // co-exist
            throw new FileAlreadyExistsException("Directory <" + zipPath.toString() + "> exists");
        }
        Path parent = zipPath.getParent();
        if (parent != null && !Files.isDirectory(parent)) {
            throw new NoSuchFileException(zipPath.toString(), parent.toString(), "Parent of file is not a directory");
        }
        if (options.contains(StandardOpenOption.CREATE_NEW)) {
        } else if (options.contains(StandardOpenOption.CREATE) && !Files.exists(zipPath)) {
            // Workaround for bug in ZIPFS in Java 7 -
            // it only creates new files on
            // StandardOpenOption.CREATE_NEW
            //
            // We'll fake it and just create file first using the legacy
            // newByteChannel()
            // - we can't inject CREATE_NEW option as it
            // could be that there are two concurrent calls to CREATE
            // the very same file,
            // with CREATE_NEW the second thread would then fail.
            EnumSet<StandardOpenOption> opts = EnumSet.of(StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW);
            origProvider(path).newFileChannel(zipPath, opts, attrs).close();
        }
    }
    // allow manifest to be updated
    return newFileChannel(path, options, attrs);
}
Example 37
Project: jdk7-dxfs-master  File: DxFileSystemProvider.java View source code
public InputStream newInputStream(Path file, OpenOption... options) throws IOException {
    if (options.length > 0) {
        for (OpenOption opt : options) {
            if (opt != StandardOpenOption.READ)
                throw new UnsupportedOperationException("'" + opt + "' not allowed");
        }
    }
    final DxPath path = toDxPath(file);
    final String fileId = path.getFileId();
    final Map<String, Object> download = api.fileDownload(fileId);
    final String url = (String) download.get("url");
    final Map<String, String> headers = (Map<String, String>) download.get("headers");
    final HttpClient client = DxHttpClient.getInstance().http();
    client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpGet get = new HttpGet(url);
    get.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES);
    for (Map.Entry<String, String> item : headers.entrySet()) {
        get.setHeader(item.getKey(), item.getValue());
    }
    return client.execute(get).getEntity().getContent();
}
Example 38
Project: NearInfinity-master  File: DlcFileSystem.java View source code
SeekableByteChannel newByteChannel(byte[] path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException {
    checkOptions(options);
    if (options.contains(StandardOpenOption.WRITE) || options.contains(StandardOpenOption.APPEND)) {
        checkWritable();
    }
    beginRead();
    try {
        ensureOpen();
        ZipNode folder = root.getNode(path);
        if (folder == null) {
            throw new NoSuchFileException(getString(path));
        }
        if (folder.isDirectory()) {
            throw new FileSystemException(getString(path), "is a directory", null);
        }
        final long basePos = folder.getCentral().getDataOffset(ch);
        final long baseSize = folder.getCentral().sizeUncompressed;
        final SeekableByteChannel sbc = Files.newByteChannel(getDlcFile(), options, attrs);
        sbc.position(basePos);
        return new SeekableByteChannel() {

            @Override
            public boolean isOpen() {
                return sbc.isOpen();
            }

            @Override
            public void close() throws IOException {
                sbc.close();
            }

            @Override
            public int write(ByteBuffer src) throws IOException {
                throw new UnsupportedOperationException();
            }

            @Override
            public SeekableByteChannel truncate(long size) throws IOException {
                throw new UnsupportedOperationException();
            }

            @Override
            public long size() throws IOException {
                return baseSize;
            }

            @Override
            public int read(ByteBuffer dst) throws IOException {
                checkOpen();
                if (sbc.position() >= basePos + baseSize) {
                    return -1;
                }
                ByteBuffer buffer = ByteBuffer.allocate(65536);
                int remaining = (int) (baseSize - position());
                remaining = Math.min(dst.remaining(), remaining);
                int processed = 0;
                while (remaining > 0) {
                    buffer.compact().position(0);
                    buffer.limit(Math.min(remaining, buffer.remaining()));
                    int nread = sbc.read(buffer);
                    if (nread < 0) {
                        break;
                    }
                    buffer.flip();
                    dst.put(buffer);
                    remaining -= nread;
                    processed += nread;
                }
                return processed;
            }

            @Override
            public SeekableByteChannel position(long newPosition) throws IOException {
                checkOpen();
                if (newPosition < 0) {
                    throw new IOException("Negative position");
                }
                sbc.position(basePos + newPosition);
                return this;
            }

            @Override
            public long position() throws IOException {
                checkOpen();
                return sbc.position() - basePos;
            }

            private void checkOpen() throws IOException {
                if (sbc == null || !sbc.isOpen()) {
                    throw new IOException("Channel not open");
                }
            }
        };
    } finally {
        endRead();
    }
}
Example 39
Project: quasar-master  File: FiberFileChannel.java View source code
/**
     * Opens or creates a file for reading and/or writing, returning a file channel to access the file.
     *
     * <p>
     * The {@code options} parameter determines how the file is opened.
     * The {@link StandardOpenOption#READ READ} and {@link StandardOpenOption#WRITE
     * WRITE} options determines if the file should be opened for reading and/or
     * writing. If neither option is contained in the array then an existing file
     * is opened for reading.
     *
     * <p>
     * In addition to {@code READ} and {@code WRITE}, the following options
     * may be present:
     *
     * <table border=1 cellpadding=5 summary="">
     * <tr> <th>Option</th> <th>Description</th> </tr>
     * <tr>
     * <td> {@link StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING} </td>
     * <td> When opening an existing file, the file is first truncated to a
     * size of 0 bytes. This option is ignored when the file is opened only
     * for reading.</td>
     * </tr>
     * <tr>
     * <td> {@link StandardOpenOption#CREATE_NEW CREATE_NEW} </td>
     * <td> If this option is present then a new file is created, failing if
     * the file already exists. When creating a file the check for the
     * existence of the file and the creation of the file if it does not exist
     * is atomic with respect to other file system operations. This option is
     * ignored when the file is opened only for reading. </td>
     * </tr>
     * <tr>
     * <td > {@link StandardOpenOption#CREATE CREATE} </td>
     * <td> If this option is present then an existing file is opened if it
     * exists, otherwise a new file is created. When creating a file the check
     * for the existence of the file and the creation of the file if it does
     * not exist is atomic with respect to other file system operations. This
     * option is ignored if the {@code CREATE_NEW} option is also present or
     * the file is opened only for reading. </td>
     * </tr>
     * <tr>
     * <td > {@link StandardOpenOption#DELETE_ON_CLOSE DELETE_ON_CLOSE} </td>
     * <td> When this option is present then the implementation makes a
     * <em>best effort</em> attempt to delete the file when closed by the
     * the {@link #close close} method. If the {@code close} method is not
     * invoked then a <em>best effort</em> attempt is made to delete the file
     * when the Java virtual machine terminates. </td>
     * </tr>
     * <tr>
     * <td>{@link StandardOpenOption#SPARSE SPARSE} </td>
     * <td> When creating a new file this option is a <em>hint</em> that the
     * new file will be sparse. This option is ignored when not creating
     * a new file. </td>
     * </tr>
     * <tr>
     * <td> {@link StandardOpenOption#SYNC SYNC} </td>
     * <td> Requires that every update to the file's content or metadata be
     * written synchronously to the underlying storage device. (see <a
     * href="../file/package-summary.html#integrity"> Synchronized I/O file
     * integrity</a>). </td>
     * <tr>
     * <tr>
     * <td> {@link StandardOpenOption#DSYNC DSYNC} </td>
     * <td> Requires that every update to the file's content be written
     * synchronously to the underlying storage device. (see <a
     * href="../file/package-summary.html#integrity"> Synchronized I/O file
     * integrity</a>). </td>
     * </tr>
     * </table>
     *
     * <p>
     * An implementation may also support additional options.
     *
     * <p>
     * The {@code executor} parameter is the {@link ExecutorService} to
     * which tasks are submitted to handle I/O events and dispatch completion
     * results for operations initiated on resulting channel.
     * The nature of these tasks is highly implementation specific and so care
     * should be taken when configuring the {@code Executor}. Minimally it
     * should support an unbounded work queue and should not run tasks on the
     * caller thread of the {@link ExecutorService#execute execute} method.
     * Shutting down the executor service while the channel is open results in
     * unspecified behavior.
     *
     * <p>
     * The {@code attrs} parameter is an optional array of file {@link
     * FileAttribute file-attributes} to set atomically when creating the file.
     *
     * <p>
     * The new channel is created by invoking the {@link
     * FileSystemProvider#newFileChannel newFileChannel} method on the
     * provider that created the {@code Path}.
     *
     * @param path       The path of the file to open or create
     * @param options    Options specifying how the file is opened
     * @param ioExecutor The thread pool or {@code null} to associate the channel with the default thread pool
     * @param attrs      An optional list of file attributes to set atomically when creating the file
     *
     * @return A new file channel
     *
     * @throws IllegalArgumentException      If the set contains an invalid combination of options
     * @throws UnsupportedOperationException If the {@code file} is associated with a provider that does not
     *                                       support creating asynchronous file channels, or an unsupported
     *                                       open option is specified, or the array contains an attribute that
     *                                       cannot be set atomically when creating the file
     * @throws IOException                   If an I/O error occurs
     * @throws SecurityException             If a security manager is installed and it denies an
     *                                       unspecified permission required by the implementation.
     *                                       In the case of the default provider, the {@link SecurityManager#checkRead(String)}
     *                                       method is invoked to check read access if the file is opened for reading.
     *                                       The {@link SecurityManager#checkWrite(String)} method is invoked to check
     *                                       write access if the file is opened for writing
     */
@Suspendable
public static FiberFileChannel open(final ExecutorService ioExecutor, final Path path, final Set<? extends OpenOption> options, final FileAttribute<?>... attrs) throws IOException {
    // FiberAsyncIO.ioExecutor(); // 
    final ExecutorService ioExec = ioExecutor != null ? ioExecutor : fiberFileThreadPool;
    AsynchronousFileChannel afc = FiberAsyncIO.runBlockingIO(fiberFileThreadPool, new CheckedCallable<AsynchronousFileChannel, IOException>() {

        @Override
        public AsynchronousFileChannel call() throws IOException {
            return AsynchronousFileChannel.open(path, options, ioExec, attrs);
        }
    });
    return new FiberFileChannel(afc);
}
Example 40
Project: shrinkwrap-master  File: FilesTestCase.java View source code
@Test
public void newBufferedWriter() throws IOException {
    final String path = "path";
    final String contents = "contents";
    final BufferedWriter writer = Files.newBufferedWriter(fs.getPath(path), Charset.defaultCharset(), (OpenOption) null);
    writer.write(contents);
    writer.close();
    final String roundtrip = new BufferedReader(new InputStreamReader(this.getArchive().get(path).getAsset().openStream())).readLine();
    Assert.assertEquals("Contents not written as expected from the buffered writer", contents, roundtrip);
}
Example 41
Project: buck-master  File: ProjectWorkspace.java View source code
/**
   * This will copy the template directory, renaming files named {@code foo.fixture} to {@code foo}
   * in the process. Files whose names end in {@code .expected} will not be copied.
   */
@SuppressWarnings("PMD.EmptyCatchBlock")
public ProjectWorkspace setUp() throws IOException {
    MoreFiles.copyRecursively(templatePath, destPath, BUILD_FILE_RENAME);
    // Stamp the buck-out directory if it exists and isn't stamped already
    try (OutputStream outputStream = new BufferedOutputStream(Channels.newOutputStream(Files.newByteChannel(destPath.resolve(BuckConstant.getBuckOutputPath().resolve(".currentversion")), ImmutableSet.<OpenOption>of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE))))) {
        outputStream.write(BuckVersion.getVersion().getBytes(Charsets.UTF_8));
    } catch (FileAlreadyExistsExceptionNoSuchFileException |  e) {
    }
    if (Platform.detect() == Platform.WINDOWS) {
        // Hack for symlinks on Windows.
        SimpleFileVisitor<Path> copyDirVisitor = new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
                // On NTFS length of path must be greater than 0 and less than 4096.
                if (attrs.size() > 0 && attrs.size() <= 4096) {
                    String linkTo = new String(Files.readAllBytes(path), UTF_8);
                    Path linkToFile;
                    try {
                        linkToFile = templatePath.resolve(linkTo);
                    } catch (InvalidPathException e) {
                        return FileVisitResult.CONTINUE;
                    }
                    if (Files.isRegularFile(linkToFile)) {
                        Files.copy(linkToFile, path, StandardCopyOption.REPLACE_EXISTING);
                    } else if (Files.isDirectory(linkToFile)) {
                        Files.delete(path);
                        MoreFiles.copyRecursively(linkToFile, path);
                    }
                }
                return FileVisitResult.CONTINUE;
            }
        };
        Files.walkFileTree(destPath, copyDirVisitor);
    }
    if (!Files.exists(getPath(".buckconfig.local"))) {
        manageLocalConfigs = true;
        // Enable the JUL build log.  This log is very verbose but rarely useful,
        // so it's disabled by default.
        addBuckConfigLocalOption("log", "jul_build_log", "true");
        // Disable the directory cache by default.  Tests that want to enable it can call
        // `enableDirCache` on this object.  Only do this if a .buckconfig.local file does not already
        // exist, however (we assume the test knows what it is doing at that point).
        addBuckConfigLocalOption("cache", "mode", "");
        // Limit the number of threads by default to prevent multiple integration tests running at the
        // same time from creating a quadratic number of threads. Tests can disable this using
        // `disableThreadLimitOverride`.
        addBuckConfigLocalOption("build", "threads", "2");
    }
    // from buck-out while watchman indexes/touches files.
    if (!Files.exists(getPath(".watchmanconfig"))) {
        writeContentsToPath("{\"ignore_dirs\":[\"buck-out\",\".buckd\"]}", ".watchmanconfig");
    }
    isSetUp = true;
    return this;
}
Example 42
Project: jsr203-hadoop-master  File: HadoopFileSystem.java View source code
private void checkOptions(Set<? extends OpenOption> options) {
    // check for options of null type and option is an intance of StandardOpenOption
    for (OpenOption option : options) {
        if (option == null)
            throw new NullPointerException();
        if (!(option instanceof StandardOpenOption))
            throw new IllegalArgumentException();
    }
}
Example 43
Project: platform_build-master  File: ProjectWorkspace.java View source code
/**
   * This will copy the template directory, renaming files named {@code foo.fixture} to {@code foo}
   * in the process. Files whose names end in {@code .expected} will not be copied.
   */
@SuppressWarnings("PMD.EmptyCatchBlock")
public ProjectWorkspace setUp() throws IOException {
    MoreFiles.copyRecursively(templatePath, destPath, BUILD_FILE_RENAME);
    // Stamp the buck-out directory if it exists and isn't stamped already
    try (OutputStream outputStream = new BufferedOutputStream(Channels.newOutputStream(Files.newByteChannel(destPath.resolve(BuckConstant.getBuckOutputPath().resolve(".currentversion")), ImmutableSet.<OpenOption>of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE))))) {
        outputStream.write(BuckVersion.getVersion().getBytes(Charsets.UTF_8));
    } catch (FileAlreadyExistsExceptionNoSuchFileException |  e) {
    }
    if (Platform.detect() == Platform.WINDOWS) {
        // Hack for symlinks on Windows.
        SimpleFileVisitor<Path> copyDirVisitor = new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
                // On NTFS length of path must be greater than 0 and less than 4096.
                if (attrs.size() > 0 && attrs.size() <= 4096) {
                    String linkTo = new String(Files.readAllBytes(path), UTF_8);
                    Path linkToFile;
                    try {
                        linkToFile = templatePath.resolve(linkTo);
                    } catch (InvalidPathException e) {
                        return FileVisitResult.CONTINUE;
                    }
                    if (Files.isRegularFile(linkToFile)) {
                        Files.copy(linkToFile, path, StandardCopyOption.REPLACE_EXISTING);
                    } else if (Files.isDirectory(linkToFile)) {
                        Files.delete(path);
                        MoreFiles.copyRecursively(linkToFile, path);
                    }
                }
                return FileVisitResult.CONTINUE;
            }
        };
        Files.walkFileTree(destPath, copyDirVisitor);
    }
    if (!Files.exists(getPath(".buckconfig.local"))) {
        manageLocalConfigs = true;
        // Disable the directory cache by default.  Tests that want to enable it can call
        // `enableDirCache` on this object.  Only do this if a .buckconfig.local file does not already
        // exist, however (we assume the test knows what it is doing at that point).
        addBuckConfigLocalOption("cache", "mode", "");
        // Limit the number of threads by default to prevent multiple integration tests running at the
        // same time from creating a quadratic number of threads. Tests can disable this using
        // `disableThreadLimitOverride`.
        addBuckConfigLocalOption("build", "threads", "2");
    }
    // from buck-out while watchman indexes/touches files.
    if (!Files.exists(getPath(".watchmanconfig"))) {
        writeContentsToPath("{\"ignore_dirs\":[\"buck-out\",\".buckd\"]}", ".watchmanconfig");
    }
    isSetUp = true;
    return this;
}
Example 44
Project: SEEP-master  File: BackupHandlerTest.java View source code
/**
	 * Run the void addBackupHandler(int,FileChannel,File) method test.
	 *
	 * @throws Exception
	 *
	 * @generatedBy CodePro at 18/10/13 19:10
	 */
public void testAddBackupHandler_1() throws Exception {
    BackupHandler fixture = new BackupHandler(new CoreRE(new WorkerNodeDescription(InetAddress.getLocalHost(), 1), new RuntimeClassLoader(new URL[] {}, new URLClassLoader(new URL[] {}))), 1);
    fixture.setGoOn(true);
    int opId = 1;
    FileChannel fc = FileChannel.open((Path) null, new OpenOption[] { null });
    File f = new File("");
    fixture.addBackupHandler(opId, fc, f);
// add additional test code here
// An unexpected exception was thrown in user code while executing this test:
//    java.lang.SecurityException: Cannot write to files while generating test cases
//       at com.instantiations.assist.eclipse.junit.CodeProJUnitSecurityManager.checkWrite(CodeProJUnitSecurityManager.java:76)
//       at java.io.File.mkdir(File.java:1237)
//       at java.io.File.mkdirs(File.java:1266)
//       at uk.ac.imperial.lsds.seep.reliable.BackupHandler.<init>(BackupHandler.java:83)
}
Example 45
Project: nifi-master  File: MockProcessSession.java View source code
@Override
public void exportTo(FlowFile flowFile, final Path path, final boolean append) {
    flowFile = validateState(flowFile);
    if (flowFile == null || path == null) {
        throw new IllegalArgumentException("argument cannot be null");
    }
    if (!(flowFile instanceof MockFlowFile)) {
        throw new IllegalArgumentException("Cannot export a flow file that I did not create");
    }
    final MockFlowFile mock = (MockFlowFile) flowFile;
    final OpenOption mode = append ? StandardOpenOption.APPEND : StandardOpenOption.CREATE;
    try (final OutputStream out = Files.newOutputStream(path, mode)) {
        out.write(mock.getData());
    } catch (final IOException e) {
        throw new FlowFileAccessException(e.toString(), e);
    }
}
Example 46
Project: fswrap-master  File: FileSystemEventAdapter.java View source code
@Override
public void newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>[] attrs, SeekableByteChannel byteChannel) {
}
Example 47
Project: Neddy-master  File: Files.java View source code
private static AsynchronousFileChannel open(Path path, Set<OpenOption> options) throws IOException {
    return AsynchronousFileChannel.open(path, options, threadPool);
}
Example 48
Project: buckaroo-master  File: Files.java View source code
public static Either<IOException, ByteChannel> openByteChannel(final Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) {
    Preconditions.checkNotNull(path);
    try {
        final ByteChannel channel = path.getFileSystem().provider().newByteChannel(path, options, attrs);
        return Either.right(channel);
    } catch (final IOException e) {
        return Either.left(e);
    }
}
Example 49
Project: elassandra-master  File: Checkpoint.java View source code
public static void write(Path checkpointFile, Checkpoint checkpoint, OpenOption... options) throws IOException {
    try (FileChannel channel = FileChannel.open(checkpointFile, options)) {
        checkpoint.write(channel);
        channel.force(false);
    }
}
Example 50
Project: xnio-master  File: FileChannel.java View source code
public static FileChannel open(Path path, OpenOption... options) throws IOException {
    return null;
}
Example 51
Project: com.revolsys.open-master  File: FileConnectionFileSystemProvider.java View source code
@Override
public SeekableByteChannel newByteChannel(final Path path, final Set<? extends OpenOption> options, final FileAttribute<?>... attrs) throws IOException {
    final Path filePath = getFilePath(path);
    return Files.newByteChannel(filePath, options, attrs);
}
Example 52
Project: dstream-master  File: HdfsFileSystemProvider.java View source code
@Override
public SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException {
    // TODO Auto-generated method stub
    return null;
}
Example 53
Project: ISAAC-master  File: ConsoleUtil.java View source code
/**
    * Write output to file.
    *
    * @param path the path
    * @throws IOException Signals that an I/O exception has occurred.
    */
public static void writeOutputToFile(Path path) throws IOException {
    final BufferedWriter bw = Files.newBufferedWriter(path, Charset.forName("UTF-8"), new OpenOption[] { StandardOpenOption.CREATE });
    bw.append(consoleOutputCache.toString());
    bw.close();
    consoleOutputCache.setLength(0);
    printsSinceReturn = 0;
}
Example 54
Project: neembuunow-master  File: DefaultSession.java View source code
@Override
public SeekableByteChannel getOrCreateResource(String nm, OpenOption... openOptions) throws Exception {
    return resources.addAndGet(FileChannel.open(sessionPath.resolve(nm), openOptions));
}
Example 55
Project: nio-fs-provider-master  File: WebdavFileSystemProvider.java View source code
@Override
public SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException {
    return new SardineChannel((WebdavPath) path);
}
Example 56
Project: epicsarchiverap-master  File: ArchPaths.java View source code
/**
	 * Returns a seekable byte channel. 
	 * In case of file systems, this is the raw SeekableByteChannel as returned by the provider.
	 * In case of zip files, we wrap the InputStream using WrappedSeekableByteChannel (which is a read only byte channel for now).
	 * @param path Path 
	 * @param options  OpenOption
	 * @return a new seekabel byte channel 
	 * @throws IOException    
	 */
public static SeekableByteChannel newByteChannel(Path path, OpenOption... options) throws IOException {
    String pathURI = path.toUri().toString();
    if (pathURI.startsWith(ZIP_PREFIX)) {
        return new WrappedSeekableByteChannel(path);
    } else {
        return Files.newByteChannel(path, options);
    }
}
Example 57
Project: gestalt-master  File: ModuleFileSystemProvider.java View source code
@Override
public SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException {
    Path underlying = getUnderlyingPath(path);
    return underlying.getFileSystem().provider().newByteChannel(underlying, options, attrs);
}
Example 58
Project: okio-master  File: Okio.java View source code
/** Returns a source that reads from {@code path}. */
// Should only be invoked on Java 7+.
@IgnoreJRERequirement
public static Source source(Path path, OpenOption... options) throws IOException {
    if (path == null)
        throw new IllegalArgumentException("path == null");
    return source(Files.newInputStream(path, options));
}
Example 59
Project: openjdk8-jdk-master  File: FaultyFileSystem.java View source code
@Override
public SeekableByteChannel newByteChannel(Path file, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException {
    triggerEx(file, "newByteChannel");
    return Files.newByteChannel(unwrap(file), options, attrs);
}
Example 60
Project: ratpack-master  File: FileIo.java View source code
/**
   * Creates a promise for an (open) async file channel.
   * <p>
   * Uses {@link AsynchronousFileChannel#open(Path, Set, ExecutorService, FileAttribute[])},
   * but uses the current execution's event loop as the executor service and no file attributes.
   *
   * @param file The path of the file to open or create
   * @param options Options specifying how the file is opened
   * @see AsynchronousFileChannel#open(Path, Set, ExecutorService, FileAttribute[])
   * @see #open(Path, Set, FileAttribute[])
   * @return a promise for an open async file channel
   */
public static Promise<AsynchronousFileChannel> open(Path file, OpenOption... options) {
    return open(file, ImmutableSet.copyOf(options));
}
Example 61
Project: strongbox-master  File: RepositoryFileSystemProvider.java View source code
public SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException {
    return storageFileSystemProvider.newByteChannel(unwrap(path), options, attrs);
}
Example 62
Project: guava-master  File: MoreFiles.java View source code
/**
   * Returns a view of the given {@code path} as a {@link ByteSource}.
   *
   * <p>Any {@linkplain OpenOption open options} provided are used when opening streams to the file
   * and may affect the behavior of the returned source and the streams it provides. See {@link
   * StandardOpenOption} for the standard options that may be provided. Providing no options is
   * equivalent to providing the {@link StandardOpenOption#READ READ} option.
   */
public static ByteSource asByteSource(Path path, OpenOption... options) {
    return new PathByteSource(path, options);
}
Example 63
Project: vmvm-master  File: ChrootUtils.java View source code
public static Path write(Path path, byte[] bytes, OpenOption... options) throws IOException {
    return Files.write(path, bytes, options);
}