List of usage examples for java.io PrintStream print
public void print(Object obj)
From source file:org.apache.cocoon.portlet.ManagedCocoonPortlet.java
/** * Process the specified <code>RenderRequest</code> producing output * on the specified <code>RenderResponse</code>. *///from w ww. ja va 2 s . c om public void render(RenderRequest req, RenderResponse res) throws PortletException, IOException { // remember when we started (used for timing the processing) long start = System.currentTimeMillis(); // add the cocoon header timestamp res.setProperty("X-Cocoon-Version", Constants.VERSION); // get the request (wrapped if contains multipart-form data) RenderRequest request = req; // Get the cocoon engine instance Cocoon cocoon = getCocoon(); // Check if cocoon was initialized if (cocoon == null) { manageException(request, res, null, null, "Initialization Problem", null /* "Cocoon was not initialized" */, null /* "Cocoon was not initialized, cannot process request" */, this.exception); return; } // We got it... Process the request String servletPath = this.servletPath; if (servletPath == null) { servletPath = "portlets/" + getPortletConfig().getPortletName(); } String pathInfo = getPathInfo(request); String uri = servletPath; if (pathInfo != null) { uri += pathInfo; } String contentType = null; ContextMap ctxMap = null; Environment env; try { if (uri.charAt(0) == '/') { uri = uri.substring(1); } env = getEnvironment(servletPath, pathInfo, uri, request, res); } catch (Exception e) { if (getLogger().isErrorEnabled()) { getLogger().error("Problem with Cocoon portlet", e); } manageException(request, res, null, uri, "Problem in creating the Environment", null, null, e); return; } try { try { // Initialize a fresh log context containing the object model: it // will be used by the CocoonLogFormatter ctxMap = ContextMap.getCurrentContext(); // Add thread name (default content for empty context) String threadName = Thread.currentThread().getName(); ctxMap.set("threadName", threadName); // Add the object model ctxMap.set("objectModel", env.getObjectModel()); // Add a unique request id (threadName + currentTime ctxMap.set("request-id", threadName + System.currentTimeMillis()); if (cocoon.process(env)) { } else { // We reach this when there is nothing in the processing change that matches // the request. For example, no matcher matches. getLogger().fatalError("The Cocoon engine failed to process the request."); manageException(request, res, env, uri, "Request Processing Failed", "Cocoon engine failed in process the request", "The processing engine failed to process the request. This could be due to lack of matching or bugs in the pipeline engine.", null); return; } } catch (ResourceNotFoundException rse) { if (getLogger().isWarnEnabled()) { getLogger().warn("The resource was not found", rse); } manageException(request, res, env, uri, "Resource Not Found", "Resource Not Found", "The requested portlet could not be found", rse); return; } catch (ConnectionResetException e) { if (getLogger().isDebugEnabled()) { getLogger().debug(e.getMessage(), e); } else if (getLogger().isWarnEnabled()) { getLogger().warn(e.getMessage()); } } catch (IOException e) { // Tomcat5 wraps SocketException into ClientAbortException which extends IOException. if (getLogger().isDebugEnabled()) { getLogger().debug(e.getMessage(), e); } else if (getLogger().isWarnEnabled()) { getLogger().warn(e.getMessage()); } } catch (Exception e) { if (getLogger().isErrorEnabled()) { getLogger().error("Internal Cocoon Problem", e); } manageException(request, res, env, uri, "Internal Server Error", null, null, e); return; } long end = System.currentTimeMillis(); String timeString = processTime(end - start); if (getLogger().isInfoEnabled()) { getLogger().info("'" + uri + "' " + timeString); } res.setProperty("X-Cocoon-Time", timeString); // FIXME: contentType is always null (see line 556) if (contentType != null && contentType.equals("text/html")) { String showTime = request.getParameter(Constants.SHOWTIME_PARAM); boolean show = this.showTime; if (showTime != null) { show = !showTime.equalsIgnoreCase("no"); } if (show) { boolean hide = this.hiddenShowTime; if (showTime != null) { hide = showTime.equalsIgnoreCase("hide"); } PrintStream out = new PrintStream(res.getPortletOutputStream()); out.print((hide) ? "<!-- " : "<p>"); out.print(timeString); out.println((hide) ? " -->" : "</p>\n"); } } } finally { if (ctxMap != null) { ctxMap.clear(); } /* * Portlet Specification 1.0, PLT.12.3.2 Output Stream and Writer Objects: * The termination of the render method of the portlet indicates * that the portlet has satisfied the request and that the output * object is to be closed. * * Portlet container will close the stream, no need to close it here. */ } }
From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.analysis.sensitivity.SobolAnalysis.java
/** * Computes and displays the first-, total-, and second- order Sobol' * sensitivities and 50% bootstrap confidence intervals. * /*from w w w .j ava2 s . c o m*/ * @param output the output stream */ private void display(PrintStream output) { output.println("Parameter Sensitivity [Confidence]"); output.println("First-Order Effects"); for (int j = 0; j < P; j++) { double[] a0 = new double[N]; double[] a1 = new double[N]; double[] a2 = new double[N]; for (int i = 0; i < N; i++) { a0[i] = A[i]; a1[i] = C_A[i][j]; a2[i] = B[i]; } output.print(" "); output.print(parameterFile.get(j).getName()); output.print(' '); output.print(computeFirstOrder(a0, a1, a2, N)); output.print(" ["); output.print(computeFirstOrderConfidence(a0, a1, a2, N, resamples)); output.println(']'); } output.println("Total-Order Effects"); for (int j = 0; j < P; j++) { double[] a0 = new double[N]; double[] a1 = new double[N]; double[] a2 = new double[N]; for (int i = 0; i < N; i++) { a0[i] = A[i]; a1[i] = C_A[i][j]; a2[i] = B[i]; } output.print(" "); output.print(parameterFile.get(j).getName()); output.print(' '); output.print(computeTotalOrder(a0, a1, a2, N)); output.print(" ["); output.print(computeTotalOrderConfidence(a0, a1, a2, N, resamples)); output.println(']'); } output.println("Second-Order Effects"); for (int j = 0; j < P; j++) { for (int k = j + 1; k < P; k++) { double[] a0 = new double[N]; double[] a1 = new double[N]; double[] a2 = new double[N]; double[] a3 = new double[N]; double[] a4 = new double[N]; for (int i = 0; i < N; i++) { a0[i] = A[i]; a1[i] = C_B[i][j]; a2[i] = C_A[i][k]; a3[i] = C_A[i][j]; a4[i] = B[i]; } output.print(" "); output.print(parameterFile.get(j).getName()); output.print(" * "); output.print(parameterFile.get(k).getName()); output.print(' '); output.print(computeSecondOrder(a0, a1, a2, a3, a4, N)); output.print(" ["); output.print(computeSecondOrderConfidence(a0, a1, a2, a3, a4, N, resamples)); output.println(']'); } } }
From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.analysis.sensitivity.ExtractData.java
@Override public void run(CommandLine commandLine) throws Exception { String separator = commandLine.hasOption("separator") ? commandLine.getOptionValue("separator") : " "; String[] fields = commandLine.getArgs(); // indicators are prepared, run the data extraction routine ResultFileReader input = null;/* ww w . java 2 s . co m*/ PrintStream output = null; try { // setup the problem if (commandLine.hasOption("problem")) { problem = ProblemFactory.getInstance().getProblem(commandLine.getOptionValue("problem")); } else { problem = new ProblemStub(Integer.parseInt(commandLine.getOptionValue("dimension"))); } try { input = new ResultFileReader(problem, new File(commandLine.getOptionValue("input"))); try { output = commandLine.hasOption("output") ? new PrintStream(new File(commandLine.getOptionValue("output"))) : System.out; // optionally print header line if (!commandLine.hasOption("noheader")) { output.print('#'); for (int i = 0; i < fields.length; i++) { if (i > 0) { output.print(separator); } output.print(fields[i]); } output.println(); } // process entries while (input.hasNext()) { ResultEntry entry = input.next(); Properties properties = entry.getProperties(); for (int i = 0; i < fields.length; i++) { if (i > 0) { output.print(separator); } if (properties.containsKey(fields[i])) { output.print(properties.getProperty(fields[i])); } else if (fields[i].startsWith("+")) { output.print(evaluate(fields[i].substring(1), entry, commandLine)); } else { throw new FrameworkException("missing field"); } } output.println(); } } finally { if ((output != null) && (output != System.out)) { output.close(); } } } finally { if (input != null) { input.close(); } } } finally { if (problem != null) { problem.close(); } } }
From source file:com.google.feedserver.tools.FeedServerClientTool.java
@SuppressWarnings("unchecked") protected void printProperty(String name, Object value, PrintStream out) { if (value != null && value instanceof Object[]) { Object[] values = (Object[]) value; for (int i = 0; i < values.length; i++) { print(out, "<" + name + (i == 0 ? " repeatable=\"true\"" : "") + ">"); if (values[i] instanceof Map) { out.println();// w ww .j a v a 2s .c om indentMore(); printMap((Map<String, Object>) values[i], out); indentLess(); } else { out.print(values[i] == null ? "" : StringEscapeUtils.escapeXml(values[i].toString())); } println(out, "</" + name + ">"); } } else if (value != null && value instanceof Map) { println(out, "<" + name + ">"); indentMore(); printMap((Map<String, Object>) value, out); indentLess(); println(out, "</" + name + ">"); } else { print(out, "<" + name + ">"); out.print(value == null ? "" : StringEscapeUtils.escapeXml(value.toString())); out.println("</" + name + ">"); } }
From source file:com.hpe.application.automation.tools.run.SseBuilder.java
private Testsuites execute(Run<?, ?> build, PrintStream logger, VariableResolver<String> buildVariableResolver) throws InterruptedException { Testsuites ret = null;//from w ww.j a va 2 s . c o m SSEBuilderPerformer performer = null; try { performer = new SSEBuilderPerformer(); ret = execute(performer, logger, buildVariableResolver); } catch (InterruptedException e) { build.setResult(Result.ABORTED); stop(performer, logger); throw e; } catch (Exception cause) { build.setResult(Result.FAILURE); logger.print(String.format("Failed to execute test, Exception: %s", cause.getMessage())); } return ret; }
From source file:org.codice.ddf.platform.status.impl.ListApplicationCommand.java
@Override protected Object doExecute() throws Exception { PrintStream console = System.out; ServiceReference ref = getBundleContext().getServiceReference(ApplicationService.class.getName()); if (ref == null) { console.println("Application Status service is unavailable."); return null; }/*from w w w . ja v a2 s . c o m*/ try { ApplicationService appService = (ApplicationService) getBundleContext().getService(ref); if (appService == null) { console.println("Application Status service is unavailable."); return null; } Set<Application> applications = appService.getApplications(); console.printf("%s%10s\n", "State", "Name"); for (Application curApp : applications) { ApplicationStatus appStatus = appService.getApplicationStatus(curApp); // only show applications that have features (gets rid of repo // aggregator 'apps') if (!curApp.getFeatures().isEmpty()) { console.print("["); switch (appStatus.getState()) { case ACTIVE: console.print(Ansi.ansi().fg(Ansi.Color.GREEN).toString()); break; case FAILED: console.print(Ansi.ansi().fg(Ansi.Color.RED).toString()); break; case INACTIVE: // don't set a color break; case UNKNOWN: console.print(Ansi.ansi().fg(Ansi.Color.YELLOW).toString()); break; default: break; } console.print(StringUtils.rightPad(appStatus.getState().toString(), STATUS_COLUMN_LENGTH)); console.print(Ansi.ansi().reset().toString()); console.println("] " + curApp.getName()); } } } finally { getBundleContext().ungetService(ref); } return null; }
From source file:es.cnio.bioinfo.bicycle.gatk.MethylationFilePair.java
private void writeMethylcytosinesHeader(PrintStream out) { out.print(MethylationCall.getMarshallHeader()); for (RodBinding<BEDFeature> binding : this.beds) { out.print("\t" + binding.getName()); }/*from w w w.j a v a 2 s . c o m*/ out.println("\tSTATUS"); }
From source file:de.juwimm.cms.model.EditionHbmDaoImpl.java
@SuppressWarnings("unchecked") @Override//from w ww.java2 s . c o m protected void handlePicturesToXmlRecursive(Integer unitId, Integer siteId, PrintStream out, EditionHbm edition) throws Exception { out.println("\t<pictures>"); try { if (unitId == null) { Collection<UnitHbm> units = getUnitHbmDao().findAll(siteId); for (UnitHbm unit : units) { Collection<PictureHbm> pictures = getPictureHbmDao().findAllPerUnit(unit.getUnitId()); for (PictureHbm picture : pictures) { out.print(picture.toXml(2)); } } } else { if (unitId == -1) unitId = getSiteHbmDao().load(siteId).getRootUnit().getUnitId(); Collection<PictureHbm> pictures = getPictureHbmDao().findAllPerUnit(unitId); for (PictureHbm pic : pictures) { out.print(pic.toXml(2)); } } } catch (Exception exe) { log.error("Error occured", exe); } out.println("\t</pictures>"); }
From source file:org.apache.hive.beeline.TestBeeLineWithArgs.java
/** * Attempt to execute a simple script file with the -f or -i option * to BeeLine (or both) to test for presence of an expected pattern * in the output (stdout or stderr), fail if not found. * Print PASSED or FAILED//from w ww.j a v a2 s. com * @param scriptText script to test the output for * @param argList arguments to be passed to the script file to execute and produce output * @param streamType Whether match should be done against STDERR or STDOUT * @param expectedMatches List of Tuple's defining the pattern to match and result of matching * @param modes testing modes we have to run the script as * @throws Exception on command execution error */ private void testScriptFile(String scriptText, List<String> argList, OutStream streamType, List<Tuple<String>> expectedMatches, List<Modes> modes) throws Throwable { // Put the script content in a temp file File scriptFile = File.createTempFile(this.getClass().getSimpleName(), "temp"); System.out.println("script file is " + scriptFile.getAbsolutePath()); scriptFile.deleteOnExit(); PrintStream os = new PrintStream(new FileOutputStream(scriptFile)); os.print(scriptText); os.close(); List<Tuple<Pattern>> patternsToBeMatched = Lists.transform(expectedMatches, new Function<Tuple<String>, Tuple<Pattern>>() { @Override public Tuple<Pattern> apply(Tuple<String> tuple) { return new Tuple<>(Pattern.compile(".*" + tuple.pattern + ".*", Pattern.DOTALL), tuple.shouldMatch); } }); for (Modes mode : modes) { String output = mode.output(scriptFile, argList, streamType); for (Tuple<Pattern> patternToMatch : patternsToBeMatched) { Matcher m = patternToMatch.pattern.matcher(output); boolean matches = m.matches(); if (patternToMatch.shouldMatch != matches) { //failed fail("Output" + output + " should" + (patternToMatch.shouldMatch ? "" : " not") + " contain " + patternToMatch.pattern.pattern()); } } } scriptFile.delete(); }
From source file:examples.ClassPropertyUsageAnalyzer.java
/** * Prints the data of one property to the given output. This will be a * single line in CSV./*from w w w . j av a2s . co m*/ * * @param out * the output to write to * @param propertyRecord * the data to write * @param propertyIdValue * the property that the data refers to */ private void printPropertyRecord(PrintStream out, PropertyRecord propertyRecord, PropertyIdValue propertyIdValue) { printTerms(out, propertyRecord.propertyDocument, propertyIdValue, null); String datatype = "Unknown"; if (propertyRecord.propertyDocument != null) { datatype = getDatatypeLabel(propertyRecord.propertyDocument.getDatatype()); } out.print("," + datatype + "," + propertyRecord.statementCount + "," + propertyRecord.itemCount + "," + propertyRecord.statementWithQualifierCount + "," + propertyRecord.qualifierCount + "," + propertyRecord.referenceCount + "," + (propertyRecord.statementCount + propertyRecord.qualifierCount + propertyRecord.referenceCount)); printRelatedProperties(out, propertyRecord); out.println(""); }