List of usage examples for java.nio.file Files newBufferedWriter
public static BufferedWriter newBufferedWriter(Path path, OpenOption... options) throws IOException
From source file:im.bci.gamesitekit.GameSiteKitMain.java
private void buildHtml(Locale locale) throws SAXException, IOException, TemplateException, ParserConfigurationException { Path localeOutputDir = outputDir.resolve(locale.getLanguage()); Files.createDirectories(localeOutputDir); HashMap<String, Object> model = new HashMap<>(); model.put("screenshots", createScreenshotsMV(localeOutputDir)); model.put("lastUpdate", new Date()); freemakerConfiguration.setLocale(locale); freemakerConfiguration.addAutoImport("manifest", "manifest.ftl"); for (String file : Arrays.asList("index", "support")) { try (BufferedWriter w = Files.newBufferedWriter(localeOutputDir.resolve(file + ".html"), Charset.forName("UTF-8"))) { freemakerConfiguration.getTemplate(file + ".ftl").process(model, w); }/*from w w w .j a va 2 s .com*/ } }
From source file:eu.itesla_project.modules.RunSecurityAnalysisTool.java
@Override public void run(CommandLine line) throws Exception { OfflineConfig config = OfflineConfig.load(); String caseFormat = line.getOptionValue("case-format"); Path caseDir = Paths.get(line.getOptionValue("case-dir")); String caseBaseName = line.getOptionValue("case-basename"); Path outputCsvFile = Paths.get(line.getOptionValue("output-csv-file")); boolean detailed = line.hasOption("detailed"); ContingenciesAndActionsDatabaseClient contingencyDb = config.getContingencyDbClientFactoryClass() .newInstance().create();/* ww w . ja v a 2 s . c om*/ LoadFlowFactory loadFlowFactory = config.getLoadFlowFactoryClass().newInstance(); try (ComputationManager computationManager = new LocalComputationManager()) { Importer importer = Importers.getImporter(caseFormat, computationManager); if (importer == null) { throw new RuntimeException("Format " + caseFormat + " not supported"); } Map<String, Map<String, List<LimitViolation>>> statusPerContingencyPerCase = Collections .synchronizedMap(new TreeMap<>()); Set<String> contingencyIds = Collections.synchronizedSet(new LinkedHashSet<>()); if (caseBaseName != null) { System.out.println("loading case " + caseBaseName + " ..."); // load the network Network network = importer.import_(new GenericReadOnlyDataSource(caseDir, caseBaseName), new Properties()); List<Contingency> contingencies = contingencyDb.getContingencies(network); contingencyIds.addAll(contingencies.stream().map(Contingency::getId).collect(Collectors.toList())); StaticSecurityAnalysis securityAnalysis = new StaticSecurityAnalysis(network, loadFlowFactory, computationManager); statusPerContingencyPerCase.put(caseBaseName, securityAnalysis.run(contingencies)); } else { Importers.importAll(caseDir, importer, true, network -> { try { List<Contingency> contingencies = contingencyDb.getContingencies(network); contingencyIds.addAll( contingencies.stream().map(Contingency::getId).collect(Collectors.toList())); StaticSecurityAnalysis securityAnalysis = new StaticSecurityAnalysis(network, loadFlowFactory, computationManager); statusPerContingencyPerCase.put(network.getId(), securityAnalysis.run(contingencies)); } catch (Exception e) { LOGGER.error(e.toString(), e); } }, dataSource -> System.out.println("loading case " + dataSource.getBaseName() + " ...")); } try (BufferedWriter writer = Files.newBufferedWriter(outputCsvFile, StandardCharsets.UTF_8)) { writer.write("base case"); for (String contingencyId : contingencyIds) { writer.write(CSV_SEPARATOR); writer.write(contingencyId); } writer.newLine(); for (Map.Entry<String, Map<String, List<LimitViolation>>> e : statusPerContingencyPerCase .entrySet()) { String baseCaseName = e.getKey(); Map<String, List<LimitViolation>> statusPerContingency = e.getValue(); writer.write(baseCaseName); for (String contingencyId : contingencyIds) { List<LimitViolation> violations = statusPerContingency.get(contingencyId); writer.write(CSV_SEPARATOR); writer.write(toString(violations, detailed)); } writer.newLine(); } } } }
From source file:it.tidalwave.bluemarine2.persistence.impl.DefaultPersistence.java
/******************************************************************************************************************* * * Exports the repository to the given file. * * @param path where to export the data to * @throws RDFHandlerException// w w w . j a v a 2s .com * @throws IOException * @throws RepositoryException * ******************************************************************************************************************/ @Override public void exportToFile(final @Nonnull Path path) throws RDFHandlerException, IOException, RepositoryException { log.info("exportToFile({})", path); Files.createDirectories(path.getParent()); try (final PrintWriter pw = new PrintWriter(Files.newBufferedWriter(path, UTF_8)); final RepositoryConnection connection = repository.getConnection()) { final RDFHandler writer = new SortingRDFHandler(new N3Writer(pw)); // FIXME: use Iterations - and sort // for (final Namespace namespace : connection.getNamespaces().asList()) // { // writer.handleNamespace(namespace.getPrefix(), namespace.getName()); // } writer.handleNamespace("bio", "http://purl.org/vocab/bio/0.1/"); writer.handleNamespace("bmmo", "http://bluemarine.tidalwave.it/2015/04/mo/"); writer.handleNamespace("dc", "http://purl.org/dc/elements/1.1/"); writer.handleNamespace("foaf", "http://xmlns.com/foaf/0.1/"); writer.handleNamespace("owl", "http://www.w3.org/2002/07/owl#"); writer.handleNamespace("mo", "http://purl.org/ontology/mo/"); writer.handleNamespace("rdfs", "http://www.w3.org/2000/01/rdf-schema#"); writer.handleNamespace("rel", "http://purl.org/vocab/relationship/"); writer.handleNamespace("vocab", "http://dbtune.org/musicbrainz/resource/vocab/"); writer.handleNamespace("xs", "http://www.w3.org/2001/XMLSchema#"); connection.export(writer); } }
From source file:eu.itesla_project.security.RunSecurityAnalysisTool.java
@Override public void run(CommandLine line) throws Exception { ComponentDefaultConfig config = new ComponentDefaultConfig(); String caseFormat = line.getOptionValue("case-format"); Path caseDir = Paths.get(line.getOptionValue("case-dir")); String caseBaseName = line.getOptionValue("case-basename"); Path outputCsvFile = Paths.get(line.getOptionValue("output-csv-file")); boolean detailed = line.hasOption("detailed"); ContingenciesProvider contingencyProvider = config.findFactoryImplClass(ContingenciesProviderFactory.class) .newInstance().create();/*from w ww . j ava2 s .c om*/ LoadFlowFactory loadFlowFactory = config.findFactoryImplClass(LoadFlowFactory.class).newInstance(); try (ComputationManager computationManager = new LocalComputationManager()) { Importer importer = Importers.getImporter(caseFormat, computationManager); if (importer == null) { throw new RuntimeException("Format " + caseFormat + " not supported"); } Map<String, Map<String, List<LimitViolation>>> statusPerContingencyPerCase = Collections .synchronizedMap(new TreeMap<>()); Set<String> contingencyIds = Collections.synchronizedSet(new LinkedHashSet<>()); if (caseBaseName != null) { System.out.println("loading case " + caseBaseName + " ..."); // load the network Network network = importer.import_(new GenericReadOnlyDataSource(caseDir, caseBaseName), new Properties()); List<Contingency> contingencies = contingencyProvider.getContingencies(network); contingencyIds.addAll(contingencies.stream().map(Contingency::getId).collect(Collectors.toList())); StaticSecurityAnalysis securityAnalysis = new StaticSecurityAnalysis(network, loadFlowFactory, computationManager); statusPerContingencyPerCase.put(caseBaseName, securityAnalysis.run(contingencies)); } else { Importers.importAll(caseDir, importer, true, network -> { try { List<Contingency> contingencies = contingencyProvider.getContingencies(network); contingencyIds.addAll( contingencies.stream().map(Contingency::getId).collect(Collectors.toList())); StaticSecurityAnalysis securityAnalysis = new StaticSecurityAnalysis(network, loadFlowFactory, computationManager); statusPerContingencyPerCase.put(network.getId(), securityAnalysis.run(contingencies)); } catch (Exception e) { LOGGER.error(e.toString(), e); } }, dataSource -> System.out.println("loading case " + dataSource.getBaseName() + " ...")); } try (BufferedWriter writer = Files.newBufferedWriter(outputCsvFile, StandardCharsets.UTF_8)) { writer.write("base case"); for (String contingencyId : contingencyIds) { writer.write(CSV_SEPARATOR); writer.write(contingencyId); } writer.newLine(); for (Map.Entry<String, Map<String, List<LimitViolation>>> e : statusPerContingencyPerCase .entrySet()) { String baseCaseName = e.getKey(); Map<String, List<LimitViolation>> statusPerContingency = e.getValue(); writer.write(baseCaseName); for (String contingencyId : contingencyIds) { List<LimitViolation> violations = statusPerContingency.get(contingencyId); writer.write(CSV_SEPARATOR); writer.write(toString(violations, detailed)); } writer.newLine(); } } } }
From source file:com.pawandubey.griffin.Griffin.java
private void initializeConfigurationSettings() throws NumberFormatException, IOException { String title = null, author = null, date = null, slug = null, layout = "post", category = null, tags = null; BufferedReader br = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8)); while (StringUtils.isEmpty(title)) { System.out.println("1. title :"); title = br.readLine();/* w w w . j a v a2 s. com*/ } while (StringUtils.isEmpty(author)) { System.out.println("2. your name : (default is " + config.getSiteAuthor() + ",press Enter omit!)"); author = br.readLine(); if (StringUtils.isBlank(author)) { author = config.getSiteAuthor(); } } while (StringUtils.isEmpty(slug)) { System.out.println("3. url :"); slug = br.readLine(); } while (StringUtils.isEmpty(category)) { System.out.println("4. category : (" + config.getCategories() + ",pick one or create new !):"); category = br.readLine(); } while (StringUtils.isEmpty(tags)) { System.out.println("5. tag : eg: tag1,tag2"); tags = br.readLine(); } while (StringUtils.isEmpty(date)) { System.out.println( "6. write date : (format :" + config.getInputDateFormat() + ",press Enter user today.)"); date = br.readLine(); if (StringUtils.isEmpty(date)) { date = LocalDateTime.now().format(DateTimeFormatter.ofPattern(config.getInputDateFormat())); } } ; Path draftPath = Paths.get(config.getSourceDir()) .resolve(title.replaceAll("\\s+|;|\\)|\\(|&", "-") + ".markdown"); String content = postTemplate.replace("#title", title).replace("#date", date).replace("#category", category) .replace("#layout", layout).replace("#author", author).replace("#tags", formatTag(tags)) .replace("#slug", slug); try (BufferedWriter bw = Files.newBufferedWriter(draftPath, StandardCharsets.UTF_8)) { bw.write(content); } catch (IOException ex) { Logger.getLogger(Parser.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("draft path [" + draftPath + "]"); System.out.println("*******************************************************************"); System.out.println(content); System.out.println("*******************************************************************"); System.out.println("draft path [" + draftPath + "]"); }
From source file:org.zaproxy.zap.extension.fuzz.httpfuzzer.ui.HttpFuzzResultsContentPanel.java
public HttpFuzzResultsContentPanel() { super(new BorderLayout()); tabbedPane = new JTabbedPane(); toolbar = new JToolBar(); toolbar.setFloatable(false);//w w w. ja v a2 s .c om toolbar.setRollover(true); messageCountLabel = new JLabel(Constant.messages.getString("fuzz.httpfuzzer.results.toolbar.messagesSent")); messageCountValueLabel = new JLabel("0"); errorCountLabel = new JLabel(Constant.messages.getString("fuzz.httpfuzzer.results.toolbar.errors")); errorCountValueLabel = new JLabel("0"); showErrorsToggleButton = new ZapToggleButton( Constant.messages.getString("fuzz.httpfuzzer.results.toolbar.button.showErrors.label")); showErrorsToggleButton.setEnabled(false); showErrorsToggleButton.setToolTipText( Constant.messages.getString("fuzz.httpfuzzer.results.toolbar.button.showErrors.tooltip")); showErrorsToggleButton.setSelectedToolTipText( Constant.messages.getString("fuzz.httpfuzzer.results.toolbar.button.showErrors.tooltip.selected")); showErrorsToggleButton.setDisabledToolTipText( Constant.messages.getString("fuzz.httpfuzzer.results.toolbar.button.showErrors.tooltip.disabled")); showErrorsToggleButton .setIcon(new ImageIcon(HttpFuzzResultsContentPanel.class.getResource("/resource/icon/16/050.png"))); showErrorsToggleButton.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (ItemEvent.SELECTED == e.getStateChange()) { showTabs(); } else { hideErrorsTab(); } } }); toolbar.add(Box.createHorizontalStrut(4)); toolbar.add(messageCountLabel); toolbar.add(Box.createHorizontalStrut(4)); toolbar.add(messageCountValueLabel); toolbar.add(Box.createHorizontalStrut(32)); toolbar.add(errorCountLabel); toolbar.add(Box.createHorizontalStrut(4)); toolbar.add(errorCountValueLabel); toolbar.add(Box.createHorizontalStrut(16)); toolbar.add(showErrorsToggleButton); JButton button = new JButton(Constant.messages.getString("fuzz.httpfuzzer.results.toolbar.button.export")); button.setIcon(new ImageIcon(HttpFuzzResultsContentPanel.class.getResource("/resource/icon/16/115.png"))); button.addActionListener((new AbstractAction() { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { WritableFileChooser chooser = new WritableFileChooser( Model.getSingleton().getOptionsParam().getUserDirectory()) { private static final long serialVersionUID = -1660943014924270012L; @Override public void approveSelection() { File file = getSelectedFile(); if (file != null) { String filePath = file.getAbsolutePath(); if (!filePath.toLowerCase(Locale.ROOT).endsWith(CSV_EXTENSION)) { setSelectedFile(new File(filePath + CSV_EXTENSION)); } } super.approveSelection(); } }; chooser.setSelectedFile(new File( Constant.messages.getString("fuzz.httpfuzzer.results.toolbar.button.export.defaultName"))); if (chooser .showSaveDialog(View.getSingleton().getMainFrame()) == WritableFileChooser.APPROVE_OPTION) { boolean success = true; try (CSVPrinter pw = new CSVPrinter( Files.newBufferedWriter(chooser.getSelectedFile().toPath(), StandardCharsets.UTF_8), CSVFormat.DEFAULT)) { pw.printRecord(currentFuzzer.getMessagesModel().getHeaders()); int count = currentFuzzer.getMessagesModel().getRowCount(); for (int i = 0; i < count; i++) { List<Object> valueOfRow = currentFuzzer.getMessagesModel().getEntry(i) .getValuesOfHeaders(); String customStateValue = fuzzResultTable.getCustomStateValue( currentFuzzer.getMessagesModel().getEntry(i).getCustomStates()); valueOfRow.add(13, customStateValue); pw.printRecord(valueOfRow); } } catch (Exception ex) { success = false; JOptionPane.showMessageDialog(View.getSingleton().getMainFrame(), Constant.messages .getString("fuzz.httpfuzzer.results.toolbar.button.export.showMessageError") + "\n" + ex.getLocalizedMessage()); logger.error("Export Failed: " + ex); } // Delay the presentation of success message, to ensure all the data was // already flushed. if (success) { JOptionPane.showMessageDialog(View.getSingleton().getMainFrame(), Constant.messages .getString("fuzz.httpfuzzer.results.toolbar.button.export.showMessageSuccessful")); } } } })); toolbar.add(Box.createHorizontalGlue()); toolbar.add(button); mainPanel = new JPanel(new BorderLayout()); fuzzResultTable = new HttpFuzzerResultsTable(RESULTS_PANEL_NAME, EMPTY_RESULTS_MODEL); errorsTable = new HttpFuzzerErrorsTable(ERRORS_PANEL_NAME, EMPTY_ERRORS_MODEL); fuzzResultTableScrollPane = new JScrollPane(); fuzzResultTableScrollPane.setViewportView(fuzzResultTable); errorsTableScrollPane = new JScrollPane(); errorsTableScrollPane.setViewportView(errorsTable); mainPanel.add(fuzzResultTableScrollPane); add(toolbar, BorderLayout.PAGE_START); add(mainPanel, BorderLayout.CENTER); }
From source file:org.mda.bcb.tcgagsdata.create.ProcessFile.java
protected void writeGeneListFile(TreeMap<String, Integer> theGeneEqList) throws IOException { File outputDir = getOutputDir(); File outputFile = new File(outputDir, "gene_list.tsv"); try (BufferedWriter bw = Files.newBufferedWriter(Paths.get(outputFile.getAbsolutePath()), Charset.availableCharsets().get("ISO-8859-1"))) { boolean first = true; for (String gene : theGeneEqList.keySet()) { if (false == first) { bw.write("\t"); } else { first = false;//from w ww .ja v a2 s. c o m } bw.write(gene); } bw.newLine(); } }
From source file:org.duracloud.snapshot.service.impl.SnapshotJobBuilder.java
/** * @param contentDir/*w w w.j a v a 2 s. com*/ * @param file * @return * @throws IOException */ private BufferedWriter createWriter(File contentDir, String file) throws IOException { Path propsPath = getPath(contentDir, file); BufferedWriter propsWriter = Files.newBufferedWriter(propsPath, StandardCharsets.UTF_8); return propsWriter; }
From source file:edu.vt.vbi.patric.cache.DataLandingGenerator.java
public boolean createCacheFileGenomes(String filePath) { boolean isSuccess = false; JSONObject jsonData = new JSONObject(); JSONObject data;//from w ww .j av a2s.c om // from WP // data data = read(baseURL + "/tab/dlp-genomes-data/?req=passphrase"); if (data != null) { jsonData.put("data", data); } // tools data = read(baseURL + "/tab/dlp-genomes-tools/?req=passphrase"); if (data != null) { jsonData.put("tools", data); } // process data = read(baseURL + "/tab/dlp-genomes-process/?req=passphrase"); if (data != null) { jsonData.put("process", data); } // download data = read(baseURL + "/tab/dlp-genomes-download/?req=passphrase"); if (data != null) { jsonData.put("download", data); } // from solr or database // add popularGenomes data = getPopularGenomes(); if (data != null) { jsonData.put("popularGenomes", data); } // add top5_1 data = getTop5List("host_name"); if (data != null) { jsonData.put("top5_1", data); } // add top5_2 data = getTop5List("isolation_country"); if (data != null) { jsonData.put("top5_2", data); } // add numberGenomes data = getGenomeCounts(); if (data != null) { jsonData.put("numberGenomes", data); } // add genomeStatus data = getGenomeStatus(); if (data != null) { jsonData.put("genomeStatus", data); } // save jsonData to file try (PrintWriter jsonOut = new PrintWriter( Files.newBufferedWriter(FileSystems.getDefault().getPath(filePath), Charset.defaultCharset()));) { jsonData.writeJSONString(jsonOut); isSuccess = true; } catch (IOException e) { LOGGER.error(e.getMessage(), e); } return isSuccess; }
From source file:org.cirdles.squid.web.SquidReportingService.java
public Path generateReports(String myFileName, InputStream prawnFile, InputStream taskFile, boolean useSBM, boolean userLinFits, String refMatFilter, String concRefMatFilter, String preferredIndexIsotopeName) throws IOException, JAXBException, SAXException { IndexIsoptopesEnum preferredIndexIsotope = IndexIsoptopesEnum.valueOf(preferredIndexIsotopeName); // Posix attributes added to support web service on Linux - ignoring windows for now Set<PosixFilePermission> perms = EnumSet.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE, GROUP_READ); // detect if prawnfile is zipped boolean prawnIsZip = false; String fileName = ""; if (myFileName == null) { fileName = DEFAULT_PRAWNFILE_NAME; } else if (myFileName.toLowerCase().endsWith(".zip")) { fileName = FilenameUtils.removeExtension(myFileName); prawnIsZip = true;//www . j a v a2 s. com } else { fileName = myFileName; } SquidProject squidProject = new SquidProject(); prawnFileHandler = squidProject.getPrawnFileHandler(); CalamariFileUtilities.initSampleParametersModels(); Path reportsZip = null; Path reportsFolder = null; try { Path uploadDirectory = Files.createTempDirectory("upload"); Path uploadDirectory2 = Files.createTempDirectory("upload2"); Path prawnFilePath; Path taskFilePath; if (prawnIsZip) { Path prawnFilePathZip = uploadDirectory.resolve("prawn-file.zip"); Files.copy(prawnFile, prawnFilePathZip); prawnFilePath = extractZippedFile(prawnFilePathZip.toFile(), uploadDirectory.toFile()); } else { prawnFilePath = uploadDirectory.resolve("prawn-file.xml"); Files.copy(prawnFile, prawnFilePath); } taskFilePath = uploadDirectory2.resolve("task-file.xls"); Files.copy(taskFile, taskFilePath); ShrimpDataFileInterface prawnFileData = prawnFileHandler .unmarshallPrawnFileXML(prawnFilePath.toString(), true); squidProject.setPrawnFile(prawnFileData); // hard-wired for now squidProject.getTask().setCommonPbModel(CommonPbModel.getDefaultModel("GA Common Lead 2018", "1.0")); squidProject.getTask().setPhysicalConstantsModel( PhysicalConstantsModel.getDefaultModel(SQUID2_DEFAULT_PHYSICAL_CONSTANTS_MODEL_V1, "1.0")); File squidTaskFile = taskFilePath.toFile(); squidProject.createTaskFromImportedSquid25Task(squidTaskFile); squidProject.setDelimiterForUnknownNames("-"); TaskInterface task = squidProject.getTask(); task.setFilterForRefMatSpotNames(refMatFilter); task.setFilterForConcRefMatSpotNames(concRefMatFilter); task.setUseSBM(useSBM); task.setUserLinFits(userLinFits); task.setSelectedIndexIsotope(preferredIndexIsotope); // process task task.applyTaskIsotopeLabelsToMassStations(); Path calamariReportsFolderAliasParent = Files.createTempDirectory("reports-destination"); Path calamariReportsFolderAlias = calamariReportsFolderAliasParent .resolve(DEFAULT_SQUID3_REPORTS_FOLDER.getName() + "-from Web Service"); File reportsDestinationFile = calamariReportsFolderAlias.toFile(); reportsEngine = prawnFileHandler.getReportsEngine(); prawnFileHandler.initReportsEngineWithCurrentPrawnFileName(fileName); reportsEngine.setFolderToWriteCalamariReports(reportsDestinationFile); reportsEngine.produceReports(task.getShrimpFractions(), (ShrimpFraction) task.getUnknownSpots().get(0), task.getReferenceMaterialSpots().size() > 0 ? (ShrimpFraction) task.getReferenceMaterialSpots().get(0) : (ShrimpFraction) task.getUnknownSpots().get(0), true, false); squidProject.produceTaskAudit(); squidProject.produceUnknownsCSV(true); squidProject.produceReferenceMaterialCSV(true); // next line report will show only super sample for now squidProject.produceUnknownsBySampleForETReduxCSV(true); Files.delete(prawnFilePath); reportsFolder = Paths.get(reportsEngine.getFolderToWriteCalamariReports().getParentFile().getPath()); } catch (IOException | JAXBException | SAXException | SquidException iOException) { Path config = Files.createTempFile("SquidWebServiceMessage", "txt", PosixFilePermissions.asFileAttribute(perms)); try (BufferedWriter writer = Files.newBufferedWriter(config, StandardCharsets.UTF_8)) { writer.write("Squid Reporting web service was not able to process supplied files."); writer.newLine(); writer.write(iOException.getMessage()); writer.newLine(); } File message = config.toFile(); Path messageDirectory = Files.createTempDirectory("message"); Path messageFilePath = messageDirectory.resolve("Squid Web Service Message.txt"); Files.copy(message.toPath(), messageFilePath); reportsFolder = messageFilePath.getParent(); } reportsZip = ZipUtility.recursivelyZip(reportsFolder); FileUtilities.recursiveDelete(reportsFolder); return reportsZip; }