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

The following examples show how to use java.io.PrintWriter#append() . These examples are extracted from open source projects. 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 Project: BlogManagePlatform   File: ServletUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 向response直接写入json,编码为UTF-8
 * @author Frodez
 * @throws IOException
 * @date 2019-01-07
 */
@SneakyThrows
public static void writeJson(HttpServletResponse response, String json, @Nullable HttpStatus status) {
	Assert.notNull(json, "json must not be null");
	if (response.isCommitted()) {
		log.warn("this response has been committed!");
		return;
	}
	if (status != null) {
		response.setStatus(status.value());
	}
	response.setCharacterEncoding(DefCharset.UTF_8);
	response.setContentType(MediaType.APPLICATION_JSON_VALUE);
	@Cleanup PrintWriter out = response.getWriter();
	out.append(json);
	out.flush();
}
 
Example 2
Source Project: android-tv-launcher   File: LogUtil.java    License: MIT License 6 votes vote down vote up
/**
 * 打印异常
 * @param exp
 */
public static synchronized void writeLog(Exception exp) {
    File f = getFile();
    if (f != null) {
        try {
            FileWriter fw = new FileWriter(f , true);
            PrintWriter pw = new PrintWriter(fw);
            pw.append("\n");
            exp.printStackTrace(pw);
            pw.flush();
            pw.close();
            fw.close();
        } catch (IOException e) {
            print("writeLog error, " + e.getMessage());
        }
    } else {
        print("writeLog error, due to the file dir is error");
    }
}
 
Example 3
@Override
public void printStackTrace(PrintWriter pw) {
    pw.print("<exception>");
    if (getResult() != null) {
        pw.print(result.toString());
    }
    pw.append("<exceptionTrace>");

    Throwable cause = getCause();
    if (cause == null) {
        super.printStackTrace(pw);
    } else {
        pw.println(this);
        pw.print("Caused by: ");
        cause.printStackTrace(pw);
    }
    pw.append("</exceptionTrace>");
    pw.println("</exception>");
}
 
Example 4
Source Project: jeesuite-config   File: WebUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static  void responseOutWithJson(HttpServletResponse response,String json) {  
    //将实体对象转换为JSON Object转换  
    response.setCharacterEncoding("UTF-8");  
    response.setContentType("application/json; charset=utf-8");  
    PrintWriter out = null;  
    try {  
        out = response.getWriter();  
        out.append(json);  
    } catch (IOException e) {  
        e.printStackTrace();  
    } finally {  
        if (out != null) {  
            out.close();  
        }  
    }  
}
 
Example 5
Source Project: Tutorials   File: ServletPOST.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException {
	String user = request.getParameter("user");
	
	response.setContentType("text/html");
	response.setCharacterEncoding("UTF-8");
	
	// create HTML response
	PrintWriter writer = response.getWriter();
	writer.append("<!DOCTYPE html>\r\n")
		  .append("<html>\r\n")
		  .append("		<head>\r\n")
		  .append("			<title>Welcome message</title>\r\n")
		  .append("		</head>\r\n")
		  .append("		<body>\r\n");
	if (user != null && !user.trim().isEmpty()) {
		writer.append("	Welcome " + user + ".\r\n");
		writer.append("	You successfully completed this javatutorial.net example.\r\n");
	} else {
		writer.append("	You did not entered a name!\r\n");
	}
	writer.append("		</body>\r\n")
		  .append("</html>\r\n");
}
 
Example 6
public String getExhaustiveDescription() {
  StringWriter errorWriter = new StringWriter();
  PrintWriter pw = new PrintWriter(errorWriter);
  for (int i = 0; i < this.exceptions.size(); ++i) {
    Throwable t = this.exceptions.get(i);
    Row action = this.actions.get(i);
    String server = this.hostnameAndPort.get(i);
    pw.append("exception");
    if (this.exceptions.size() > 1) {
      pw.append(" #" + i);
    }
    pw.append(" from " + server + " for "
      + ((action == null) ? "unknown key" : Bytes.toStringBinary(action.getRow())));
    if (t != null) {
      pw.println();
      t.printStackTrace(pw);
    }
  }
  pw.flush();
  return errorWriter.toString();
}
 
