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:com.oneops.daq.dao.PerfDao.java

/**
 * Sets the state filename and open a file channel for writing.
 *
 * @param filename file name of state//  ww w.  ja  va  2 s  .co m
 */
public void setStateFilename(String filename) {
    stateFilename = filename;
    File sFile = new File(stateFilename);
    try {
        if (!sFile.exists()) {
            sFile.createNewFile();
        }
        logger.info("Creating the file channel for " + stateFilename);
        statChannel = FileChannel.open(Paths.get(stateFilename), StandardOpenOption.WRITE);
    } catch (Exception ex) {
        logger.error("Error setting stat file." + sFile.getAbsolutePath(), ex);
        System.exit(1);
    }
}

From source file:org.darkware.wpman.wpcli.WPCLI.java

/**
 * Update the local WP-CLI tool to the most recent version.
 *///from w w  w . ja  v  a2 s  .  c  o  m
public static void update() {
    try {
        WPManager.log.info("Downloading new version of WP-CLI.");

        CloseableHttpClient httpclient = HttpClients.createDefault();

        URI pharURI = new URIBuilder().setScheme("http").setHost("raw.githubusercontent.com")
                .setPath("/wp-cli/builds/gh-pages/phar/wp-cli.phar").build();

        WPManager.log.info("Downloading from: {}", pharURI);
        HttpGet downloadRequest = new HttpGet(pharURI);

        CloseableHttpResponse response = httpclient.execute(downloadRequest);

        WPManager.log.info("Download response: {}", response.getStatusLine());
        WPManager.log.info("Download content type: {}", response.getFirstHeader("Content-Type").getValue());

        FileChannel wpcliFile = FileChannel.open(WPCLI.toolPath, StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);

        response.getEntity().writeTo(Channels.newOutputStream(wpcliFile));
        wpcliFile.close();

        Set<PosixFilePermission> wpcliPerms = new HashSet<>();
        wpcliPerms.add(PosixFilePermission.OWNER_READ);
        wpcliPerms.add(PosixFilePermission.OWNER_WRITE);
        wpcliPerms.add(PosixFilePermission.OWNER_EXECUTE);
        wpcliPerms.add(PosixFilePermission.GROUP_READ);
        wpcliPerms.add(PosixFilePermission.GROUP_EXECUTE);

        Files.setPosixFilePermissions(WPCLI.toolPath, wpcliPerms);
    } catch (URISyntaxException e) {
        WPManager.log.error("Failure building URL for WPCLI download.", e);
        System.exit(1);
    } catch (IOException e) {
        WPManager.log.error("Error while downloading WPCLI client.", e);
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:com.willwinder.universalgcodesender.model.GUIBackendPreprocessorTest.java

@Test
public void testGcodeStreamPreprocessAndExportToFile() throws Exception {
    System.out.println("gcodeStreamPreprocessAndExportToFile");
    GUIBackend backend = new GUIBackend();
    GcodeParser gcp = new GcodeParser();

    // Double all the commands that go in.
    gcp.addCommandProcessor(commandDoubler);

    // Create GcodeStream input file by putting it through the preprocessor.
    List<String> lines = Arrays.asList("line one", "line two");
    Files.write(outputFile, lines, Charset.defaultCharset(), StandardOpenOption.WRITE);
    backend.preprocessAndExportToFile(gcp, outputFile.toFile(), inputFile.toFile());

    // Pass a gcodestream into 
    backend.preprocessAndExportToFile(gcp, inputFile.toFile(), outputFile.toFile());

    List<String> expectedResults = Arrays.asList("line one", "line one", "line one", "line one", "line two",
            "line two", "line two", "line two");

    try (GcodeStreamReader reader = new GcodeStreamReader(outputFile.toFile())) {
        Assert.assertEquals(expectedResults.size(), reader.getNumRows());

        for (String expected : expectedResults) {
            Assert.assertEquals(expected, reader.getNextCommand().getCommandString());
        }//  w  w  w .j  a  va  2  s .co  m
    }
}

From source file:com.reactive.hzdfs.io.MemoryMappedChunkHandler.java

@Override
public void writeNext(FileChunk chunk) throws IOException {
    log.debug("[writeNext] " + chunk);
    if (file == null) {
        initWriteFile(chunk);//from  w  w w. j  ava2 s  .c o m
        oStream = FileChannel.open(file.toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE,
                StandardOpenOption.APPEND);

        /*
         * From javadocs:
         * "The behavior of this method when the requested region is not completely contained within this channel's file is unspecified. 
         * Whether changes made to the content or size of the underlying file, by this program or another, are propagated to the buffer 
         * is unspecified. The rate at which changes to the buffer are propagated to the file is unspecified."
         * 
         * Initially this is a 0 byte file. So how do we write to a new file??
         */
        log.debug("mapping byte buffer for write");
        mapBuff = oStream.map(MapMode.READ_WRITE, 0, chunk.getFileSize());

        if (log.isDebugEnabled()) {
            debugInitialParams();
            log.debug("Writing to target file- " + file + ". Expecting chunks to receive- " + chunk.getSize());
        }
    }

    doAttribCheck(chunk);

    //this is probably unreachable
    if (!mapBuff.hasRemaining()) {
        position += mapBuff.position();
        unmap(mapBuff);
        mapBuff = oStream.map(MapMode.READ_WRITE, position, chunk.getFileSize());
    }

    mapBuff.put(chunk.getChunk());
    fileSize += chunk.getChunk().length;

    if (fileSize > chunk.getFileSize())
        throw new IOException(
                "File size [" + fileSize + "] greater than expected size [" + chunk.getFileSize() + "]");

}

From source file:org.schedulesdirect.grabber.ProgramTask.java

@Override
public void run() {
    long start = System.currentTimeMillis();
    DefaultJsonRequest req = factory.get(DefaultJsonRequest.Action.POST, RestNouns.PROGRAMS, clnt.getHash(),
            clnt.getUserAgent(), clnt.getBaseUrl());
    try {/*from   ww  w .  jav  a  2 s . c  o  m*/
        JSONArray resp = Config.get().getObjectMapper().readValue(req.submitForJson(this.req), JSONArray.class);
        for (int i = 0; i < resp.length(); ++i) {
            JSONObject o = resp.getJSONObject(i);
            String id = o.optString("programID", "<unknown>");
            if (!JsonResponseUtils.isErrorResponse(o)) {
                if (id.startsWith("EP"))
                    seriesIds.add(Program.convertToSeriesId(id));
                Path p = vfs.getPath(targetDir, String.format("%s.txt", id));
                Files.write(p, o.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET), StandardOpenOption.WRITE,
                        StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE);
            } else if (JsonResponseUtils.getErrorCode(o) == ApiResponse.INVALID_PROGID
                    || JsonResponseUtils.getErrorCode(o) == ApiResponse.PROGRAMID_QUEUED) {
                String msg = String.format("Missing program object: %s", id);
                if (!logMissingAtDebug)
                    LOG.warn(msg);
                else
                    LOG.debug(msg);
                if (retrySet != null)
                    retrySet.add(id);
            } else
                throw new InvalidJsonObjectException("Error received for Program", o.toString(3));
        }
    } catch (JSONException | JsonParseException e) {
        Grabber.failedTask = true;
        LOG.error("JSONError!", e);
        throw new RuntimeException(e);
    } catch (IOException e) {
        Grabber.failedTask = true;
        LOG.error("IOError receiving program data; filling in empty program info for non-existent program ids!",
                e);
        try {
            JSONArray ids = this.req;
            for (int i = 0; i < ids.length(); ++i) {
                String id = ids.getString(i);
                Path p = vfs.getPath(targetDir, String.format("%s.txt", id));
                if (!Files.exists(p))
                    Files.write(p, Program.EMPTY_PROGRAM.getBytes(ZipEpgClient.ZIP_CHARSET));
            }
        } catch (Exception x) {
            LOG.error("Unexpected error!", x);
            throw new RuntimeException(x);
        }
    }
    LOG.info(String.format("Completed ProgramTask in %dms [%d programs]", System.currentTimeMillis() - start,
            this.req.length()));
}

From source file:org.cryptomator.ui.settings.SettingsProvider.java

private void save(Settings settings) {
    Objects.requireNonNull(settings);
    try {/* w  w w  . j a va  2s .c  om*/
        final Path settingsPath = getSettingsPath();
        Files.createDirectories(settingsPath.getParent());
        final OutputStream out = Files.newOutputStream(settingsPath, StandardOpenOption.WRITE,
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE);
        objectMapper.writeValue(out, settings);
        LOG.info("Settings saved to " + settingsPath);
    } catch (IOException e) {
        LOG.error("Failed to save settings.", e);
    }
}

From source file:io.github.dsheirer.record.wave.WaveWriter.java

/**
 * Opens the file and writes a wave header.
 *///w  w w .  j a va2s  . c  o  m
private void open() throws IOException {
    int version = 2;

    while (Files.exists(mFile)) {
        mFile = Paths.get(mFile.toFile().getAbsolutePath().replace(".wav", "_" + version + ".wav"));
        version++;
    }

    mFileChannel = (FileChannel.open(mFile, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW));

    ByteBuffer header = getWaveHeader(mAudioFormat);

    while (header.hasRemaining()) {
        mFileChannel.write(header);
    }
}

From source file:org.kalypso.grid.BinaryGeoGrid.java

/**
 * Opens an existing grid for read-only access.<br>
 * Dispose the grid after it is no more needed in order to release the given resource.
 * //from   w w  w . ja v  a  2  s.c  o  m
 * @param writeable
 *          If <code>true</code>, the grid is opened for writing and a {@link IWriteableGeoGrid} is returned.
 */
public static BinaryGeoGrid openGrid(final URL url, final Coordinate origin, final Coordinate offsetX,
        final Coordinate offsetY, final String sourceCRS, final boolean writeable) throws IOException {
    /* Tries to find a file from the given url. */
    File fileFromUrl = ResourceUtilities.findJavaFileFromURL(url);
    File binFile = null;
    if (fileFromUrl == null)
        fileFromUrl = FileUtils.toFile(url);

    if (fileFromUrl == null) {
        /*
         * If url cannot be converted to a file, write its contents to a temporary file which will be deleted after the
         * grid gets disposed.
         */
        fileFromUrl = File.createTempFile("local", ".bin");
        fileFromUrl.deleteOnExit();
        FileUtils.copyURLToFile(url, fileFromUrl);
        binFile = fileFromUrl; // set in order to delete on dispose
    }

    FileChannel channel;
    if (writeable)
        channel = FileChannel.open(fileFromUrl.toPath(), StandardOpenOption.WRITE, StandardOpenOption.READ);
    else
        channel = FileChannel.open(fileFromUrl.toPath(), StandardOpenOption.READ);

    return new BinaryGeoGrid(channel, binFile, origin, offsetX, offsetY, sourceCRS);
}

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

@Override
public long createFileAtomic(String fileName, InputStream inputStream) throws IOException {
    long fileSize;
    Path filePath = this.directory.resolve(fileName);
    Path fileTempPath = this.directory.resolve(fileName + ".part");

    try (ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream);
            FileChannel fc = FileChannel.open(fileTempPath, StandardOpenOption.WRITE,
                    StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE)) {
        fileSize = fc.transferFrom(readableByteChannel, 0, Long.MAX_VALUE);
    }//w  w w .  j av  a2  s  .co  m

    Files.move(fileTempPath, filePath);

    return fileSize;
}

