Java Code Examples for java.io.PrintWriter#flush()

The following examples show how to use java.io.PrintWriter#flush() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MailData.java    From openbd-core with GNU General Public License v3.0 6 votes vote down vote up
private void spoolToDisk() throws IOException{
  fileSpool = mail25.getSpoolFile();

  //- Create the output
  fileWriter  = new FileWriter(fileSpool);
  printWriter = new PrintWriter( new BufferedWriter( fileWriter ) );

  //- Page out to disk what we already have collected
  String out = new String( byteArray.toByteArray() );
  printWriter.print( out );
  printWriter.flush();
  
  //-- Reset the internal buffer, and set it to null to let it be garbage collected
  byteArray.reset();
  byteArray = null;
}
 
Example 2
Source File: RETest.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Fail with an error. Will print a big failure message to System.out.
 *
 * @param s Failure description
 */
void fail(String s)
{
    failures++;
    say("" + NEW_LINE + "");
    say("*******************************************************");
    say("*********************  FAILURE!  **********************");
    say("*******************************************************");
    say("" + NEW_LINE + "");
    say(s);
    say("");
    // make sure the writer gets flushed.
    if (compiler != null) {
        PrintWriter writer = new PrintWriter( System.out );
        compiler.dumpProgram( writer );
        writer.flush();
        say("" + NEW_LINE + "");
    }
}
 