Example 7
Source Project: MicroCommunity   File: OrdersException.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void printStackTrace(PrintWriter pw) {
    pw.print("<exception>");
    if (getResult() != null) {
        pw.print(result.toString());
    }
    pw.append("<exceptionTrace>");

    Throwable cause = getCause();
    if (cause == null) {
        super.printStackTrace(pw);
    } else {
        pw.println(this);
        pw.print("Caused by: ");
        cause.printStackTrace(pw);
    }
    pw.append("</exceptionTrace>");
    pw.println("</exception>");
}
 
Example 8
Source Project: vertx-codegen   File: EnumCheatsheetGen.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String render(EnumModel model, int index, int size, Map<String, Object> session) {
  StringWriter buffer = new StringWriter();
  PrintWriter html = new PrintWriter(buffer);
  if (index == 0) {
    html.append("= Enums\n");
    html.append("\n");
  }
  render(model, html);
  html.append("\n");
  return buffer.toString();
}
 
Example 9
Source Project: j-road   File: XTeeElement.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes" })
public void marshall(Class parentType,
                     QName elementType,
                     ExtensibilityElement extension,
                     PrintWriter pw,
                     Definition def,
                     ExtensionRegistry extReg) throws WSDLException {
  pw.append("        <" + XTeeWsdlDefinition.XROAD_PREFIX + ":" + elementType.getLocalPart() + ">");
  pw.append(((XTeeElement) extension).getValue());
  pw.append("</" + XTeeWsdlDefinition.XROAD_PREFIX + ":" + elementType.getLocalPart() + ">\n");
}
 
Example 10
private void appendHdfsHome(PrintWriter fw, String hdfsHome) {
  // Unset HADOOP_HOME/HADOOP_YARN_HOME to make sure host machine's envs
  // won't pollute docker's env.
  fw.append("export HADOOP_HOME=\n");
  fw.append("export HADOOP_YARN_HOME=\n");
  fw.append("export HADOOP_HDFS_HOME=" + hdfsHome + "\n");
  fw.append("export HADOOP_COMMON_HOME=" + hdfsHome + "\n");
}
 
Example 11
public BulkImportResult executePostFileRequest(Class<?> resultClass, String filePath) throws MarketoException {
    String boundary = "Talend_tMarketoBulkExec_" + String.valueOf(System.currentTimeMillis());
    try {
        URL url = new URL(current_uri.toString());
        HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
        urlConn.setRequestMethod("POST");
        urlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        urlConn.setRequestProperty("accept", "text/json");
        urlConn.setDoOutput(true);
        String requestBody = buildRequest(filePath); // build the request body
        PrintWriter wr = new PrintWriter(new OutputStreamWriter(urlConn.getOutputStream()));
        wr.append("--" + boundary + "\r\n");
        wr.append("Content-Disposition: form-data; name=\"file\";filename=\"" + filePath + "\";\r\n");
        wr.append("Content-type: text/plain; charset=\"utf-8\"\r\n");
        wr.append("Content-Transfer-Encoding: text/plain\r\n");
        wr.append("MIME-Version: 1.0\r\n");
        wr.append("\r\n");
        wr.append(requestBody);
        wr.append("\r\n");
        wr.append("--" + boundary);
        wr.flush();
        wr.close();
        return (BulkImportResult) new Gson().fromJson(getReaderFromHttpResponse(urlConn), resultClass);
    } catch (IOException e) {
        LOG.error("POST request failed: {}", e.getMessage());
        throw new MarketoException(REST, e.getMessage());
    }
}
 
Example 12
@Override
public void dump(PrintWriter writer) {
    writer.append("\nHistoryReportJniBridge [").append("started: " + mStarted.get())
            .append(", initialized: " + isInitialized());
    if (isInitialized()) {
        writer.append(", " + nativeDump(mNativeHistoryReportJniBridge));
    }
    writer.append("]");
}
 
Example 13
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
  try {
    String classNames = req.getParameter("classes");
    PrintWriter out = resp.getWriter();
    List<Class<?>> testClasses = loadClasses(classNames.split("[\\r\\n]+"));
    String output = runTests(testClasses, req, resp);
    out.append(output);
    out.close();
  } catch (Exception e) {
    throw new ServletException(e);
  }
}
 
