List of usage examples for java.io PrintWriter close
public void close()
From source file:duty_scheduler.Scheduler.java
/** * Prints analytics data to a space separated file called analytics.txt *///from w ww . j av a2 s. c o m private static void printAnalytics() { String analyticsFile = "analytics.txt"; PrintWriter analysisOut = null; try { analysisOut = new PrintWriter(analyticsFile); for (double[] generationData : analytics) { for (double dataPoint : generationData) { analysisOut.print(String.format("%.3f ", dataPoint)); } analysisOut.println(); } } catch (IOException e) { ErrorChecker.printExceptionToLog(e); } finally { analysisOut.close(); } }
From source file:org.glowroot.tests.WebDriverSetup.java
private static CentralModule createCentralModule(int uiPort, int grpcPort) throws Exception { File centralDir = new File("target"); File propsFile = new File(centralDir, "glowroot-central.properties"); PrintWriter props = new PrintWriter(propsFile); props.println("cassandra.keyspace=glowroot_unit_tests"); byte[] bytes = new byte[16]; new SecureRandom().nextBytes(bytes); props.println("cassandra.symmetricEncryptionKey=" + BaseEncoding.base16().lowerCase().encode(bytes)); props.println("grpc.httpPort=" + grpcPort); props.println("ui.port=" + uiPort); props.close(); String prior = System.getProperty("glowroot.log.dir"); try {/*from w w w . j a va 2 s.c o m*/ System.setProperty("glowroot.log.dir", "target"); return CentralModule.create(centralDir); } finally { if (prior == null) { System.clearProperty("glowroot.log.dir"); } else { System.setProperty("glowroot.log.dir", prior); } } }
From source file:com.microsoftopentechnologies.intellij.helpers.AndroidStudioHelper.java
public static void deleteActivityTemplates(Object caller) throws IOException, InterruptedException { String[] cmd = null;/*w ww .j a v a 2s. c o m*/ String templatePath = URLDecoder .decode(ApplicationComponent.class.getResource("").getPath().replace("file:/", ""), "UTF-8"); templatePath = templatePath.replace("/", File.separator); templatePath = templatePath.substring(0, templatePath.indexOf(File.separator + "lib")); templatePath = templatePath + File.separator + "plugins" + File.separator + "android" + File.separator; templatePath = templatePath + "lib" + File.separator + "templates" + File.separator + "activities" + File.separator; String[] env = null; String tmpdir = getTempLocation(); BufferedInputStream bufferedInputStream = new BufferedInputStream( ServiceCodeReferenceHelper.getTemplateResource("ActivityTemplate.zip")); unZip(bufferedInputStream, tmpdir); if (System.getProperty("os.name").toLowerCase().startsWith("windows")) { try { VirtualFile mobileTemplate = LocalFileSystem.getInstance() .findFileByIoFile(new File(templatePath + mobileServicesTemplateName)); VirtualFile officeTemplate = LocalFileSystem.getInstance() .findFileByIoFile(new File(templatePath + officeTemplateName)); if (mobileTemplate != null) mobileTemplate.delete(caller); if (officeTemplate != null) officeTemplate.delete(caller); } catch (IOException ex) { PrintWriter printWriter = new PrintWriter(tmpdir + "\\script.bat"); printWriter.println("@echo off"); printWriter.println("del \"" + templatePath + mobileServicesTemplateName + "\" /Q /S"); printWriter.println("del \"" + templatePath + officeTemplateName + "\" /Q /S"); printWriter.flush(); printWriter.close(); String[] tmpcmd = { tmpdir + "\\elevate.exe", "script.bat", "1" }; cmd = tmpcmd; ArrayList<String> tempenvlist = new ArrayList<String>(); for (String envval : System.getenv().keySet()) tempenvlist.add(String.format("%s=%s", envval, System.getenv().get(envval))); tempenvlist.add("PRECOMPILE_STREAMLINE_FILES=1"); env = new String[tempenvlist.size()]; tempenvlist.toArray(env); Runtime rt = Runtime.getRuntime(); Process proc = rt.exec(cmd, env, new File(tmpdir)); proc.waitFor(); } } else if (System.getProperty("os.name").toLowerCase().startsWith("mac")) { VirtualFile mobileTemplate = LocalFileSystem.getInstance() .findFileByIoFile(new File(templatePath + mobileServicesTemplateName)); VirtualFile officeTemplate = LocalFileSystem.getInstance() .findFileByIoFile(new File(templatePath + officeTemplateName)); if (mobileTemplate != null && officeTemplate != null) { exec(new String[] { "osascript", "-e", "do shell script \"rm -r \\\"/" + templatePath + mobileServicesTemplateName + "\\\"\"", "-e", "do shell script \"rm -r \\\"/" + templatePath + officeTemplateName + "\\\"\"" }, tmpdir); } } else { try { VirtualFile mobileTemplate = LocalFileSystem.getInstance() .findFileByIoFile(new File(templatePath + mobileServicesTemplateName)); VirtualFile officeTemplate = LocalFileSystem.getInstance() .findFileByIoFile(new File(templatePath + officeTemplateName)); mobileTemplate.delete(caller); officeTemplate.delete(caller); } catch (IOException ex) { JPasswordField pf = new JPasswordField(); int okCxl = JOptionPane.showConfirmDialog(null, pf, "To copy Microsoft Services templates, the plugin needs your password:", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (okCxl == JOptionPane.OK_OPTION) { String password = new String(pf.getPassword()); exec(new String[] { "echo", password, "|", "sudo", "-S", "rm", "-r", tmpdir + mobileServicesTemplateName, templatePath + mobileServicesTemplateName }, tmpdir); exec(new String[] { "echo", password, "|", "sudo", "-S", "rm", "-r", tmpdir + officeTemplateName, templatePath + officeTemplateName }, tmpdir); } } } }
From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step11GoldDataStatistics.java
/** * (1) Plain text with 4 columns: (1) the rank of the document in the list * (2) average agreement rate over queries (3) standard deviation of * agreement rate over queries. (4) average length of the document in the * rank.//w ww . j av a 2 s .c o m */ public static void statistics1(File inputDir, File outputDir) throws Exception { SortedMap<Integer, DescriptiveStatistics> mapDocumentRankObservedAgreement = new TreeMap<>(); SortedMap<Integer, DescriptiveStatistics> mapDocumentRankDocLength = new TreeMap<>(); // iterate over query containers for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) { QueryResultContainer queryResultContainer = QueryResultContainer .fromXML(FileUtils.readFileToString(f, "utf-8")); for (QueryResultContainer.SingleRankedResult rankedResult : queryResultContainer.rankedResults) { // add new entries if (!mapDocumentRankObservedAgreement.containsKey(rankedResult.rank)) { mapDocumentRankObservedAgreement.put(rankedResult.rank, new DescriptiveStatistics()); } if (!mapDocumentRankDocLength.containsKey(rankedResult.rank)) { mapDocumentRankDocLength.put(rankedResult.rank, new DescriptiveStatistics()); } Double observedAgreement = rankedResult.observedAgreement; if (observedAgreement == null) { System.err .println("Observed agreement is null; " + f.getName() + ", " + rankedResult.clueWebID); } else { // update value mapDocumentRankObservedAgreement.get(rankedResult.rank).addValue(observedAgreement); mapDocumentRankDocLength.get(rankedResult.rank).addValue(rankedResult.plainText.length()); } } } PrintWriter pw = new PrintWriter(new FileWriter(new File(outputDir, "stats1.csv"))); for (Map.Entry<Integer, DescriptiveStatistics> entry : mapDocumentRankObservedAgreement.entrySet()) { pw.printf(Locale.ENGLISH, "%d\t%.4f\t%.4f\t%.4f\t%.4f%n", entry.getKey(), entry.getValue().getMean(), entry.getValue().getStandardDeviation(), mapDocumentRankDocLength.get(entry.getKey()).getMean(), mapDocumentRankDocLength.get(entry.getKey()).getStandardDeviation()); } pw.close(); }
From source file:gov.nih.nci.evs.browser.servlet.ValueSetServlet.java
public static void create_vs_subtree(HttpServletRequest request, HttpServletResponse response, int view, String dictionary, String version, String vsd_uri) { request.getSession().removeAttribute("b"); request.getSession().removeAttribute("m"); response.setContentType("text/html"); PrintWriter out = null; //String checked_vocabularies = HTTPUtils.cleanXSS((String) request.getParameter("checked_vocabularies")); //String partial_checked_vocabularies = HTTPUtils.cleanXSS((String) request.getParameter("partial_checked_vocabularies")); //System.out.println("partial_checked_vocabularies: " + partial_checked_vocabularies); try {/*w ww . j a v a 2 s . c o m*/ out = response.getWriter(); } catch (Exception ex) { ex.printStackTrace(); return; } //String message = (String) request.getSession().getAttribute("message"); try { out.close(); } catch (Exception ex) { ex.printStackTrace(); return; } }
From source file:eu.annocultor.converters.europeana.EuropeanaSolrDocumentTagger.java
public static void start(String solrServerFrom, String solrServerTo, String query, int start) throws MalformedURLException, Exception { Environment environment = new EnvironmentImpl(); PrintWriter log = new PrintWriter( new FileWriter(new File(environment.getAnnoCultorHome(), "enrichment.log"))); try {//from www.j a v a2s . c o m EuropeanaSolrDocumentTagger tagger = new EuropeanaSolrDocumentTagger(query, solrServerFrom, solrServerTo, start, log); tagger.init("Europeana"); if (start == 0) { tagger.clearDestination(query); } tagger.tag(); tagger.report(); ReportPresenter.generateReport(environment.getAnnoCultorHome()); } catch (Exception e) { e.printStackTrace(new PrintWriter(log)); } finally { log.write("SEMANTIC ENRICHMENT COMPLETED"); log.flush(); log.close(); } }
From source file:org.sead.repositories.reference.util.SEADGoogleLogin.java
public static String getAccessToken() { try {//from w w w. jav a 2 s .c om refresh_token = new String(Files.readAllBytes(Paths.get("refresh.txt"))); } catch (IOException e1) { } if (refresh_token == null) { getAuthCode(); // Ask user to login via browser System.out.println( "Did not find stored refresh token. Initiating first-time device authorization request.\n"); System.out.println("1) Go to : " + verification_url + " in your browser\n"); System.out.println("2) Type : " + user_code + " in your browser\n"); System.out.println("3) Hit <Return> to continue.\n"); try { System.in.read(); } catch (IOException e) { log.debug("Error getting user response: " + e.getMessage()); } System.out.println("Proceeding"); getTokensFromCode(); if (refresh_token != null) { PrintWriter writer = null; try { writer = new PrintWriter("refresh.txt", "UTF-8"); writer.print(refresh_token); } catch (FileNotFoundException e) { log.error("Could not write refresh.txt: " + e.getMessage()); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (writer != null) { writer.close(); } } } } else { getTokenFromRefreshToken(); } return access_token; }
From source file:at.tuwien.ifs.somtoolbox.data.InputDataWriter.java
public static void writeAsSOMLib(TemplateVector tv, String fileName) throws IOException { Logger.getLogger("at.tuwien.ifs.somtoolbox") .info("Start writing new template vector to '" + fileName + "'."); PrintWriter writer = FileUtils.openFileForWriting("Template Vector", fileName, fileName.endsWith(".gz")); writeTempplateHeaderToFile(writer, fileName, tv.numVectors(), tv.dim(), tv.numinfo()); for (int i = 0; i < tv.dim(); i++) { writeElementToFile(writer, i, tv.getElement(i)); }//w w w . j a v a2 s .c o m writer.flush(); writer.close(); Logger.getLogger("at.tuwien.ifs.somtoolbox").info("Finished."); }
From source file:ca.cutterslade.match.scheduler.Main.java
private static String summary(final Scheduler scheduler) { final StringWriter w = new StringWriter(); final PrintWriter p = new PrintWriter(w); final String columnFormat = " %15s"; p.printf(columnFormat, "Day"); p.printf(columnFormat, "Time"); for (final Court c : scheduler.getCourts()) { p.printf(columnFormat, c.getGym().getName() + '-' + c.getName()); }//from www . ja va2 s . co m p.println(); for (final Day d : scheduler.getDays()) for (final Time t : scheduler.getTimes()) { p.printf(columnFormat, d.getName()); p.printf(columnFormat, t.getName()); for (final Court c : scheduler.getCourts()) { final Match m = scheduler.getMatch(d, t, c); p.printf(columnFormat, teamsString(m)); } p.println(); } p.close(); return w.toString(); }
From source file:com.cloudera.csd.tools.MetricTools.java
/** * Writes usage message to 'stream'.// w w w . j a v a 2s . c om * * @param stream output stream. * @throws UnsupportedEncodingException */ public static void printUsageMessage(OutputStream stream) throws UnsupportedEncodingException { PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream, "UTF-8"))); try { String header = "Cloudera Manager Metric Tools"; String footer = ""; HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(writer, HelpFormatter.DEFAULT_WIDTH, "metric tools", header, OPTIONS, HelpFormatter.DEFAULT_LEFT_PAD, HelpFormatter.DEFAULT_DESC_PAD, footer, true); // auto-usage: whether to also show // the command line args on the usage line. } finally { writer.close(); } }