List of usage examples for java.io PrintStream close
public void close()
From source file:com.p5solutions.core.utils.ReflectionUtility.java
/** * Gets the log stack trace./*from ww w. j a v a 2 s. c o m*/ * * @param e * the e * @return the log stack trace */ public static String getStackTrace(Throwable e) { if (e == null) { return ""; } ByteArrayOutputStream os = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(os); try { e.printStackTrace(ps); String ret = os.toString(); ps.close(); os.close(); return ret; } catch (IOException t) { logger.error("Error in closing the output stream for byte array when getting stack trace on exception " + e.toString()); } return ""; }
From source file:br.com.ingenieux.mojo.beanstalk.env.DumpEnvironmentSettings.java
protected Object executeInternal() throws Exception { DescribeConfigurationOptionsResult configOptions = getService() .describeConfigurationOptions(new DescribeConfigurationOptionsRequest() .withApplicationName(applicationName).withEnvironmentName(curEnv.getEnvironmentName())); for (ConfigurationOptionDescription o : configOptions.getOptions()) { String key = String.format("beanstalk.env.%s.%s", o.getNamespace().replace(":", "."), o.getName()); for (Map.Entry<String, ConfigurationOptionSetting> entry : COMMON_PARAMETERS.entrySet()) { ConfigurationOptionSetting cos = entry.getValue(); if (cos.getNamespace().equals(o.getNamespace()) && cos.getOptionName().equals(o.getName())) { key = entry.getKey();/*from ww w . j a va 2 s .co m*/ break; } } defaultSettings.put(key, o); } DescribeConfigurationSettingsResult configurationSettings = getService() .describeConfigurationSettings(new DescribeConfigurationSettingsRequest() .withApplicationName(applicationName).withEnvironmentName(curEnv.getEnvironmentName())); Properties newProperties = new Properties(); if (configurationSettings.getConfigurationSettings().isEmpty()) { throw new IllegalStateException("No Configuration Settings received"); } ConfigurationSettingsDescription configSettings = configurationSettings.getConfigurationSettings().get(0); Map<String, ConfigurationOptionSetting> keyMap = new LinkedHashMap<String, ConfigurationOptionSetting>(); for (ConfigurationOptionSetting d : configSettings.getOptionSettings()) { String key = String.format("beanstalk.env.%s.%s", d.getNamespace().replaceAll(":", "."), d.getOptionName()); String defaultValue = ""; String outputKey = key; keyMap.put(key, d); for (Map.Entry<String, ConfigurationOptionSetting> cosEntry : COMMON_PARAMETERS.entrySet()) { ConfigurationOptionSetting v = cosEntry.getValue(); boolean match = v.getNamespace().equals(d.getNamespace()) && v.getOptionName().equals(d.getOptionName()); if (match) { outputKey = cosEntry.getKey(); break; } } if (defaultSettings.containsKey(outputKey)) { defaultValue = StringUtils.defaultString(defaultSettings.get(outputKey).getDefaultValue()); } String value = d.getValue(); if (null == value || StringUtils.isBlank("" + value)) { continue; } if (!defaultValue.equals(value)) { if (!value.contains(curEnv.getEnvironmentId())) { getLog().info("Adding property " + key); if (changedOnly) { String curValue = project.getProperties().getProperty(outputKey); if (!value.equals(curValue)) { newProperties.put(outputKey, value); } } else { newProperties.put(outputKey, value); } } else { getLog().info("Ignoring property " + outputKey + "(value=" + value + ") due to containing references to the environment id"); } } else { getLog().debug("Ignoring property " + key + " (defaulted)"); } } if ("properties".equals(this.outputFileFormat)) { String comment = "elastic beanstalk environment properties for " + curEnv.getEnvironmentName(); if (null != outputFile) { newProperties.store(new FileOutputStream(outputFile), comment); } else { newProperties.store(System.out, comment); } } else if ("yaml".equals(this.outputFileFormat)) { PrintStream printStream = System.out; if (null != outputFile) { printStream = new PrintStream(outputFile); } printStream.println("option_settings:"); for (Map.Entry<Object, Object> e : newProperties.entrySet()) { ConfigurationOptionSetting c = keyMap.get("" + e.getKey()); String value = "" + e.getValue(); printStream.println(" - namespace: " + c.getNamespace()); printStream.println(" option_name: " + c.getOptionName()); printStream.println(" value: " + value); } printStream.close(); } return null; }
From source file:com.google.cloud.dataflow.sdk.runners.worker.TextReaderTest.java
private void testStringPayload(String[] lines, String separator, boolean stripNewlines) throws Exception { File tmpFile = tmpFolder.newFile(); List<String> expected = new ArrayList<>(); PrintStream writer = new PrintStream(new FileOutputStream(tmpFile)); for (String line : lines) { writer.print(line);//w w w . ja v a 2s . c o m writer.print(separator); expected.add(stripNewlines ? line : line + separator); } writer.close(); TextReader<String> textReader = new TextReader<>(tmpFile.getPath(), stripNewlines, null, null, StringUtf8Coder.of(), TextIO.CompressionType.UNCOMPRESSED); List<String> actual = new ArrayList<>(); try (Reader.ReaderIterator<String> iterator = textReader.iterator()) { while (iterator.hasNext()) { actual.add(iterator.next()); } } assertEquals(expected, actual); }
From source file:org.apache.oodt.cas.protocol.sftp.TestJschSftpProtocol.java
private File createPubKeyForPort(int port) throws IOException { PrintStream ps = null; BufferedReader br = null;/* w w w . java 2s . c o m*/ try { File publicKeyFile = new File(publicKeysDir, "sample-dsa.pub"); br = new BufferedReader( new FileReader(new File("src/test/resources/sample-dsa.pub").getAbsoluteFile())); ps = new PrintStream(new FileOutputStream(publicKeyFile)); String nextLine; while ((nextLine = br.readLine()) != null) { ps.println(nextLine.replace("2022", Integer.toString(port))); } return publicKeyFile; } finally { try { ps.close(); } catch (Exception ignored) { } try { br.close(); } catch (Exception ignored) { } } }
From source file:com.cybernostics.forks.jsp2x.Main.java
private boolean process(String inputFileName) { boolean success = false; try {/*from www. j a v a 2 s . c om*/ final File logFile = outputFile(inputFileName + ".log"); final PrintStream logStream = new PrintStream(logFile); try { PrintStream stdout = System.out; PrintStream stderr = System.err; try { System.setOut(logStream); System.setErr(logStream); try { new Jsp2JspX(inputFileName, outputFile(rewritePath(inputFileName)), this).convert(); } catch (Throwable t) { handleThrowable(t); } } finally { System.setErr(stderr); System.setOut(stdout); } } finally { logStream.close(); if (logFile.length() == 0) { success = true; logFile.delete(); } } } catch (Throwable t) { handleThrowable(t); } return success; }
From source file:cc.wikitools.lucene.hadoop.FetchWikipediaArticleHdfs.java
@SuppressWarnings("static-access") @Override/*from www . j a v a2 s.c o m*/ public int run(String[] args) throws Exception { Options options = new Options(); options.addOption( OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_OPTION)); options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("id").create(ID_OPTION)); options.addOption( OptionBuilder.withArgName("string").hasArg().withDescription("title").create(TITLE_OPTION)); CommandLine cmdline = null; CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (!(cmdline.hasOption(ID_OPTION) || cmdline.hasOption(TITLE_OPTION)) || !cmdline.hasOption(INDEX_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(FetchWikipediaArticle.class.getName(), options); System.exit(-1); } String indexLocation = cmdline.getOptionValue(INDEX_OPTION); HdfsWikipediaSearcher searcher = new HdfsWikipediaSearcher(new Path(indexLocation), getConf()); PrintStream out = new PrintStream(System.out, true, "UTF-8"); if (cmdline.hasOption(ID_OPTION)) { int id = Integer.parseInt(cmdline.getOptionValue(ID_OPTION)); Document doc = searcher.getArticle(id); if (doc == null) { System.err.print("id " + id + " doesn't exist!\n"); } else { out.println(doc.getField(IndexField.TEXT.name).stringValue()); } } else { String title = cmdline.getOptionValue(TITLE_OPTION); Document doc = searcher.getArticle(title); if (doc == null) { System.err.print("article \"" + title + "\" doesn't exist!\n"); } else { out.println(doc.getField(IndexField.TEXT.name).stringValue()); } } searcher.close(); out.close(); return 0; }
From source file:br.com.ingenieux.mojo.beanstalk.env.DumpInstancesMojo.java
@Override protected Object executeInternal() throws Exception { AmazonEC2 ec2 = clientFactory.getService(AmazonEC2Client.class); DescribeEnvironmentResourcesResult envResources = getService().describeEnvironmentResources( new DescribeEnvironmentResourcesRequest().withEnvironmentId(curEnv.getEnvironmentId()) .withEnvironmentName(curEnv.getEnvironmentName())); List<String> instanceIds = new ArrayList<String>(); for (Instance i : envResources.getEnvironmentResources().getInstances()) { instanceIds.add(i.getId());/*from ww w .j a va 2s. com*/ } DescribeInstancesResult ec2Instances = ec2 .describeInstances(new DescribeInstancesRequest().withInstanceIds(instanceIds)); PrintStream printStream = null; if (null != outputFile) { printStream = new PrintStream(outputFile); } for (Reservation r : ec2Instances.getReservations()) { for (com.amazonaws.services.ec2.model.Instance i : r.getInstances()) { String ipAddress = dumpPrivateAddresses ? i.getPrivateIpAddress() : StringUtils.defaultString(i.getPublicIpAddress(), i.getPrivateDnsName()); String instanceId = i.getInstanceId(); if (null != printStream) { printStream.println(ipAddress + " # " + instanceId); } else { getLog().info(" * " + instanceId + ": " + ipAddress); } } } if (null != printStream) { printStream.close(); } return null; }
From source file:org.apache.nifi.processors.poi.ConvertExcelToCSVProcessor.java
/** * Handles an individual Excel sheet from the entire Excel document. Each sheet will result in an individual flowfile. * * @param session//from ww w . java2 s . c o m * The NiFi ProcessSession instance for the current invocation. */ private void handleExcelSheet(ProcessSession session, FlowFile originalParentFF, final InputStream sheetInputStream, ExcelSheetReadConfig readConfig, CSVFormat csvFormat) throws IOException { FlowFile ff = session.create(); try { final DataFormatter formatter = new DataFormatter(); final InputSource sheetSource = new InputSource(sheetInputStream); final SheetToCSV sheetHandler = new SheetToCSV(readConfig, csvFormat); final XMLReader parser = SAXHelper.newXMLReader(); //If Value Formatting is set to false then don't pass in the styles table. // This will cause the XSSF Handler to return the raw value instead of the formatted one. final StylesTable sst = readConfig.getFormatValues() ? readConfig.getStyles() : null; final XSSFSheetXMLHandler handler = new XSSFSheetXMLHandler(sst, null, readConfig.getSharedStringsTable(), sheetHandler, formatter, false); parser.setContentHandler(handler); ff = session.write(ff, new OutputStreamCallback() { @Override public void process(OutputStream out) throws IOException { PrintStream outPrint = new PrintStream(out); sheetHandler.setOutput(outPrint); try { parser.parse(sheetSource); sheetInputStream.close(); sheetHandler.close(); outPrint.close(); } catch (SAXException se) { getLogger().error("Error occurred while processing Excel sheet {}", new Object[] { readConfig.getSheetName() }, se); } } }); ff = session.putAttribute(ff, SHEET_NAME, readConfig.getSheetName()); ff = session.putAttribute(ff, ROW_NUM, new Long(sheetHandler.getRowCount()).toString()); if (StringUtils.isNotEmpty(originalParentFF.getAttribute(CoreAttributes.FILENAME.key()))) { ff = session.putAttribute(ff, SOURCE_FILE_NAME, originalParentFF.getAttribute(CoreAttributes.FILENAME.key())); } else { ff = session.putAttribute(ff, SOURCE_FILE_NAME, UNKNOWN_SHEET_NAME); } //Update the CoreAttributes.FILENAME to have the .csv extension now. Also update MIME.TYPE ff = session.putAttribute(ff, CoreAttributes.FILENAME.key(), updateFilenameToCSVExtension(ff.getAttribute(CoreAttributes.UUID.key()), ff.getAttribute(CoreAttributes.FILENAME.key()), readConfig.getSheetName())); ff = session.putAttribute(ff, CoreAttributes.MIME_TYPE.key(), CSV_MIME_TYPE); session.transfer(ff, SUCCESS); } catch (SAXException | ParserConfigurationException saxE) { getLogger().error("Failed to create instance of Parser.", saxE); ff = session.putAttribute(ff, ConvertExcelToCSVProcessor.class.getName() + ".error", saxE.getMessage()); session.transfer(ff, FAILURE); } finally { sheetInputStream.close(); } }
From source file:com.qut.middleware.spep.authn.bindings.impl.AuthnPostBindingImpl.java
private void handleAuthnRequest(HttpServletRequest request, HttpServletResponse response, AuthnProcessorData data, SPEP spep) throws AuthenticationException { try {/* ww w . j a v a2 s . c o m*/ String remoteAddress = request.getRemoteAddr(); this.logger.info("[Authn for {}] Initiating HTTP POST binding. Creating AuthnRequest", remoteAddress); String document = buildAuthnRequestDocument(request.getParameter("redirectURL"), request, response, data, spep); PrintStream out = new PrintStream(response.getOutputStream()); /* Set cookie to allow javascript enabled browsers to autosubmit, ensures navigation with the back button is not broken because auto submit is active for only a very short period */ Cookie autoSubmit = new Cookie("spepAutoSubmit", "enabled"); autoSubmit.setMaxAge(172800); //set expiry to be 48 hours just to make sure we still work with badly configured clocks skewed from GMT autoSubmit.setPath("/"); response.addCookie(autoSubmit); response.setStatus(HttpServletResponse.SC_OK); response.setHeader("Content-Type", "text/html"); out.print(document); out.close(); this.logger.info("[Authn for {}] Sent AuthnRequest successfully", remoteAddress); } catch (IOException e) { throw new AuthenticationException("Unable to send response due to an I/O error.", e); } }
From source file:com.zimbra.cs.service.authenticator.CertUtil.java
private void outputCert(String outputFlePath, boolean dump) throws Exception { PrintStream outStream; if (outputFlePath != null) { outStream = new PrintStream(outputFlePath); } else {//from w w w.j a va2 s . c o m outStream = System.out; } try { if (dump) { outStream.println(cert.toString()); } else { printCert(outStream); } } finally { outStream.flush(); if (outputFlePath != null) { outStream.close(); } } }