Example 14
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
  resp.setContentType("text");
  PrintWriter out = resp.getWriter();

  ClassLoader cl = getClass().getClassLoader();
  out.append("CLASS LOADER:\n\n");
  out.append("Name: ").append(cl != null ? cl.getClass().getName() : null).append('\n');
  if (cl instanceof URLClassLoader) {
    URLClassLoader urlCl = (URLClassLoader) cl;
    out.append("Urls: ").append('\n');
    for (URL url : urlCl.getURLs()) {
      out.append(url.toString()).append('\n');
    }
  }

  out.append("\nENVIRONMENT VARIABLES:\n\n");
  Map<String, String> envVars = System.getenv();
  for (Map.Entry<String, String> entry : envVars.entrySet()) {
    out.append(entry.getKey()).append("=").append(entry.getValue()).append('\n');
  }

  out.append("\n\nSYSTEM PROPERTIES:\n\n");
  System.getProperties().list(out);

  out.close();
}
 
Example 15
Source Project: REST-Sample-Code   File: CreateEmailTemplate.java    License: MIT License 5 votes vote down vote up
private void addMultipartData(String boundary, String requestBody,
                          PrintWriter wr, String paramName) {
    wr.append("--" + boundary + "\r\n");
    wr.append("Content-Disposition: form-data; name=\"" + paramName + "\"");
    wr.append("\r\n");
    wr.append("\r\n");
    wr.append(requestBody);
    wr.append("\r\n");
}
 
Example 16
@RequestMapping(value = "/PlayAutoMassiveGame")
public void playAutoMassiveGame(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("deck1") String deck1, @RequestParam("deck2") String deck2,
        @RequestParam("hlv1") int heroLv1, @RequestParam("hlv2") int heroLv2, @RequestParam("count") int count,
        @RequestParam("fa") int firstAttack, @RequestParam("do") int deckOrder,
        @RequestParam("p1hhpb") int p1HeroHpBuff, @RequestParam("p1catb") int p1CardAtBuff, @RequestParam("p1chpb") int p1CardHpBuff,
        @RequestParam("p2hhpb") int p2HeroHpBuff, @RequestParam("p2catb") int p2CardAtBuff, @RequestParam("p2chpb") int p2CardHpBuff,
        @RequestParam("vc1") String victoryConditionText1
) throws IOException {
    PrintWriter writer = response.getWriter();
    try {
        logger.info("PlayAutoMassiveGame from " + request.getRemoteAddr() + ":");
        String logMessage = String.format("Deck1=%s<br />Deck2=%s<br />Lv1=%d, Lv2=%d, FirstAttack=%d, DeckOrder=%d, Count=%d, VictoryCondition1=%s",
            deck1, deck2, heroLv1, heroLv2, firstAttack, deckOrder, count, victoryConditionText1);
        logger.info(logMessage);
        this.userActionRecorder.addAction(new UserAction(new Date(), request.getRemoteAddr(), "Play Auto Massive Game", logMessage));
        VictoryCondition vc1 = VictoryCondition.parse(victoryConditionText1);
        outputBattleOptions(writer, firstAttack, deckOrder, p1HeroHpBuff, p1CardAtBuff, p1CardHpBuff, p2HeroHpBuff, p2CardAtBuff, p2CardHpBuff, vc1);
        GameSetup setup = GameSetup.setupArenaGame(
                deck1, deck2, heroLv1, heroLv2,
                p1CardAtBuff, p1CardHpBuff, p1HeroHpBuff, p2CardAtBuff, p2CardHpBuff, p2HeroHpBuff,
                firstAttack, deckOrder, vc1, count, new DummyGameUI());
        ArenaGameResult result = GameLauncher.playArenaGame(setup);
        GameResultStat stat = result.getStat();
        writer.append(Utils.getCurrentDateTime() + "<br />");
        writer.append(result.getDeckValidationResult());
        writer.append("<table>");
        writer.append("<tr><td>超时: </td><td>" + stat.getTimeoutCount() + "</td></tr>");
        writer.append("<tr><td>玩家1获胜: </td><td>" + stat.getP1Win() + "</td></tr>");
        writer.append("<tr><td>玩家2获胜: </td><td>" + stat.getP2Win() + "</td></tr>");
        if (!(vc1 instanceof DummyVictoryCondition)) {
            writer.append("<tr><td>条件符合: </td><td>" + stat.getConditionMet() + "</td></tr>");
        }
        writer.append("</table>");
        writer.append("<input type='hidden' value='myrate" + stat.getP1Win() + "' />");
        logger.info("TO:P1:P2 = " + stat.getTimeoutCount() + ":" + stat.getP1Win() + ":" + stat.getP2Win());
    } catch (Exception e) {
        writer.print(errorHelper.handleError(e, false));
    }
}
 
