List of usage examples for java.io PrintWriter print
public void print(Object obj)
From source file:org.freewheelschedule.freewheel.controlserver.ControlThread.java
private boolean workerAwaitingCommand(BufferedReader result, PrintWriter command, String hostname) throws IOException { String response = result.readLine(); if (response.equals(HELO)) { command.print(HELO + " " + hostname + "\r\n"); command.flush();// w w w .j a va 2s . co m response = result.readLine(); } return response.equals(COMMAND); }
From source file:de.mpg.imeji.presentation.servlet.autocompleter.java
/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) *//*w w w . j av a 2s. c o m*/ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String suggest = request.getParameter("searchkeyword"); String datasource = request.getParameter("datasource"); String responseString = ""; if (suggest.isEmpty()) { suggest = "a"; } else if (datasource != null && !datasource.isEmpty()) { HttpClient client = new HttpClient(); GetMethod getMethod = new GetMethod(datasource + URLEncoder.encode(suggest.toString(), "UTF-8")); try { client.executeMethod(getMethod); responseString = new String(StorageUtils.toBytes(getMethod.getResponseBodyAsStream()), "UTF-8"); if (datasource != null && responseString != null) responseString = passResult(responseString, datasource); } catch (Exception e) { throw new RuntimeException(e); } finally { getMethod.releaseConnection(); } } response.setContentType("application/json"); PrintWriter out = response.getWriter(); out.print(responseString); out.flush(); out.close(); }
From source file:com.ss.Controller.T4uApproveRefundServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w. j a v a2 s .c o m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(true); T4uUser user = (T4uUser) session.getAttribute(T4uConstants.T4uUser); if (!user.getUserGroup().equals("officer")) // Not authorised, only user himself can cancel order response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Not authorised"); else try { long orderId = Long.parseLong(request.getParameter("orderId")); T4uOrder order = T4uOrderDAO.getOrderById(orderId); if (order.getOrderStatus() == 2) { // Current status is Pending T4uOrderDAO.changeOrderStatus(orderId, 3, user); T4uOrder t4uOrder = new T4uOrder(); t4uOrder.setOrderId(orderId); String json = new Gson().toJson(t4uOrder); response.setContentType("application/json"); // Get the printwriter object from response to write the required json object to the output stream PrintWriter out = response.getWriter(); // Assuming your json object is **jsonObject**, perform the following, it will return your json object out.print(json); out.flush(); } else // Not pending status response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad order status"); } catch (NumberFormatException ex) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "NumberFormatException"); } }
From source file:mapbuilder.ProxyRedirect.java
/*************************************************************************** * Process the HTTP Get request//from w ww.j a v a 2s.c o m */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException { try { if (log.isDebugEnabled()) { Enumeration e = request.getHeaderNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); String value = request.getHeader(name); log.debug("request header:" + name + ":" + value); } } // Transfer bytes from in to out log.debug("HTTP GET: transferring..."); //execute the GET String serverUrl = request.getParameter("url"); if (serverUrl.startsWith("http://") || serverUrl.startsWith("https://")) { log.info("GET param serverUrl:" + serverUrl); HttpClient client = new HttpClient(); GetMethod httpget = new GetMethod(serverUrl); client.executeMethod(httpget); if (log.isDebugEnabled()) { Header[] respHeaders = httpget.getResponseHeaders(); for (int i = 0; i < respHeaders.length; ++i) { String headerName = respHeaders[i].getName(); String headerValue = respHeaders[i].getValue(); log.debug("responseHeaders:" + headerName + "=" + headerValue); } } //dump response to out if (httpget.getStatusCode() == HttpStatus.SC_OK) { //force the response to have XML content type (WMS servers generally don't) response.setContentType("text/xml"); String responseBody = httpget.getResponseBodyAsString().trim(); // use encoding of the request or UTF8 String encoding = request.getCharacterEncoding(); if (encoding == null) encoding = "UTF-8"; response.setCharacterEncoding(encoding); log.info("responseEncoding:" + encoding); // do not set a content-length of the response (string length might not match the response byte size) //response.setContentLength(responseBody.length()); log.info("responseBody:" + responseBody); PrintWriter out = response.getWriter(); out.print(responseBody); response.flushBuffer(); } else { log.error("Unexpected failure: " + httpget.getStatusLine().toString()); } httpget.releaseConnection(); } else { throw new ServletException("only HTTP(S) protocol supported"); } } catch (Throwable e) { throw new ServletException(e); } }
From source file:be.fedict.eid.dss.admin.portal.AccountingExportServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LOG.debug("doGet"); HttpSession httpSession = request.getSession(); Identity identity = (Identity) httpSession.getAttribute("org.jboss.seam.security.identity"); if (false == identity.hasRole("admin")) { response.sendError(HttpURLConnection.HTTP_FORBIDDEN, "no admin role"); return;/*from ww w . j av a 2 s . com*/ } response.setContentType("text/csv"); PrintWriter printWriter = response.getWriter(); List<AccountingEntity> accountingEntities = this.accountingService.listAll(); for (AccountingEntity accountingEntity : accountingEntities) { printWriter.print("\""); printWriter.print(accountingEntity.getDomain()); printWriter.print("\",\""); printWriter.print(accountingEntity.getRequests()); printWriter.println("\""); } }
From source file:daylightchart.daylightchart.calculation.RiseSetUtility.java
/** * Debug calculations.// www . j av a 2 s . com * * @param writer * Writer to write to * @param location * Location to debug * @param daylightBandType * Types of band type to write to */ @SuppressWarnings("boxing") private static void writeCalculations(final Writer writer, final Location location, final TwilightType twilight, final DaylightBandType... daylightBandType) { if (writer == null || location == null) { return; } final DecimalFormat format = new DecimalFormat("00.000"); format.setMaximumFractionDigits(3); final int year = Year.now().getValue(); final Options options = new Options(); options.setTwilightType(twilight); final RiseSetYearData riseSetYear = createRiseSetYear(location, year, options); final PrintWriter printWriter = new PrintWriter(writer, true); // Header printWriter.printf("Location\t%s%nDate\t%s%n%n", location, year); // Bands final List<DaylightBand> bands = riseSetYear.getBands(); for (final Iterator<DaylightBand> iterator = bands.iterator(); iterator.hasNext();) { final DaylightBand band = iterator.next(); if (!ArrayUtils.contains(daylightBandType, band.getDaylightBandType())) { iterator.remove(); } } printWriter.printf("\t\t\t"); if (ArrayUtils.contains(daylightBandType, DaylightBandType.twilight)) { printWriter.printf("\t\t"); } for (final DaylightBand band : bands) { printWriter.printf("Band\t%s\t", band.getName()); } printWriter.println(); // Data rows printWriter.print("Date\tSunrise\tSunset"); if (ArrayUtils.contains(daylightBandType, DaylightBandType.twilight)) { printWriter.println("\tTwilight Rise\tTwilight Set"); } else { printWriter.println(); } final List<RawRiseSet> rawRiseSets = riseSetYear.getRawRiseSets(); final List<RawRiseSet> rawTwilights = riseSetYear.getRawTwilights(); for (int i = 0; i < rawRiseSets.size(); i++) { final RawRiseSet rawRiseSet = rawRiseSets.get(i); printWriter.printf("%s\t%s\t%s", rawRiseSet.getDate(), format.format(rawRiseSet.getSunrise()), format.format(rawRiseSet.getSunset())); if (ArrayUtils.contains(daylightBandType, DaylightBandType.twilight)) { final RawRiseSet rawTwilight = rawTwilights.get(i); printWriter.printf("\t%s\t%s", format.format(rawTwilight.getSunrise()), format.format(rawTwilight.getSunset())); } for (final DaylightBand band : bands) { final RiseSet riseSet = band.get(rawRiseSet.getDate()); if (riseSet == null) { printWriter.print("\t\t"); } else { printWriter.printf("\t%s\t%s", riseSet.getSunrise().toLocalTime().format(DateTimeFormatter.ofPattern("HH:mm:ss")), riseSet.getSunset().toLocalTime().format(DateTimeFormatter.ofPattern("HH:mm:ss"))); } } printWriter.println(); } }
From source file:de.tudarmstadt.ukp.experiments.argumentation.sequence.writers.PlainTextWriter.java
@Override public void process(JCas aJCas) throws AnalysisEngineProcessException { try {// w ww . java 2s . c om File outFile = new File(outputFolder, DocumentMetaData.get(aJCas).getDocumentId() + ".txt"); PrintWriter out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8")); for (Sentence sentence : JCasUtil.select(aJCas, Sentence.class)) { // print sentence coordinates out.print(sentence.getBegin() + "," + sentence.getEnd() + "\t"); // print tokens delimited by tab space for (Token token : JCasUtil.selectCovered(Token.class, sentence)) { out.print(token.getCoveredText()); out.print("\t"); } out.println(); } out.flush(); IOUtils.closeQuietly(out); } catch (IOException e) { throw new AnalysisEngineProcessException(e); } }
From source file:org.clothocad.phagebook.controllers.AutoCompleteController.java
@RequestMapping(value = "/autoCompleteVendors", method = RequestMethod.GET) protected void autoCompleteVendors(@RequestParam Map<String, String> params, HttpServletResponse response) throws ServletException, IOException { //I WILL RETURN THE MAP AS A JSON OBJECT.. it is client side's issue to parse all data for what they need! //they could check over there if the schema matches what they are querying for and so i can do this generically! //user should be logged in so I will log in as that user. String name = params.get("name") != null ? params.get("name") : ""; boolean isValid = false; System.out.println("Name is: " + name); if (!name.equals("")) { isValid = true;// w w w . j av a2 s .c o m } if (isValid) { ClothoConnection conn = new ClothoConnection(Args.clothoLocation); Clotho clothoObject = new Clotho(conn); //TODO: we need to have an authentication token at some point String username = this.backendPhagebookUser; String password = this.backendPhagebookPassword; Map loginMap = new HashMap(); loginMap.put("username", username); loginMap.put("credentials", password); clothoObject.login(loginMap); Map query = new HashMap(); query.put("query", name); // the value for which we are querying. query.put("key", "name"); // the key of the object we are querying List<Vendor> vendors = ClothoAdapter.queryVendor(query, clothoObject, ClothoAdapter.QueryMode.STARTSWITH); org.json.JSONArray responseArray = new org.json.JSONArray(); for (Vendor vend : vendors) { JSONObject obj = new JSONObject(); obj.put("id", vend.getId()); obj.put("name", vend.getName()); responseArray.put(obj); } response.setStatus(HttpServletResponse.SC_ACCEPTED); response.setContentType("application/json"); PrintWriter out = response.getWriter(); out.print(responseArray); out.flush(); out.close(); clothoObject.logout(); conn.closeConnection(); } response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.setContentType("application/json"); JSONObject reply = new JSONObject(); reply.put("message", "Auto Complete requires a query parameter"); PrintWriter out = response.getWriter(); out.print(reply); out.flush(); out.close(); }
From source file:com.mycompany.TFolderResource.java
protected void doBody(PrintWriter pw) { System.out.println("dobody - " + children.size()); pw.print("<ul>"); for (Resource r : this.children) { String href = r.getName(); if (r instanceof CollectionResource) { href = href + "/"; }//from ww w.ja v a 2 s. c o m pw.print("<li><a href='" + href + "'>" + r.getName() + "(" + r.getClass().getCanonicalName() + ")" + "</a></li>"); } pw.print("</ul>"); }
From source file:com.netsteadfast.greenstep.base.interceptor.UserLoginInterceptor.java
private String redirectLogin(Map<String, Object> session, boolean getUserCurrentCookieFail) throws Exception { SecurityUtils.getSubject().logout(); if (session != null) { UserAccountHttpSessionSupport.remove(session); }/* w w w .ja va2 s .c om*/ String header = ServletActionContext.getRequest().getHeader("X-Requested-With"); String isDojoContentPaneXhrLoad = ServletActionContext.getRequest() .getParameter(Constants.IS_DOJOX_CONTENT_PANE_XHR_LOAD); if ("XMLHttpRequest".equalsIgnoreCase(header) && !YesNo.YES.equals(isDojoContentPaneXhrLoad)) { PrintWriter printWriter = ServletActionContext.getResponse().getWriter(); printWriter.print(Constants.NO_LOGIN_JSON_DATA); printWriter.flush(); printWriter.close(); return null; } if (YesNo.YES.equals(isDojoContentPaneXhrLoad)) { if (getUserCurrentCookieFail) { return Constants._S2_RESULT_LOGOUT_AGAIN; } return Constants._S2_RESULT_LOGIN_AGAIN; } if (getUserCurrentCookieFail) { return "logout"; } return "login"; }