Example usage for java.nio.file StandardOpenOption WRITE

List of usage examples for java.nio.file StandardOpenOption WRITE

Introduction

In this page you can find the example usage for java.nio.file StandardOpenOption WRITE.

Prototype

StandardOpenOption WRITE

To view the source code for java.nio.file StandardOpenOption WRITE.

Click Source Link

Document

Open for write access.

Usage

From source file:org.apache.hadoop.yarn.server.nodemanager.containermanager.ContainerSecurityUpdaterTask.java

private void writeInternal(Path target, ByteBuffer data) throws IOException {
    try (FileChannel fc = FileChannel.open(target, StandardOpenOption.WRITE, StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING)) {
        int numOfRetries = 0;
        FileLock lock = null;//from ww w. ja  va 2 s  . co  m
        while (lock == null && numOfRetries < 5) {
            try {
                lock = fc.tryLock();
                fc.write(data);
            } catch (OverlappingFileLockException ex) {
                lock = null;
                numOfRetries++;
                try {
                    TimeUnit.MILLISECONDS.sleep(100);
                } catch (InterruptedException iex) {
                    throw new IOException(iex);
                }
            } finally {
                if (lock != null) {
                    lock.release();
                }
            }
        }
    }
}

From source file:it.greenvulcano.configuration.BaseConfigurationManager.java

@Override
public void install(String name, byte[] archive) throws IOException {

    Path configurationPath = getConfigurationPath(name);
    try (ZipInputStream zipArchive = new ZipInputStream(new ByteArrayInputStream(archive))) {
        if (zipArchive.getNextEntry() != null) {
            Files.write(configurationPath, archive, StandardOpenOption.WRITE, StandardOpenOption.CREATE,
                    StandardOpenOption.TRUNCATE_EXISTING);
        } else {/*from  ww w  .ja  va  2s .  c  om*/
            throw new IOException("Empty or invalid zip archive");
        }

    }

}

From source file:nl.salp.warcraft4j.casc.cdn.util.CascFileExtractor.java

