List of usage examples for java.nio.file Files newBufferedWriter
public static BufferedWriter newBufferedWriter(Path path, OpenOption... options) throws IOException
From source file:org.kurento.room.test.AutodiscoveryKmsUrlTest.java
@Test public void test() throws IOException { Path backup = null;/* w w w .j a va 2 s .co m*/ Path configFile = Paths.get(StandardSystemProperty.USER_HOME.value(), ".kurento", "config.properties"); System.setProperty("kms.uris", "[\"autodiscovery\"]"); try { if (Files.exists(configFile)) { backup = configFile.getParent().resolve("config.properties.old"); Files.move(configFile, backup); log.debug("Backed-up old config.properties"); } Files.createDirectories(configFile.getParent()); try (BufferedWriter writer = Files.newBufferedWriter(configFile, StandardCharsets.UTF_8)) { writer.write("kms.url.provider: " + TestKmsUrlProvider.class.getName() + "\r\n"); } String contents = new String(Files.readAllBytes(configFile)); log.debug("Config file contents:\n{}", contents); ConfigurableApplicationContext app = KurentoRoomServerApp.start(new String[] { "--server.port=7777" }); NotificationRoomManager notifRoomManager = app.getBean(NotificationRoomManager.class); final RoomManager roomManager = notifRoomManager.getRoomManager(); final KurentoClientSessionInfo kcSessionInfo = new DefaultKurentoClientSessionInfo("participantId", "roomName"); new Thread(new Runnable() { @Override public void run() { roomManager.joinRoom("userName", "roomName", false, kcSessionInfo, "participantId"); } }).start(); try { Boolean result = queue.poll(10, TimeUnit.SECONDS); if (result == null) { fail("Event in KmsUrlProvider not called"); } else { if (!result) { fail("Test failed"); } } } catch (InterruptedException e) { fail("KmsUrlProvider was not called"); } } finally { Files.delete(configFile); if (backup != null) { Files.move(backup, configFile); } } }
From source file:eu.itesla_project.modules.rules.CheckSecurityTool.java
private static void writeCsv2(Map<String, Map<SecurityIndexId, SecurityRuleCheckStatus>> checkStatusPerBaseCase, Path outputCsvFile) throws IOException { Objects.requireNonNull(outputCsvFile); Set<SecurityIndexId> securityIndexIds = new LinkedHashSet<>(); for (Map<SecurityIndexId, SecurityRuleCheckStatus> checkStatus : checkStatusPerBaseCase.values()) { securityIndexIds.addAll(checkStatus.keySet()); }// w w w . j a va2s .c om try (BufferedWriter writer = Files.newBufferedWriter(outputCsvFile, StandardCharsets.UTF_8)) { writer.write("Base case"); for (SecurityIndexId securityIndexId : securityIndexIds) { writer.write(CSV_SEPARATOR); writer.write(securityIndexId.toString()); } writer.newLine(); for (Map.Entry<String, Map<SecurityIndexId, SecurityRuleCheckStatus>> entry : checkStatusPerBaseCase .entrySet()) { String baseCaseName = entry.getKey(); writer.write(baseCaseName); Map<SecurityIndexId, SecurityRuleCheckStatus> checkStatus = entry.getValue(); for (SecurityIndexId securityIndexId : securityIndexIds) { writer.write(CSV_SEPARATOR); SecurityRuleCheckStatus status = checkStatus.get(securityIndexId); writer.write(status.name()); } writer.newLine(); } } }
From source file:eu.itesla_project.eurostag.EurostagExportTool.java
@Override public void run(CommandLine line) throws Exception { ComponentDefaultConfig defaultConfig = ComponentDefaultConfig.load(); EurostagConfig eurostagConfig = EurostagConfig.load(); Path caseFile = Paths.get(line.getOptionValue("case-file")); Path outputDir = Paths.get(line.getOptionValue("output-dir")); if (!Files.isDirectory(outputDir)) { throw new RuntimeException(outputDir + " is not a directory"); }//from w w w . ja v a 2 s . co m DynamicDatabaseClient ddbClient = new IIDMDynamicDatabaseFactory().create(eurostagConfig.isDdbCaching()); System.out.println("loading case..."); // load network Network network = Importers.loadNetwork(caseFile); if (network == null) { throw new RuntimeException("Case '" + caseFile + "' not found"); } network.getStateManager().allowStateMultiThreadAccess(true); System.out.println("exporting ech..."); // export .ech and dictionary EurostagEchExportConfig exportConfig = new EurostagEchExportConfig(); BranchParallelIndexes parallelIndexes = BranchParallelIndexes.build(network, exportConfig); EurostagDictionary dictionary = EurostagDictionary.create(network, parallelIndexes, exportConfig); new EurostagEchExport(network, exportConfig, parallelIndexes, dictionary) .write(outputDir.resolve("sim.ech")); try (Writer writer = Files.newBufferedWriter(outputDir.resolve("sim.ech"), StandardCharsets.UTF_8)) { EsgGeneralParameters parameters = new EsgGeneralParameters(); parameters.setTransformerVoltageControl(false); parameters.setSvcVoltageControl(false); EsgNetwork networkEch = new EurostagEchExport(network, exportConfig, parallelIndexes, dictionary) .createNetwork(parameters); new EurostagNetworkModifier().hvLoadModelling(networkEch); new EsgWriter(networkEch, parameters).write(writer, network.getId() + "/" + network.getStateManager().getWorkingStateId()); } dictionary.dump(outputDir.resolve("dict.csv")); System.out.println("exporting dta..."); // export .dta ddbClient.dumpDtaFile(outputDir, "sim.dta", network, parallelIndexes.toMap(), EurostagUtil.VERSION, dictionary.toMap()); System.out.println("exporting seq..."); // export .seq EurostagScenario scenario = new EurostagScenario(SimulationParameters.load(), eurostagConfig); try (BufferedWriter writer = Files.newBufferedWriter(outputDir.resolve(PRE_FAULT_SEQ_FILE_NAME), StandardCharsets.UTF_8)) { scenario.writePreFaultSeq(writer, PRE_FAULT_SAC_FILE_NAME); } ContingenciesProvider contingenciesProvider = defaultConfig .newFactoryImpl(ContingenciesProviderFactory.class).create(); scenario.writeFaultSeqArchive(contingenciesProvider.getContingencies(network), network, dictionary, faultNum -> FAULT_SEQ_FILE_NAME.replace( eu.itesla_project.computation.Command.EXECUTION_NUMBER_PATTERN, Integer.toString(faultNum))) .as(ZipExporter.class).exportTo(outputDir.resolve(ALL_SCENARIOS_ZIP_FILE_NAME).toFile()); // export limits try (OutputStream os = Files.newOutputStream(outputDir.resolve(LIMITS_ZIP_FILE_NAME))) { EurostagImpactAnalysis.writeLimits(network, dictionary, os); } }
From source file:org.tallison.cc.CCGetter.java
private void execute(Path indexFile, Path rootDir, Path statusFile) throws IOException { int count = 0; BufferedWriter writer = Files.newBufferedWriter(statusFile, StandardCharsets.UTF_8); InputStream is = null;/*from www. j a v a 2 s . com*/ try { if (indexFile.endsWith(".gz")) { is = new BufferedInputStream(new GZIPInputStream(Files.newInputStream(indexFile))); } else { is = new BufferedInputStream(Files.newInputStream(indexFile)); } try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) { String line = reader.readLine(); while (line != null) { processRow(line, rootDir, writer); if (++count % 100 == 0) { logger.info(indexFile.getFileName().toString() + ": " + count); } line = reader.readLine(); } } } finally { IOUtils.closeQuietly(is); try { writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:io.github.robwin.swagger2markup.petstore.Swagger2MarkupTest.java
@Test public void createSpringfoxSwaggerJson() throws Exception { //String designFirstSwaggerLocation = Swagger2MarkupTest.class.getResource("/swagger.yaml").getPath(); String outputDir = System.getProperty("io.springfox.staticdocs.outputDir"); MvcResult mvcResult = this.mockMvc.perform(get("/v2/api-docs").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andReturn(); MockHttpServletResponse response = mvcResult.getResponse(); String swaggerJson = response.getContentAsString(); Files.createDirectories(Paths.get(outputDir)); try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, "swagger.json"), StandardCharsets.UTF_8)) { writer.write(swaggerJson);/*from w ww .j a v a 2 s . c o m*/ } }
From source file:com.google.cloud.runtimes.builder.buildsteps.docker.StageDockerArtifactBuildStep.java
@Override protected void doBuild(Path directory, Map<String, String> metadata) throws BuildStepException { try {//from w w w . j av a 2 s. c om // TODO wrap this in a try block and log a more friendly message if not found Path artifact = getArtifact(directory, metadata); logger.info("Found artifact {}", artifact); // make staging dir Path stagingDir = directory.resolve(DOCKER_STAGING_DIR); if (Files.exists(stagingDir)) { logger.info("Found a docker staging directory in provided sources. Cleaning {}", stagingDir.toString()); FileUtils.deleteDirectory(stagingDir.toFile()); } Files.createDirectory(stagingDir); metadata.put(BuildStepMetadataConstants.DOCKER_STAGING_PATH, stagingDir.toString()); logger.info("Preparing docker files in {}", stagingDir); // copy the artifact into the staging dir Files.copy(artifact, stagingDir.resolve(artifact.getFileName())); // copy the .dockerignore file into staging dir, if it exists Path dockerIgnoreFile = directory.resolve(DOCKER_IGNORE_FILE); if (Files.isRegularFile(dockerIgnoreFile)) { Files.copy(dockerIgnoreFile, stagingDir.resolve(DOCKER_IGNORE_FILE)); } // Generate dockerfile String dockerfile = dockerfileGenerator.generateDockerfile(artifact.getFileName()); Path dockerFileDest = stagingDir.resolve("Dockerfile"); try (BufferedWriter writer = Files.newBufferedWriter(dockerFileDest, StandardCharsets.US_ASCII)) { writer.write(dockerfile); } } catch (IOException | ArtifactNotFoundException | TooManyArtifactsException e) { throw new BuildStepException(e); } }
From source file:net.sourceforge.pmd.renderers.YAHTMLRenderer.java
private void renderIndex(String outputDir) throws IOException { try (PrintWriter out = new PrintWriter( Files.newBufferedWriter(new File(outputDir, "index.html").toPath(), StandardCharsets.UTF_8))) { out.println("<!DOCTYPE html>"); out.println("<html>"); out.println(" <head>"); out.println(" <meta charset=\"UTF-8\">"); out.println(" <title>PMD</title>"); out.println(" </head>"); out.println(" <body>"); out.println(" <h2>Package View</h2>"); out.println(" <table border=\"1\" align=\"center\" cellspacing=\"0\" cellpadding=\"3\">"); out.println(" <tr><th>Package</th><th>Class</th><th>#</th></tr>"); for (ReportNode node : reportNodesByPackage.values()) { out.print(" <tr><td><b>"); out.print(node.getPackageName()); out.print("</b></td> <td>"); if (node.hasViolations()) { out.print("<a href=\""); out.print(node.getClassName()); out.print(".html"); out.print("\">"); out.print(node.getClassName()); out.print("</a>"); } else { out.print(node.getClassName()); }//from ww w . j av a2s . c om out.print("</td> <td>"); out.print(node.getViolationCount()); out.print("</td></tr>"); out.println(); } out.println(" </table>"); out.println(" </body>"); out.println("</html>"); } }
From source file:eu.itesla_project.modules.validation.OverloadValidationTool.java
private static void writeCsv(Set<String> contingencyIds, Map<String, Map<String, OverloadStatus>> statusPerContingencyPerCase, Path outputDir) throws IOException { try (BufferedWriter writer = Files.newBufferedWriter(outputDir.resolve("comparison.csv"), StandardCharsets.UTF_8)) { writer.write("base case"); for (String contingencyId : contingencyIds) { writer.write(CSV_SEPARATOR); writer.write(contingencyId + " load flow"); writer.write(CSV_SEPARATOR); writer.write(contingencyId + " offline rule"); }/* w ww . ja va 2 s . c o m*/ writer.newLine(); for (Map.Entry<String, Map<String, OverloadStatus>> e : statusPerContingencyPerCase.entrySet()) { String baseCaseName = e.getKey(); Map<String, OverloadStatus> statusPerContingency = e.getValue(); writer.write(baseCaseName); for (String contingencyId : contingencyIds) { OverloadStatus overloadStatus = statusPerContingency.get(contingencyId); writer.write(CSV_SEPARATOR); writer.write(Boolean.toString(overloadStatus.isLfOk())); writer.write(CSV_SEPARATOR); writer.write(Boolean.toString(overloadStatus.isOfflineRuleOk())); } writer.newLine(); } } List<String> categories = Arrays.asList("OK_OK", "NOK_NOK", "OK_NOK", "NOK_OK"); Map<String, Map<String, AtomicInteger>> synthesisPerContingency = new HashMap<>(); for (String contingencyId : contingencyIds) { synthesisPerContingency.put(contingencyId, categories.stream().collect(Collectors.toMap(Function.identity(), e -> new AtomicInteger()))); } for (Map.Entry<String, Map<String, OverloadStatus>> e : statusPerContingencyPerCase.entrySet()) { Map<String, OverloadStatus> statusPerContingency = e.getValue(); for (String contingencyId : contingencyIds) { OverloadStatus overloadStatus = statusPerContingency.get(contingencyId); synthesisPerContingency.get(contingencyId).get( okToString(overloadStatus.isLfOk()) + "_" + okToString(overloadStatus.isOfflineRuleOk())) .incrementAndGet(); } } try (BufferedWriter writer = Files.newBufferedWriter(outputDir.resolve("synthesis.csv"), StandardCharsets.UTF_8)) { writer.write("contingency"); for (String c : categories) { writer.write(CSV_SEPARATOR); writer.write(c); } writer.newLine(); for (Map.Entry<String, Map<String, AtomicInteger>> e : synthesisPerContingency.entrySet()) { String contingencyId = e.getKey(); Map<String, AtomicInteger> count = e.getValue(); writer.write(contingencyId); for (String c : categories) { writer.write(CSV_SEPARATOR); writer.write(Integer.toString(count.get(c).get())); } writer.newLine(); } } }
From source file:org.onehippo.cms7.essentials.dashboard.utils.GlobalUtils.java
/** * Write text content to a file (UTF-8)//from ww w . jav a 2s .co m * * @param content text content * @param path path to save file to */ public static void writeToFile(final CharSequence content, final Path path) { try (BufferedWriter writer = Files.newBufferedWriter(path, Charsets.UTF_8)) { writer.append(content); writer.flush(); } catch (IOException e) { log.error("Error writing file {}", e); } }
From source file:eu.itesla_project.modules.histo.tools.PrintCaseAttributesTool.java
@Override public void run(CommandLine line) throws Exception { String caseFormat = line.getOptionValue("case-format"); Path caseDir = Paths.get(line.getOptionValue("case-dir")); Set<HistoDbAttributeId> attributeIds = new LinkedHashSet<>(); for (String str : line.getOptionValue("attributes").split(",")) { attributeIds.add(HistoDbAttributeIdParser.parse(str)); }/*from w w w.j a v a 2s .co m*/ Path outputCsvFile = Paths.get(line.getOptionValue("output-csv-file")); try (ComputationManager computationManager = new LocalComputationManager()) { Importer importer = Importers.getImporter(caseFormat, computationManager); if (importer == null) { throw new ITeslaException("Format " + caseFormat + " not supported"); } try (BufferedWriter writer = Files.newBufferedWriter(outputCsvFile, StandardCharsets.UTF_8)) { writer.write("Case name"); for (HistoDbAttributeId attributeId : attributeIds) { writer.write(CSV_SEPARATOR); writer.write(attributeId.toString()); } writer.newLine(); Importers.importAll(caseDir, importer, false, network -> { try { writer.write(network.getId()); Map<HistoDbAttributeId, Object> values = IIDM2DB .extractCimValues(network, new IIDM2DB.Config(null, false)).getSingleValueMap(); for (HistoDbAttributeId attributeId : attributeIds) { writer.write(CSV_SEPARATOR); Object value = values.get(attributeId); if (value != null) { writer.write(value.toString()); } } writer.newLine(); } catch (Exception e) { LOGGER.error(e.toString(), e); } }); } } }