List of usage examples for java.nio.file StandardOpenOption TRUNCATE_EXISTING
StandardOpenOption TRUNCATE_EXISTING
To view the source code for java.nio.file StandardOpenOption TRUNCATE_EXISTING.
Click Source Link
From source file:org.basinmc.maven.plugins.minecraft.AbstractArtifactMojo.java
/** * Fetches any resources from a remote HTTP server and stores it in a specified file. *///from w ww . j a v a2 s.c om protected void fetch(@Nonnull URI uri, @Nonnull Path target) throws IOException { this.fetch(uri, FileChannel.open(target, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)); }
From source file:org.darkware.wpman.security.ChecksumDatabase.java
/** * Write the database to the attached file path. This path is declared in the constructor and cannot be * changed./* w w w .j a v a 2 s. c om*/ */ public void writeDatabase() { this.lock.writeLock().lock(); try { ChecksumDatabase.log.info("Writing integrity database: {}", this.dbFile); try (BufferedWriter db = Files.newBufferedWriter(this.dbFile, StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) { for (Map.Entry<Path, String> entry : this.hashes.entrySet()) { db.write(entry.getKey().toString()); db.write(":"); db.write(entry.getValue()); db.newLine(); } } catch (IOException e) { ChecksumDatabase.log.error("Error while writing integrity database: {}", e.getLocalizedMessage(), e); } } finally { this.lock.writeLock().unlock(); } }
From source file:org.cyclop.service.common.FileStorage.java
private FileChannel openForWrite(Path histPath) throws IOException { FileChannel byteChannel = FileChannel.open(histPath, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE); byteChannel.force(true);/*from w w w .j av a2s . c om*/ FileChannel lockChannel = lock(histPath, byteChannel); return lockChannel; }
From source file:com.evolveum.midpoint.model.intest.manual.CsvBackingStore.java
protected void replaceInCsv(String[] data) throws IOException { List<String> lines = Files.readAllLines(Paths.get(CSV_TARGET_FILE.getPath())); boolean found = false; for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); String[] cols = line.split(","); if (cols[0].matches("\"" + data[0] + "\"")) { lines.set(i, formatCsvLine(data)); found = true;//from ww w . j av a2 s . c o m } } if (!found) { throw new IllegalStateException("Not found in CSV: " + data[0]); } Files.write(Paths.get(CSV_TARGET_FILE.getPath()), lines, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); }
From source file:org.eclipse.vorto.remoterepository.internal.dao.FilesystemModelDAO.java
@Override public ModelView saveModel(ModelContent modelContent) { ModelId mID = modelContent.getModelId(); ModelView mv = ModelFactory.newModelView(mID, "Newly Added Model, ...."); Path dirToSave = this.resolveDirectoryPathToModel(mID); Path fileToSave = this.resolvePathToModel(mID); try {//w w w. j a v a 2 s . com if (!Files.exists(dirToSave)) { Files.createDirectories(dirToSave); } if (!Files.exists(fileToSave)) { Files.createFile(fileToSave); } else { Files.deleteIfExists(fileToSave); } Files.write(fileToSave, modelContent.getContent(), StandardOpenOption.TRUNCATE_EXISTING); return mv; } catch (IOException e) { throw new RuntimeException("An I/O error was thrown while saving new model file: " + mID.toString(), e); } }
From source file:org.apache.metron.dataloads.nonbulk.flatfile.SimpleEnrichmentFlatFileLoaderIntegrationTest.java
@BeforeClass public static void setup() throws Exception { UnitTestHelper.setJavaLoggingLevel(Level.SEVERE); Map.Entry<HBaseTestingUtility, Configuration> kv = HBaseUtil.INSTANCE.create(true); config = kv.getValue();// w w w .j a va 2 s. co m testUtil = kv.getKey(); testTable = testUtil.createTable(Bytes.toBytes(tableName), Bytes.toBytes(cf)); zookeeperUrl = getZookeeperUrl(config.get("hbase.zookeeper.quorum"), testUtil.getZkCluster().getClientPort()); setupGlobalConfig(zookeeperUrl); for (Result r : testTable.getScanner(Bytes.toBytes(cf))) { Delete d = new Delete(r.getRow()); testTable.delete(d); } if (lineByLineExtractorConfigFile.exists()) { lineByLineExtractorConfigFile.delete(); } Files.write(lineByLineExtractorConfigFile.toPath(), lineByLineExtractorConfig.getBytes(), StandardOpenOption.CREATE_NEW, StandardOpenOption.TRUNCATE_EXISTING); if (wholeFileExtractorConfigFile.exists()) { wholeFileExtractorConfigFile.delete(); } Files.write(wholeFileExtractorConfigFile.toPath(), wholeFileExtractorConfig.getBytes(), StandardOpenOption.CREATE_NEW, StandardOpenOption.TRUNCATE_EXISTING); if (stellarExtractorConfigFile.exists()) { stellarExtractorConfigFile.delete(); } Files.write(stellarExtractorConfigFile.toPath(), stellarExtractorConfig.replace("%ZK_QUORUM%", zookeeperUrl).getBytes(), StandardOpenOption.CREATE_NEW, StandardOpenOption.TRUNCATE_EXISTING); if (customLineByLineExtractorConfigFile.exists()) { customLineByLineExtractorConfigFile.delete(); } Files.write( customLineByLineExtractorConfigFile.toPath(), customLineByLineExtractorConfig .replace("%EXTRACTOR_CLASS%", CSVExtractor.class.getName()).getBytes(), StandardOpenOption.CREATE_NEW, StandardOpenOption.TRUNCATE_EXISTING); if (file1.exists()) { file1.delete(); } Files.write(file1.toPath(), "google1.com,1,foo2\n".getBytes(), StandardOpenOption.CREATE_NEW, StandardOpenOption.TRUNCATE_EXISTING); if (file2.exists()) { file2.delete(); } Files.write(file2.toPath(), "google2.com,2,foo2\n".getBytes(), StandardOpenOption.CREATE_NEW, StandardOpenOption.TRUNCATE_EXISTING); if (multilineFile.exists()) { multilineFile.delete(); } if (multilineGzFile.exists()) { multilineGzFile.delete(); } if (multilineGzFile.exists()) { multilineZipFile.delete(); } PrintWriter[] pws = new PrintWriter[] {}; try { ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(multilineZipFile)); ZipEntry entry = new ZipEntry("file"); zos.putNextEntry(entry); pws = new PrintWriter[] { new PrintWriter(multilineFile), new PrintWriter(zos), new PrintWriter(new GZIPOutputStream(new FileOutputStream(multilineGzFile))) }; for (int i = 0; i < NUM_LINES; ++i) { for (PrintWriter pw : pws) { pw.println("google" + i + ".com," + i + ",foo" + i); } } } finally { for (PrintWriter pw : pws) { pw.close(); } } }
From source file:it.greenvulcano.configuration.BaseConfigurationManager.java
@Override public synchronized void saveXMLConfigProperties(Properties xmlConfigProperties) throws IOException { if (xmlConfigProperties != null) { try (OutputStream xmlConfigPropertiesOutputStream = Files.newOutputStream( Paths.get(XMLConfig.getBaseConfigPath(), "XMLConfig.properties"), StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) { xmlConfigProperties.store(xmlConfigPropertiesOutputStream, null); }/*from w w w. ja va 2s. c o m*/ } }
From source file:org.jboss.pull.player.LabelProcessor.java
/** * Processes the pull requests {@link #add(org.jboss.dmr.ModelNode) added}. * <p/>//from w w w . ja va 2 s . c o m * This should normally only be invoked once as it makes API calls to GitHub. */ void process() { try { // Get all the open issues to lessen the hits to the API final ModelNode openIssues = getIssues(); // Process each issue in the model for (Property property : issuesModel.asPropertyList()) { final ModelNode value = property.getValue(); // Get the PR url final String prUrl = value.get("pull_request_url").asString(); if (openIssues.hasDefined(prUrl)) { final ModelNode openIssue = openIssues.get(prUrl); // Get the current labels final List<String> currentLabels = getLabels(openIssue); // If no labels are present, we can delete the issue if (currentLabels.isEmpty()) { issuesModel.remove(property.getName()); } else { boolean changeRequired = false; // Process the labels only requiring a change if the label was defined in the configuration final List<String> newLabels = new ArrayList<>(); for (String label : currentLabels) { if (labels.isRemovable(label)) { final String newLabel = labels.getReplacement(label); if (newLabel != null) { newLabels.add(newLabel); } changeRequired = true; } else { newLabels.add(label); } } // Check that the PR has been changed and a change is required if (changeRequired && value.hasDefined("new-sha")) { final String issueUrl = value.get("issue_url").asString(); // Set the new labels setLabels(issueUrl, newLabels); // Node needs to be removed issuesModel.remove(property.getName()); } else if (!changeRequired) { // No change in labels has been required, remove the issue issuesModel.remove(property.getName()); } } } else { // The issue/PR may be closed, we can just delete it issuesModel.remove(property.getName()); } } // Write the issues out to a file try (final PrintWriter writer = new PrintWriter(Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.SYNC, StandardOpenOption.CREATE))) { issuesModel.writeJSONString(writer, false); } } catch (IOException e) { e.printStackTrace(err); } }
From source file:org.ballerinalang.test.packaging.ImportModuleTestCase.java
/** * Importing installed modules in test sources. * * @throws BallerinaTestException When an error occurs executing the command. *///from w ww .ja v a 2 s . c om @Test(description = "Test importing installed modules in test sources") public void testResolveImportsFromInstalledModulesInTests() throws BallerinaTestException, IOException { Path projPath = tempProjectDirectory.resolve("thirdProj"); Files.createDirectories(projPath); FileUtils.copyDirectory( Paths.get((new File("src/test/resources/import-test-in-cache")).getAbsolutePath()).toFile(), projPath.toFile()); Files.createDirectories(projPath.resolve(".ballerina")); // ballerina install abc balClient.runMain("install", new String[] { "mod2" }, envVariables, new String[] {}, new LogLeecher[] {}, projPath.toString()); // Delete module 'abc' from the project PackagingTestUtils.deleteFiles(projPath.resolve("mod2")); PackagingTestUtils.deleteFiles(projPath.resolve(".ballerina").resolve("repo")); // Rename org-name to "natasha" in Ballerina.toml Path tomlFilePath = projPath.resolve("Ballerina.toml"); String content = "[project]\norg-name = \"natasha\"\nversion = \"1.0.0\"\n"; Files.write(tomlFilePath, content.getBytes(), StandardOpenOption.TRUNCATE_EXISTING); // Module fanny/mod2 will be picked from home repository since it was installed before balClient.runMain("build", new String[] {}, envVariables, new String[] {}, new LogLeecher[] {}, projPath.toString()); Assert.assertTrue(Files.exists(projPath.resolve(".ballerina").resolve("repo").resolve("natasha") .resolve("mod1").resolve("1.0.0").resolve("mod1.zip"))); LogLeecher sLeecher = new LogLeecher("Hello!! I got a message from a cached repository module --> 100"); balClient.runMain("test", new String[] { "mod1" }, envVariables, new String[] {}, new LogLeecher[] { sLeecher }, projPath.toString()); sLeecher.waitForText(3000); }
From source file:io.spotnext.maven.mojo.TransformTypesMojo.java
/** {@inheritDoc} */ @Override//from w ww .j a v a 2 s. c o m public void execute() throws MojoExecutionException { if (skip) { getLog().info("Skipping type transformation!"); return; } trackExecution("start"); final ClassLoader classLoader = getClassloader(); final List<ClassFileTransformer> transformers = getClassFileTransformers(classLoader); List<File> classFiles = FileUtils.getFiles(project.getBuild().getOutputDirectory(), f -> f.getAbsolutePath().endsWith(".class")); getLog().debug("Found class files for processing: " + classFiles.stream().map(f -> f.getName()).collect(Collectors.joining(", "))); if (CollectionUtils.isNotEmpty(transformers)) { if (CollectionUtils.isNotEmpty(classFiles)) { getLog().info(String.format("Transforming %s classes", classFiles.size())); for (final File f : classFiles) { if (f.getName().endsWith(Constants.CLASS_EXTENSION)) { String relativeClassFilePath = StringUtils.remove(f.getPath(), project.getBuild().getOutputDirectory()); relativeClassFilePath = StringUtils.removeStart(relativeClassFilePath, "/"); final String className = relativeClassFilePath.substring(0, relativeClassFilePath.length() - Constants.CLASS_EXTENSION.length()); trackExecution("Loading class: " + f.getAbsolutePath()); byte[] byteCode; try { byteCode = Files.readAllBytes(f.toPath()); } catch (final IOException e) { String message = String.format("Can't read bytecode for class %s", className); buildContext.addMessage(f, 0, 0, message, BuildContext.SEVERITY_ERROR, e); throw new IllegalStateException(message, e); } trackExecution("Loaded class: " + f.getAbsolutePath()); for (final ClassFileTransformer t : transformers) { try { // log exceptions into separate folder, to be able to inspect them even if Eclipse swallows them ... if (t instanceof AbstractBaseClassTransformer) { ((AbstractBaseClassTransformer) t).setErrorLogger(this::logError); } // returns null if nothing has been transformed byteCode = t.transform(classLoader, className, null, null, byteCode); } catch (final Exception e) { String exception = "Exception during transformation of class: " + f.getAbsolutePath() + "\n" + e.getMessage(); trackExecution(exception); String message = String.format("Can't transform class %s, transformer %s: %s", className, t.getClass().getSimpleName(), ExceptionUtils.getStackTrace(e)); buildContext.addMessage(f, 0, 0, message, BuildContext.SEVERITY_ERROR, e); throw new MojoExecutionException(exception, e); } } if (byteCode != null && byteCode.length > 0) { try { Files.write(f.toPath(), byteCode, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); trackExecution("Saved transformed class: " + f.getAbsolutePath()); } catch (final IOException e) { String message = "Could not write modified class: " + relativeClassFilePath; buildContext.addMessage(f, 0, 0, message, BuildContext.SEVERITY_ERROR, e); throw new IllegalStateException(message); } finally { buildContext.refresh(f); getLog().info("Applied transformation to type: " + f.getAbsolutePath()); } } else { trackExecution("No changes made for class: " + f.getAbsolutePath()); getLog().debug("No transformation was applied to type: " + f.getAbsolutePath()); } } } } else { getLog().info("No class files found"); } trackExecution("All classes in build output folder transformed"); if (includeJars) { final String packaging = project.getPackaging(); final Artifact artifact = project.getArtifact(); if ("jar".equals(packaging) && artifact != null) { try { final File source = artifact.getFile(); if (source.isFile()) { final File destination = new File(source.getParent(), "instrument.jar"); final JarTransformer transformer = new JarTransformer(getLog(), classLoader, Arrays.asList(source), transformers); transformer.transform(destination); final File sourceRename = new File(source.getParent(), "notransform-" + source.getName()); if (source.renameTo(sourceRename)) { throw new MojoExecutionException(String.format("Could not move %s to %s", source.toString(), sourceRename.toString())); } if (destination.renameTo(sourceRename)) { throw new MojoExecutionException(String.format("Could not move %s to %s", destination.toString(), sourceRename.toString())); } buildContext.refresh(destination); } } catch (final Exception e) { buildContext.addMessage(artifact.getFile(), 0, 0, e.getMessage(), BuildContext.SEVERITY_ERROR, e); throw new MojoExecutionException(e.getMessage(), e); } } else { getLog().debug(String.format("Artifact %s not a jar file", artifact != null ? (artifact.getGroupId() + ":" + artifact.getArtifactId()) : "<null>")); } } } else { getLog().info("No class transformers configured"); } }