private Optional<Path> extractFile(Path destination, long filenameHash)
        throws CascExtractionException, DataReadingException, DataParsingException {
    Optional<Path> file;
    if (isWritableFile(destination)) {
        try {/*from ww  w.  j  a  v a  2  s  . c  om*/
            Files.createDirectories(destination.getParent());
            try (DataReader in = context.getFileDataReader(filenameHash);
                    OutputStream out = Files.newOutputStream(destination, StandardOpenOption.CREATE,
                            StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
                while (in.hasRemaining()) {
                    int chunkSize = (int) Math.min(CHUNK_SIZE, in.remaining());
                    byte[] chunk = in.readNext(DataTypeFactory.getByteArray(chunkSize));
                    out.write(chunk);
                }
                out.flush();
                file = Optional.of(destination);
            } catch (CascEntryNotFoundException e) {
                file = Optional.empty();
            }
        } catch (IOException e) {
            throw new CascExtractionException(
                    format("Error while extraction CASC file to %s: %s", destination, e.getMessage()), e);
        }
    } else {
        throw new CascExtractionException(format(
                "Unable to extract a file to %s, the path already exists and is not a file or not writable.",
                destination));
    }
    return file;
}

From source file:org.cryptomator.webdav.jackrabbit.DavLocatorFactoryImpl.java

@Override
public void writePathSpecificMetadata(String encryptedPath, byte[] encryptedMetadata) throws IOException {
    final Path metaDataFile = fsRoot.resolve(encryptedPath);
    Files.write(metaDataFile, encryptedMetadata, StandardOpenOption.WRITE, StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.DSYNC);
}

From source file:org.wikidata.wdtk.util.DirectoryManagerImpl.java

@Override
public void createFile(String fileName, String fileContents) throws IOException {
    Path filePath = this.directory.resolve(fileName);
    try (BufferedWriter bufferedWriter = Files.newBufferedWriter(filePath, StandardCharsets.UTF_8,
            StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW)) {
        bufferedWriter.write(fileContents);
    }// w w w  .  j  a v a 2s  .  c o m
}

From source file:org.sonar.plugins.csharp.CSharpSensorTest.java

@Before
public void prepare() throws Exception {
    workDir = temp.newFolder().toPath();
    Path srcDir = Paths.get("src/test/resources/CSharpSensorTest");
    Files.walk(srcDir).forEach(path -> {
        if (Files.isDirectory(path)) {
            return;
        }//from w w w.ja  v a  2 s .  c o  m
        Path relativized = srcDir.relativize(path);
        try {
            Path destFile = workDir.resolve(relativized);
            if (!Files.exists(destFile.getParent())) {
                Files.createDirectories(destFile.getParent());
            }
            Files.copy(path, destFile, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    });
    File csFile = new File("src/test/resources/Program.cs").getAbsoluteFile();

    EncodingInfo msg = EncodingInfo.newBuilder().setEncoding("UTF-8").setFilePath(csFile.getAbsolutePath())
            .build();
    try (OutputStream output = Files.newOutputStream(workDir.resolve("output-cs\\encoding.pb"))) {
        msg.writeDelimitedTo(output);
    } catch (IOException e) {
        throw new IllegalStateException("could not save message to file", e);
    }

    Path roslynReport = workDir.resolve("roslyn-report.json");
    Files.write(roslynReport,
            StringUtils
                    .replace(new String(Files.readAllBytes(roslynReport), StandardCharsets.UTF_8), "Program.cs",
                            StringEscapeUtils.escapeJavaScript(csFile.getAbsolutePath()))
                    .getBytes(StandardCharsets.UTF_8),
            StandardOpenOption.WRITE);

    tester = SensorContextTester.create(new File("src/test/resources"));
    tester.fileSystem().setWorkDir(workDir.toFile());

    inputFile = new DefaultInputFile(tester.module().key(), "Program.cs").setLanguage(CSharpPlugin.LANGUAGE_KEY)
            .initMetadata(new FileMetadata().readMetadata(new FileReader(csFile)));
    tester.fileSystem().add(inputFile);

    fileLinesContext = mock(FileLinesContext.class);
    fileLinesContextFactory = mock(FileLinesContextFactory.class);
    when(fileLinesContextFactory.createFor(inputFile)).thenReturn(fileLinesContext);

    extractor = mock(SonarAnalyzerScannerExtractor.class);
    when(extractor.executableFile(CSharpPlugin.LANGUAGE_KEY))
            .thenReturn(new File(workDir.toFile(), SystemUtils.IS_OS_WINDOWS ? "fake.bat" : "fake.sh"));

    noSonarFilter = mock(NoSonarFilter.class);
    settings = new Settings();

    CSharpConfiguration csConfigConfiguration = new CSharpConfiguration(settings);
    sensor = new CSharpSensor(settings, extractor, fileLinesContextFactory, noSonarFilter,
            csConfigConfiguration,
            new EncodingPerFile(
                    ProjectDefinition.create().setProperty(CoreProperties.ENCODING_PROPERTY, "UTF-8"),
                    new SonarQubeVersion(tester.getSonarQubeVersion())));
}

From source file:com.github.jinahya.verbose.codec.BinaryCodecTest.java

protected final void encodeDecode(final ReadableByteChannel expectedChannel) throws IOException {

    if (expectedChannel == null) {
        throw new NullPointerException("null expectedChannel");
    }//from  w  ww .ja  v  a 2  s.co  m

    final Path encodedPath = Files.createTempFile("test", null);
    getRuntime().addShutdownHook(new Thread(() -> {
        try {
            Files.delete(encodedPath);
        } catch (final IOException ioe) {
            ioe.printStackTrace(System.err);
        }
    }));
    final WritableByteChannel encodedChannel = FileChannel.open(encodedPath, StandardOpenOption.WRITE);

    final ByteBuffer decodedBuffer = ByteBuffer.allocate(128);
    final ByteBuffer encodedBuffer = ByteBuffer.allocate(decodedBuffer.capacity() << 1);

    while (expectedChannel.read(decodedBuffer) != -1) {
        decodedBuffer.flip(); // limit -> position; position -> zero
        encoder.encode(decodedBuffer, encodedBuffer);
        encodedBuffer.flip();
        encodedChannel.write(encodedBuffer);
        encodedBuffer.compact(); // position -> n  + 1; limit -> capacity
        decodedBuffer.compact();
    }

    decodedBuffer.flip();
    while (decodedBuffer.hasRemaining()) {
        encoder.encode(decodedBuffer, encodedBuffer);
        encodedBuffer.flip();
        encodedChannel.write(encodedBuffer);
        encodedBuffer.compact();
    }

    encodedBuffer.flip();
    while (encodedBuffer.hasRemaining()) {
        encodedChannel.write(encodedBuffer);
    }
}

From source file:neembuu.uploader.v2tov3conversion.ConvertUploaderClass.java

public void writeTo(Path out) throws IOException {
    Files.write(out, out_lines, Charset.defaultCharset(), StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);
}

From source file:de.tuberlin.uebb.jbop.access.ClassAccessor.java

/**
 * Stores a classfile for the given Classdescriptor.
 * /*from   w  ww  .ja  va 2  s  . c o  m*/
 * The Class for the File could be loaded with the ClassLoader proposed by this
 * Class ({@link #getClassloader()}) or any suitable ClassLoader using the returned
 * Path of the Classfile.
 * 
 * @param classDescriptor
 *          the class descriptor
 * @return the path of the written File
 * @throws JBOPClassException
 *           the jBOP class exception
 */
public static Path store(final ClassDescriptor classDescriptor) throws JBOPClassException {

    final Path packageDir = Paths.get(TMP_DIR.toString(), classDescriptor.getPackageDir());
    final Path classFile = Paths.get(packageDir.toString(), classDescriptor.getSimpleName() + ".class");
    try {
        Files.createDirectories(packageDir);
        Files.write(classFile, classDescriptor.getClassData(), StandardOpenOption.CREATE,
                StandardOpenOption.WRITE);
        classDescriptor.setFile(classFile.toString());
        return classFile;
    } catch (final IOException e) {
        throw new JBOPClassException(
                "Data of Class " + classDescriptor.getName() + " could not be written to file.", e);
    }
}

From source file:org.cryptomator.ui.InitializeController.java

@FXML
protected void initializeVault(ActionEvent event) {
    setControlsDisabled(true);//from   w w  w .j a  v a2 s  .c o m
    if (!isDirectoryEmpty() && !shouldEncryptExistingFiles()) {
        return;
    }
    final String masterKeyFileName = usernameField.getText() + Aes256Cryptor.MASTERKEY_FILE_EXT;
    final Path masterKeyPath = directory.getPath().resolve(masterKeyFileName);
    final CharSequence password = passwordField.getCharacters();
    OutputStream masterKeyOutputStream = null;
    try {
        progressIndicator.setVisible(true);
        masterKeyOutputStream = Files.newOutputStream(masterKeyPath, StandardOpenOption.WRITE,
                StandardOpenOption.CREATE_NEW);
        directory.getCryptor().encryptMasterKey(masterKeyOutputStream, password);
        final Future<?> futureDone = FXThreads.runOnBackgroundThread(this::encryptExistingContents);
        FXThreads.runOnMainThreadWhenFinished(futureDone, (result) -> {
            progressIndicator.setVisible(false);
            progressIndicator.setVisible(false);
            directory.getCryptor().swipeSensitiveData();
            if (listener != null) {
                listener.didInitialize(this);
            }
        });
    } catch (FileAlreadyExistsException ex) {
        setControlsDisabled(false);
        progressIndicator.setVisible(false);
        messageLabel.setText(localization.getString("initialize.messageLabel.alreadyInitialized"));
    } catch (InvalidPathException ex) {
        setControlsDisabled(false);
        progressIndicator.setVisible(false);
        messageLabel.setText(localization.getString("initialize.messageLabel.invalidPath"));
    } catch (IOException ex) {
        setControlsDisabled(false);
        progressIndicator.setVisible(false);
        LOG.error("I/O Exception", ex);
    } finally {
        usernameField.setText(null);
        passwordField.swipe();
        retypePasswordField.swipe();
        IOUtils.closeQuietly(masterKeyOutputStream);
    }
}