List of usage examples for java.io PrintWriter print
public void print(Object obj)
From source file:org.epics.archiverappliance.utils.ui.GetUrlContent.java
/** * Combine JSON arrays of JSON objects from multiple URL's in sequence and sends them to the writer.. * The difference from combineJSONArrays is that inserts a newline after each element. * /*from www .j a v a 2 s.c om*/ * @param urlStrs multiple URLs * @param out PrintWriter */ public static void combineJSONArraysAndPrintln(List<String> urlStrs, PrintWriter out) { out.println("["); boolean first = true; for (String urlStr : urlStrs) { try { logger.debug("Getting the contents of " + urlStr + " as a JSON array."); JSONParser parser = new JSONParser(); try (InputStream is = getURLContentAsStream(urlStr)) { JSONArray content = (JSONArray) parser.parse(new InputStreamReader(is)); if (content != null) { for (Object obj : content) { JSONObject jsonObj = (JSONObject) obj; if (first) { first = false; } else { out.println(","); } out.print(JSONValue.toJSONString(jsonObj)); } } else { logger.debug(urlStr + " returned an empty array"); } } } catch (IOException ex) { logger.error("Exception getting contents of internal URL " + urlStr, ex); } catch (ParseException pex) { logger.error( "Parse exception getting contents of internal URL " + urlStr + " at " + pex.getPosition(), pex); } } out.println("]"); }
From source file:net.sf.j2ep.responsehandlers.TraceResponseHandler.java
/** * Will either respond with data from the underlying server * or the proxy's own data./*from w w w . j a v a 2 s .co m*/ * @see net.sf.j2ep.model.ResponseHandler#process(javax.servlet.http.HttpServletResponse) */ public void process(HttpServletResponse response) throws IOException { if (proxyTargeted) { response.setStatus(HttpServletResponse.SC_OK); response.setHeader("content-type", "message/http"); response.setHeader("Connection", "close"); String path = method.getPath(); String protocol = method.getParams().getVersion().toString(); PrintWriter writer = response.getWriter(); writer.println("TRACE " + path + " " + protocol); Header[] headers = method.getRequestHeaders(); for (int i = 0; i < headers.length; i++) { writer.print(headers[i]); } writer.flush(); writer.close(); } else { setHeaders(response); response.setStatus(getStatusCode()); sendStreamToClient(response); } }
From source file:de.viaboxx.nlstools.formats.BundleWriterJavaInterface.java
protected PrintWriter printIndent(PrintWriter pw) { for (int i = 0; i < indentNum; i++) { pw.print(" "); }//from ww w. ja v a2 s. c om return pw; }
From source file:ru.mystamps.web.controller.SitemapController.java
@GetMapping(Url.SITEMAP_XML) public void getSitemapXml(HttpServletResponse response) { response.setContentType("application/xml"); response.setCharacterEncoding("UTF-8"); DateFormat dateFormatter = new SimpleDateFormat(DATE_FORMAT, Locale.ENGLISH); try {//from w w w .j a v a 2 s . c om PrintWriter writer = response.getWriter(); writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); writer.println("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">"); writer.print("\t<url>\t\t<loc>"); writer.print(Url.PUBLIC_URL); writer.print(Url.INDEX_PAGE); writer.println("</loc>\t</url>"); for (SitemapInfoDto item : seriesService.findAllForSitemap()) { writer.println("\t<url>"); writer.print("\t\t<loc>"); writer.print(createLocEntry(item)); writer.println("</loc>"); writer.print("\t\t<lastmod>"); writer.print(createLastModEntry(dateFormatter, item)); writer.println("</lastmod>"); writer.println("\t</url>"); } writer.println("</urlset>"); } catch (IOException ex) { LOG.error("Can't return sitemap.xml: {}", ex.getMessage()); } }
From source file:com.flexive.war.servlet.CeFileUpload.java
@Override public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { String renderContent = null;//from w w w .jav a 2 s. co m try { final HttpServletRequest request = (HttpServletRequest) servletRequest; final BeContentEditorBean ceb = null; // = ContentEditorBean.getSingleton().getInstance(request); if (ceb == null) { renderContent = "No Content Editor Bean is active"; } else { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List /* FileItem */ items = upload.parseRequest(request); BinaryDescriptor binary = null; String xpath = null; for (Object item1 : items) { FileItem item = (FileItem) item1; if (item.isFormField()) { if (item.getFieldName().equalsIgnoreCase("result")) { renderContent = item.getString().replaceAll("\\\\n", "\\\n"); } else if (item.getFieldName().equalsIgnoreCase("xpath")) { xpath = item.getString(); } } else { InputStream uploadedStream = null; try { uploadedStream = item.getInputStream(); String name = item.getName(); if (name.indexOf('\\') > 0) name = name.substring(name.lastIndexOf('\\') + 1); binary = new BinaryDescriptor(name, item.getSize(), uploadedStream); } finally { if (uploadedStream != null) uploadedStream.close(); } } // System.out.println("Item: " + item.getName()); } //FxContent co = ceb.getContent(); FxBinary binProperty = new FxBinary(binary); //co.setValue(xpath, binProperty); //ceb.getContentEngine().prepareSave(co); } } catch (Throwable t) { System.err.println(t.getMessage()); t.printStackTrace(); renderContent = t.getMessage(); } // Render the result PrintWriter w = servletResponse.getWriter(); if (renderContent == null) { renderContent = "No content"; } w.print(renderContent); w.close(); servletResponse.setContentType("text/html"); servletResponse.setContentLength(renderContent.length()); ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_OK); }
From source file:com.jjtree.servelet.Login.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request// w w w. j a va2s . c om * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); JSONObject jsonObject = JConverter.convert(request); if (jsonObject == null) { return; } String account = null; String password = null; try { account = jsonObject.getString("account"); password = jsonObject.getString("password"); if (account == null || password == null) { return; } } catch (JSONException ex) { Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex); } try { // Register JDBC driver Class.forName(JConstant.JDBC_DRIVER); // Open a connection conn = DriverManager.getConnection(JConstant.DB_URL, JConstant.USER, JConstant.PASSWORD); // Execute SQL query stmt = conn.createStatement(); String sql = null; boolean isPhone = JString.isPhoneNumber(account); if (isPhone) { sql = "SELECT * FROM JUser WHERE mobile = '" + account + "'"; } boolean isEmail = JString.isEmail(account); if (isEmail) { sql = "SELECT * FROM JUser WHERE email = '" + account + "'"; } ResultSet rs = stmt.executeQuery(sql); // Extract data from result set while (rs.next()) { //Retrieve by column name int accountID = rs.getInt("userID"); String pass = rs.getString("password"); if (password != null) { if (password.equals(pass)) { String accountUrl = "/accounts/" + accountID; JSONObject accountObject = JServeletManager.fetchFrom(request, accountUrl); PrintWriter writer = response.getWriter(); writer.print(accountObject); writer.flush(); } } } // Clean-up environment rs.close(); stmt.close(); conn.close(); } catch (SQLException se) { try { //Handle errors for JDBC JResponse.sendErrorMessage(1, "login failed!", response); } catch (JSONException ex) { Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex); } se.printStackTrace(); } catch (Exception e) { try { //Handle errors for JDBC JResponse.sendErrorMessage(1, "login failed!", response); } catch (JSONException ex) { Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex); } //Handle errors for Class.forName e.printStackTrace(); } finally { //finally block used to close resources try { if (stmt != null) { stmt.close(); } } catch (SQLException se2) { } // nothing we can do try { if (conn != null) { conn.close(); } } catch (SQLException se) { se.printStackTrace(); } //end finally try } //end try }
From source file:com.ucap.uccc.cmis.impl.webservices.CmisWebServicesServlet.java
private void printXml(HttpServletRequest request, HttpServletResponse response, String doc, UrlBuilder baseUrl) throws ServletException, IOException { response.setStatus(HttpServletResponse.SC_OK); response.setContentType("text/xml"); response.setCharacterEncoding(IOUtils.UTF8); String respDoc = doc;/*from w ww . j a va 2s .com*/ respDoc = BASE_PATTERN.matcher(respDoc).replaceAll(baseUrl.toString()); respDoc = CORE_PATTERN.matcher(respDoc) .replaceAll((new UrlBuilder(baseUrl)).addPath("cmis").addParameter("core").toString()); respDoc = MSG_PATTERN.matcher(respDoc) .replaceAll((new UrlBuilder(baseUrl)).addPath("cmis").addParameter("msg").toString()); PrintWriter pw = response.getWriter(); pw.print(respDoc); pw.flush(); }
From source file:fr.ippon.wip.http.reponse.Response.java
/** * Print the response content to a MimeResponse (RenderResponse or * ResourceResponse)//from w w w . j av a 2 s.co m * * In the RESOURCE phase, this method can send binary content and set * Content-Type and HTTP status code * * @param portalRequest * @param portalResponse * @param printLogout * @throws IOException */ public void printResponseContent(PortletRequest portalRequest, MimeResponse portalResponse, boolean printLogout) throws IOException { if (portalRequest instanceof RenderRequest && !portalURLComputed) { computePortalURL(portalRequest, portalResponse); } if (portalResponse instanceof ResourceResponse) { // Set content-type & return code portalResponse.setContentType(mimeType); portalResponse.setProperty(ResourceResponse.HTTP_STATUS_CODE, Integer.toString(responseCode)); } if (isBinary()) { if (portalResponse instanceof ResourceResponse) { OutputStream os = portalResponse.getPortletOutputStream(); IOUtils.copy(new ByteArrayInputStream(content), os); os.close(); } } else { PrintWriter writer = portalResponse.getWriter(); if (portalResponse instanceof RenderResponse && printLogout) { writer.print(getLogoutButton((RenderResponse) portalResponse)); } writer.print(new String(content, charset)); writer.close(); } }
From source file:org.loklak.api.server.ImportProfileServlet.java
private void doDelete(RemoteAccess.Post post, HttpServletResponse response) throws IOException { String callback = post.get("callback", null); boolean jsonp = callback != null && callback.length() > 0; String id = post.get("id_str", ""); if ("".equals(id)) { response.sendError(400, "your request must contain a `id_str` parameter."); return;//from w w w .java2s.c o m } String screen_name = post.get("screen_name", ""); if ("".equals(screen_name)) { response.sendError(400, "your request must contain a `screen_name` parameter."); return; } ImportProfileEntry entry = DAO.SearchLocalImportProfiles(id); List<String> sharers = entry.getSharers(); boolean sharerExists = sharers.remove(screen_name); entry.setSharers(sharers); boolean successful = false; if (sharerExists && DAO.writeImportProfile(entry, true)) { successful = true; } else { throw new IOException("Unable to delete import profile : " + entry.getId()); } post.setResponse(response, "application/javascript"); XContentBuilder json = XContentFactory.jsonBuilder().prettyPrint().lfAtEnd(); json.startObject(); json.field("status", "ok"); json.field("records", sharerExists && successful ? 1 : 0); json.field("message", "deleted"); json.endObject(); // write json response.setCharacterEncoding("UTF-8"); PrintWriter sos = response.getWriter(); if (jsonp) sos.print(callback + "("); sos.print(json.string()); if (jsonp) sos.println(");"); sos.println(); }
From source file:com.gargoylesoftware.htmlunit.html.DomText.java
/** * Recursively writes the XML data for the node tree starting at <code>node</code>. * * @param indent white space to indent child nodes * @param printWriter writer where child nodes are written *///from w w w .j a v a 2 s . c o m @Override protected void printXml(final String indent, final PrintWriter printWriter) { String data = getData(); if (org.apache.commons.lang3.StringUtils.isNotBlank(data)) { printWriter.print(indent); if (!(getParentNode() instanceof HtmlStyle) || !data.startsWith("<!--") || !data.endsWith("-->")) { data = StringUtils.escapeXmlChars(data); } printWriter.print(data); printWriter.print("\r\n"); } printChildrenAsXml(indent, printWriter); }