Java Code Examples for javax.servlet.http.HttpServletResponse#getWriter()

The following examples show how to use javax.servlet.http.HttpServletResponse#getWriter() . 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: CaseServlet.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();

    HttpGet httpGet = new HttpGet("http://localhost:8080" + req.getContextPath() + "/case/context-propagate");
    CloseableHttpResponse response1 = httpclient.execute(httpGet);
    try {
        HttpEntity entity1 = response1.getEntity();
        EntityUtils.consume(entity1);
    } finally {
        response1.close();
    }

    PrintWriter printWriter = resp.getWriter();
    printWriter.write("success");
    printWriter.flush();
    printWriter.close();
}
 
Example 2
Source File: WFSExceptionWriter.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Given the information on construction, writes the necessary exception information.
 *
 * @param hsr the Servlet Response to write to
 * @throws IOException
 */
public void write(HttpServletResponse hsr) throws IOException {
  PrintWriter xmlResponse = hsr.getWriter();

  xmlResponse.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
  xmlResponse.append("<ows:ExceptionReport xml:lang=\"en-US\" xsi:schemaLocation=\"http://www.opengis.net/ows/1.1"
      + " http://schemas.opengis.net/ows/1.1.0/owsExceptionReport.xsd\" version=\"2.0.0\" xmlns:ows=\"http://www.opengis.net/ows/1.1\""
      + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">");
  xmlResponse.append("<ows:Exception ");
  if (locator != null)
    xmlResponse.append("locator=\"" + locator + "\" ");
  xmlResponse.append("exceptionCode=\"" + ExceptionCode + "\">");
  xmlResponse.append("<ows:ExceptionText>" + text + "</ows:ExceptionText>");
  xmlResponse.append("</ows:Exception>");
  xmlResponse.append("</ows:ExceptionReport>");
}
 
Example 3
Source File: TestApplicationHttpRequest.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    Map map = req.getParameterMap();

    boolean insertWorks;
    try {
        map.put("test", new Integer[] { Integer.valueOf(0) });
        insertWorks = true;
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        insertWorks = false;
    }

    resp.setContentType("text/plain");
    resp.setCharacterEncoding("UTF-8");
    PrintWriter pw = resp.getWriter();
    if (insertWorks) {
        pw.print("FAIL");
    } else {
        pw.print("OK");
    }
}
 
Example 4
Source File: StatuszServlet.java    From swellrt with Apache License 2.0 6 votes vote down vote up
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  resp.setContentType("text/html");

  PrintWriter writer = resp.getWriter();
  writeHeader(writer);

  String show = req.getParameter("show");
  if (show == null) {
    show = SHOW_SESSION_MEASUREMENTS;
  }
  switch (show) {
    case SHOW_SESSION_MEASUREMENTS:
      writeSessionMeasurements(writer);
      break;
    case SHOW_GLOBAL_MEASUREMENTS:
      writeGlobalMeasurements(writer);
      break;
    case SHOW_STATS:
      writeStats(writer);
      break;
  }
}
 
Example 5
Source File: PathFilter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
		throws IOException, ServletException {
	if (req instanceof HttpServletRequest) {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		String path = request.getContextPath();

		PrintWriter out = response.getWriter();
		CharResponseWrapper wrapper = new CharResponseWrapper((HttpServletResponse) response);
		filterChain.doFilter(request, wrapper);
		CharArrayWriter caw = new CharArrayWriter();
		caw.write(wrapper.toString().replace("${path}", path));
		String result = caw.toString();
		response.setContentLength(result.length());
		out.write(result);
	}
}
 
Example 6
Source File: DecisiontableEditorServletHandler.java    From urule with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	String method=retriveMethod(req);
	if(method!=null){
		invokeMethod(method, req, resp);
	}else{
		VelocityContext context = new VelocityContext();
		context.put("contextPath", req.getContextPath());
		String file=req.getParameter("file");
		String project = buildProjectNameFromFile(file);
		if(project!=null){
			context.put("project", project);
		}
		resp.setContentType("text/html");
		resp.setCharacterEncoding("utf-8");
		Template template=ve.getTemplate("html/decisiontable-editor.html","utf-8");
		PrintWriter writer=resp.getWriter();
		template.merge(context, writer);
		writer.close();
	}
}
 