Example 17
private void verifyClassIntegrity(ClassNode classNode) {
    // Do not COMPUTE_FRAMES. If you COMPUTE_FRAMES and you pop too many items off the stack or do other weird things that mess up the
    // stack map frames, it'll crash on classNode.accept(cw).
    ClassWriter cw = new SimpleClassWriter(ClassWriter.COMPUTE_MAXS/* | ClassWriter.COMPUTE_FRAMES*/, classRepo);
    classNode.accept(cw);
    
    byte[] classData = cw.toByteArray();

    ClassReader cr = new ClassReader(classData);
    classNode = new SimpleClassNode();
    cr.accept(classNode, 0);

    for (MethodNode methodNode : classNode.methods) {
        Analyzer<BasicValue> analyzer = new Analyzer<>(new SimpleVerifier(classRepo));
        try {
            analyzer.analyze(classNode.name, methodNode);
        } catch (AnalyzerException e) {
            // IF WE DID OUR INSTRUMENTATION RIGHT, WE SHOULD NEVER GET AN EXCEPTION HERE!!!!
            StringWriter writer = new StringWriter();
            PrintWriter printWriter = new PrintWriter(writer);
            
            printWriter.append(methodNode.name + " encountered " + e);
            
            Printer printer = new Textifier();
            TraceMethodVisitor traceMethodVisitor = new TraceMethodVisitor(printer);
            
            AbstractInsnNode insn = methodNode.instructions.getFirst();
            while (insn != null) {
                if (insn == e.node) {
                    printer.getText().add("----------------- BAD INSTRUCTION HERE -----------------\n");
                }
                insn.accept(traceMethodVisitor);
                insn = insn.getNext();
            }
            printer.print(printWriter);
            printWriter.flush(); // we need this or we'll get incomplete results
            
            throw new IllegalStateException(writer.toString(), e);
        }
    }
}
 
Example 18
/**
 * Sends given response to the socket.
 */
protected void send(OutputStream outputStream) {
    SimpleDateFormat gmtFrmt = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
    gmtFrmt.setTimeZone(TimeZone.getTimeZone("GMT"));

    try {
        if (this.status == null) {
            throw new Error("sendResponse(): Status can't be null.");
        }
        PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream, new ContentType(this.mimeType).getEncoding())), false);
        pw.append("HTTP/1.1 ").append(this.status.getDescription()).append(" \r\n");
        if (this.mimeType != null) {
            printHeader(pw, "Content-Type", this.mimeType);
        }
        if (getHeader("date") == null) {
            printHeader(pw, "Date", gmtFrmt.format(new Date()));
        }
        for (Entry<String, String> entry : this.header.entrySet()) {
            printHeader(pw, entry.getKey(), entry.getValue());
        }
        if (getHeader("connection") == null) {
            printHeader(pw, "Connection", (this.keepAlive ? "keep-alive" : "close"));
        }
        if (getHeader("content-length") != null) {
            encodeAsGzip = false;
        }
        if (encodeAsGzip) {
            printHeader(pw, "Content-Encoding", "gzip");
            setChunkedTransfer(true);
        }
        long pending = this.data != null ? this.contentLength : 0;
        if (this.requestMethod != Method.HEAD && this.chunkedTransfer) {
            printHeader(pw, "Transfer-Encoding", "chunked");
        } else if (!encodeAsGzip) {
            pending = sendContentLengthHeaderIfNotAlreadyPresent(pw, pending);
        }
        pw.append("\r\n");
        pw.flush();
        sendBodyWithCorrectTransferAndEncoding(outputStream, pending);
        outputStream.flush();
        safeClose(this.data);
    } catch (IOException ioe) {
        NanoHTTPD.LOG.log(Level.SEVERE, "Could not send response to the client", ioe);
    }
}
 
