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

The following are Jave code examples for showing how to use flush() of the java.io.PrintWriter class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Backend   File: StatsHandler.java   View Source Code Vote up 6 votes
public void handle(String s, Request request, HttpServletRequest httpServletRequest,
    HttpServletResponse response) throws IOException, ServletException {
  /*
  * Writing the response, for the stats request over netty
  */
  System.out.println("New Statrequest!");
  response.setContentType("application/json; charset=UTF-8");
  PrintWriter printout = response.getWriter();
  JSONObject JObject = new JSONObject();
  JObject.put("down", "1000");
  JObject.put("up", "300");

  printout.print(JObject);
  printout.flush();

}
 
Example 2
Project: openjdk-jdk10   File: DocLint.java   View Source Code Vote up 6 votes
/**
 * Simple API entry point.
 * @param args Options and operands for doclint
 * @throws BadArgs if an error is detected in any args
 * @throws IOException if there are problems with any of the file arguments
 */
public void run(String... args) throws BadArgs, IOException {
    PrintWriter out = new PrintWriter(System.out);
    try {
        run(out, args);
    } finally {
        out.flush();
    }
}
 
Example 3
Project: openjdk-jdk10   File: Messager.java   View Source Code Vote up 6 votes
/**
 * Print a message.
 * Part of DocErrorReporter.
 *
 * @param pos the position where the error occurs
 * @param msg message to print
 */
public void printNotice(SourcePosition pos, String msg) {
    if (diagListener != null) {
        report(DiagnosticType.NOTE, pos, msg);
        return;
    }

    PrintWriter noticeWriter = getWriter(WriterKind.NOTICE);
    if (pos == null)
        noticeWriter.println(msg);
    else
        noticeWriter.println(pos + ": " + msg);
    noticeWriter.flush();
}
 
Example 4
Project: neo-java-web-gradle-plugin   File: InstallSdkTest.java   View Source Code Vote up 6 votes
private void setUpNegativeCustomLocation() throws Exception {
	File buildFile = testProjectDir.newFile("build.gradle");
	PrintWriter printWriter = new PrintWriter(buildFile);
	printWriter.println("plugins { id 'com.tts.scp-neo-plugin' version '0.0.2' } ");
	printWriter.println("scpSettings { sdkVersion = '3.39.10' ");
	printWriter.println("sdkLocation = '' }");
	printWriter.println("repositories { mavenCentral()	}");
	printWriter.flush();
	printWriter.close();
}
 
Example 5
Project: monarch   File: GemFireVersion.java   View Source Code Vote up 6 votes
public static String asString() {
  StringWriter sw = new StringWriter(256);
  PrintWriter pw = new PrintWriter(sw);
  print(pw);
  pw.flush();
  return sw.toString();
}
 
Example 6
Project: WeiMusicCommunity-server   File: WebController.java   View Source Code Vote up 6 votes
@RequestMapping("/webloginAJ")
public void countGoodsNumByCategoryId(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("text/piain;charset=Utf-8");
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);


    HttpJson json = new HttpJson();
    json.setStatusCode(400);
    json.setMessage("testMessage");
    json.constractJsonString();

    try {
        PrintWriter out = response.getWriter();
        String jsonpCallback = request.getParameter("jsonpCallback");// 客户端请求
        JSONObject object = new JSONObject();
        List<Login> send = new ArrayList<>();
        for (Integer i = 0; i < 3; i++) {
            Login thisl = new Login();
            thisl.setUAName(i.toString() + "啦啦啦啦");
            send.add(thisl);
        }
        object.put("list", send);
        out.println(jsonpCallback + "(" + object.toString() + ")");// 返回jsonp格式数据
        out.flush();
        out.close();
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }
}
 
Example 7
Project: incubator-netbeans   File: StandardLogger.java   View Source Code Vote up 6 votes
private static void deliverStackTrace(Throwable t, AntEvent originalEvent) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    t.printStackTrace(pw);
    pw.flush();
    deliverBlockOfTextAsLines(sw.toString(), originalEvent, AntEvent.LOG_ERR);
}
 
Example 8
Project: OftenPorter   File: WServletResponse.java   View Source Code Vote up 6 votes
@Override
public void doClose(Object writeObject) throws IOException
{
    setContentType(writeObject);
    PrintWriter printWriter = response.getWriter();
    printWriter.print(writeObject);
    printWriter.flush();
    printWriter.close();
}
 