Example 7
Source File: TaskCaseLogController.java    From LuckyFrameWeb with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 查询用例日志明细列表
 */
@RequiresPermissions("testexecution:taskCaseExecute:list")
@RequestMapping(value = "/list")
public void list(HttpServletRequest request,HttpServletResponse response) throws IOException
{
	response.setCharacterEncoding("utf-8");
	PrintWriter pw = response.getWriter();
	String taskCaseIdStr = request.getParameter("taskCaseId");
	int taskCaseId = 0;
	// 得到客户端传递的查询参数
	if (StringUtils.isNotEmpty(taskCaseIdStr)) {
		taskCaseId = Integer.parseInt(taskCaseIdStr);
	}
			
       List<TaskCaseLog> loglist = taskCaseLogService.selectTaskCaseLogListByTaskCaseId(taskCaseId);
	// 转换成json字符串
	JSONArray recordJson= JSONArray.parseArray(JSON.toJSONString(loglist));
	pw.print(recordJson);
}
 
Example 8
Source File: DatabaseHelper.java    From Benchmark with GNU General Public License v2.0 6 votes vote down vote up
public static void printResults(String query, int[] counts, HttpServletResponse response) throws IOException{
	PrintWriter out = response.getWriter();
	out.write("<!DOCTYPE html>\n<html>\n<body>\n<p>");
	out.write("For query: " + ESAPI.encoder().encodeForHTML(query) + "<br>");
	try {
		if(counts.length > 0){
			if(counts[0] == Statement.SUCCESS_NO_INFO){
				out.write("The SQL query was processed successfully but the number of rows affected is unknown.");
				System.out.println("The SQL query was processed successfully but the number of rows affected is unknown.");
			}else if(counts[0] == Statement.EXECUTE_FAILED){
				out.write("The SQL query failed to execute successfully and occurs only if a driver continues to process commands after a command fails");
				System.out.println("The SQL query failed to execute successfully and occurs only if a driver continues to process commands after a command fails");
			}else{
				out.write("The number of affected rows are: " + counts[0]);
				System.out.println("The number of affected rows are: " + counts[0]);
			}
		}
	} finally {
		out.write("</p>\n</body>\n</html>");
	}
}
 
Example 9
Source File: Collections14.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String s1 = req.getParameter(FIELD_NAME);
    LinkedList c = new LinkedList();
    for(int i = 0; i < 3000; i++){
    	c.addFirst("i: " + i);
    }
    c.addLast(s1);
    
    PrintWriter writer = resp.getWriter();  
  	writer.println(c.getLast());                    /* BAD */
}
 
Example 10
Source File: HelloWorldServlet.java    From hawkular-agent with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Integer num = Integer.valueOf(mbean.getTestInteger().intValue() + 1);
    mbean.setTestInteger(num);
    resp.setContentType("text/html");
    PrintWriter writer = resp.getWriter();
    writer.println("<html><head><title>helloworld</title></head><body><h1>");
    writer.println(mbean.getTestString());
    writer.println(" #");
    writer.println(num);
    writer.println("</h1></body></html>");
    writer.close();
}
 
Example 11
Source File: JsonHttp.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * Writes a JSON servlet response securely with a parser breaker.
 *
 * @throws IOException if we failed to write to {@code rsp}.
 */
public static void write(HttpServletResponse rsp, Map<String, ?> jsonObject) throws IOException {
  checkNotNull(jsonObject);
  rsp.setContentType(JSON_UTF_8.toString());
  // This prevents IE from MIME-sniffing a response away from the declared Content-Type.
  rsp.setHeader(X_CONTENT_TYPE_OPTIONS, "nosniff");
  // This is a defense in depth that prevents browsers from trying to render the content of the
  // response, even if all else fails. It's basically another anti-sniffing mechanism in the sense
  // that if you hit this url directly, it would try to download the file instead of showing it.
  rsp.setHeader(CONTENT_DISPOSITION, "attachment");
  try (Writer writer = rsp.getWriter()) {
    writer.write(JSON_SAFETY_PREFIX);
    writeJSONString(jsonObject, writer);
  }
}
 