From source file:io.druid.indexing.worker.executor.ExecutorLifecycle.java

@LifecycleStart
public void start() throws InterruptedException {
    final File taskFile = Preconditions.checkNotNull(taskExecutorConfig.getTaskFile(), "taskFile");
    final File statusFile = Preconditions.checkNotNull(taskExecutorConfig.getStatusFile(), "statusFile");
    final InputStream parentStream = Preconditions.checkNotNull(taskExecutorConfig.getParentStream(),
            "parentStream");

    try {/*w  w w  . j ava  2  s . c  o m*/
        task = jsonMapper.readValue(taskFile, Task.class);

        log.info("Running with task: %s", jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(task));
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }

    // Avoid running the same task twice on the same machine by locking the task base directory.

    final File taskLockFile = taskConfig.getTaskLockFile(task.getId());

    try {
        synchronized (this) {
            if (taskLockChannel == null && taskLockFileLock == null) {
                taskLockChannel = FileChannel.open(taskLockFile.toPath(), StandardOpenOption.CREATE,
                        StandardOpenOption.WRITE);

                log.info("Attempting to lock file[%s].", taskLockFile);
                final long startLocking = System.currentTimeMillis();
                final long timeout = DateTimes.utc(startLocking).plus(taskConfig.getDirectoryLockTimeout())
                        .getMillis();
                while (taskLockFileLock == null && System.currentTimeMillis() < timeout) {
                    taskLockFileLock = taskLockChannel.tryLock();
                    if (taskLockFileLock == null) {
                        Thread.sleep(100);
                    }
                }

                if (taskLockFileLock == null) {
                    throw new ISE("Could not acquire lock file[%s] within %,dms.", taskLockFile,
                            timeout - startLocking);
                } else {
                    log.info("Acquired lock file[%s] in %,dms.", taskLockFile,
                            System.currentTimeMillis() - startLocking);
                }
            } else {
                throw new ISE("Already started!");
            }
        }
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }

    if (taskExecutorConfig.isParentStreamDefined()) {
        // Spawn monitor thread to keep a watch on parent's stdin
        // If stdin reaches eof, the parent is gone, and we should shut down
        parentMonitorExec.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    while (parentStream.read() != -1) {
                        // Toss the byte
                    }
                } catch (Exception e) {
                    log.error(e, "Failed to read from stdin");
                }

                // Kind of gross, but best way to kill the JVM as far as I know
                log.info("Triggering JVM shutdown.");
                System.exit(2);
            }
        });
    }

    // Won't hurt in remote mode, and is required for setting up locks in local mode:
    try {
        if (!task.isReady(taskActionClientFactory.create(task))) {
            throw new ISE("Task[%s] is not ready to run yet!", task.getId());
        }
    } catch (Exception e) {
        throw new ISE(e, "Failed to run task[%s] isReady", task.getId());
    }

    statusFuture = Futures.transform(taskRunner.run(task), new Function<TaskStatus, TaskStatus>() {
        @Override
        public TaskStatus apply(TaskStatus taskStatus) {
            try {
                log.info("Task completed with status: %s",
                        jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(taskStatus));

                final File statusFileParent = statusFile.getParentFile();
                if (statusFileParent != null) {
                    FileUtils.forceMkdir(statusFileParent);
                }
                jsonMapper.writeValue(statusFile, taskStatus);

                return taskStatus;
            } catch (Exception e) {
                throw Throwables.propagate(e);
            }
        }
    });
}