Example usage for java.nio.file StandardOpenOption CREATE

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

Introduction

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

Prototype

StandardOpenOption CREATE

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

Click Source Link

Document

Create a new file if it does not exist.

Usage

From source file:io.spotnext.maven.mojo.TransformTypesMojo.java

private void trackExecution(String message) throws IllegalStateException {
    if (debug) {//from  ww w .j a v  a2 s .c o m
        try {
            File tempDir = FileUtils.getTempDirectory();

            Files.write(Paths.get(tempDir.getAbsolutePath(), "transform-classes.log"),
                    (new Date().toString() + ": " + message + "\n").getBytes(StandardCharsets.UTF_8),
                    StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        } catch (Exception e) {
            throw new IllegalStateException("error", e);
        }
    }
}

From source file:net.sf.jabref.gui.journals.ManageJournalsPanel.java

private void storeSettings() {
    Path filePath = null;//ww  w.  j a  v a 2s . com
    if (newFile.isSelected()) {
        if (!newNameTf.getText().isEmpty()) {
            filePath = Paths.get(newNameTf.getText());
        }
    } else {
        filePath = Paths.get(personalFile.getText());

    }

    if (filePath != null) {
        try (OutputStream stream = Files.newOutputStream(filePath, StandardOpenOption.CREATE);
                OutputStreamWriter writer = new OutputStreamWriter(stream,
                        Globals.prefs.getDefaultEncoding())) {
            for (JournalEntry entry : tableModel.getJournals()) {
                writer.write(entry.getName());
                writer.write(" = ");
                writer.write(entry.getAbbreviation());
                writer.write(Globals.NEWLINE);
            }
        } catch (IOException e) {
            LOGGER.warn("Problem writing abbreviation file", e);
        }
        String filename = filePath.toString();
        if ("".equals(filename)) {
            filename = null;
        }
        Globals.prefs.put(JabRefPreferences.PERSONAL_JOURNAL_LIST, filename);
    }

    // Store the list of external files set up:
    List<String> extFiles = new ArrayList<>();
    for (ExternalFileEntry efe : externals) {
        if (!"".equals(efe.getValue())) {
            extFiles.add(efe.getValue());
        }
    }
    Globals.prefs.putStringList(JabRefPreferences.EXTERNAL_JOURNAL_LISTS, extFiles);

    // Update journal abbreviation loader
    Globals.journalAbbreviationLoader.update(JournalAbbreviationPreferences.fromPreferences(Globals.prefs));
}

From source file:org.apache.nifi.controller.repository.VolatileContentRepository.java

@Override
public long exportTo(final ContentClaim claim, final Path destination, final boolean append, final long offset,
        final long length) throws IOException {
    if (claim == null) {
        if (append) {
            return 0L;
        }/*from   w  w w .  j  av a2s.  c o  m*/
        Files.createFile(destination);
        return 0L;
    }

    final StandardOpenOption openOption = append ? StandardOpenOption.APPEND : StandardOpenOption.CREATE;
    try (final InputStream in = read(claim);
            final OutputStream destinationStream = Files.newOutputStream(destination, openOption)) {

        if (offset > 0) {
            StreamUtils.skip(in, offset);
        }

        StreamUtils.copy(in, destinationStream, length);
        return length;
    }
}

From source file:codes.thischwa.c5c.impl.LocalConnector.java

@Override
public void saveFile(String backendPath, String content) throws C5CException {
    Path file = buildRealPath(backendPath);
    OutputStream out = null;//from w w  w . jav  a2  s.c om
    try {
        out = Files.newOutputStream(file, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
        IOUtils.write(content, out, PropertiesLoader.getDefaultEncoding());
    } catch (IOException e) {
        logger.warn("Error while saving content of {}", backendPath);
        throw new C5CException(FilemanagerAction.SAVEFILE, e.getMessage());
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:org.opencb.cellbase.app.transform.VariationParser.java

private Path addVariationIdToTranscriptVariationFile(Map<Integer, Integer> variationFeatureToVariationId)
        throws IOException {
    Path transcriptVariationTempFile = variationDirectoryPath.resolve(TRANSCRIPT_VARIATION_FILENAME + ".tmp");
    this.logger.info("Adding variation Id to transcript variations and saving them into "
            + transcriptVariationTempFile + " ...");
    Stopwatch stopwatch = Stopwatch.createStarted();

    Path unpreprocessedTranscriptVariationFile = variationDirectoryPath.resolve(TRANSCRIPT_VARIATION_FILENAME);
    BufferedReader br = getBufferedReader(unpreprocessedTranscriptVariationFile);
    BufferedWriter bw = Files.newBufferedWriter(transcriptVariationTempFile, Charset.defaultCharset(),
            StandardOpenOption.CREATE, StandardOpenOption.WRITE);

    String line;//from  w  ww  . j  av a 2s  .  c om
    while ((line = br.readLine()) != null) {
        // TODO: add limit parameter would do that run faster?
        // TODO: use a precompiled pattern would improve efficiency
        Integer variationFeatureId = Integer.valueOf(line.split("\t")[1]);
        Integer variationId = variationFeatureToVariationId.get(variationFeatureId);
        bw.write(line + "\t" + variationId + "\n");
    }

    br.close();
    bw.close();

    this.logger.info("Added");
    this.logger.debug("Elapsed time adding variation Id to transcript variation file: " + stopwatch);

    return transcriptVariationTempFile;
}

From source file:org.elasticsearch.plugins.PluginManagerIT.java

/**
 * @deprecated support for this is not going to stick around, seriously.
 *///w ww  .  ja  v  a 2 s  . co  m
@Deprecated
public void testAlreadyInstalledNotIsolated() throws Exception {
    String pluginName = "fake-plugin";
    Path pluginDir = createTempDir().resolve(pluginName);
    Files.createDirectories(pluginDir);
    // create a jar file in the plugin
    Path pluginJar = pluginDir.resolve("fake-plugin.jar");
    try (ZipOutputStream out = new JarOutputStream(
            Files.newOutputStream(pluginJar, StandardOpenOption.CREATE))) {
        out.putNextEntry(new ZipEntry("foo.class"));
        out.closeEntry();
    }
    String pluginUrl = createPlugin(pluginDir, "description", "fake desc", "name", pluginName, "version", "1.0",
            "elasticsearch.version", Version.CURRENT.toString(), "java.version",
            System.getProperty("java.specification.version"), "isolated", "false", "jvm", "true", "classname",
            "FakePlugin");

    // install
    ExitStatus status = new PluginManagerCliParser(terminal).execute(args("install " + pluginUrl));
    assertEquals("unexpected exit status: output: " + terminal.getTerminalOutput(), ExitStatus.OK, status);

    // install again
    status = new PluginManagerCliParser(terminal).execute(args("install " + pluginUrl));
    List<String> output = terminal.getTerminalOutput();
    assertEquals("unexpected exit status: output: " + output, ExitStatus.IO_ERROR, status);
    boolean foundExpectedMessage = false;
    for (String line : output) {
        foundExpectedMessage |= line.contains("already exists");
    }
    assertTrue(foundExpectedMessage);
}

From source file:org.ballerinalang.test.packaging.PackagingNegativeTestCase.java

/**
 * Override content in file.//from w w  w  .j  a  v a 2  s . c o m
 *
 * @param filePath path of file to override
 * @param content  content to be written
 * @throws IOException
 */
private void writeToFile(Path filePath, String content) throws IOException {
    Files.write(filePath, content.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
}

From source file:io.druid.segment.realtime.appenderator.AppenderatorImpl.java

private void lockBasePersistDirectory() {
    if (basePersistDirLock == null) {
        try {/*from  w  w  w.j a  v a 2 s .co  m*/
            basePersistDirLockChannel = FileChannel.open(computeLockFile().toPath(), StandardOpenOption.CREATE,
                    StandardOpenOption.WRITE);

            basePersistDirLock = basePersistDirLockChannel.tryLock();
            if (basePersistDirLock == null) {
                throw new ISE("Cannot acquire lock on basePersistDir: %s", computeLockFile());
            }
        } catch (IOException e) {
            throw Throwables.propagate(e);
        }
    }
}

From source file:edu.wustl.lookingglass.community.CommunityRepository.java

private void lockRepo() throws IOException {
    this.syncLockChannel = FileChannel.open(Paths.get(syncLockPath), StandardOpenOption.WRITE,
            StandardOpenOption.CREATE);
    FileLock lock = this.syncLockChannel.lock(); // gets an exclusive lock
    assert lock.isValid();
    this.syncLockChannel.write(ByteBuffer.wrap(ManagementFactory.getRuntimeMXBean().getName().getBytes()));
}

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

private void updateZip(NetworkEpgClient clnt) throws IOException, JSONException, JsonParseException {
    Set<String> completedListings = new HashSet<String>();
    LOG.debug(String.format("Using %d worker threads", globalOpts.getMaxThreads()));
    pool = createThreadPoolExecutor();/*from   ww w  . jav  a 2 s  .  c om*/
    start = System.currentTimeMillis();
    File dest = grabOpts.getTarget();
    cachedSeriesIds = new HashSet<String>();
    boolean rmDest = false;
    if (dest.exists()) {
        ZipEpgClient zipClnt = null;
        try {
            zipClnt = new ZipEpgClient(dest);
            if (!zipClnt.getUserStatus().getLastServerRefresh()
                    .before(clnt.getUserStatus().getLastServerRefresh())) {
                LOG.info(
                        "Current cache file contains latest data from Schedules Direct server; use --force-download to force a new download from server.");
                boolean force = grabOpts.isForce();
                if (!force)
                    return;
                else
                    LOG.warn("Forcing an update of data with the server due to user request!");
            }
        } catch (Exception e) {
            if (grabOpts.isKeep()) {
                LOG.error("Existing cache is invalid, keeping by user request!", e);
                return;
            } else {
                LOG.warn("Existing cache is invalid, deleting it; use --keep-bad-cache to keep existing cache!",
                        e);
                rmDest = true;
            }
        } finally {
            if (zipClnt != null)
                try {
                    zipClnt.close();
                } catch (IOException e) {
                }
            if (rmDest && !dest.delete())
                throw new IOException("Unable to delete " + dest);
        }
    }

    freshZip = !dest.exists();
    try (FileSystem vfs = FileSystems.newFileSystem(new URI(String.format("jar:%s", dest.toURI())),
            Collections.singletonMap("create", "true"))) {
        if (freshZip) {
            Path target = vfs.getPath(ZipEpgClient.ZIP_VER_FILE);
            Files.write(target, Integer.toString(ZipEpgClient.ZIP_VER).getBytes(ZipEpgClient.ZIP_CHARSET));
        }
        ProgramCache progCache = ProgramCache.get(vfs);
        Path lineups = vfs.getPath("lineups.txt");
        Files.deleteIfExists(lineups);
        Path scheds = vfs.getPath("/schedules/");
        if (!Files.isDirectory(scheds))
            Files.createDirectory(scheds);
        Path maps = vfs.getPath("/maps/");
        PathUtils.removeDirectory(maps);
        Files.createDirectory(maps);
        Path progs = vfs.getPath("/programs/");
        if (!Files.isDirectory(progs))
            Files.createDirectory(progs);
        Path logos = vfs.getPath("/logos/");
        if (!Files.isDirectory(logos))
            Files.createDirectory(logos);
        Path md5s = vfs.getPath("/md5s/");
        if (!Files.isDirectory(md5s))
            Files.createDirectory(md5s);
        Path cache = vfs.getPath(LOGO_CACHE);
        if (Files.exists(cache)) {
            String cacheData = new String(Files.readAllBytes(cache), ZipEpgClient.ZIP_CHARSET);
            logoCache = Config.get().getObjectMapper().readValue(cacheData, JSONObject.class);
        } else
            logoCache = new JSONObject();
        Path seriesInfo = vfs.getPath("/seriesInfo/");
        if (!Files.isDirectory(seriesInfo))
            Files.createDirectories(seriesInfo);
        loadSeriesInfoIds(seriesInfo);
        missingSeriesIds = Collections.synchronizedSet(new HashSet<String>());
        loadRetryIds(vfs.getPath(SERIES_INFO_DATA));

        JSONObject resp = Config.get().getObjectMapper().readValue(
                factory.get(DefaultJsonRequest.Action.GET, RestNouns.LINEUPS, clnt.getHash(),
                        clnt.getUserAgent(), globalOpts.getUrl().toString()).submitForJson(null),
                JSONObject.class);
        if (!JsonResponseUtils.isErrorResponse(resp))
            Files.write(lineups, resp.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET));
        else
            LOG.error("Received error response when requesting lineup data!");

        for (Lineup l : clnt.getLineups()) {
            buildStationList();
            JSONObject o = Config.get().getObjectMapper()
                    .readValue(
                            factory.get(DefaultJsonRequest.Action.GET, l.getUri(), clnt.getHash(),
                                    clnt.getUserAgent(), globalOpts.getUrl().toString()).submitForJson(null),
                            JSONObject.class);
            Files.write(vfs.getPath("/maps", ZipEpgClient.scrubFileName(String.format("%s.txt", l.getId()))),
                    o.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET));
            JSONArray stations = o.getJSONArray("stations");
            JSONArray ids = new JSONArray();
            for (int i = 0; i < stations.length(); ++i) {
                JSONObject obj = stations.getJSONObject(i);
                String sid = obj.getString("stationID");
                if (stationList != null && !stationList.contains(sid))
                    LOG.debug(String.format("Skipped %s; not listed in station file", sid));
                else if (completedListings.add(sid)) {
                    ids.put(sid);
                    if (!grabOpts.isNoLogos()) {
                        if (logoCacheInvalid(obj))
                            pool.execute(new LogoTask(obj, vfs, logoCache));
                        else if (LOG.isDebugEnabled())
                            LOG.debug(String.format("Skipped logo for %s; already cached!",
                                    obj.optString("callsign", null)));
                    } else if (!logosWarned) {
                        logosWarned = true;
                        LOG.warn("Logo downloads disabled by user request!");
                    }
                } else
                    LOG.debug(String.format("Skipped %s; already downloaded.", sid));
                //pool.setMaximumPoolSize(5); // Processing these new schedules takes all kinds of memory!
                if (ids.length() == grabOpts.getMaxSchedChunk()) {
                    pool.execute(new ScheduleTask(ids, vfs, clnt, progCache, factory));
                    ids = new JSONArray();
                }
            }
            if (ids.length() > 0)
                pool.execute(new ScheduleTask(ids, vfs, clnt, progCache, factory));
        }
        pool.shutdown();
        try {
            LOG.debug("Waiting for SchedLogoExecutor to terminate...");
            if (pool.awaitTermination(15, TimeUnit.MINUTES))
                LOG.debug("SchedLogoExecutor: Terminated successfully.");
            else {
                failedTask = true;
                LOG.warn(
                        "SchedLogoExecutor: Termination timed out; some tasks probably didn't finish properly!");
            }
        } catch (InterruptedException e) {
            failedTask = true;
            LOG.warn(
                    "SchedLogoExecutor: Termination interrupted); some tasks probably didn't finish properly!");
        }
        Files.write(cache, logoCache.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET),
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
        ScheduleTask.commit(vfs);

        pool = createThreadPoolExecutor();
        //pool.setMaximumPoolSize(5); // Again, we've got memory problems
        String[] dirtyPrograms = progCache.getDirtyIds();
        progCache.markAllClean();
        progCache = null;
        LOG.info(String.format("Identified %d program ids requiring an update!", dirtyPrograms.length));
        Collection<String> progIds = new ArrayList<String>();
        for (String progId : dirtyPrograms) {
            progIds.add(progId);
            if (progIds.size() == grabOpts.getMaxProgChunk()) {
                pool.execute(new ProgramTask(progIds, vfs, clnt, factory, missingSeriesIds, "programs", null,
                        false));
                progIds.clear();
            }
        }
        if (progIds.size() > 0)
            pool.execute(
                    new ProgramTask(progIds, vfs, clnt, factory, missingSeriesIds, "programs", null, false));
        pool.shutdown();
        try {
            LOG.debug("Waiting for ProgramExecutor to terminate...");
            if (pool.awaitTermination(15, TimeUnit.MINUTES)) {
                LOG.debug("ProgramExecutor: Terminated successfully.");
                Iterator<String> itr = missingSeriesIds.iterator();
                while (itr.hasNext()) {
                    String id = itr.next();
                    if (cachedSeriesIds.contains(id))
                        itr.remove();
                }
                if (missingSeriesIds.size() > 0) {
                    LOG.info(String.format("Grabbing %d series info programs!", missingSeriesIds.size()));
                    Set<String> retrySet = new HashSet<>();
                    try {
                        new ProgramTask(missingSeriesIds, vfs, clnt, factory, missingSeriesIds, "seriesInfo",
                                retrySet, true).run();
                    } catch (RuntimeException e) {
                        LOG.error("SeriesInfo task failed!", e);
                        Grabber.failedTask = true;
                    }
                    Path seriesInfoData = vfs.getPath(SERIES_INFO_DATA);
                    if (retrySet.size() > 0) {
                        StringBuilder sb = new StringBuilder();
                        for (String id : retrySet)
                            sb.append(id + "\n");
                        Files.write(seriesInfoData, sb.toString().getBytes(ZipEpgClient.ZIP_CHARSET),
                                StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING,
                                StandardOpenOption.CREATE);
                    } else if (Files.exists(seriesInfoData))
                        Files.delete(seriesInfoData);
                }
            } else {
                failedTask = true;
                LOG.warn("ProgramExecutor: Termination timed out; some tasks probably didn't finish properly!");
            }
        } catch (InterruptedException e) {
            failedTask = true;
            LOG.warn("ProgramExecutor: Termination interrupted); some tasks probably didn't finish properly!");
        }

        String userData = clnt.getUserStatus().toJson();
        if (failedTask) {
            LOG.error("One or more tasks failed!  Resetting last data refresh timestamp to zero.");
            SimpleDateFormat fmt = Config.get().getDateTimeFormat();
            String exp = fmt.format(new Date(0L));
            JSONObject o = Config.get().getObjectMapper().readValue(userData, JSONObject.class);
            o.put("lastDataUpdate", exp);
            userData = o.toString(2);
        }
        Path p = vfs.getPath(USER_DATA);
        Files.write(p, userData.getBytes(ZipEpgClient.ZIP_CHARSET), StandardOpenOption.WRITE,
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE);
        removeIgnoredStations(vfs);
    } catch (URISyntaxException e1) {
        throw new RuntimeException(e1);
    } finally {
        Runtime rt = Runtime.getRuntime();
        LOG.info(String.format("MemStats:%n\tFREE: %s%n\tUSED: %s%n\t MAX: %s",
                FileUtils.byteCountToDisplaySize(rt.freeMemory()),
                FileUtils.byteCountToDisplaySize(rt.totalMemory()),
                FileUtils.byteCountToDisplaySize(rt.maxMemory())));
    }
}