Example 12
Source File: PrerenderSeoService.java    From prerender-java with MIT License 5 votes vote down vote up
private boolean beforeRender(HttpServletRequest request, HttpServletResponse response) throws IOException {
    if (preRenderEventHandler != null) {
        final String html = preRenderEventHandler.beforeRender(request);
        if (isNotBlank(html)) {
            final PrintWriter writer = response.getWriter();
            writer.write(html);
            writer.flush();
            closeQuietly(writer);
            return true;
        }
    }
    return false;
}
 
Example 13
Source File: LogViewerServlet.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  resp.setContentType("text/plain");

  PrintWriter writer = resp.getWriter();

  boolean applogs = true;
  if ("false".equals(req.getParameter("applogs"))) {
    applogs = false;
  }

  boolean combined = false;
  if ("true".equals(req.getParameter("combined"))) {
    combined = true;
  }

  LogQuery query = LogQuery.Builder.withIncludeAppLogs(true).includeIncomplete(true);
  for (RequestLogs record : LogServiceFactory.getLogService().fetch(query)) {
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(record.getStartTimeUsec() / 1000);

    writer.println(String.format("\nDate: %s", cal.getTime().toString()));
    if (combined) {
      writer.println("COMBINED:" + record.getCombined());
    } else {
      writer.println("URL: " + record.getResource());
      writer.println("");
    }
    if (applogs) {
      List<AppLogLine> appLogs = record.getAppLogLines();
      for (AppLogLine appLog : appLogs) {
        writer.println("[" + appLog.getLogLevel() + "] " + appLog.getLogMessage());
      }
    }
  }
}
 
Example 14
Source File: AutoBattleController.java    From CardFantasy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@RequestMapping(value = "/SimulateLilith1MatchGame", headers = "Accept=application/json")
public void simulateLilith1MatchGame(HttpServletRequest request, HttpServletResponse response,
    @RequestParam("deck") String deck, @RequestParam("ecg") boolean enableCustomGuards,
    @RequestParam("cg") String customGuards, @RequestParam("cgab") int customGuardsAtBuff, @RequestParam("cghb") int customGuardsHpBuff,
    @RequestParam("count") int count, @RequestParam("gt") int gameType,
    @RequestParam("hlv") int heroLv, @RequestParam("ln") String lilithName,
    @RequestParam("tc") int targetRemainingGuardCount, @RequestParam("rhp") int remainingHP,
    @RequestParam("ec") String eventCardNames
    ) throws IOException {
    PrintWriter writer = response.getWriter();
    response.setContentType("application/json");
    try {
        String logMessage = String.format("Deck=%s<br />HeroLV=%d, Lilith=%s, GameType=%d, EventCards=%s", deck, heroLv, lilithName, gameType, eventCardNames);
        logger.info("SimulateLilith1MatchGame: " + logMessage);
        this.userActionRecorder.addAction(new UserAction(new Date(), request.getRemoteAddr(), "Simulate Lilith 1Match Game", logMessage));

        PlayerInfo player1 = null;
        if (enableCustomGuards && gameType == 0) {
            List<Skill> player1Buffs = PvlEngine.getCardBuffs(customGuardsAtBuff, customGuardsHpBuff);
            player1 = PlayerBuilder.build(false, "莉莉丝", lilithName + "," + customGuards, 99999, player1Buffs, 100);
        } else {
            player1 = PlayerBuilder.buildLilith(lilithDataStore, lilithName, gameType == 0);
        }
        List<Skill> player2Buffs = buildBuffsForLilithEvents(eventCardNames);
        PlayerInfo player2 = PlayerBuilder.build(true, "玩家", deck, heroLv, player2Buffs, 100);
        StructuredRecordGameUI ui = new StructuredRecordGameUI();
        BattleEngine engine = new BattleEngine(ui, Rule.getDefault());
        engine.registerPlayers(player1, player2);
        if (gameType == 1) {
            Player lilithPlayer = engine.getStage().getPlayers().get(0);
            CardInfo lilithCard = lilithPlayer.getDeck().toList().get(0);
            lilithCard.setRemainingHP(remainingHP);
        }
        engine.playGame();
        BattleRecord record = ui.getRecord();
        writer.print(jsonHandler.toJson(record));
    } catch (Exception e) {
        writer.print(errorHelper.handleError(e, true));
    }
}
 