Example 9
Project: jaer   File: LoggingWindow.java   View Source Code Vote up 6 votes
public void addVersionInfo() {
    Properties props = new Properties();
    // when running from webstart  we are not allowed to open a file on the local file system, but we can
    // get a the contents of a resource, which in this case is the echo'ed date stamp written by ant on the last build
    ClassLoader cl = this.getClass().getClassLoader(); // get this class'es class loader
    addLogInfo("\nLoading version info from resource " + AEViewerAboutDialog.VERSION_FILE);
    URL versionURL = cl.getResource(AEViewerAboutDialog.VERSION_FILE); // get a URL to the time stamp file
    addLogInfo("\nVersion URL=" + versionURL + "\n");

    if (versionURL != null) {
        try {
            Object urlContents = versionURL.getContent();
            BufferedReader in = null;
            if (urlContents instanceof InputStream) {
                props.load((InputStream) urlContents);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream(2048);
        PrintWriter ps = new PrintWriter(baos);
        props.list(ps);
        ps.flush();
        try {
            addLogInfo("\n" + baos.toString("UTF-8"));
        } catch (UnsupportedEncodingException ex) {
            System.err.println("cannot encode version information in LoggingWindow.addVersionInfo: " + ex.toString());
        }
    } else {
        props.setProperty("version", "missing file " + AEViewerAboutDialog.VERSION_FILE + " in jAER.jar");
    }

}
 
Example 10
Project: hadoop   File: FSNamesystem.java   View Source Code Vote up 6 votes
/**
 * Dump all metadata into specified file
 */
void metaSave(String filename) throws IOException {
  checkSuperuserPrivilege();
  checkOperation(OperationCategory.UNCHECKED);
  writeLock();
  try {
    checkOperation(OperationCategory.UNCHECKED);
    File file = new File(System.getProperty("hadoop.log.dir"), filename);
    PrintWriter out = new PrintWriter(new BufferedWriter(
        new OutputStreamWriter(new FileOutputStream(file), Charsets.UTF_8)));
    metaSave(out);
    out.flush();
    out.close();
  } finally {
    writeUnlock();
  }
}
 
Example 11
Project: openjdk-jdk10   File: T6345974.java   View Source Code Vote up 6 votes
public static void main(String[] args) throws Exception {
    PrintWriter out = new PrintWriter(System.out, true);
    JavacTool tool = JavacTool.create();
    try (StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null)) {
        File testSrc = new File(System.getProperty("test.src"));
        Iterable<? extends JavaFileObject> f =
            fm.getJavaFileObjectsFromFiles(Arrays.asList(new File(testSrc, "T6345974.java")));
        JavacTask task = tool.getTask(out, fm, null, null, null, f);
        Iterable<? extends CompilationUnitTree> trees = task.parse();
        out.flush();

        Scanner s = new Scanner();
        for (CompilationUnitTree t: trees)
            s.scan(t, null);
    }
}
 
Example 12
Project: uavstack   File: Logger.java   View Source Code Vote up 6 votes
private String exception2String(Throwable e) {

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        e.printStackTrace(pw);
        pw.flush();
        sw.flush();

        return sw.toString();
    }
 
Example 13
Project: spanner-jdbc   File: Logger.java   View Source Code Vote up 6 votes
public void log(String str, Throwable t)
{
	PrintWriter writer = DriverManager.getLogWriter();
	if (writer == null)
	{
		return;
	}

	synchronized (this)
	{
		buffer.setLength(0);
		dateFormat.format(new Date(), buffer, dummyPosition);
		buffer.append(connectionIDString);
		buffer.append(str);

		// synchronize to ensure that the exception (if any) does
		// not get split up from the corresponding log message
		synchronized (writer)
		{
			writer.println(buffer.toString());
			if (t != null)
			{
				t.printStackTrace(writer);
			}
		}
		writer.flush();
	}
}
 
Example 14
Project: OpenJSharp   File: Global.java   View Source Code Vote up 6 votes
private Object printImpl(final boolean newLine, final Object... objects) {
    @SuppressWarnings("resource")
    final PrintWriter out = scontext != null? new PrintWriter(scontext.getWriter()) : getContext().getEnv().getOut();
    final StringBuilder sb = new StringBuilder();

    for (final Object obj : objects) {
        if (sb.length() != 0) {
            sb.append(' ');
        }

        sb.append(JSType.toString(obj));
    }

    // Print all at once to ensure thread friendly result.
    if (newLine) {
        out.println(sb.toString());
    } else {
        out.print(sb.toString());
    }

    out.flush();

    return UNDEFINED;
}
 
Example 15
Project: xproject   File: GlobalFormAuthenticationFilter.java   View Source Code Vote up 6 votes
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
	HttpServletRequest req = (HttpServletRequest) request;
	HttpServletResponse res = (HttpServletResponse) response;
	if(isAsynRequest(req, res)){
		WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
		Result<Object> result = new Result<Object>();
		result.setCode("401");
		result.setSuccess(false);
		result.setMessage(Messages.getMessage(getDefaultNoPermissionMessageI18nCode(), null, getDefaultNoPermissionMessage()));
		res.setCharacterEncoding("UTF-8");
		res.setContentType("application/json;charset=UTF-8");
		PrintWriter out = res.getWriter();
		out.println(JsonUtils.object2Json(result));
		out.flush();
		out.close();
		return false;
	}else{
		return super.onAccessDenied(request, response);
	}
}
 
