List of usage examples for javax.servlet ServletOutputStream write
public abstract void write(int b) throws IOException;
From source file:info.toegepaste.www.service.PdfServiceImpl.java
@Override public void exportPdf(File temp) throws FileNotFoundException, IOException { FacesContext fc = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse(); response.setHeader("Content-Disposition", "attachment; filename=rapport.pdf"); response.setContentLength((int) temp.length()); ServletOutputStream out = null; FileInputStream input = new FileInputStream(temp); byte[] buffer = new byte[1024]; out = response.getOutputStream();/* w w w .j av a 2 s .c om*/ int i = 0; while ((i = input.read(buffer)) != -1) { out.write(buffer); out.flush(); } fc.responseComplete(); }
From source file:net.sourceforge.fenixedu.presentationTier.Action.manager.enrolments.CurriculumLineLogsDA.java
public ActionForward viewCurriculumLineLogStatisticsChartOperations(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException { final ExecutionSemester executionSemester = getDomainObject(request, "executionSemesterId"); if (executionSemester != null) { final CurriculumLineLogStatisticsCalculator curriculumLineLogStatisticsCalculator = new CurriculumLineLogStatisticsCalculator( executionSemester);/* w ww . j av a 2 s. c o m*/ ServletOutputStream writer = null; try { writer = response.getOutputStream(); response.setContentType("image/jpeg"); writer.write(curriculumLineLogStatisticsCalculator.getOperationsChart()); writer.flush(); } finally { writer.close(); response.flushBuffer(); } } return null; }
From source file:org.gcaldaemon.core.servlet.ServletListener.java
private final void processRequest(HttpServletRequest req, HttpServletResponse rsp, boolean getMethod) throws ServletException, IOException { try {//www . j a va 2 s . c o m // Transform HttpServletRequest to Request Request request = new Request(); request.method = getMethod ? GET_METHOD : PUT_METHOD; // Transform URL request.url = req.getPathInfo(); int i = request.url.indexOf('@'); if (i != -1) { request.url = request.url.substring(0, i) + "%40" + request.url.substring(i + 1); } // Get the properties of the request HashMap properties = new HashMap(); Enumeration names = req.getHeaderNames(); String header; while (names.hasMoreElements()) { header = (String) names.nextElement(); properties.put(formatString(header.toCharArray()), req.getHeader(header)); } // Transform username and password header = (String) properties.get(AUTHORIZATION); if (header != null && header.startsWith(BASIC)) { header = StringUtils.decodeBASE64(header.substring(6)); int n = header.indexOf(COLON); if (n != 0) { request.username = header.substring(0, n); } if (n != header.length() - 1) { request.password = header.substring(n + 1); } } // Get Content-Length header int contentLength = 0; header = (String) properties.get(CONTENT_LENGTH); if (header != null && header.length() != 0) { contentLength = Integer.parseInt(header); } // Read body if (contentLength != 0) { int packet, readed = 0; request.body = new byte[contentLength]; ServletInputStream in = req.getInputStream(); while (readed != contentLength) { packet = in.read(request.body, readed, contentLength - readed); if (packet == -1) { throw new EOFException(); } readed += packet; } } // Redirect request to superclass Response response; if (getMethod) { response = doGet(request); } else { response = doPut(request); } // Set response status rsp.setStatus(response.status); // Add unauthorized header and realm if (response.status == STATUS_UNAUTHORIZED) { String realm = null; int s, e = request.url.indexOf("%40"); if (e != -1) { s = request.url.lastIndexOf('/', e); if (s != -1) { realm = request.url.substring(s + 1, e).replace('.', ' '); } } if (realm == null) { s = request.url.indexOf("private"); if (s != -1) { e = request.url.indexOf('/', s + 7); if (e != -1) { realm = request.url.substring(s + 8, e); } } } if (realm == null || realm.length() == 0) { realm = "Google Account"; } rsp.addHeader("WWW-Authenticate", "Basic realm=\"" + realm + '\"'); } // Write body ServletOutputStream out = null; try { out = rsp.getOutputStream(); out.write(response.body); } finally { if (out != null) { try { out.close(); } catch (Exception ignored) { } } } } catch (Exception processingError) { throw new ServletException("Unable to process " + req.getMethod() + " request!", processingError); } }
From source file:com.kolich.spring.views.mappers.KolichMappingPNGView.java
@Override public void myRenderMergedOutputModel(final KolichViewSerializable payload, final HttpServletRequest request, final HttpServletResponse response) throws Exception { final ServletOutputStream os = response.getOutputStream(); // Be sure to set the Content-Length header on a MP3 audio file // response to the client (some MP3 players don't like chunked // transfer encoding so this fixes that). final byte[] bytes = payload.getEntity().getBytes(); response.setContentLength(bytes.length); os.write(bytes); // Quietly close the output stream. IOUtils.closeQuietly(os);/*from w w w .j a v a 2s. c om*/ }
From source file:org.wso2.carbon.bpel.ui.bpel2svg.PNGGenarateServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request// www . j a va 2 s. c o m * @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 { Log log = LogFactory.getLog(PNGGenarateServlet.class); HttpSession session = request.getSession(true); String pid = CharacterEncoder.getSafeText(request.getParameter("pid")); ServletConfig config = getServletConfig(); String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); ConfigurationContext configContext = (ConfigurationContext) config.getServletContext() .getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); String processDef; ProcessManagementServiceClient client; SVGInterface svg; String svgStr; try { client = new ProcessManagementServiceClient(cookie, backendServerURL, configContext, request.getLocale()); //Gets the bpel process definition needed to create the SVG from the processId processDef = client.getProcessInfo(QName.valueOf(pid)).getDefinitionInfo().getDefinition() .getExtraElement().toString(); BPELInterface bpel = new BPELImpl(); //Converts the bpel process definition to an omElement which is how the AXIS2 Object Model (AXIOM) // represents an XML document OMElement bpelStr = bpel.load(processDef); /** * Process the OmElement containing the bpel process definition * Process the subactivites of the bpel process by iterating through the omElement * */ bpel.processBpelString(bpelStr); //Create a new instance of the LayoutManager for the bpel process LayoutManager layoutManager = BPEL2SVGFactory.getInstance().getLayoutManager(); //Set the layout of the SVG to vertical layoutManager.setVerticalLayout(true); //Get the root activity i.e. the Process Activity layoutManager.layoutSVG(bpel.getRootActivity()); svg = new SVGImpl(); //Set the root activity of the SVG i.e. the Process Activity svg.setRootActivity(bpel.getRootActivity()); //Set the content type of the HTTP response as "image/png" response.setContentType("image/png"); //Create an instance of ServletOutputStream to write the output ServletOutputStream sos = response.getOutputStream(); //Convert the image as a byte array of a PNG byte[] pngBytes = svg.toPNGBytes(); // stream to write binary data into the response sos.write(pngBytes); sos.flush(); sos.close(); } catch (ProcessManagementException e) { log.error("PNG Generation Error", e); } }
From source file:org.cloudifysource.cloudformation.converter.CloudifyPrivateEc2ConverterController.java
private void returnErrorMessage(final HttpServletResponse response, final String message) throws IOException { final String errorMessage = String.format("{\"status\":\"error\", \"error\":\"%s\"}", message); final ServletOutputStream outputStream = response.getOutputStream(); final byte[] messageBytes = errorMessage.getBytes(); outputStream.write(messageBytes); }
From source file:com.seer.datacruncher.spring.ForgetPasswordController.java
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean isEmailSent = false; String userName = request.getParameter("userName"); String email = request.getParameter("email"); ServletOutputStream out = null; response.setContentType("application/json"); out = response.getOutputStream();//from ww w .j a v a 2s . c o m if (userName == null || "".equalsIgnoreCase(userName.trim())) { out.write("userNameRequired".getBytes()); out.flush(); out.close(); return null; } if (email == null || "".equalsIgnoreCase(email.trim())) { out.write("emailRequired".getBytes()); out.flush(); out.close(); return null; } UserEntity userEntity = new UserEntity(); userEntity = usersDao.findUserByNameNMailId(userName, email); ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd")); Update updateResult = new Update(); if (userEntity != null) { String tempPassword = RandomStringUtils.randomAlphanumeric(4); userEntity.setPassword(tempPassword); updateResult = usersDao.update(userEntity); if (updateResult.isSuccess()) { MailConfig mailConfig = new MailConfig(); mailConfig.setMailTo(userEntity.getEmail()); mailConfig.setMailFrom(mailFrom); mailConfig.setSubject(mailSubject); Map<String, String> model = new HashMap<String, String>(); model.put("name", userEntity.getUserName()); model.put("tempPassword", tempPassword); String mailContent = CommonUtils.mergeVelocityTemplateForEmail(velocityEngine, mailTemplate, model); mailConfig.setText(mailContent); try { Mail.getJavaMailService().sendMail(mailConfig); isEmailSent = true; } catch (Exception e) { isEmailSent = false; log.error("Failed to dispatch mail:", e); } } if (!isEmailSent) { updateResult.setMessage(I18n.getMessage("error.emailConfigError")); updateResult.setSuccess(false); } else { updateResult.setMessage(I18n.getMessage("success.emailConfigSuccess")); } } else { updateResult.setMessage(I18n.getMessage("error.emailError")); updateResult.setSuccess(false); } out.write(mapper.writeValueAsBytes(updateResult)); out.flush(); out.close(); return null; }
From source file:arena.web.view.DownloadView.java
@Override @SuppressWarnings("unchecked") protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setStatus(HttpServletResponse.SC_OK); String mt = (mimeTypeParam != null ? (String) model.get(mimeTypeParam) : this.mimeType); if (mt != null) { response.setContentType(this.mimeType); }/*from w w w .ja va 2 s .co m*/ Object contentObj = model.get(this.contentParam); String fileName = ServletUtils.replaceWildcards(this.filenamePattern, this.allowRequestArgs, model, request); if (!fileName.equals("")) { String rfc2047Name = javax.mail.internet.MimeUtility.encodeText(fileName, "UTF-8", null); String fullHeader = "attachment;filename=" + rfc2047Name; response.setHeader("Content-Disposition", fullHeader); } ServletOutputStream out = response.getOutputStream(); if (contentObj instanceof byte[]) { byte[] content = (byte[]) model.get(this.contentParam); response.setContentLength(content == null ? 0 : content.length); if (content != null && content.length > 0) { out.write(content); } } else if (contentObj instanceof InputStream) { InputStream content = (InputStream) contentObj; byte[] buffer = new byte[response.getBufferSize()]; int read = 0; while ((read = content.read(buffer)) >= 0) { out.write(buffer, 0, read); } if (this.closeStream) { content.close(); } } }
From source file:com.cognitivabrasil.repositorio.web.FileController.java
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST) @ResponseBody/*from w ww . j av a2s. c o m*/ public String upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, org.apache.commons.fileupload.FileUploadException { if (file == null) { file = new Files(); file.setSizeInBytes(0L); } Integer docId = null; String docPath = null; String responseString = RESP_SUCCESS; boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { try { ServletFileUpload x = new ServletFileUpload(new DiskFileItemFactory()); List<FileItem> items = x.parseRequest(request); for (FileItem item : items) { InputStream input = item.getInputStream(); // Handle a form field. if (item.isFormField()) { String attribute = item.getFieldName(); String value = Streams.asString(input); switch (attribute) { case "chunks": this.chunks = Integer.parseInt(value); break; case "chunk": this.chunk = Integer.parseInt(value); break; case "filename": file.setName(value); break; case "docId": if (value.isEmpty()) { throw new org.apache.commons.fileupload.FileUploadException( "No foi informado o id do documento."); } docId = Integer.parseInt(value); docPath = Config.FILE_PATH + "/" + docId; File documentPath = new File(docPath); // cria o diretorio documentPath.mkdirs(); break; default: break; } } // Handle a multi-part MIME encoded file. else { try { File uploadFile = new File(docPath, item.getName()); BufferedOutputStream bufferedOutput; bufferedOutput = new BufferedOutputStream(new FileOutputStream(uploadFile, true)); byte[] data = item.get(); bufferedOutput.write(data); bufferedOutput.close(); } catch (Exception e) { LOG.error("Erro ao salvar o arquivo.", e); file = null; throw e; } finally { if (input != null) { try { input.close(); } catch (IOException e) { LOG.error("Erro ao fechar o ImputStream", e); } } file.setName(item.getName()); file.setContentType(item.getContentType()); file.setPartialSize(item.getSize()); } } } if ((this.chunk == this.chunks - 1) || this.chunks == 0) { file.setLocation(docPath + "/" + file.getName()); if (docId != null) { file.setDocument(documentsService.get(docId)); } fileService.save(file); file = null; } } catch (org.apache.commons.fileupload.FileUploadException | IOException | NumberFormatException e) { responseString = RESP_ERROR; LOG.error("Erro ao salvar o arquivo", e); file = null; throw e; } } // Not a multi-part MIME request. else { responseString = RESP_ERROR; } response.setContentType("application/json"); byte[] responseBytes = responseString.getBytes(); response.setContentLength(responseBytes.length); ServletOutputStream output = response.getOutputStream(); output.write(responseBytes); output.flush(); return responseString; }
From source file:com.jd.survey.web.security.LoginController.java
@RequestMapping(method = RequestMethod.GET, value = "/w/{uuid}", produces = "image/gif") public void getWhiteGif(@PathVariable("uuid") String uuid, Principal principal, HttpServletRequest httpServletRequest, HttpServletResponse response) { try {/*from w w w .ja v a 2 s . co m*/ Invitation invitation = surveySettingsService.invitation_findByUuid(uuid); if (invitation != null) { surveySettingsService.invitation_updateAsRead(invitation.getId()); } //white 1 x 1 pixel gif binary byte[] trackingGif = { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x1, 0x0, 0x1, 0x0, (byte) 0x80, 0x0, 0x0, (byte) 0xff, (byte) 0xff, (byte) 0xff, 0x0, 0x0, 0x0, 0x2c, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x1, 0x0, 0x0, 0x2, 0x2, 0x44, 0x1, 0x0, 0x3b }; response.setContentType("image/gif"); ServletOutputStream servletOutputStream = response.getOutputStream(); servletOutputStream.write(trackingGif); servletOutputStream.flush(); } catch (Exception e) { log.error(e.getMessage(), e); throw (new RuntimeException(e)); } }