List of usage examples for java.nio.file Files write
public static Path write(Path path, Iterable<? extends CharSequence> lines, Charset cs, OpenOption... options) throws IOException
From source file:eu.freme.bpt.service.FailurePolicyTest.java
private File createDir() throws IOException { File dir = Files.createTempDirectory("testDir").toFile(); try {/*from w ww . ja v a 2 s .c o m*/ FileUtils.forceDeleteOnExit(dir); } catch (IOException e) { e.printStackTrace(); } // now create some files in it File file1 = new File(dir, "file1"); File file2 = new File(dir, "file2"); Files.write(file1.toPath(), "Hello".getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.WRITE); Files.write(file2.toPath(), "World".getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.WRITE); return dir; }
From source file:ai.susi.mind.SusiIdentity.java
/** * Add a cognition to the identity. This will cause that we forget cognitions after * the awareness threshold has passed.//www .ja v a 2 s . co m * @param cognition * @return self */ public SusiIdentity add(SusiCognition cognition) { this.short_term_memory.learn(cognition); List<SusiCognition> forgottenCognitions = this.short_term_memory.limitAwareness(this.attention); forgottenCognitions.forEach(c -> this.long_term_memory.learn(c)); // TODO add a rule to memorize only the most important ones try { Files.write(this.memorydump.toPath(), UTF8.getBytes(cognition.getJSON().toString(0) + "\n"), StandardOpenOption.APPEND, StandardOpenOption.CREATE); } catch (JSONException | IOException e) { e.printStackTrace(); } return this; }
From source file:org.elasticsearch.xpack.security.authc.esnative.tool.SetupPasswordToolIT.java
@SuppressWarnings("unchecked") public void testSetupPasswordToolAutoSetup() throws Exception { final String testConfigDir = System.getProperty("tests.config.dir"); logger.info("--> CONF: {}", testConfigDir); final Path configPath = PathUtils.get(testConfigDir); setSystemPropsForTool(configPath);/*from w w w . j a v a 2 s.co m*/ Response nodesResponse = client().performRequest("GET", "/_nodes/http"); Map<String, Object> nodesMap = entityAsMap(nodesResponse); Map<String, Object> nodes = (Map<String, Object>) nodesMap.get("nodes"); Map<String, Object> firstNode = (Map<String, Object>) nodes.entrySet().iterator().next().getValue(); Map<String, Object> firstNodeHttp = (Map<String, Object>) firstNode.get("http"); String nodePublishAddress = (String) firstNodeHttp.get("publish_address"); final int lastColonIndex = nodePublishAddress.lastIndexOf(':'); InetAddress actualPublishAddress = InetAddresses.forString(nodePublishAddress.substring(0, lastColonIndex)); InetAddress expectedPublishAddress = new NetworkService(Collections.emptyList()) .resolvePublishHostAddresses(Strings.EMPTY_ARRAY); final int port = Integer.valueOf(nodePublishAddress.substring(lastColonIndex + 1)); List<String> lines = Files.readAllLines(configPath.resolve("elasticsearch.yml")); lines = lines.stream() .filter(s -> s.startsWith("http.port") == false && s.startsWith("http.publish_port") == false) .collect(Collectors.toList()); lines.add(randomFrom("http.port", "http.publish_port") + ": " + port); if (expectedPublishAddress.equals(actualPublishAddress) == false) { lines.add("http.publish_address: " + InetAddresses.toAddrString(actualPublishAddress)); } Files.write(configPath.resolve("elasticsearch.yml"), lines, StandardCharsets.UTF_8, StandardOpenOption.TRUNCATE_EXISTING); MockTerminal mockTerminal = new MockTerminal(); SetupPasswordTool tool = new SetupPasswordTool(); final int status; if (randomBoolean()) { mockTerminal.addTextInput("y"); // answer yes to continue prompt status = tool.main(new String[] { "auto" }, mockTerminal); } else { status = tool.main(new String[] { "auto", "--batch" }, mockTerminal); } assertEquals(0, status); String output = mockTerminal.getOutput(); logger.info("CLI TOOL OUTPUT:\n{}", output); String[] outputLines = output.split("\\n"); Map<String, String> userPasswordMap = new HashMap<>(); Arrays.asList(outputLines).forEach(line -> { if (line.startsWith("PASSWORD ")) { String[] pieces = line.split(" "); String user = pieces[1]; String password = pieces[pieces.length - 1]; logger.info("user [{}] password [{}]", user, password); userPasswordMap.put(user, password); } }); assertEquals(4, userPasswordMap.size()); userPasswordMap.entrySet().forEach(entry -> { final String basicHeader = "Basic " + Base64.getEncoder() .encodeToString((entry.getKey() + ":" + entry.getValue()).getBytes(StandardCharsets.UTF_8)); try { Response authenticateResponse = client().performRequest("GET", "/_xpack/security/_authenticate", new BasicHeader("Authorization", basicHeader)); assertEquals(200, authenticateResponse.getStatusLine().getStatusCode()); Map<String, Object> userInfoMap = entityAsMap(authenticateResponse); assertEquals(entry.getKey(), userInfoMap.get("username")); } catch (IOException e) { throw new UncheckedIOException(e); } }); }
From source file:org.cloudfoundry.dependency.resource.InAction.java
private void writeVersion() { try {/*from w ww.j a va 2s. com*/ String version = new VersionHolder(this.request.getVersion().getRef()).toRepositoryVersion(); Path versionFile = Files.createDirectories(this.destination).resolve("version"); Files.write(versionFile, Collections.singletonList(version), StandardOpenOption.CREATE, StandardOpenOption.WRITE); } catch (IOException e) { throw Exceptions.propagate(e); } }
From source file:no.imr.stox.functions.acoustic.PgNapesIO.java
public static void export2(String cruise, String country, String callSignal, String path, String fileName, List<DistanceBO> distances, Double groupThickness, Integer freqFilter, String specFilter, boolean withZeros) { Set<Integer> freqs = distances.stream().flatMap(dist -> dist.getFrequencies().stream()) .map(FrequencyBO::getFreq).collect(Collectors.toSet()); if (freqFilter == null && freqs.size() == 1) { freqFilter = freqs.iterator().next(); }// ww w.j a v a 2 s. co m if (freqFilter == null) { System.out.println("Multiple frequencies, specify frequency filter as parameter"); return; } Integer freqFilterF = freqFilter; // ef.final List<String> acList = distances.parallelStream().flatMap(dist -> dist.getFrequencies().stream()) .filter(fr -> freqFilterF.equals(fr.getFreq())).map(f -> { DistanceBO d = f.getDistanceBO(); LocalDateTime sdt = LocalDateTime.ofInstant(d.getStart_time().toInstant(), ZoneOffset.UTC); Double intDist = d.getIntegrator_dist(); String month = StringUtils.leftPad(sdt.getMonthValue() + "", 2, "0"); String day = StringUtils.leftPad(sdt.getDayOfMonth() + "", 2, "0"); String hour = StringUtils.leftPad(sdt.getHour() + "", 2, "0"); String minute = StringUtils.leftPad(sdt.getMinute() + "", 2, "0"); String log = Conversion.formatDoubletoDecimalString(d.getLog_start(), "0.0"); String acLat = Conversion.formatDoubletoDecimalString(d.getLat_start(), "0.000"); String acLon = Conversion.formatDoubletoDecimalString(d.getLon_start(), "0.000"); return Stream .of(d.getNation(), d.getPlatform(), d.getCruise(), log, sdt.getYear(), month, day, hour, minute, acLat, acLon, intDist, f.getFreq(), f.getThreshold()) .map(o -> o == null ? "" : o.toString()).collect(Collectors.joining("\t")) + "\t"; }).collect(Collectors.toList()); String fil1 = path + "/" + fileName + ".txt"; acList.add(0, Stream.of("Country", "Vessel", "Cruise", "Log", "Year", "Month", "Day", "Hour", "Min", "AcLat", "AcLon", "Logint", "Frequency", "Sv_threshold").collect(Collectors.joining("\t"))); try { Files.write(Paths.get(fil1), acList, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); } catch (IOException ex) { Logger.getLogger(PgNapesIO.class.getName()).log(Level.SEVERE, null, ex); } acList.clear(); // Acoustic values distances.stream().filter(d -> d.getPel_ch_thickness() != null) .flatMap(dist -> dist.getFrequencies().stream()).filter(fr -> freqFilterF.equals(fr.getFreq())) .forEachOrdered(f -> { try { Double groupThicknessF = Math.max(f.getDistanceBO().getPel_ch_thickness(), groupThickness); Map<String, Map<Integer, Double>> pivot = f.getSa().stream() .filter(s -> s.getCh_type().equals("P")).map(s -> new SAGroup(s, groupThicknessF)) .filter(s -> s.getSpecies() != null && (specFilter == null || specFilter.equals(s.getSpecies()))) // create pivot table: species (dim1) -> depth interval index (dim2) -> sum sa (group aggregator) .collect(Collectors.groupingBy(SAGroup::getSpecies, Collectors.groupingBy( SAGroup::getDepthGroupIdx, Collectors.summingDouble(SAGroup::sa)))); if (pivot.isEmpty() && specFilter != null && withZeros) { pivot.put(specFilter, new HashMap<>()); } Integer maxGroupIdx = pivot.entrySet().stream().flatMap(e -> e.getValue().keySet().stream()) .max(Integer::compare).orElse(null); if (maxGroupIdx == null) { return; } acList.addAll(pivot.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey)) .flatMap(e -> { return IntStream.range(0, maxGroupIdx + 1).boxed().map(groupIdx -> { Double chUpDepth = groupIdx * groupThicknessF; Double chLowDepth = (groupIdx + 1) * groupThicknessF; Double sa = e.getValue().get(groupIdx); if (sa == null) { sa = 0d; } String res = null; if (withZeros || sa > 0d) { DistanceBO d = f.getDistanceBO(); String log = Conversion.formatDoubletoDecimalString(d.getLog_start(), "0.0"); LocalDateTime sdt = LocalDateTime .ofInstant(d.getStart_time().toInstant(), ZoneOffset.UTC); String month = StringUtils.leftPad(sdt.getMonthValue() + "", 2, "0"); String day = StringUtils.leftPad(sdt.getDayOfMonth() + "", 2, "0"); //String sas = String.format(Locale.UK, "%11.5f", sa); res = Stream .of(d.getNation(), d.getPlatform(), d.getCruise(), log, sdt.getYear(), month, day, e.getKey(), chUpDepth, chLowDepth, sa) .map(o -> o == null ? "" : o.toString()) .collect(Collectors.joining("\t")); } return res; }).filter(s -> s != null); }).collect(Collectors.toList())); } catch (Exception e) { e.printStackTrace(); } }); String fil2 = path + "/" + fileName + "Values.txt"; acList.add(0, Stream.of("Country", "Vessel", "Cruise", "Log", "Year", "Month", "Day", "Species", "ChUppDepth", "ChLowDepth", "SA").collect(Collectors.joining("\t"))); try { Files.write(Paths.get(fil2), acList, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); } catch (IOException ex) { Logger.getLogger(PgNapesIO.class.getName()).log(Level.SEVERE, null, ex); } }
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 av a 2 s.c om } }
From source file:com.ontotext.s4.service.S4ServiceClientIntegrationTest.java
@Test public void testAnnotateFileContentsDescClient() throws Exception { File f = new File("test-file"); try {//w ww . jav a 2 s . c o m Path p = f.toPath(); ArrayList<String> lines = new ArrayList<>(1); lines.add(documentText); Files.write(p, lines, Charset.forName("UTF-8"), StandardOpenOption.CREATE); AnnotatedDocument result = apiDesc.annotateFileContents(f, Charset.forName("UTF-8"), documentMimeType); assertTrue(result.getText().contains("Barack")); } finally { f.delete(); } }
From source file:com.ontotext.s4.service.S4ServiceClientIntegrationTest.java
@Test public void testClassifyFileContentsDescClient() throws Exception { ServiceDescriptor temp = ServicesCatalog.getItem("news-classifier"); S4ServiceClient client = new S4ServiceClient(temp, testApiKeyId, testApiKeyPass); File f = new File("test-file"); try {//from www . j av a2 s. c o m Path p = f.toPath(); ArrayList<String> lines = new ArrayList<>(1); lines.add(documentText); Files.write(p, lines, Charset.forName("UTF-8"), StandardOpenOption.CREATE); ClassifiedDocument result = client.classifyFileContents(f, Charset.forName("UTF-8"), documentMimeType); assertNotNull(result.getCategory()); assertEquals(3, result.getAllScores().size()); } finally { f.delete(); } }
From source file:io.apiman.common.es.util.ApimanEmbeddedElastic.java
private void writeProcessId() throws IOException { try {//from w w w. j a v a 2s.co m // Create parent directory (i.e. ~/.cache/apiman/es-pid-{identifier}) Files.createDirectories(pidPath.getParent()); // Get the elasticServer instance variable Field elasticServerField = elastic.getClass().getDeclaredField("elasticServer"); elasticServerField.setAccessible(true); Object elasticServerInstance = elasticServerField.get(elastic); // ElasticServer package-scoped so we can't get the real type. // Get the process ID (pid) long field from ElasticServer Field pidField = elasticServerInstance.getClass().getDeclaredField("pid"); pidField.setAccessible(true); pid = (int) pidField.get(elasticServerInstance); // Get the pid // Write to the PID file Files.write(pidPath, String.valueOf(pid).getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND); } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException(e); } }
From source file:org.eclipse.che.api.local.storage.stack.StackLocalStorage.java
/** * Save {@link StackIcon} of the {@code stack} to the local storage * * @param stack/*from w w w. j a v a2s .co m*/ * {@link StackImpl} which contains {@link StackIcon} to store */ private void saveIcon(StackImpl stack) { try { StackIcon stackIcon = stack.getStackIcon(); if (stackIcon != null && stackIcon.getData() != null) { Path iconParentDirectory = iconFolderPath.resolve(stack.getId()); Files.createDirectories(iconParentDirectory); Path iconPath = iconParentDirectory.resolve(stackIcon.getName()); Files.write(iconPath, stackIcon.getData(), CREATE, TRUNCATE_EXISTING); } } catch (IOException ex) { LOG.error(format("Failed to save icon for stack with id '%s'", stack.getId()), ex); } }