Example 16
Project: hadoop   File: CLI.java   View Source Code Vote up 6 votes
@Private
public void displayJobList(JobStatus[] jobs, PrintWriter writer) {
  writer.println("Total jobs:" + jobs.length);
  writer.printf(headerPattern, "JobId", "State", "StartTime", "UserName",
    "Queue", "Priority", "UsedContainers",
    "RsvdContainers", "UsedMem", "RsvdMem", "NeededMem", "AM info");
  for (JobStatus job : jobs) {
    int numUsedSlots = job.getNumUsedSlots();
    int numReservedSlots = job.getNumReservedSlots();
    int usedMem = job.getUsedMem();
    int rsvdMem = job.getReservedMem();
    int neededMem = job.getNeededMem();
    writer.printf(dataPattern,
        job.getJobID().toString(), job.getState(), job.getStartTime(),
        job.getUsername(), job.getQueue(), 
        job.getPriority().name(),
        numUsedSlots < 0 ? UNAVAILABLE : numUsedSlots,
        numReservedSlots < 0 ? UNAVAILABLE : numReservedSlots,
        usedMem < 0 ? UNAVAILABLE : String.format(memPattern, usedMem),
        rsvdMem < 0 ? UNAVAILABLE : String.format(memPattern, rsvdMem),
        neededMem < 0 ? UNAVAILABLE : String.format(memPattern, neededMem),
        job.getSchedulingInfo());
  }
  writer.flush();
}
 
Example 17
Project: n4js   File: NpmLogger.java   View Source Code Vote up 6 votes
/** Dispatches given message with {@link Logger#info} and to the {@code STD_OUT} of used output stream. */
public void logInfo(final String message) {
	LOGGER.info(message);
	// Print writer is intentionally not released, its just a wrapper to log a message.
	final PrintWriter pw = new PrintWriter(osProvider.getOutputStream(STD_OUT, OutputRedirection.REDIRECT));
	pw.append(getTimestamp() + message + lineSeparator());
	pw.flush();
}
 
Example 18
Project: hadoop   File: TestHamlet.java   View Source Code Vote up 5 votes
@Test public void testSubViews() {
  Hamlet h = newHamlet().
      title("test sub-views").
      div("#view1")._(TestView1.class)._().
      div("#view2")._(TestView2.class)._();

  PrintWriter out = h.getWriter();
  out.flush();
  assertEquals(0, h.nestLevel);
  verify(out).print("["+ TestView1.class.getName() +"]");
  verify(out).print("["+ TestView2.class.getName() +"]");
}
 
Example 19
Project: springsecuritystudy   File: RestAuthenticationFailureHandler.java   View Source Code Vote up 5 votes
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException exception) throws IOException, ServletException {
    LOGGER.info("auth failure!");
    JSONResponse jsonResponse = new JSONResponse();
    jsonResponse.addError(DefaultException.Error.invalid_parameter.name(), exception.getMessage());
    response.addHeader("Content-type", "application/json; charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    PrintWriter printWriter = response.getWriter();
    printWriter.write(jsonResponse.toString());
    printWriter.flush();
    printWriter.close();
}
 
Example 20
Project: openjdk-jdk10   File: PropMap.java   View Source Code Vote up 5 votes
void list(PrintStream out) {
    PrintWriter outw = new PrintWriter(out);
    list(outw);
    outw.flush();
}