Example 15
Source File: TwitterShowUserServlet.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(final HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    TwitterOAuthResponse twitterOAuthResponse = getTwitterOAuthResponse(request);
    ConfigurationBuilder cb = new ConfigurationBuilder();

    cb.setDebugEnabled(true)
            .setOAuthConsumerKey(this.identityProvider.getConfig().get("clientId"))
            .setOAuthConsumerSecret(this.identityProvider.getConfig().get("clientSecret"))
            .setOAuthAccessToken(twitterOAuthResponse.getToken())
            .setOAuthAccessTokenSecret(twitterOAuthResponse.getTokenSecret());

    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();

    try {
        User user = twitter.users().showUser(twitterOAuthResponse.getScreenName());

        response.setContentType(MediaType.APPLICATION_JSON);

        PrintWriter writer = response.getWriter();

        writer.println(new ObjectMapper().writeValueAsString(user));

        writer.flush();
    } catch (TwitterException e) {
        throw new RuntimeException("Could not load social profile.", e);
    }
}
 
Example 16
Source File: CreateObj.java    From openprodoc with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 *
 * @param Req
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 */
@Override
protected void processRequest(HttpServletRequest Req, HttpServletResponse response) throws ServletException, IOException
{   
response.setContentType("text/xml;charset=UTF-8");
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();  
StringBuilder Resp=new StringBuilder(200);
try {
String S;
//Resp.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
String Id=Req.getParameter("Id");
if (Id==null || Id.length()==0)
    Resp.append("<status>Undefined Type Id</status>");
else
    {
    PDObjDefs Def=new PDObjDefs(getSessOPD(Req));
    Def.Load(Id);
    Def.CreateObjectTables(Id, Def.getClassType().equals(Def.CT_FOLDER));
    Resp.append("<status>OK</status>");
    }   
out.println(Resp.toString());
} catch (Exception Ex)
        {
        out.println(Resp);    
        out.println("<status>");
        PrepareError(Req, Ex.getLocalizedMessage(), out);
        out.println("</status>");
        }
finally {
out.close();
        }
}
 
Example 17
Source File: TestAbstractAjpProcessor.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private void doRequest(HttpServletRequest request, HttpServletResponse response,
        boolean isPost) throws IOException {

    long readCount = 0;

    try (InputStream s = request.getInputStream()) {
        byte[] buf = new byte[4096];
        int read;
        do {
            if (callAvailable) {
                int available = s.available();
                read = s.read(buf);
                availableList.add(Integer.valueOf(available));
                readList.add(Integer.valueOf(read));
            } else {
                read = s.read(buf);
            }
            if (read > 0) {
                readCount += read;
            }
        } while (read > 0);
    }

    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");

    try (PrintWriter w = response.getWriter()) {
        w.println("Method: " + (isPost ? "POST" : "GET") + ". Reading request body...");
        w.println("Request Body length in bytes: " + readCount);
    }
}
 
Example 18
Source File: OdeAuthFilter.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
void writeWhitelistErrorMessage(HttpServletResponse response) throws IOException {
  response.setContentType("text/plain; charset=utf-8");
  PrintWriter out = response.getWriter();
  out.print("You are attempting to connect to this App Inventor service with the login ID:\n\n" +
      localUser.getUserEmail() + "\n\nThat ID has not been authorized to use this service.  " +
      "If you believe that you were in fact given authorization, you should contact the " +
      "service operator.");
}
 
