@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { throw new ServletException("Only HttpServletRequest requests are supported"); } final HttpServletRequest httpRequest = (HttpServletRequest) request; final HttpServletResponse httpResponse = (HttpServletResponse) response; // extract the callback method from the request query parameters String callback = getCallbackMethod(httpRequest); if (!isJSONPRequest(callback)) { // Request is not a JSONP request move on chain.doFilter(request, response); } else { // Need to check if the callback method is safe if (!SAFE_PRN.matcher(callback).matches()) { throw new ServletException( "JSONP Callback method '" + CALLBACK_METHOD + "' parameter not valid function"); } // Will stream updated response final ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); // Create a custom response wrapper to adding in the padding HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(httpResponse) { @Override public ServletOutputStream getOutputStream() throws IOException { return new ServletOutputStream() { @Override public void write(int b) throws IOException { byteStream.write(b); } }; } @Override public PrintWriter getWriter() throws IOException { return new PrintWriter(byteStream); } }; // Process the rest of the filter chain, including the JAX-RS request chain.doFilter(request, responseWrapper); // Override response content and encoding response.setContentType(CONTENT_TYPE); response.setCharacterEncoding("UTF-8"); // Write the padded updates to the output stream. response.getOutputStream().write((callback + "(").getBytes()); response.getOutputStream().write(byteStream.toByteArray()); response.getOutputStream().write(");".getBytes()); } }
private void sendProcessingError(Throwable t, ServletResponse response) { String stackTrace = getStackTrace(t); if (stackTrace != null && !stackTrace.equals("")) { try { response.setContentType("text/html"); PrintStream ps = new PrintStream(response.getOutputStream()); PrintWriter pw = new PrintWriter(ps); pw.print("<html>\n<head>\n<title>Error</title>\n</head>\n<body>\n"); // NOI18N // PENDING! Localize this for next official release pw.print("<h1>The resource did not process correctly</h1>\n<pre>\n"); pw.print(stackTrace); pw.print("</pre></body>\n</html>"); // NOI18N pw.close(); ps.close(); response.getOutputStream().close(); } catch (Exception ex) { } } else { try { PrintStream ps = new PrintStream(response.getOutputStream()); t.printStackTrace(ps); ps.close(); response.getOutputStream().close(); } catch (Exception ex) { } } }
@Override public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { servletResponse.getOutputStream().print("["); filterChain.doFilter(servletRequest, servletResponse); servletResponse.getOutputStream().print("]"); }
/* ------------------------------------------------------------ */ private void commitResponse(ServletResponse response, Request baseRequest) throws IOException { if (baseRequest.getResponse().isWriting()) { try { response.getWriter().close(); } catch (IllegalStateException e) { response.getOutputStream().close(); } } else { try { response.getOutputStream().close(); } catch (IllegalStateException e) { response.getWriter().close(); } } }
@Override public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { String attributesToEncryptPropertyFileName = request.getParameter(ATTRIBUTES_TO_ENCRYPT_PROPERTIES); if (StringUtils.isBlank(attributesToEncryptPropertyFileName)) { throw new IllegalArgumentException( "No valid " + ATTRIBUTES_TO_ENCRYPT_PROPERTIES + " parameter was passed to this Servlet."); } boolean checkOjbEncryptConfig = true; String checkOjbEncryptConfigValue = request.getParameter(CHECK_OJB_ENCRYPT_CONFIG); if (!StringUtils.isBlank(checkOjbEncryptConfigValue)) { checkOjbEncryptConfig = Boolean.valueOf(checkOjbEncryptConfigValue).booleanValue(); } execute(attributesToEncryptPropertyFileName, checkOjbEncryptConfig); response .getOutputStream() .write( ("<html><body><p>Successfully encrypted attributes as defined in: " + attributesToEncryptPropertyFileName + "</p></body></html>") .getBytes()); }
/** * @see {@link ExternalContext#getResponseOutputStream()} * @since JSF 2.0 */ @Override public OutputStream getResponseOutputStream() throws IOException { if (portletResponse instanceof MimeResponse) { if (facesImplementationServletResponse != null) { logger.debug( "Delegating to AFTER_VIEW_CONTENT servletResponse=[{0}]", facesImplementationServletResponse); return facesImplementationServletResponse.getOutputStream(); } else { MimeResponse mimeResponse = (MimeResponse) portletResponse; return mimeResponse.getPortletOutputStream(); } } else { if (manageIncongruities) { return incongruityContext.getResponseOutputStream(); } else { throw new IllegalStateException(); } } }
// --> /demo/getAudio/getAudio @RequestMapping(value = "/getAudio", method = RequestMethod.GET) @ResponseBody public void getAudio(ServletResponse response) throws IOException { File imageFile = new File("E:\\My Music\\Nhac Chuong\\Sinbad.mp3"); byte[] byteArray = IOUtils.toByteArray(new FileInputStream(imageFile)); response.setContentType("audio/mpeg"); response.getOutputStream().write(byteArray); }
// --> /demo/getAudio/getImage @RequestMapping(value = "/getImage", method = RequestMethod.GET) @ResponseBody public void getImage(ServletResponse response) throws IOException { File imageFile = new File("E:\\Hinh Anh\\WP_000337.png"); byte[] byteArray = IOUtils.toByteArray(new FileInputStream(imageFile)); response.setContentType("image/png"); response.getOutputStream().write(byteArray); }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (null != request.getAttribute("FLAG")) { chain.doFilter(request, response); return; } request.setAttribute("FLAG", FLAG); String encoding = this.encoding; HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; String resourcePath = req.getServletPath(); RequestContext requestContext = new RequestContext(config.getServletContext(), req, resourcePath); request.setAttribute("context", requestContext); for (Decorator decorator : decorators) { int returned = decorator.parseRequest(req, res, requestContext); switch (returned) { case Decorator.OK: // do nothing break; case Decorator.REDIRECT: res.sendRedirect(requestContext.getResourcePath()); return; case Decorator.MOVED_PERMANENTLY: res.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); res.setHeader("Location", requestContext.getResourcePath()); return; default: // do nothing } } if (pattern.matcher(requestContext.getResourcePath()).matches()) { WebContent content = new WebContent(); if (requestContext.getResourcePath().startsWith("/WEB-INF/admin/")) { encoding = "UTF-8"; } ByteArrayResponseWrapper wrapper = new ByteArrayResponseWrapper(res); request.getRequestDispatcher(requestContext.getResourcePath()).include(req, wrapper); wrapper.finish(); content.setWholeContent(wrapper.getString(encoding)); response.setContentType(wrapper.getContentType()); content.finish(); for (Decorator decorator : decorators) { decorator.decorate(requestContext, content, content); content.finish(); } byte[] theContent = content.toString().getBytes(encoding); response.setContentLength(theContent.length); response.getOutputStream().write(theContent); return; } request.getRequestDispatcher(requestContext.getResourcePath()).forward(req, res); }
/** * @param pServletRequest parameter * @param pServletResponse parameter * @throws IOException exception * @throws ServletException exception */ @Override public void handleService(ServletRequest pServletRequest, ServletResponse pServletResponse) throws IOException, ServletException { final ByteArrayOutputStream pdf = new ByteArrayOutputStream(); final String deliveryId = pServletRequest.getParameter(DELIVERY_ID_PARAM); RepositoryItem orderBOItem = mOrderManager.getFactureBO(deliveryId); OutputStream out = null; if (orderBOItem != null) { RepositoryItem orderFOItem = mOrderManager.getOrderFO(orderBOItem); String profileId = (String) orderFOItem.getPropertyValue(CastoConstantesOrders.ORDER_PROPERTY_PROFILEID); String currProfileId = getProfileServices().getCurrentProfileId(); if (!currProfileId.equalsIgnoreCase(profileId)) { if (isLoggingError()) { logError( "Facture with id=" + deliveryId + " doesn't belong to profile with id=" + currProfileId); } return; } Map params = new HashMap(); params.put( "url", pServletRequest.getScheme() + "://" + pServletRequest.getServerName() + ":" + pServletRequest.getServerPort()); try { PrintPdfHelper.getInstance().generateInvoicePdf(pdf, orderBOItem, params, mCountryList); // Set header pServletResponse.setContentType(CONTENT_TYPE_PDF); pServletResponse.setContentLength(pdf.size()); out = pServletResponse.getOutputStream(); pdf.writeTo(out); out.flush(); } catch (IOException e) { logError(e); } finally { if (out != null) { out.close(); } } } else { logError("Facture with id=" + deliveryId + " was not found."); } // end if-else }
protected void writeData(ServletResponse response, String data) throws IOException { idleCheck.activity(); Log.debug("Session[" + session.getSessionId() + "]: writeData(START): " + data); ServletOutputStream os = response.getOutputStream(); os.println("Content-Type: text/plain"); os.println(); os.println(data); os.println(boundarySeperator); response.flushBuffer(); Log.debug("Session[" + session.getSessionId() + "]: writeData(END): " + data); }
@Override public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; checkOutput: { if (!configurer.determineEnvironment().equals(configurer.getDefaultEnvironment()) || useWhileInDefaultEnvironment) { String path = getResourcePath(request); String gzipPath = path + ".gz"; if (useGzipCompression(request, response, path, gzipPath)) { File output = new File(getServletContext().getRealPath(gzipPath)); if (output.exists()) { response.addHeader("Content-Encoding", "gzip"); ServletOutputStream sos = servletResponse.getOutputStream(); BufferedInputStream bis = null; try { bis = new BufferedInputStream(new FileInputStream(output)); boolean eof = false; while (!eof) { int temp = bis.read(); if (temp < 0) { eof = true; } else { sos.write(temp); } } } finally { sos.flush(); try { if (bis != null) { bis.close(); } } catch (Exception e) { // do nothing } } break checkOutput; } } } chain.doFilter(request, response); } }
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { List list = (List) ((HttpServletRequest) req).getSession().getAttribute("regionhistoryinfo"); String historydate = (String) ((HttpServletRequest) req).getSession().getAttribute("mystatdate"); res.setContentType("image/jpeg"); String title = null; if (list.size() == 0) { logger.info("list is null"); } else { title = historydate + "各地市短信发送情况显示图"; JFreeChart jfreechart = createChart(getDataSet(list), title); int width = 700; int height = 490; Font font = new Font("黑体", Font.CENTER_BASELINE, 12); ChartUtilities.writeChartAsJPEG(res.getOutputStream(), 1.0f, jfreechart, width, height, null); } }
@Override public void service( javax.servlet.ServletRequest servletRequest, javax.servlet.ServletResponse servletResponse) throws ServletException, IOException { HttpServletRequest req = (HttpServletRequest) servletRequest; HttpServletResponse resp = (HttpServletResponse) servletResponse; try { setThreadlocals(req, resp); tlServletConfig.set(config); Request request = new ServletRequest(req, servletContext); Response response = new ServletResponse(resp); httpManager.process(request, response); } finally { clearThreadlocals(); tlServletConfig.remove(); ServletRequest.clearThreadLocals(); servletResponse.getOutputStream().flush(); servletResponse.flushBuffer(); } }
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; response.setContentType("image/png"); response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expire", 0); try { Session session = SecurityUtils.getSubject().getSession(); String token = EncoderHelper.getChallangeAndWriteImage(captchaService, "png", res.getOutputStream()); session.removeAttribute(KEY_CAPTCHA); session.setAttribute(KEY_CAPTCHA, token); } catch (Exception e) { e.printStackTrace(); } }
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { ServletOutputStream sos = null; try { sos = response.getOutputStream(); // set buffer size response.setBufferSize(FAILED.length() * 2); // Write some data to the stream sos.println(FAILED); // Reset the response response.reset(); sos.println(PASSED); } catch (IllegalStateException e) { throw e; } }
@Override public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { String mitabUrl = request.getParameter("mitabUrl"); String url = mitabUrl.substring(0, mitabUrl.lastIndexOf("/")); String query = mitabUrl.substring(mitabUrl.lastIndexOf("/")); if (query != null) { query = UrlUtils.encodeUrl(query); String encodedUrl = url + query; if (log.isDebugEnabled()) log.debug("encodedUrl: " + encodedUrl); final URL inputUrl = new URL(encodedUrl); final InputStream is = inputUrl.openStream(); ServletOutputStream stream = response.getOutputStream(); try { response.setContentType("text/plain"); final Tab2Cytoscapeweb tab2Cytoscapeweb = new Tab2Cytoscapeweb(); String output = null; try { output = tab2Cytoscapeweb.convert(is); } catch (PsimiTabException e) { throw new IllegalStateException("Could not parse input MITAB.", e); } stream.write(output.getBytes()); stream.flush(); } finally { is.close(); } } } // We don't have url
/** @see javax.faces.context.ExternalContext#getResponseOutputStream() */ @Override public OutputStream getResponseOutputStream() throws IOException { return response.getOutputStream(); }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; if (!isIncluded(httpRequest) && acceptsGZipEncoding(httpRequest) && !response.isCommitted()) { // Client accepts zipped content if (log.isTraceEnabled()) { log.trace("{} Written with gzip compression", httpRequest.getRequestURL()); } // Create a gzip stream final ByteArrayOutputStream compressed = new ByteArrayOutputStream(); final GZIPOutputStream gzout = new GZIPOutputStream(compressed); // Handle the request final GZipServletResponseWrapper wrapper = new GZipServletResponseWrapper(httpResponse, gzout); wrapper.setDisableFlushBuffer(true); chain.doFilter(request, wrapper); wrapper.flush(); gzout.close(); // double check one more time before writing out // repsonse might have been committed due to error if (response.isCommitted()) { return; } // return on these special cases when content is empty or unchanged switch (wrapper.getStatus()) { case HttpServletResponse.SC_NO_CONTENT: case HttpServletResponse.SC_RESET_CONTENT: case HttpServletResponse.SC_NOT_MODIFIED: return; default: } // Saneness checks byte[] compressedBytes = compressed.toByteArray(); boolean shouldGzippedBodyBeZero = GZipResponseUtil.shouldGzippedBodyBeZero(compressedBytes, httpRequest); boolean shouldBodyBeZero = GZipResponseUtil.shouldBodyBeZero(httpRequest, wrapper.getStatus()); if (shouldGzippedBodyBeZero || shouldBodyBeZero) { // No reason to add GZIP headers or write body if no content was written or status code // specifies no // content response.setContentLength(0); return; } // Write the zipped body GZipResponseUtil.addGzipHeader(httpResponse); response.setContentLength(compressedBytes.length); response.getOutputStream().write(compressedBytes); } else { // Client does not accept zipped content - don't bother zipping if (log.isTraceEnabled()) { log.trace( "{} Written without gzip compression because the request does not accept gzip", httpRequest.getRequestURL()); } chain.doFilter(request, response); } }
/** * Writes the given object as response body to the servlet response * * <p>The content type will be set to {@link HttpConstants#CONTENT_TYPE_JAVA_SERIALIZED_OBJECT} * * @param response servlet response * @param target object to write * @throws IOException is thrown if error writing */ public static void writeObjectToServletResponse(ServletResponse response, Object target) throws IOException { response.setContentType(HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT); writeObjectToStream(response.getOutputStream(), target); }
protected void writeJSON(JSONObject object, ServletResponse resp) throws IOException { resp.setContentType("application/json"); OutputStreamWriter writer = new OutputStreamWriter(resp.getOutputStream(), "utf-8"); writer.write(object.toString()); writer.flush(); }
public ServletOutputStream getOutputStream() throws IOException { return response.getOutputStream(); }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { chain.doFilter(request, response); ServletOutputStream os = response.getOutputStream(); os.print("Hello"); }
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; String requestPath; if (request.getQueryString() == null) { requestPath = request.getRequestURI(); } else { requestPath = request.getRequestURI() + "?" + request.getQueryString(); } String key = null; String keyFromHeader = request.getHeader("API-Key"); String keyFromParam = request.getParameter("api_key"); if (keyFromHeader == keyFromParam) { key = keyFromHeader; } else { if (keyFromHeader == null) { key = keyFromParam; } else if (keyFromParam == null) { key = keyFromHeader; } else { // Keys don't match. Don't continue. ErrorJSONObject errorObj = new ErrorJSONObject( "API key presented in Header does not match API key presented as URL Parameter."); ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); String json = ow.writeValueAsString(errorObj); res.getOutputStream().write(json.getBytes()); } } if (key == null) { for (int i = 0; i < ALLOWED_REQUEST_PATHS.length; i++) { if (request.getServletPath().matches(ALLOWED_REQUEST_PATHS[i])) { chain.doFilter(req, res); // continue return; } } // No Key. Don't continue. ErrorJSONObject errorObj = new ErrorJSONObject("API key must be presented in order to use this API"); ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); String json = ow.writeValueAsString(errorObj); res.getOutputStream().write(json.getBytes()); } else { ApiKeyDTO retrievedKey = apiKeyManager.findKey(key); if (retrievedKey == null) { // Invalid key. Don't continue. ErrorJSONObject errorObj = new ErrorJSONObject("Invalid API Key"); ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); String json = ow.writeValueAsString(errorObj); res.getOutputStream().write(json.getBytes()); } else { try { apiKeyManager.logApiKeyActivity(key, requestPath); } catch (EntityCreationException e) { throw new ServletException(e); } chain.doFilter(req, res); // continue } } }
@Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { if (req instanceof HttpServletRequest && resp instanceof HttpServletResponse) { HttpServletRequest httpReq = ((HttpServletRequest) req); HttpServletResponse httpResp = ((HttpServletResponse) resp); String requestEnrichment = httpReq.getHeader(ENRICHMENT_REQUEST); if (requestEnrichment != null && !"null".equals(requestEnrichment)) { final AtomicReference<NonWritingServletOutputStream> stream = new AtomicReference<NonWritingServletOutputStream>(); final AtomicReference<NonWritingPrintWriter> writer = new AtomicReference<NonWritingPrintWriter>(); HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper((HttpServletResponse) resp) { @Override public ServletOutputStream getOutputStream() throws IOException { stream.set(new NonWritingServletOutputStream()); return stream.get(); } @Override public PrintWriter getWriter() throws IOException { writer.set(NonWritingPrintWriter.newInstance()); return writer.get(); } }; String responseEnrichment = "null"; try { RequestPayload requestPayload = SerializationUtils.deserializeFromBase64(requestEnrichment); ServerAssertion serverAssertion = requestPayload.getAssertion(); ManagerBuilder builder = ManagerBuilder.from().extension(Class.forName(DEFAULT_EXTENSION_CLASS)); Manager manager = builder.create(); manager.start(); manager.bind(ApplicationScoped.class, Manager.class, manager); manager.inject(this); req.setAttribute( WarpCommons.LIFECYCLE_MANAGER_STORE_REQUEST_ATTRIBUTE, lifecycleManagerStore); manager.fire(new BeforeSuite()); manager.fire(new BeforeRequest(req)); lifecycleManagerStore.get().bind(ServletRequest.class, req); assertionRegistry.get().registerAssertion(serverAssertion); lifecycleManager.get().fireLifecycleEvent(new BeforeServletEvent()); try { chain.doFilter(req, responseWrapper); lifecycleManager.get().fireLifecycleEvent(new AfterServletEvent()); // request successfully finished TestResult firstFailedResult = testResultStore.get().getFirstFailed(); if (firstFailedResult == null) { ResponsePayload responsePayload = new ResponsePayload(serverAssertion); responseEnrichment = SerializationUtils.serializeToBase64(responsePayload); httpResp.setHeader(ENRICHMENT_RESPONSE, responseEnrichment); } else { Throwable throwable = firstFailedResult.getThrowable(); if (throwable instanceof InvocationTargetException) { throwable = throwable.getCause(); } ResponsePayload responsePayload = new ResponsePayload(throwable); enrichResponse(httpResp, responsePayload); } } catch (Exception e) { log.log(Level.SEVERE, "The error occured during request execution", e); throw e; } finally { assertionRegistry.get().unregisterAssertion(serverAssertion); lifecycleManagerStore.get().unbind(ServletRequest.class, req); manager.fire(new AfterRequest(req)); manager.fire(new AfterSuite()); } } catch (Throwable e) { // exception occured during request execution ResponsePayload responsePayload = new ResponsePayload(e); responseEnrichment = SerializationUtils.serializeToBase64(responsePayload); httpResp.setHeader(ENRICHMENT_RESPONSE, responseEnrichment); httpResp.sendError(500); } if (writer.get() != null) { writer.get().finallyWriteAndClose(resp.getOutputStream()); } if (stream.get() != null) { stream.get().finallyWriteAndClose(resp.getOutputStream()); } return; } } chain.doFilter(req, resp); }
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; String r = sc.getRealPath(""); String path = fc.getInitParameter(request.getRequestURI()); if (path != null && path.equals("nocache")) { chain.doFilter(request, response); return; } path = r + path; String id = request.getRequestURI() + request.getQueryString(); String localeSensitive = fc.getInitParameter("locale-sensitive"); if (localeSensitive != null) { StringWriter ldata = new StringWriter(); Enumeration locales = request.getLocales(); while (locales.hasMoreElements()) { Locale locale = (Locale) locales.nextElement(); ldata.write(locale.getISO3Language()); } id = id + ldata.toString(); } File tempDir = (File) sc.getAttribute("javax.servlet.context.tempdir"); String temp = tempDir.getAbsolutePath(); File file = new File(temp + id); if (path == null) { path = sc.getRealPath(request.getRequestURI()); } File current = new File(path); try { long now = Calendar.getInstance().getTimeInMillis(); if (!file.exists() || (file.exists() && current.lastModified() > file.lastModified()) || cacheTimeout < now - file.lastModified()) { String name = file.getAbsolutePath(); name = name.substring(0, name.lastIndexOf("/") == -1 ? 0 : name.lastIndexOf("/")); new File(name).mkdirs(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); CacheResponseWrapper wrappedResponse = new CacheResponseWrapper(response, baos); chain.doFilter(req, wrappedResponse); FileOutputStream fos = new FileOutputStream(file); fos.write(baos.toByteArray()); fos.flush(); fos.close(); } } catch (ServletException e) { if (!file.exists()) { throw new ServletException(e); } } catch (IOException e) { if (!file.exists()) { throw e; } } FileInputStream fis = new FileInputStream(file); String mt = sc.getMimeType(request.getRequestURI()); response.setContentType(mt); ServletOutputStream sos = res.getOutputStream(); for (int i = fis.read(); i != -1; i = fis.read()) { sos.write((byte) i); } }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { response.getOutputStream().println("Extra Info"); chain.doFilter(request, response); }
public void service(ServletRequest request, ServletResponse response) { int font; pdflib p = null; int i, blockcontainer, page; String infile = "boilerplate.pdf"; /* This is where font/image/PDF input files live. Adjust as necessary. * * Note that this directory must also contain the LuciduxSans font * outline and metrics files. */ String searchpath = "../data"; String[][] data = { {"name", "Victor Kraxi"}, {"business.title", "Chief Paper Officer"}, {"business.address.line1", "17, Aviation Road"}, {"business.address.city", "Paperfield"}, {"business.telephone.voice", "phone +1 234 567-89"}, {"business.telephone.fax", "fax +1 234 567-98"}, {"business.email", "*****@*****.**"}, {"business.homepage", "www.kraxi.com"}, }; byte[] buf; ServletOutputStream out; try { p = new pdflib(); // Generate a PDF in memory; insert a file name to create PDF on disk if (p.begin_document("", "") == -1) { throw new Exception("Error: " + p.get_errmsg()); } /*Set the search path for fonts and PDF files */ p.set_parameter("SearchPath", searchpath); p.set_info("Creator", "businesscard.java"); p.set_info("Author", "Thomas Merz"); p.set_info("Title", "PDFlib block processing sample (Java)"); blockcontainer = p.open_pdi(infile, "", 0); if (blockcontainer == -1) { throw new Exception("Error: " + p.get_errmsg()); } page = p.open_pdi_page(blockcontainer, 1, ""); if (page == -1) { throw new Exception("Error: " + p.get_errmsg()); } p.begin_page_ext(20, 20, ""); // dummy page size // This will adjust the page size to the block container's size. p.fit_pdi_page(page, 0, 0, "adjustpage"); // Fill all text blocks with dynamic data for (i = 0; i < (int) data.length; i++) { if (p.fill_textblock(page, data[i][0], data[i][1], "embedding encoding=unicode") == -1) { System.err.println("Warning: " + p.get_errmsg()); } } p.end_page_ext(""); // close page p.close_pdi_page(page); p.end_document(""); // close PDF document p.close_pdi(blockcontainer); buf = p.get_buffer(); response.setContentType("application/pdf"); response.setContentLength(buf.length); out = response.getOutputStream(); out.write(buf); out.close(); } catch (PDFlibException e) { System.err.print("PDFlib exception occurred in businesscard sample:\n"); System.err.print( "[" + e.get_errnum() + "] " + e.get_apiname() + ": " + e.get_errmsg() + "\n"); } catch (Exception e) { System.err.println(e.getMessage()); } finally { if (p != null) { p.delete(); /* delete the PDFlib object */ } } }