List of usage examples for java.io PrintWriter write
public void write(String s)
From source file:com.streamsets.datacollector.http.JMXJsonServlet.java
/** * Process a GET request for the specified resource. * * @param request//from ww w. ja v a 2s.c om * The servlet request we are processing * @param response * The servlet response we are creating */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) { try { JsonGenerator jg = null; String jsonpcb = null; PrintWriter writer = null; try { writer = response.getWriter(); // "callback" parameter implies JSONP outpout jsonpcb = request.getParameter(CALLBACK_PARAM); if (jsonpcb != null) { response.setContentType("application/javascript; charset=utf8"); writer.write(jsonpcb + "("); } else { response.setContentType("application/json; charset=utf8"); } jg = jsonFactory.createGenerator(writer); jg.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET); jg.useDefaultPrettyPrinter(); jg.writeStartObject(); // query per mbean attribute String getmethod = request.getParameter("get"); if (getmethod != null) { String[] splitStrings = getmethod.split("\\:\\:"); if (splitStrings.length != 2) { jg.writeStringField("result", "ERROR"); jg.writeStringField("message", "query format is not as expected."); jg.flush(); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } listBeans(jg, new ObjectName(splitStrings[0]), splitStrings[1], response); return; } // query per mbean String qry = request.getParameter("qry"); if (qry == null) { qry = "*:*"; } listBeans(jg, new ObjectName(qry), null, response); } finally { if (jg != null) { jg.close(); } if (jsonpcb != null) { writer.write(");"); } if (writer != null) { writer.close(); } } } catch (IOException e) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (MalformedObjectNameException e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } }
From source file:com.flexive.extractor.PdfExtractor.java
/** * Extracts the text informations from the pdf file. * * @param in the input stream to read from * @return the extracted information, or null if no text extraction was possible *//*from w ww . j a v a 2 s . c o m*/ public ExtractedData extract(final InputStream in) { ByteArrayOutputStream baos = null; PrintWriter writer = null; PDDocument document = null; try { baos = new ByteArrayOutputStream(); writer = new PrintWriter(baos); document = PDDocument.load(in); PDFTextStripper stripper = new PDFTextStripper(); try { stripper.writeText(document, writer); } catch (IOException e) { // usually because text extraction is not allowed LOG.warn("Failed to extract text from PDF file: " + e.getMessage()); } FxSummaryInformation fxsi = new FxSummaryInformation(document); writer.write(fxsi.getFTIndexInformations()); writer.flush(); return new ExtractedData(fxsi, baos.toString()); } catch (Exception exc) { exc.printStackTrace(); return null; } finally { try { if (writer != null) writer.close(); } catch (Exception exc) { /*ignore*/} try { if (baos != null) baos.close(); } catch (Exception exc) { /*ignore*/} try { if (document != null) document.close(); } catch (Exception exc) { /*ignore*/} } }
From source file:com.appeligo.showfiles.ShowFile.java
/** * @param response/*from ww w.j av a 2 s . co m*/ * @param out * @param path * @throws FileNotFoundException * @throws IOException */ private void showFlash(HttpServletResponse response, PrintWriter out, String path) throws FileNotFoundException, IOException { response.setContentType("application/x-shockwave-flash"); BufferedInputStream s = new BufferedInputStream(new FileInputStream(documentRoot + path)); int ch; while ((ch = s.read()) >= 0) { out.write(ch); } }
From source file:eu.stratosphere.nephele.jobmanager.web.JobmanagerInfoServlet.java
/** * Writes all updates (events) for a given job since a given time * /*from ww w.j a v a2 s.com*/ * @param wrt * @param jobId */ private void writeJsonUpdatesForJob(PrintWriter wrt, JobID jobId) { try { List<AbstractEvent> events = jobmanager.getEvents(jobId); //Serialize job to json wrt.write("{"); wrt.write("\"jobid\": \"" + jobId + "\","); wrt.write("\"timestamp\": \"" + System.currentTimeMillis() + "\","); wrt.write("\"recentjobs\": ["); boolean first = true; for (RecentJobEvent rje : jobmanager.getRecentJobs()) { if (first) { first = false; } else { wrt.write(","); } wrt.write("\"" + rje.getJobID().toString() + "\""); } wrt.write("],"); wrt.write("\"vertexevents\": ["); first = true; for (AbstractEvent event : events) { if (event instanceof ExecutionStateChangeEvent) { if (first) { first = false; } else { wrt.write(","); } ExecutionStateChangeEvent vertexevent = (ExecutionStateChangeEvent) event; wrt.write("{"); wrt.write("\"vertexid\": \"" + vertexevent.getVertexID() + "\","); wrt.write("\"newstate\": \"" + vertexevent.getNewExecutionState() + "\","); wrt.write("\"timestamp\": \"" + vertexevent.getTimestamp() + "\""); wrt.write("}"); } } wrt.write("],"); wrt.write("\"jobevents\": ["); first = true; for (AbstractEvent event : events) { if (event instanceof JobEvent) { if (first) { first = false; } else { wrt.write(","); } JobEvent jobevent = (JobEvent) event; wrt.write("{"); wrt.write("\"newstate\": \"" + jobevent.getCurrentJobStatus() + "\","); wrt.write("\"timestamp\": \"" + jobevent.getTimestamp() + "\""); wrt.write("}"); } } wrt.write("]"); wrt.write("}"); } catch (EofException eof) { // Connection closed by client LOG.info("Info server for jobmanager: Connection closed by client, EofException"); } catch (IOException ioe) { // Connection closed by client LOG.info("Info server for jobmanager: Connection closed by client, IOException"); } }
From source file:controllers.ServerController.java
public void askFinished(HttpServletRequest request, HttpServletResponse response) { try {/*from w w w . ja v a 2s .c om*/ PrintWriter out = response.getWriter(); String threadName = request.getParameter("threadName"); boolean isFinished = threadsList.get(threadName).isFinished(); if (isFinished) threadsList.remove(threadName); response.setContentType("application/json"); OperationStatus operationStatus = new OperationStatus(isFinished, "hola"); GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); out.write(gson.toJson(operationStatus)); } catch (IOException ex) { Logger.getLogger(ServerController.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.olegchir.wicket_spring_security_example.init.CsrfTokenFilter.java
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { //Inspired by Spring documentation: //http://spring.io/blog/2013/08/21/spring-security-3-2-0-rc1-highlights-csrf-protection/ //http://docs.spring.io/spring-security/site/docs/3.2.0.CI-SNAPSHOT/reference/html/csrf.html //And this discussion about Tymeleaf: //http://stackoverflow.com/questions/23669424/cant-create-csrf-token-with-spring-security //Set HTTP Headers CsrfToken token = (CsrfToken) request.getAttribute("_csrf"); // Spring Security will allow the Token to be included in this header name response.setHeader("X-CSRF-HEADER", token.getHeaderName()); // Spring Security will allow the token to be included in this parameter name response.setHeader("X-CSRF-PARAM", token.getParameterName()); // this is the value of the token to be included as either a header or an HTTP parameter response.setHeader("X-CSRF-TOKEN", token.getToken()); //Modify HTML // Wrap the response in a wrapper so we can get at the text after calling the next filter PrintWriter out = response.getWriter(); CharResponseWrapper wrapper = new CharResponseWrapper((HttpServletResponse) response); filterChain.doFilter(request, wrapper); String modifiedHtml = wrapper.toString(); // Extract the text from the completed servlet and apply the regexes modifiedHtml = modifiedHtml.replace("${_csrf.token}", token.getToken()); modifiedHtml = modifiedHtml.replace("${_csrf.parameterName}", token.getParameterName()); modifiedHtml = modifiedHtml.replace("${_csrf.headerName}", token.getHeaderName()); // Write our modified text to the real response response.setContentLength(modifiedHtml.getBytes().length); out.write(modifiedHtml); out.close();//from ww w . ja va 2s .c o m }
From source file:controllers.ServerController.java
public void download(HttpServletRequest request, HttpServletResponse response) throws IOException, InterruptedException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); //indicar el archivo String filename = "consultas.txt"; //la ruta donde esta el archivo dentro de cups String filepath = "/opt"; response.setContentType("APPLICATION/OCTET-STREAM"); response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); FileInputStream fileInputStream = new FileInputStream(filepath + filename); int i;/*w w w . j av a 2 s . c o m*/ while ((i = fileInputStream.read()) != -1) out.write(i); fileInputStream.close(); out.close(); }
From source file:edu.vt.vbi.patric.portlets.IDMapping.java
@SuppressWarnings("unchecked") public void serveResource(ResourceRequest request, ResourceResponse response) throws PortletException, IOException { String sraction = request.getParameter("sraction"); if (sraction != null && sraction.equals("save_params")) { Map<String, String> key = new HashMap<>(); String keyword = request.getParameter("keyword"); String from = request.getParameter("from"); String fromGroup = request.getParameter("fromGroup"); String to = request.getParameter("to"); String toGroup = request.getParameter("toGroup"); if (!keyword.equals("")) { key.put("keyword", keyword.replaceAll("\n", " OR ").replaceAll(",", " OR ")); }//from w w w .j av a 2 s . c o m key.put("from", from); key.put("to", to); key.put("fromGroup", fromGroup); key.put("toGroup", toGroup); // random long pk = (new Random()).nextLong(); SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, jsonWriter.writeValueAsString(key)); PrintWriter writer = response.getWriter(); writer.write("" + pk); writer.close(); } else if (sraction != null && sraction.equals("filters")) { // this.responseWriteFilters(response); this.responseWriteFiltersStatic(response); } else if (sraction != null && sraction.equals("download")) { processDownload(request, response); } else { DataApiHandler dataApi = new DataApiHandler(request); String pk = request.getParameter("pk"); Map<String, String> key = jsonReader .readValue(SessionHandler.getInstance().get(SessionHandler.PREFIX + pk)); LOGGER.debug("id mapping param: {}", key); JSONObject jsonResult = processIDMapping(dataApi, key.get("from"), key.get("fromGroup"), key.get("to"), key.get("toGroup"), key.get("keyword")); response.setContentType("application/json"); jsonResult.writeJSONString(response.getWriter()); } }
From source file:com.esri.gpt.sdisuite.IntegrationLinkServlet.java
/** * Writes characters to the response stream. * @param response the servlet response// www. jav a2s. c o m * @param content the content to write * @param charset the response character encoding * @param contentType the response content type * @throws IOException if an IO exception occurs */ private void writeCharacterResponse(HttpServletResponse response, String content, String charset, String contentType) throws IOException { PrintWriter writer = null; try { if (content.length() > 0) { response.setCharacterEncoding(charset); response.setContentType(contentType); writer = response.getWriter(); writer.write(content); writer.flush(); } } finally { try { if (writer != null) { writer.flush(); writer.close(); } } catch (Exception ef) { LOGGER.log(Level.SEVERE, "Error closing PrintWriter.", ef); } } }
From source file:it.anggen.generation.WebappGenerator.java
private void generateForbiddenJsp_old() { HtmlCanvas html = new HtmlCanvas(); try {/* w w w. j a v a 2 s . c om*/ html.render(HtmlGenerator.docType); html.html().head().title().content("Access forbidden"); htmlGenerator.incluseCssFiles(html); htmlGenerator.includeJavascriptScripts(html, false); html._head().body().content("Access forbidden!!!")._html(); File file = new File(""); String directoryViewPages = file.getAbsolutePath() + generator.htmlDirectory + "/"; File dir = new File(directoryViewPages); if (!dir.exists()) dir.mkdirs(); File myJsp = new File(directoryViewPages + "forbidden.jsp"); PrintWriter writer; try { System.out.println("Written " + myJsp.getAbsolutePath()); writer = new PrintWriter(myJsp, "UTF-8"); writer.write(html.toHtml()); writer.close(); } catch (FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }