List of usage examples for java.io PrintStream print
public void print(Object obj)
From source file:org.apache.cocoon.portlet.CocoonPortlet.java
/** * Process the specified <code>RenderRequest</code> producing output * on the specified <code>RenderResponse</code>. *//*from ww w .ja v a 2 s . c o m*/ public void render(RenderRequest req, RenderResponse res) throws PortletException, IOException { /* HACK for reducing class loader problems. */ /* example: xalan extensions fail if someone adds xalan jars in tomcat3.2.1/lib */ if (this.initClassLoader) { try { Thread.currentThread().setContextClassLoader(this.classLoader); } catch (Exception e) { } } // 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 getCocoon(request.getParameter(Constants.RELOAD_PARAM)); // Check if cocoon was initialized if (this.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 (this.cocoon.process(env)) { contentType = env.getContentType(); } 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); 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(); } try { if (request instanceof MultipartActionRequest) { if (getLogger().isDebugEnabled()) { getLogger().debug("Deleting uploaded file(s)."); } ((MultipartActionRequest) request).cleanup(); } } catch (IOException e) { getLogger().error("Cocoon got an Exception while trying to cleanup the uploaded files.", e); } /* * 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:org.bigtextml.topics.ParallelTopicModel.java
public void printTopWords(PrintStream out, int numWords, boolean usingNewLines) { out.print(displayTopWords(numWords, usingNewLines)); }
From source file:com.opengamma.analytics.financial.model.volatility.local.LocalVolatilityPDEGreekCalculator.java
public void smileDynamic(final PrintStream ps, final double expiry, final LocalVolatilitySurfaceStrike localVol, final ForwardCurve forwardCurve) { final double forward = forwardCurve.getForward(expiry); final double maxProxyDelta = 0.4; final PDEFullResults1D pdeRes = runForwardPDESolver(forwardCurve, localVol, _isCall, _theta, expiry, maxProxyDelta, _timeSteps, _spaceSteps, _timeGridBunching, _spaceGridBunching, 1.0); final int n = pdeRes.getNumberSpaceNodes(); ps.println("Strike\tVol"); for (int i = 0; i < n; i++) { final double m = pdeRes.getSpaceValue(i); if (m > 0.3 && m < 3.0) { final double k = m * forward; final double mPrice = pdeRes.getFunctionValue(i); double impVol = 0; try { impVol = BlackFormulaRepository.impliedVolatility(mPrice, 1.0, m, expiry, _isCall); } catch (final Exception e) { }//from w ww . j a va 2 s .c o m ps.println(k + "\t" + impVol); } } ps.print("\n"); //finally run the backwards PDE solver 100 times with different strikes, interpolating to get vol final double maxForward = 3.5 * forward; PDEResults1D res = runBackwardsPDESolver(forward, localVol, _isCall, _theta, expiry, maxForward, _timeSteps, _spaceSteps, _timeGridBunching, _spaceGridBunching, forward); final int xIndex = res.getGrid().getLowerBoundIndexForSpace(forward); final double f1 = res.getSpaceValue(xIndex); final double f2 = res.getSpaceValue(xIndex + 1); final double w = (f2 - forward) / (f2 - f1); ps.println( "Result of running 100 backwards PDE solvers all with different strikes. Delta and gamma for each strike" + " is calculated from finite difference on the grid"); ps.println("Strike\tVol\tDelta\tGamma"); for (int i = 0; i < 100; i++) { final double k = forward * (0.3 + 2.7 * i / 99.0); res = runBackwardsPDESolver(k, localVol, _isCall, _theta, expiry, maxForward, _timeSteps, _spaceSteps, _timeGridBunching, _spaceGridBunching, forward); double vol = 0; try { final double vol1 = BlackFormulaRepository.impliedVolatility(res.getFunctionValue(xIndex), f1, k, expiry, _isCall); final double vol2 = BlackFormulaRepository.impliedVolatility(res.getFunctionValue(xIndex + 1), f2, k, expiry, _isCall); vol = w * vol1 + (1 - w) * vol2; } catch (final Exception e) { } ps.println(k + "\t" + vol); } ps.println("\n"); // //debug // PDEFullResults1D pdeResDebug = runForwardPDESolverDebug(forward, localVol, _isCall, _theta, expiry, maxForward, _timeSteps, _spaceSteps, _timeGridBunching, _spaceGridBunching, forward); // for (int i = 0; i < n; i++) { // double k = pdeResDebug.getSpaceValue(i); // double price = pdeResDebug.getFunctionValue(i); // double impVol = 0; // try { // impVol = BlackFormulaRepository.impliedVolatility(price, forward, k, expiry, _isCall); // } catch (Exception e) { // } // double priceShift = pdeResDebugShift.getFunctionValue(i); // double impVolShift = 0; // try { // impVolShift = BlackFormulaRepository.impliedVolatility(priceShift, forwardShift, k, expiry, _isCall); // } catch (Exception e) { // } // ps.println(k + "\t" + impVol + "\t" + impVolShift); // } }
From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.analysis.sensitivity.Analysis.java
@Override public void run(CommandLine commandLine) throws Exception { PrintStream output = null; //parse required parameters parameterFile = new ParameterFile(new File(commandLine.getOptionValue("parameterFile"))); parameters = loadParameters(new File(commandLine.getOptionValue("parameters"))); metric = Integer.parseInt(commandLine.getOptionValue("metric")); //parse optional parameters if (commandLine.hasOption("band")) { bandWidth = Integer.parseInt(commandLine.getOptionValue("band")); }/*w w w . j a v a 2s.c o m*/ if (commandLine.hasOption("threshold")) { threshold = Double.parseDouble(commandLine.getOptionValue("threshold")); } //if analyzing hypervolume, require the hypervolume option if (metric == 0) { if (commandLine.hasOption("hypervolume")) { threshold *= Double.parseDouble(commandLine.getOptionValue("hypervolume")); } else { throw new MissingOptionException("requires hypervolume option"); } } try { //setup the output stream if (commandLine.hasOption("output")) { output = new PrintStream(new File(commandLine.getOptionValue("output"))); } else { output = System.out; } //process all the files listed on the command line String[] filenames = commandLine.getArgs(); for (int i = 0; i < filenames.length; i++) { if (i > 0) { output.println(); } metrics = loadMetrics(new File(filenames[i])); output.print(filenames[i]); output.println(":"); output.print(" Best: "); output.println(calculateBest()); output.print(" Attainment: "); output.println(calculateAttainment()); if (commandLine.hasOption("controllability")) { output.print(" Controllability: "); output.println(calculateControllability()); } if (commandLine.hasOption("efficiency")) { output.print(" Efficiency: "); output.println(calculateEfficiency()); } } } finally { if ((output != null) && (output != System.out)) { output.close(); } } }
From source file:org.cruxframework.crux.tools.schema.DefaultSchemaGenerator.java
/** * //from w ww .j a v a 2s .co m * @param out * @param library * @param added * @param processorClass */ private void generateAttributes(PrintStream out, String library, Set<String> added, Class<?> processorClass) { TagAttributesDeclaration attrsDecl = processorClass.getAnnotation(TagAttributesDeclaration.class); if (attrsDecl != null) { for (TagAttributeDeclaration attr : attrsDecl.value()) { if (!added.contains(attr.value())) { out.print("<xs:attribute name=\"" + attr.value() + "\" type=\"" + getSchemaType(attr.type(), library, attr.supportsDataBinding()) + "\" "); if (attr.required()) { out.print("use=\"required\" "); } else { String defaultValue = attr.defaultValue(); if (defaultValue.length() > 0) out.print("default=\"" + defaultValue + "\" "); } out.println(">"); String attrDescription = attr.description(); if (attrDescription != null && attrDescription.length() > 0) { out.println("<xs:annotation>"); out.println("<xs:documentation>" + StringEscapeUtils.escapeXml(attrDescription) + "</xs:documentation>"); out.println("</xs:annotation>"); } out.println("</xs:attribute>"); added.add(attr.value()); } } } TagAttributes attrs = processorClass.getAnnotation(TagAttributes.class); if (attrs != null) { for (TagAttribute attr : attrs.value()) { if (!added.contains(attr.value()) && !attr.xsdIgnore()) { out.print("<xs:attribute name=\"" + attr.value() + "\" type=\"" + getSchemaType(attr.type(), library, attr.supportsDataBinding()) + "\" "); if (attr.required()) { out.print("use=\"required\" "); } else { String defaultValue = attr.defaultValue(); if (defaultValue.length() > 0) out.print("default=\"" + defaultValue + "\" "); } out.println(">"); String attrDescription = attr.description(); if (attrDescription != null && attrDescription.length() > 0) { out.println("<xs:annotation>"); out.println("<xs:documentation>" + StringEscapeUtils.escapeXml(attrDescription) + "</xs:documentation>"); out.println("</xs:annotation>"); } out.println("</xs:attribute>"); added.add(attr.value()); } } } }
From source file:fr.inrialpes.exmo.align.cli.WGroupEval.java
public void printHTML(Vector<Vector<Object>> result, PrintStream writer) { // variables for computing iterative harmonic means int expected = 0; // expected so far int foundVect[]; // found so far int correctFoundVect[]; // correct so far int correctExpVect[]; // correct so far long timeVect[]; // time so far fsize = format.length();//from ww w . ja v a2 s.co m // JE: the writer should be put out // JE: the h-means computation should be put out as well Formatter formatter = new Formatter(writer); // Print the header if (embedded != true) writer.println("<html><head></head><body>"); writer.println("<table border='2' frame='sides' rules='groups'>"); writer.println("<colgroup align='center' />"); // for each algo <td spancol='2'>name</td> for (String m : listAlgo) { writer.println("<colgroup align='center' span='" + fsize + "' />"); } // For each file do a writer.println("<thead valign='top'><tr><th>algo</th>"); // for each algo <td spancol='2'>name</td> for (String m : listAlgo) { writer.println("<th colspan='" + fsize + "'>" + m + "</th>"); } writer.println("</tr></thead><tbody><tr><td>test</td>"); // for each algo <td>Prec.</td><td>Rec.</td> for (String m : listAlgo) { for (int i = 0; i < fsize; i++) { writer.print("<td>"); if (format.charAt(i) == 'p') { writer.print("Prec."); } else if (format.charAt(i) == 'f') { writer.print("FMeas."); } else if (format.charAt(i) == 'o') { writer.print("Over."); } else if (format.charAt(i) == 't') { writer.print("Time"); } else if (format.charAt(i) == 'r') { writer.print("Rec."); } writer.println("</td>"); } //writer.println("<td>Prec.</td><td>Rec.</td>"); } writer.println("</tr></tbody><tbody>"); foundVect = new int[size]; correctFoundVect = new int[size]; correctExpVect = new int[size]; timeVect = new long[size]; for (int k = size - 1; k >= 0; k--) { foundVect[k] = 0; correctFoundVect[k] = 0; correctExpVect[k] = 0; timeVect[k] = 0; } // </tr> // For each directory <tr> boolean colored = false; for (Vector<Object> test : result) { double newexpected = -1.; if (colored == true && color != null) { colored = false; writer.println("<tr bgcolor=\"" + color + "\">"); } else { colored = true; writer.println("<tr>"); } ; // Print the directory <td>bla</td> writer.println("<td>" + (String) test.get(0) + "</td>"); // For each record print the values <td>bla</td> Enumeration<Object> f = test.elements(); f.nextElement(); for (int k = 0; f.hasMoreElements(); k++) { WeightedPREvaluator eval = (WeightedPREvaluator) f.nextElement(); if (eval != null) { // iterative H-means computation if (newexpected == -1.) { newexpected = eval.getExpected(); expected += newexpected; } foundVect[k] += eval.getFound(); correctFoundVect[k] += eval.getCorrectFound(); correctExpVect[k] += eval.getCorrectExpected(); timeVect[k] += eval.getTime(); for (int i = 0; i < fsize; i++) { writer.print("<td>"); if (format.charAt(i) == 'p') { formatter.format("%1.2f", eval.getPrecision()); } else if (format.charAt(i) == 'f') { formatter.format("%1.2f", eval.getFmeasure()); } else if (format.charAt(i) == 'o') { formatter.format("%1.2f", eval.getOverall()); } else if (format.charAt(i) == 't') { if (eval.getTime() == 0) { writer.print("-"); } else { formatter.format("%1.2f", eval.getTime()); } } else if (format.charAt(i) == 'r') { formatter.format("%1.2f", eval.getRecall()); } writer.println("</td>"); } } else { // JE 2013: will break if the previous tests are all NULL correctExpVect[k] += newexpected; // Nothing needs to be incremented for precision for (int i = 0; i < fsize; i++) writer.print("<td>n/a</td>"); writer.println(); } } writer.println("</tr>"); } writer.print("<tr bgcolor=\"yellow\"><td>H-mean</td>"); // Here we are computing a sheer average. // While in the column results we print NaN when the returned // alignment is empty, // here we use the real values, i.e., add 0 to both correctVect and // foundVect, so this is OK for computing the average. int k = 0; // ??? for (String m : listAlgo) { double precision = 1. - (double) correctFoundVect[k] / foundVect[k]; double recall = 1. - (double) correctExpVect[k] / expected; for (int i = 0; i < fsize; i++) { writer.print("<td>"); if (format.charAt(i) == 'p') { formatter.format("%1.2f", precision); } else if (format.charAt(i) == 'f') { formatter.format("%1.2f", 2 * precision * recall / (precision + recall)); } else if (format.charAt(i) == 'o') { formatter.format("%1.2f", recall * (2 - (1 / precision))); } else if (format.charAt(i) == 't') { if (timeVect[k] == 0) { writer.print("-"); } else { formatter.format("%1.2f", timeVect[k]); } } else if (format.charAt(i) == 'r') { formatter.format("%1.2f", recall); } writer.println("</td>"); } ; k++; } writer.println("</tr>"); writer.println("</tbody></table>"); writer.println("<p><small>n/a: result alignment not provided or not readable<br />"); writer.println("NaN: division per zero, likely due to empty alignment.</small></p>"); if (embedded != true) writer.println("</body></html>"); }
From source file:josejamilena.pfc.servidor.chartserver.ClientHandler.java
/** * Mtodo que ejecuta el Thread./*from ww w . ja va 2s.c om*/ */ @Override public void run() { try { BufferedReader in = new BufferedReader(new InputStreamReader(miSocketServidor.getInputStream())); PrintStream out = new PrintStream(new BufferedOutputStream(miSocketServidor.getOutputStream())); String s = in.readLine(); // System.out.println(s); // Salida para el Log // Atiende a servir archivos. String filename = ""; StringTokenizer st = new StringTokenizer(s); try { // Parsea la peticin desde el comando GET if (st.hasMoreElements() && st.nextToken().equalsIgnoreCase("GET") && st.hasMoreElements()) { filename = st.nextToken(); } else { throw new FileNotFoundException(); } // Aade "/" with "index.html" if (filename.endsWith("/")) { filename += nombreFichero; } // Quita / del nombre del archivo while (filename.indexOf("/") == 0) { filename = filename.substring(1); } // Reemplaza "/" por "\" en el path para servidores en Win32 filename = filename.replace('/', File.separator.charAt(0)); /* Comprueba caracteres no permitidos, para impedir acceder a directorios superiores */ if ((filename.indexOf("..") >= 0) || (filename.indexOf(':') >= 0) || (filename.indexOf('|') >= 0)) { throw new FileNotFoundException(); } // Si la peticin de acceso a un directorio no tiene "/", // envia al cliente un respuesta HTTP if (new File(filename).isDirectory()) { filename = filename.replace('\\', '/'); out.print( "HTTP/1.0 301 Movido permantemente \r\n" + "Albergado en: /" + filename + "/\r\n\r\n"); out.close(); return; } // Abriendo el archivo (puede lanzar FileNotFoundException) InputStream f = new FileInputStream(filename); // Determina el tipe MIME e imprime la cabecera HTTP String mimeType = "text/plain"; if (filename.endsWith(".html") || filename.endsWith(".htm")) { mimeType = "text/html"; } else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg")) { mimeType = "image/jpeg"; } else if (filename.endsWith(".gif")) { mimeType = "image/gif"; } else if (filename.endsWith(".class")) { mimeType = "application/octet-stream"; } else if (filename.endsWith(".jnlp")) { mimeType = "application/x-java-jnlp-file"; } out.print("HTTP/1.0 200 OK\r\n" + "Server: josejamilena_Torito-Chart-Server\r\n" + "Content-type: " + mimeType + "\r\n\r\n"); // Envia el fichero ala cliente, y cierra la conexin byte[] a = new byte[bufferSize]; int n; while ((n = f.read(a)) > 0) { out.write(a, 0, n); } f.close(); out.close(); } catch (FileNotFoundException x) { out.println("HTTP/1.0 404 No encontrado.\r\n" + "Server: josejamilena_Torito-Chart-Server\r\n" + "Content-type: text/html\r\n\r\n" + "<html><head></head><body>" + "El fichero " + filename + " no ha sido encontrado.</body></html>\n"); out.close(); } } catch (IOException x) { System.out.println(x); } finally { File aborrar = new File(nombreFichero); org.apache.commons.io.FileUtils.deleteQuietly(aborrar); } }
From source file:org.bigtextml.topics.ParallelTopicModel.java
public void printState(PrintStream out) { out.println("#doc source pos typeindex type topic"); out.print("#alpha : "); for (int topic = 0; topic < numTopics; topic++) { out.print(alpha[topic] + " "); }// ww w .java 2 s.c om out.println(); out.println("#beta : " + beta); for (int doc = 0; doc < data.size(); doc++) { BigFeatureSequence tokenSequence = (BigFeatureSequence) ((TopicAssignment) (data.get(doc))).instance .getData(); BigLabelSequence topicSequence = ((TopicAssignment) (data.get(doc))).topicSequence; String source = "NA"; if (((TopicAssignment) data.get(doc)).instance.getSource() != null) { source = ((TopicAssignment) data.get(doc)).instance.getSource().toString(); } Formatter output = new Formatter(new StringBuilder(), Locale.US); for (int pi = 0; pi < topicSequence.getLength(); pi++) { int type = tokenSequence.getIndexAtPosition(pi); int topic = topicSequence.getIndexAtPosition(pi); output.format("%d %s %d %d %s %d\n", doc, source, pi, type, alphabet.lookupObject(type), topic); /* out.print(doc); out.print(' '); out.print(source); out.print(' '); out.print(pi); out.print(' '); out.print(type); out.print(' '); out.print(alphabet.lookupObject(type)); out.print(' '); out.print(topic); out.println(); */ } out.print(output); } }
From source file:edu.stanford.muse.index.Indexer.java
/** prints super doc index, debug only */ public void printIndex(PrintStream out) { for (Map.Entry<Document, List<Posting>> entry : superdocToPostingsIndex.entrySet()) { Document doc = entry.getKey(); List<Posting> list = entry.getValue(); out.print("Document " + doc.description + ": "); for (Posting p : list) out.print(p.term + "(" + 1000.0f * p.tf * p.idf + ") "); out.println();//from w ww . j ava2 s . co m } }
From source file:es.cnio.bioinfo.bicycle.gatk.MethylationFilePair.java
private void printSummary(GlobalMethylationStatistics stats, String cutoffDetails) throws FileNotFoundException { PrintStream summary = new PrintStream(new FileOutputStream(getSummaryFile())); summary.println("====METHYLATION RESULTS======================================================="); summary.println("File: " + getSummaryFile().getName()); summary.println("Date: " + new Date()); summary.println();/*from w w w. j a va2 s . c om*/ summary.println("====ANALYSIS PARAMETERS======================================================="); summary.println(" Correct non-CG: " + this.correctNonCG); summary.println(" Filters:" + (listerFilter == null ? "\n" : "\n " + listerFilter.toString().replace(",", "\n" + " "))); summary.println(" remove clonal reads: " + this.removeClonal); summary.println(" FDR threshold: " + this.FDR); summary.println(); summary.println("====ERROR ESTIMATION AND SIGNIFICANCE ADJUSTMENTS============================="); //error rates summary.print(" Error rates ("); if (!this.errorRate.equals("")) { summary.println("fixed):"); } else if (!this.controlGenome.equals("")) { summary.println("from control genome: " + this.controlGenome + "):"); } summary.println(" " + this.error.toString().replaceAll("\n", "\n ")); summary.println(" p-value cutoffs: " + this.cutOffs); summary.println(); summary.println("====METHYLATION ANALYSIS RESULTS=============================================="); //statistics summary.println(stats); //cut-off details summary.println("Cut-off computation details:\n" + cutoffDetails); }