Example 3
Source File: PrintReporter.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public final void run() {
    synchronized (this) {
        for (ResourceAggregator r : resources.keySet()) {
            if (r.enabled()) {
                PrintWriter writer = resources.get(r);
                try {
                    ResourceReport report = r.getReport();
                    if (report != null) {
                        String prefix = String.format("%d\t%d\t%s\t%s\t%s\t%d\t%s", report.getStart(), report.getEnd(), report.getResource().toString(),
                                report.getResourceID(), report.getMachine(), report.getProcessID(), report.getProcessName());
                        for (TenantOperationReport tr : report.getTenantReportList()) {
                            writer.printf("%s\t%s\t%d\t%d\t%d\t%d\n", prefix, tr.getOperation().toString(), tr.getTenantClass(), tr.getNumFinished(),
                                    tr.getTotalLatency(), tr.getTotalWork());
                        }
                        writer.flush();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
 
Example 4
Source File: AssertableDiagnostics.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected void printDiagnostic(StringBuffer out, String prefix, Diagnostic d) {
	final String indent = "  ";
	out.append(prefix);
	out.append(d);
	if (d.getChildren().size() > 0 || d.getException() != null) {
		out.append(" {\n");
		String prefix2 = prefix + indent;
		if (d.getException() != null) {
			out.append(prefix2);
			ByteArrayOutputStream s = new ByteArrayOutputStream();
			PrintWriter pw = new PrintWriter(s);
			d.getException().printStackTrace(pw);
			pw.flush();
			out.append(s.toString());
			out.append("\n");
		}
		for (Diagnostic c : d.getChildren())
			printDiagnostic(out, prefix2, c);
		out.append(prefix);
		out.append("}\n");
	} else
		out.append("\n");
}
 
Example 5
Source File: RelOptUtil.java    From Quicksql with MIT License 5 votes vote down vote up
/**
 * Dumps a plan as a string.
 *
 * @param header Header to print before the plan. Ignored if the format is XML
 * @param rel Relational expression to explain
 * @param format Output format
 * @param detailLevel Detail level
 * @return Plan
 */
public static String dumpPlan(
    String header,
    RelNode rel,
    SqlExplainFormat format,
    SqlExplainLevel detailLevel) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    if (!header.equals("")) {
        pw.println(header);
    }
    RelWriter planWriter;
    switch (format) {
        case XML:
            planWriter = new RelXmlWriter(pw, detailLevel);
            break;
        case JSON:
            planWriter = new RelJsonWriter();
            rel.explain(planWriter);
            return ((RelJsonWriter) planWriter).asString();
        default:
            planWriter = new RelWriterImpl(pw, detailLevel, false);
    }
    rel.explain(planWriter);
    pw.flush();
    return sw.toString();
}
 
Example 6
Source File: RapidShareUploaderPlugin.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
public static void writeHttpContent(String content) {

        try {

            System.out.println(content);
            pw = new PrintWriter(new OutputStreamWriter(uc.getOutputStream()), true);
            pw.print(content);
            pw.flush();
            pw.close();
            br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
            String httpResp = br.readLine();
            Map<String, List<String>> headerFields = uc.getHeaderFields();
            if (headerFields.containsKey("Set-Cookie")) {
                List<String> header = headerFields.get("Set-Cookie");
                for (int i = 0; i < header.size(); i++) {
                    String tmp = header.get(i);
                    if (tmp.contains("skey")) {
                        skeycookie = tmp;
                    }
                    if (tmp.contains("user")) {
                        usercookie = tmp;
                    }
                }
            } else {
                System.out.println("shit");
            }
            System.out.println();
            skeycookie = skeycookie.substring(0, skeycookie.indexOf(";"));
            System.out.println(skeycookie);
            if (!usercookie.contains("user")) {
                login = false;
            } else {
                login = true;
                usercookie = usercookie.substring(0, usercookie.indexOf(";"));
                System.out.println(usercookie);
            }
        } catch (Exception e) {
            //System.out.println("ex " + e.toString());
        }
    }
 
Example 7
Source File: Service.java    From MeiAutoRead with MIT License 5 votes vote down vote up
public void run() {
    try {
        /** 获取客户端传来的信息 */
        // 由Socket对象得到输入流,并构造相应的BufferedReader对象
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        System.out.println("由Socket对象得到输入流,并构造相应的BufferedReader对象");
        String line = bufferedReader.readLine();
        /** 发送服务端准备传输的 */
        // 由Socket对象得到输出流,并构造PrintWriter对象
        PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
        System.out.println("由Socket对象得到输出流,并构造PrintWriter对象");
        // 获取从客户端读入的字符串
        System.out.println("while循环:获取从客户端读入的字符串");
        System.out.println("while循环:客户端返回 : " + line);
        String repeat = mServiceGetText.getText(line);
        System.out.println("while循环:服务器将返回:" + repeat);
        //printWriter.print("hello Client, I am Server!");
        printWriter.print(repeat);
        System.out.println("while循环:准备刷新返回");
        printWriter.flush();
        System.out.println("while循环:已刷新返回");
        System.out.println("关闭Socket");
        /** 关闭Socket*/
        printWriter.close();
        bufferedReader.close();
        socket.close();
    } catch (IOException e) {
        System.out.println("socket 连接线程发生错误:" + e.toString());
    }
}
 
Example 8
Source File: Group.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void writeAll(final PrintWriter pw) {
    root.traverse(new Visitor() {
        public void visit(Node node) {
            node.write(pw);
        }
    });
    pw.flush();
}
 
Example 9
Source File: ChunkedServlet.java    From android-http-server with GNU General Public License v3.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException {
    response.getHeaders().setHeader(HEADER_TRANSFER_ENCODING, "chunked");
    PrintWriter printWriter = response.getWriter();
    printWriter.print("This is an example of chunked transfer type. ");
    printWriter.flush();
    printWriter.print("Chunked transfer type can be used when the final length of the data is not known.");
}
 
Example 10
Source File: MaxWarns.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
String javadoc(File f) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    String[] args = { "-Xdoclint:none", "-d", "api", f.getPath() };
    int rc = com.sun.tools.javadoc.Main.execute("javadoc", pw, pw, pw,
            com.sun.tools.doclets.standard.Standard.class.getName(), args);
    pw.flush();
    return sw.toString();
}
 
Example 11
Source File: TestHamlet.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Test public void testHamlet() {
  Hamlet h = newHamlet().
      title("test").
      h1("heading 1").
      p("#id.class").
        b("hello").
        em("world!")._().
      div("#footer").
        _("Brought to you by").
        a("http://hostname/", "Somebody")._();

  PrintWriter out = h.getWriter();
  out.flush();
  assertEquals(0, h.nestLevel);
  verify(out).print("<title");
  verify(out).print("test");
  verify(out).print("</title>");
  verify(out).print("<h1");
  verify(out).print("heading 1");
  verify(out).print("</h1>");
  verify(out).print("<p");
  verify(out).print(" id=\"id\"");
  verify(out).print(" class=\"class\"");
  verify(out).print("<b");
  verify(out).print("hello");
  verify(out).print("</b>");
  verify(out).print("<em");
  verify(out).print("world!");
  verify(out).print("</em>");
  verify(out).print("<div");
  verify(out).print(" id=\"footer\"");
  verify(out).print("Brought to you by");
  verify(out).print("<a");
  verify(out).print(" href=\"http://hostname/\"");
  verify(out).print("Somebody");
  verify(out).print("</a>");
  verify(out).print("</div>");
  verify(out, never()).print("</p>");
}
 
Example 12
Source File: WP2RDFXMLWriter.java    From GeoTriples with Apache License 2.0 5 votes vote down vote up
@Override
protected void writeBody(Model model, PrintWriter pw, String base,
		boolean inclXMLBase) {
	setSpaceFromTabCount();
	writeRDFHeader(model, pw);
	writeRDFStatements(model, pw);
	writeRDFTrailer(pw, base);
	pw.flush();
}
 
Example 13
Source File: FailOverExecutionControlProvider.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create and return a locally executing {@code ExecutionControl} instance.
 * At least one parameter should have a spec.
 *
 * @param env the execution environment, provided by JShell
 * @param parameters the modified parameter map.
 * @return the execution engine
 * @throws Throwable if all the given providers fail, the exception that
 * occurred on the first attempt to create the execution engine.
 */
@Override
public ExecutionControl generate(ExecutionEnv env, Map<String, String> parameters)
        throws Throwable {
    Throwable thrown = null;
    for (int i = 0; i <= 9; ++i) {
        String param = parameters.get("" + i);
        if (param != null && !param.isEmpty()) {
            try {
                ExecutionControl ec =  ExecutionControl.generate(env, param);
                logger().finest(
                        String.format("FailOverExecutionControlProvider: Success %s -- %d = %s\n",
                                name(), i, param));
                return ec;
            } catch (Throwable ex) {
                logger().warning(
                        String.format("FailOverExecutionControlProvider: Failure %s -- %d = %s -- %s\n",
                                name(), i, param, ex.toString()));
                StringWriter writer = new StringWriter();
                PrintWriter log = new PrintWriter(writer);
                log.println("FailOverExecutionControlProvider:");
                ex.printStackTrace(log);
                log.flush();
                logger().fine(writer.toString());
                // only care about the first, and only if they all fail
                if (thrown == null) {
                    thrown = ex;
                }
            }
        }

    }
    logger().severe("FailOverExecutionControlProvider: Terminating, failovers exhausted");
    if (thrown == null) {
        throw new IllegalArgumentException("All least one parameter must be set to a provider.");
    }
    throw thrown;
}
 
Example 14
Source File: SVMLightSaver.java    From tsml with GNU General Public License v3.0 5 votes vote down vote up
/**
  * Writes a Batch of instances.
  * 
  * @throws IOException 	throws IOException if saving in batch mode 
  * 				is not possible
  */
 public void writeBatch() throws IOException {
   if (getInstances() == null)
     throw new IOException("No instances to save");
   
   if (getRetrieval() == INCREMENTAL)
     throw new IOException("Batch and incremental saving cannot be mixed.");
   
   setRetrieval(BATCH);
   setWriteMode(WRITE);

   if ((retrieveFile() == null) && (getWriter() == null)) {
     for (int i = 0; i < getInstances().numInstances(); i++)
System.out.println(instanceToSvmlight(getInstances().instance(i)));
     setWriteMode(WAIT);
   }
   else {
     PrintWriter outW = new PrintWriter(getWriter());
     for (int i = 0; i < getInstances().numInstances(); i++)
outW.println(instanceToSvmlight(getInstances().instance(i)));
     outW.flush();
     outW.close();
     setWriteMode(WAIT);
     outW = null;
     resetWriter();
     setWriteMode(CANCEL);
   }
 }
 
Example 15
Source File: IndexFileWriter.java    From annotation-tools with MIT License 5 votes vote down vote up
private IndexFileWriter(AScene scene,
        Writer out) throws DefException {
    this.scene = scene;
    pw = new PrintWriter(out);
    write();
    pw.flush();
}
 
Example 16
Source File: MathException.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Prints the stack trace of this exception to the specified stream.
 *
 * @param out  the <code>PrintStream</code> to use for output
 */
@Override
public void printStackTrace(PrintStream out) {
    synchronized (out) {
        PrintWriter pw = new PrintWriter(out, false);
        printStackTrace(pw);
        // Flush the PrintWriter before it's GC'ed.
        pw.flush();
    }
}
 
Example 17
Source File: OptimisticTypesPersistence.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * A helper that prints an exception stack trace into a string. We have to do this as if we just pass the exception
 * to {@link DebugLogger#warning(Object...)}, it will only log the exception message and not the stack, making
 * problems harder to diagnose.
 * @param e the exception
 * @return the string representation of {@link Exception#printStackTrace()} output.
 */
private static String exceptionToString(final Exception e) {
    final StringWriter sw = new StringWriter();
    final PrintWriter pw = new PrintWriter(sw, false);
    e.printStackTrace(pw);
    pw.flush();
    return sw.toString();
}
 
Example 18
Source File: InternalRunnable.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String toString() {
    final StringWriter sw = new StringWriter();
    final PrintWriter pw = new PrintWriter(sw);
    if(runExecuted) {
        pw.println("InternalRunnable.run() executed!");
    }
    pw.println("InternalRunnable.toString() executed!");
    pw.flush();
    return sw.toString();
}
 
Example 19
Source File: ControllerAuthorityCheckInterceptor.java    From bamboobsc with Apache License 2.0 4 votes vote down vote up
@Override
public String intercept(ActionInvocation actionInvocation) throws Exception {
	String actionName = actionInvocation.getProxy().getActionName();
	String url = actionName + Constants._S2_ACTION_EXTENSION;		
	Subject subject = SecurityUtils.getSubject();
	/*
	if ( !Constants.getSystem().equals(Constants.getMainSystem()) ) {
		SecurityUtils.setSecurityManager( (DefaultSecurityManager)AppContext.getBean("securityManager") );
		subject = SecurityUtils.getSubject();			
	}
	*/
	if (subject.hasRole(Constants.SUPER_ROLE_ALL) || subject.hasRole(Constants.SUPER_ROLE_ADMIN)) {
		SysEventLogSupport.log( (String)subject.getPrincipal(), Constants.getSystem(), url, true );
		return actionInvocation.invoke();
	}		
	Annotation[] annotations = actionInvocation.getAction().getClass().getAnnotations();
	Annotation[] actionMethodAnnotations = null;
	Method[] methods = actionInvocation.getAction().getClass().getMethods();
	for (Method method : methods) {
		if (actionInvocation.getProxy().getMethod().equals(method.getName())) {
			actionMethodAnnotations = method.getAnnotations();
		}
	}		
	if (this.isControllerAuthority(annotations, actionMethodAnnotations, subject)) {
		SysEventLogSupport.log( (String)subject.getPrincipal(), Constants.getSystem(), url, true );
		return actionInvocation.invoke();
	}		
	if (subject.isPermitted(url) || subject.isPermitted("/"+url)) {
		SysEventLogSupport.log( (String)subject.getPrincipal(), Constants.getSystem(), url, true );
		return actionInvocation.invoke();
	}
	logger.warn("[decline] user=" + subject.getPrincipal() + " url=" + url);
	String isDojoxContentPane = ServletActionContext.getRequest().getParameter(Constants.IS_DOJOX_CONTENT_PANE_XHR_LOAD);
	if (YesNo.YES.equals(isDojoxContentPane)) { // dojox.layout.ContentPane 它的 X-Requested-With 是 XMLHttpRequest
		SysEventLogSupport.log( (String)subject.getPrincipal(), Constants.getSystem(), url, false );
		return Constants._S2_RESULT_NO_AUTHORITH;
	}
	String header = ServletActionContext.getRequest().getHeader("X-Requested-With");
	if ("XMLHttpRequest".equalsIgnoreCase(header)) {
		PrintWriter printWriter = ServletActionContext.getResponse().getWriter();
		printWriter.print(Constants.NO_AUTHZ_JSON_DATA);
           printWriter.flush();
           printWriter.close();
           SysEventLogSupport.log( (String)subject.getPrincipal(), Constants.getSystem(), url, false );
		return null;
	}
	SysEventLogSupport.log( (String)subject.getPrincipal(), Constants.getSystem(), url, false );
	return Constants._S2_RESULT_NO_AUTHORITH;
}
 
Example 20
Source File: DefaultTajoCliOutputFormatter.java    From tajo with Apache License 2.0 4 votes vote down vote up
@Override
public void printResult(PrintWriter sout, InputStream sin, TableDesc tableDesc,
                        float responseTime, ResultSet res) throws Exception {
  long resultRows = tableDesc.getStats() == null ? -1 : tableDesc.getStats().getNumRows();
  if (resultRows == -1) {
    resultRows = Integer.MAX_VALUE;
  }

  if (res == null) {
    sout.println(getQuerySuccessMessage(tableDesc, responseTime, 0, "inserted", true));
    return;
  }
  ResultSetMetaData rsmd = res.getMetaData();
  int numOfColumns = rsmd.getColumnCount();
  for (int i = 1; i <= numOfColumns; i++) {
    if (i > 1) sout.print(",  ");
    String columnName = rsmd.getColumnName(i);
    sout.print(columnName);
  }
  sout.println("\n-------------------------------");

  int numOfPrintedRows = 0;
  int totalPrintedRows = 0;
  boolean endOfTuple = true;
  while (res.next()) {
    for (int i = 1; i <= numOfColumns; i++) {
      if (i > 1) sout.print(",  ");
      String columnValue = res.getString(i);
      if(res.wasNull()){
        sout.print(nullChar);
      } else {
        sout.print(columnValue);
      }
    }
    sout.println();
    sout.flush();
    numOfPrintedRows++;
    totalPrintedRows++;
    if (printPause && printPauseRecords > 0 && totalPrintedRows < resultRows && numOfPrintedRows >= printPauseRecords) {
      if (resultRows < Integer.MAX_VALUE) {
        sout.print("(" + totalPrintedRows + "/" + resultRows + " rows, continue... 'q' is quit)");
      } else {
        sout.print("(" + totalPrintedRows + " rows, continue... 'q' is quit)");
      }
      sout.flush();
      if (sin != null) {
        if (sin.read() == QUIT_COMMAND) {
          endOfTuple = false;
          sout.println();
          break;
        }
      }
      numOfPrintedRows = 0;
      sout.println();
    }
  }
  sout.println(getQuerySuccessMessage(tableDesc, responseTime, totalPrintedRows, "selected", endOfTuple));
  sout.flush();
}