Example 19
Source File: DavServlet.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
/**
 * Send a multistatus element containing a complete error report to the client.
 * 
 * @param req
 *        Servlet request
 * @param resp
 *        Servlet response
 * @param errorList
 *        List of error to be displayed
 */
private void sendReport(HttpServletRequest req, HttpServletResponse resp, Hashtable<String,Integer> errorList) throws ServletException,
		IOException
{

	resp.setStatus(SakaidavStatus.SC_MULTI_STATUS);

	String absoluteUri = req.getRequestURI();
	String relativePath = getRelativePath(req);
	
	XMLWriter generatedXML = new XMLWriter();
	generatedXML.writeXMLHeader();

	generatedXML.writeElement("D", "multistatus" + generateNamespaceDeclarations(), XMLWriter.OPENING);

	Enumeration<String> pathList = errorList.keys();
	while (pathList.hasMoreElements())
	{

		String errorPath = pathList.nextElement();
		int errorCode = ((Integer) errorList.get(errorPath)).intValue();

		generatedXML.writeElement("D", "response", XMLWriter.OPENING);

		generatedXML.writeElement("D", "href", XMLWriter.OPENING);
		String toAppend = errorPath.substring(relativePath.length());
		if (!toAppend.startsWith("/")) toAppend = "/" + toAppend;
		generatedXML.writeText(absoluteUri + toAppend);
		generatedXML.writeElement("D", "href", XMLWriter.CLOSING);
		generatedXML.writeElement("D", "status", XMLWriter.OPENING);
		generatedXML.writeText("HTTP/1.1 " + errorCode + " " + SakaidavStatus.getStatusText(errorCode));
		generatedXML.writeElement("D", "status", XMLWriter.CLOSING);

		generatedXML.writeElement("D", "response", XMLWriter.CLOSING);

	}

	generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING);

	Writer writer = resp.getWriter();
	writer.write(generatedXML.toString());
	writer.close();

}
 
Example 20
Source File: FederationServlet.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
    IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head><title>WS Federation Systests Spring Examples</title></head>");
    out.println("<body>");
    out.println("<p>Request url: "); out.println(request.getRequestURL()); out.println("</p>");

    out.print("<p>userPrincipal=");
    Principal p = request.getUserPrincipal();
    if (p != null) {
        out.print(p.getName());
    }
    out.println("</p>");

    List<String> roleListToCheck = Arrays.asList("Admin", "Manager", "User", "Authenticated");
    for (String item : roleListToCheck) {
        out.println("<p>role:" + item + "=" + ((request.isUserInRole(item)) ? "true" : "false") + "</p>");
    }

    if (p instanceof FedizPrincipal) {
        FedizPrincipal fp = (FedizPrincipal)p;

        ClaimCollection claims = fp.getClaims();
        for (Claim c : claims) {
            out.println("<p>" + c.getClaimType().toString() + "=" + c.getValue() + "</p>");
        }

        Element el = fp.getLoginToken();
        if (el != null) {
            out.println("loginToken=FOUND{FedizPrincipal}<p>");
        }

        el = SecurityTokenThreadLocal.getToken();
        if (el != null) {
            out.println("loginToken=FOUND{SecurityTokenThreadLocal}<p>");
        }
    }

    out.println("</body>");

    // Access Spring security context
    Assert.notNull(SecurityContextHolder.getContext().getAuthentication(),
                   "SecurityContextHolder Authentication not null");

    Authentication obj = SecurityContextHolder.getContext().getAuthentication();
    System.out.println("getCredentials: " + obj.getCredentials().toString());
    System.out.println("getDetails: " + obj.getDetails().toString());
    System.out.println("getName: " + obj.getName().toString());
    System.out.println("getAuthorities: " + obj.getAuthorities().toString());
    System.out.println("getPrincipal: " + obj.getPrincipal().toString());

}