Example 19
Source Project: Smack   File: StateDescriptorGraph.java    License: Apache License 2.0 4 votes vote down vote up
public static <E> void stateDescriptorGraphToDot(Collection<GraphVertex<StateDescriptor>> vertexes,
                PrintWriter dotOut, boolean breakStateName) {
    dotOut.append("digraph {\n");
    dfs(vertexes,
            finishedVertex -> {
               boolean isMultiVisitState = finishedVertex.element.isMultiVisitState();
               boolean isFinalState = finishedVertex.element.isFinalState();
               boolean isNotImplemented = finishedVertex.element.isNotImplemented();

               String style = null;
               if (isMultiVisitState) {
                   style = "bold";
               } else if (isFinalState) {
                   style = "filled";
               } else if (isNotImplemented) {
                   style = "dashed";
               }

               if (style == null) {
                   return;
               }

               dotOut.append('"')
                   .append(finishedVertex.element.getFullStateName(breakStateName))
                   .append("\" [ ")
                   .append("style=")
                   .append(style)
                   .append(" ]\n");
           },
           (from, to, edgeId, totalEdgeCount) -> {
               dotOut.append("  \"")
                   .append(from.element.getFullStateName(breakStateName))
                   .append("\" -> \"")
                   .append(to.element.getFullStateName(breakStateName))
                   .append('"');
               if (totalEdgeCount > 1) {
                   // Note that 'dot' requires *double* quotes to enclose the value.
                   dotOut.append(" [xlabel=\"")
                   .append(Integer.toString(edgeId))
                   .append("\"]");
               }
               dotOut.append(";\n");
           });
    dotOut.append("}\n");
}
 
Example 20
@Override
public void render(RenderRequest renderRequest, RenderResponse renderResponse)
      throws PortletException, IOException {

   ModuleTestCaseDetails tcd = new ModuleTestCaseDetails();

   PrintWriter writer = renderResponse.getWriter();

   /* TestCase: V3HeaderPortletTests_SPEC15_Header_cookie8 */
   /*
    * Details: "Cookies set during the Header phase should be available to
    * the portlet during the Resource phase"
    */
   writer.write(
         "<div id=\"V3HeaderPortletTests_SPEC15_Header\">no resource output.</div>\n");
   ResourceURL resurl = renderResponse.createResourceURL();
   resurl.setCacheability(PAGE);
   writer.write("<script>\n");
   writer.write("(function () {\n");
   writer.write("   var xhr = new XMLHttpRequest();\n");
   writer.write("   xhr.onreadystatechange=function() {\n");
   writer.write("      if (xhr.readyState==4 && xhr.status==200) {\n");
   writer.write(
         "         document.getElementById(\"V3HeaderPortletTests_SPEC15_Header\").innerHTML=xhr.responseText;\n");
   writer.write("      }\n");
   writer.write("   };\n");
   writer.write(
         "   xhr.open(\"GET\",\"" + resurl.toString() + "\",true);\n");
   writer.write("   xhr.send();\n");
   writer.write("})();\n");
   writer.write("</script>\n");

   /* TestCase: V3HeaderPortletTests_SPEC15_Header_cookie10 */
   /*
    * Details: "Cookies set during the Header phase should be available to
    * the portlet during a subsequent Render phase"
    */
   Cookie[] cookies = renderRequest.getCookies();
   StringBuilder txt = new StringBuilder(128);
   txt.append("<p>Debug info:");
   txt.append("<br>");
   txt.append("# Cookies: ").append(cookies.length).append("<br>");
   TestResult tr2 = tcd
         .getTestResultFailed(V3HEADERPORTLETTESTS_SPEC15_HEADER_COOKIE10);
   for (Cookie c : cookies) {
      txt.append("Name: ").append(c.getName());
      txt.append(", Value: ").append(c.getValue()).append("<br>");
      if (c.getName().equals("header_tr2_cookie")
            && c.getValue().equals("true")) {
         txt.append("<br>").append("Found my cookie!").append("<br>");
         c.setMaxAge(0);
         c.setValue("");
         tr2.setTcSuccess(true);
      }
   }
   tr2.writeTo(writer);
   txt.append("</p>");
   writer.append(txt.toString());

   String msg = (String) renderRequest.getAttribute(
         RESULT_ATTR_PREFIX + "HeaderPortletTests_SPEC15_Header");
   writer.write("<p>" + msg + "</p>");
   renderRequest.removeAttribute(
         RESULT_ATTR_PREFIX + "HeaderPortletTests_SPEC15_Header");

}