List of usage examples for javax.servlet ServletOutputStream write
public abstract void write(int b) throws IOException;
From source file:eu.freme.broker.tools.internationalization.EInternationalizationFilter.java
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { if (!(req instanceof HttpServletRequest) || !(res instanceof HttpServletResponse)) { chain.doFilter(req, res);//from w ww. j av a 2 s . co m return; } HttpServletRequest httpRequest = (HttpServletRequest) req; HttpServletResponse httpResponse = (HttpServletResponse) res; if (httpRequest.getMethod().equals("OPTIONS")) { chain.doFilter(req, res); return; } String uri = httpRequest.getRequestURI(); for (Pattern pattern : endpointBlacklistRegex) { if (pattern.matcher(uri).matches()) { chain.doFilter(req, res); return; } } String informat = getInformat(httpRequest); String outformat = getOutformat(httpRequest); if (outformat != null && (informat == null || !outformat.equals(informat))) { Exception exception = new BadRequestException("Can only convert to outformat \"" + outformat + "\" when informat is also \"" + outformat + "\""); exceptionHandlerService.writeExceptionToResponse(httpRequest, httpResponse, exception); return; } if (outformat != null && !outputFormats.contains(outformat)) { Exception exception = new BadRequestException("\"" + outformat + "\" is not a valid output format"); exceptionHandlerService.writeExceptionToResponse(httpRequest, httpResponse, exception); return; } if (informat == null) { chain.doFilter(req, res); return; } boolean roundtripping = false; if (outformat != null) { roundtripping = true; logger.debug("convert from " + informat + " to " + outformat); } else { logger.debug("convert input from " + informat + " to nif"); } // do conversion of informat to nif // create BodySwappingServletRequest String inputQueryString = req.getParameter("input"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (InputStream requestInputStream = inputQueryString == null ? /* * read * data * from * request * body */req.getInputStream() : /* * read data from query string input * parameter */new ReaderInputStream(new StringReader(inputQueryString), "UTF-8")) { // copy request content to buffer IOUtils.copy(requestInputStream, baos); } // create request wrapper that converts the body of the request from the // original format to turtle Reader nif; byte[] baosData = baos.toByteArray(); if (baosData.length == 0) { Exception exception = new BadRequestException("No input data found in request."); exceptionHandlerService.writeExceptionToResponse(httpRequest, httpResponse, exception); return; } ByteArrayInputStream bais = new ByteArrayInputStream(baosData); try { nif = eInternationalizationApi.convertToTurtle(bais, informat.toLowerCase()); } catch (ConversionException e) { logger.error("Error", e); throw new InternalServerErrorException("Conversion from \"" + informat + "\" to NIF failed"); } BodySwappingServletRequest bssr = new BodySwappingServletRequest((HttpServletRequest) req, nif, roundtripping); if (!roundtripping) { chain.doFilter(bssr, res); return; } ConversionHttpServletResponseWrapper dummyResponse; try { dummyResponse = new ConversionHttpServletResponseWrapper(httpResponse, eInternationalizationApi, new ByteArrayInputStream(baosData), informat, outformat); chain.doFilter(bssr, dummyResponse); ServletOutputStream sos = httpResponse.getOutputStream(); byte[] data = dummyResponse.writeBackToClient(); httpResponse.setContentLength(data.length); sos.write(data); sos.flush(); sos.close(); } catch (ConversionException e) { e.printStackTrace(); // exceptionHandlerService.writeExceptionToResponse((HttpServletResponse)res,new // InternalServerErrorException()); } }
From source file:com.jd.survey.web.reports.ReportController.java
/** * Exports survey data to a comma delimited values file * @param surveyDefinitionId/*from w w w . ja v a 2 s . c o m*/ * @param principal * @param response */ @Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" }) @RequestMapping(value = "/{id}", params = "csv", produces = "text/html") public void surveyCSVExport(@PathVariable("id") Long surveyDefinitionId, Principal principal, HttpServletRequest httpServletRequest, HttpServletResponse response) { try { User user = userService.user_findByLogin(principal.getName()); if (!securityService.userIsAuthorizedToManageSurvey(surveyDefinitionId, user)) { log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo() + " attempted by user login:" + principal.getName() + "from IP:" + httpServletRequest.getLocalAddr()); response.sendRedirect("../accessDenied"); //throw new AccessDeniedException("Unauthorized access attempt"); } String columnName; SurveyDefinition surveyDefinition = surveySettingsService.surveyDefinition_findById(surveyDefinitionId); List<Map<String, Object>> surveys = reportDAO.getSurveyData(surveyDefinitionId); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append( "\"id\",\"Survey Name\",\"User Login\",\"Submission Date\",\"Creation Date\",\"Last Update Date\","); for (SurveyDefinitionPage page : surveyDefinition.getPages()) { for (Question question : page.getQuestions()) { if (question.getType().getIsMatrix()) { for (QuestionRowLabel questionRowLabel : question.getRowLabels()) { for (QuestionColumnLabel questionColumnLabel : question.getColumnLabels()) { stringBuilder.append("\" p" + page.getOrder() + "q" + question.getOrder() + "r" + questionRowLabel.getOrder() + "c" + questionColumnLabel.getOrder() + "\","); } } continue; } if (question.getType().getIsMultipleValue()) { for (QuestionOption questionOption : question.getOptions()) { stringBuilder.append("\" p" + page.getOrder() + "q" + question.getOrder() + "o" + questionOption.getOrder() + "\","); } continue; } stringBuilder.append("\"p" + page.getOrder() + "q" + question.getOrder() + "\","); } } stringBuilder.deleteCharAt(stringBuilder.length() - 1); //delete the last comma stringBuilder.append("\n"); for (Map<String, Object> record : surveys) { stringBuilder.append(record.get("survey_id") == null ? "" : "\"" + record.get("survey_id").toString().replace("\"", "\"\"") + "\","); stringBuilder.append(record.get("type_name") == null ? "" : "\"" + record.get("type_name").toString().replace("\"", "\"\"") + "\","); stringBuilder.append(record.get("login") == null ? "" : "\"" + record.get("login").toString().replace("\"", "\"\"") + "\","); stringBuilder.append(record.get("submission_date") == null ? "" : "\"" + record.get("creation_date").toString().replace("\"", "\"\"") + "\","); stringBuilder.append(record.get("creation_date") == null ? "" : "\"" + record.get("last_update_date").toString().replace("\"", "\"\"") + "\","); stringBuilder.append(record.get("last_update_date") == null ? "" : "\"" + record.get("last_update_date").toString().replace("\"", "\"\"") + "\","); for (SurveyDefinitionPage page : surveyDefinition.getPages()) { for (Question question : page.getQuestions()) { if (question.getType().getIsMatrix()) { for (QuestionRowLabel questionRowLabel : question.getRowLabels()) { for (QuestionColumnLabel questionColumnLabel : question.getColumnLabels()) { columnName = "p" + page.getOrder() + "q" + question.getOrder() + "r" + questionRowLabel.getOrder() + "c" + questionColumnLabel.getOrder(); stringBuilder.append(record.get(columnName) == null ? "," : "\"" + record.get(columnName).toString().replace("\"", "\"\"") + "\","); } } continue; } if (question.getType().getIsMultipleValue()) { for (QuestionOption questionOption : question.getOptions()) { columnName = "p" + page.getOrder() + "q" + question.getOrder() + "o" + questionOption.getOrder(); stringBuilder.append(record.get(columnName) == null ? "," : "\"" + record.get(columnName).toString().replace("\"", "\"\"") + "\","); } continue; } columnName = "p" + page.getOrder() + "q" + question.getOrder(); stringBuilder.append(record.get(columnName) == null ? "," : "\"" + record.get(columnName).toString().replace("\"", "\"\"") + "\","); } } stringBuilder.deleteCharAt(stringBuilder.length() - 1); //delete the last comma stringBuilder.append("\n"); } //Zip file manipulations Code ByteArrayOutputStream bos = new ByteArrayOutputStream(); ZipEntry zipentry; ZipOutputStream zipfile = new ZipOutputStream(bos); zipentry = new ZipEntry("survey" + surveyDefinition.getId() + ".csv"); zipfile.putNextEntry(zipentry); zipfile.write(stringBuilder.toString().getBytes("UTF-8")); zipfile.close(); //response.setContentType("text/html; charset=utf-8"); response.setContentType("application/octet-stream"); // Set standard HTTP/1.1 no-cache headers. response.setHeader("Cache-Control", "no-store, no-cache,must-revalidate"); // Set IE extended HTTP/1.1 no-cache headers (use addHeader). response.addHeader("Cache-Control", "post-check=0, pre-check=0"); // Set standard HTTP/1.0 no-cache header. response.setHeader("Pragma", "no-cache"); response.setHeader("Content-Disposition", "inline;filename=survey" + surveyDefinition.getId() + ".zip"); ServletOutputStream servletOutputStream = response.getOutputStream(); //servletOutputStream.write(stringBuilder.toString().getBytes("UTF-8")); servletOutputStream.write(bos.toByteArray()); servletOutputStream.flush(); } catch (Exception e) { log.error(e.getMessage(), e); throw new RuntimeException(e); } }
From source file:com.tasktop.c2c.server.internal.wiki.server.WikiServiceController.java
@Section(value = "Attachments") @Title("Retrieve Image") @Documentation("Retrieve an Image from a Page") @RequestMapping(value = "{pageId}/attachment/{name:.*}", method = RequestMethod.GET) public void getImage(@PathVariable(value = "pageId") Integer pageId, @PathVariable(value = "name") String imageName, HttpServletRequest request, HttpServletResponse response) throws IOException { String etag = request.getHeader("If-None-Match"); if (etag != null && etag.length() > 1 && etag.charAt(0) == '"' && etag.charAt(etag.length() - 1) == '"') { etag = etag.substring(1, etag.length() - 1); }/* w w w .ja v a 2 s . c om*/ Attachment attachment; try { attachment = service.retrieveAttachmentByNameWithETag(pageId, imageName, etag); } catch (EntityNotFoundException e) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if (attachment.getContent() == null) { // ETag match response.sendError(HttpServletResponse.SC_NOT_MODIFIED); return; } String modified = formatRFC2822(attachment.getModificationDate()); if (modified.equals(request.getHeader("If-Modified-Since"))) { response.sendError(HttpServletResponse.SC_NOT_MODIFIED); return; } response.setStatus(HttpServletResponse.SC_OK); response.setContentLength(attachment.getSize()); response.setContentType(attachment.getMimeType()); response.setHeader("ETag", "\"" + attachment.getEtag() + "\""); response.setHeader("Modified", modified); ServletOutputStream outputStream = response.getOutputStream(); try { outputStream.write(attachment.getContent()); } finally { outputStream.close(); } }
From source file:org.fenixedu.academic.ui.struts.action.internationalRelatOffice.candidacy.erasmus.ErasmusIndividualCandidacyProcessDA.java
public ActionForward retrieveLearningAgreement(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { MobilityIndividualApplicationProcess process = getProcess(request); final LearningAgreementDocument document = new LearningAgreementDocument(process); byte[] data = ReportsUtils.generateReport(document).getData(); response.setContentLength(data.length); response.setContentType("application/pdf"); response.addHeader("Content-Disposition", "attachment; filename=" + document.getReportFileName() + ".pdf"); final ServletOutputStream writer = response.getOutputStream(); writer.write(data); writer.flush();// w w w . j a va 2 s . co m writer.close(); response.flushBuffer(); return mapping.findForward(""); }
From source file:net.sourceforge.fenixedu.presentationTier.Action.internationalRelatOffice.candidacy.erasmus.ErasmusIndividualCandidacyProcessDA.java
public ActionForward retrieveLearningAgreement(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { MobilityIndividualApplicationProcess process = getProcess(request); final LearningAgreementDocument document = new LearningAgreementDocument(process); byte[] data = ReportsUtils.exportMultipleToPdfAsByteArray(document); response.setContentLength(data.length); response.setContentType("application/pdf"); response.addHeader("Content-Disposition", "attachment; filename=" + document.getReportFileName() + ".pdf"); final ServletOutputStream writer = response.getOutputStream(); writer.write(data); writer.flush();//ww w . java 2 s . c om writer.close(); response.flushBuffer(); return mapping.findForward(""); }
From source file:com.concursive.connect.web.modules.documents.beans.FileDownload.java
/** * Description of the Method// w ww . j a v a 2s . c o m * * @param context Description of the Parameter * @param text Description of the Parameter * @throws Exception Description of the Exception */ public void sendTextAsFile(ActionContext context, String text) throws Exception { context.getResponse().setContentType("application/octet-stream"); context.getResponse().setHeader("Content-Disposition", "attachment;filename=" + displayName + ";"); context.getResponse().setContentLength((int) text.length()); ServletOutputStream outputStream = context.getResponse().getOutputStream(); StringReader strReader = new StringReader(text); int data; while ((data = strReader.read()) != -1) { outputStream.write(data); } strReader.close(); outputStream.close(); }
From source file:org.ejbca.extra.ra.ScepRAServlet.java
/** * Sends back a number of bytes// www.j a v a 2 s .c o m * * @param bytes DER encoded certificate to be returned * @param out output stream to send to * @param contentType mime type to send back bytes as * @param fileName to call the file in a Content-disposition, can be null to leave out this header * * @throws Exception on error */ private void sendBinaryBytes(byte[] bytes, HttpServletResponse out, String contentType, String filename) throws Exception { if ((bytes == null) || (bytes.length == 0)) { log.error("0 length can not be sent to client!"); return; } if (filename != null) { // We must remove cache headers for IE removeCacheHeaders(out); out.setHeader("Content-disposition", "filename=\"" + filename + "\""); } // Set content-type to general file out.setContentType(contentType); out.setContentLength(bytes.length); // Write the certificate ServletOutputStream os = out.getOutputStream(); os.write(bytes); out.flushBuffer(); log.debug("Sent " + bytes.length + " bytes to client"); }
From source file:org.extensiblecatalog.ncip.v2.responder.implprof1.NCIPServlet.java
/** * Create a valid version 2 NCIPMessage response indicating a "Temporary Processing Failure", without * relying on any facilities of the Toolkit. This method is to be used when handling exceptions that * indicate that Toolkit services such as * {@link ServiceHelper#generateProblems(org.extensiblecatalog.ncip.v2.service.ProblemType, String, String, String)} ()} * may fail.//from w w w. ja v a 2 s.c o m * @param response the HttpServletResponse object to use * @param detail the text message to include in the ProblemDetail element * @throws ServletException if there is an IOException writing to the response object's output stream */ protected void returnProblem(HttpServletResponse response, String detail) throws ServletException { String problemMsg = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" // TODO: The version, namespace, etc. ought to come from ServiceContext + "<ns1:NCIPMessage ns1:version=\"http://www.niso.org/ncip/v2_0/imp1/xsd/ncip_v2_0.xsd\"" + " xmlns:ns1=\"http://www.niso.org/2008/ncip\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + " xsi:schemaLocation=\"http://www.niso.org/2008/ncip ncip_v2_0.xsd\">\n" + " <ns1:Problem>\n" + " <ns1:ProblemType ns1:Scheme=\"http://www.niso.org/ncip/v1_0/schemes/processingerrortype/generalprocessingerror.scm\">Temporary Processing Failure</ns1:ProblemType>\n" + " <ns1:ProblemDetail>" + StringEscapeUtils.escapeXml(detail) + "</ns1:ProblemDetail>\n" + " </ns1:Problem>\n" + "</ns1:NCIPMessage>"; byte[] problemMsgBytes = problemMsg.getBytes(); response.setContentLength(problemMsgBytes.length); try { ServletOutputStream outputStream = response.getOutputStream(); outputStream.write(problemMsgBytes); outputStream.flush(); } catch (IOException e) { throw new ServletException("Exception writing Problem response.", e); } }
From source file:ai.h2o.servicebuilder.CompilePojoServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { File tmp = null;/*from w w w. ja v a 2s . co m*/ try { //create temp directory tmp = createTempDirectory("compilePojo"); logger.info("tmp dir {}", tmp); // get input files List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); List<String> pojofiles = new ArrayList<String>(); String jarfile = null; for (FileItem i : items) { String field = i.getFieldName(); String filename = i.getName(); if (filename != null && filename.length() > 0) { if (field.equals("pojo")) { pojofiles.add(filename); } if (field.equals("jar")) { jarfile = filename; } FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmp, filename)); } } if (pojofiles.isEmpty() || jarfile == null) throw new Exception("need pojofile(s) and jarfile"); // create output directory File out = new File(tmp.getPath(), "out"); boolean mkDirResult = out.mkdir(); if (!mkDirResult) throw new Exception("Can't create output directory (out)"); if (servletPath == null) throw new Exception("servletPath is null"); copyExtraFile(servletPath, "extra" + File.separator, tmp, "H2OPredictor.java", "H2OPredictor.java"); FileUtils.copyDirectoryToDirectory( new File(servletPath, "extra" + File.separator + "WEB-INF" + File.separator + "lib"), tmp); copyExtraFile(servletPath, "extra" + File.separator, new File(out, "META-INF"), "MANIFEST.txt", "MANIFEST.txt"); // Compile the pojo(s) for (String pojofile : pojofiles) { runCmd(tmp, Arrays.asList("javac", "-target", JAVA_TARGET_VERSION, "-source", JAVA_TARGET_VERSION, "-J-Xmx" + MEMORY_FOR_JAVA_PROCESSES, "-cp", jarfile + ":lib/*", "-d", "out", pojofile, "H2OPredictor.java"), "Compilation of pojo failed: " + pojofile); } // create jar result file runCmd(out, Arrays.asList("jar", "xf", tmp + File.separator + jarfile), "jar extraction of h2o-genmodel failed"); runCmd(out, Arrays.asList("jar", "xf", tmp + File.separator + "lib" + File.separator + "gson-2.6.2.jar"), "jar extraction of gson failed"); runCmd(out, Arrays.asList("jar", "cfm", tmp + File.separator + "result.jar", "META-INF" + File.separator + "MANIFEST.txt", "."), "jar creation failed"); byte[] resjar = IOUtils.toByteArray(new FileInputStream(tmp + File.separator + "result.jar")); if (resjar == null) throw new Exception("Can't create jar of compiler output"); logger.info("jar created, size {}", resjar.length); // send jar back ServletOutputStream sout = response.getOutputStream(); response.setContentType("application/octet-stream"); String outputFilename = pojofiles.get(0).replace(".java", ""); response.setHeader("Content-disposition", "attachment; filename=" + outputFilename + ".jar"); response.setContentLength(resjar.length); sout.write(resjar); sout.close(); response.setStatus(HttpServletResponse.SC_OK); } catch (Exception e) { logger.error("post failed", e); // send the error message back String message = e.getMessage(); if (message == null) message = "no message"; logger.error(message); response.getWriter().write(message); response.getWriter().write(Arrays.toString(e.getStackTrace())); response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } finally { // if the temp directory is still there we delete it try { if (tmp != null && tmp.exists()) FileUtils.deleteDirectory(tmp); } catch (IOException e) { logger.error("Can't delete tmp directory"); } } }
From source file:org.gbif.portal.web.controller.taxonomy.NameIdMapperController.java
/** * @see org.springframework.web.servlet.mvc.AbstractFormController#handleRequestInternal(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *///from w w w . j av a2s .c o m @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { if (isFormSubmission(request) && request.getParameter("export") != null) { ServletOutputStream sOut = response.getOutputStream(); response.setHeader("Content-Disposition", "attachment; name-id-pairs.txt"); //get all the supplied names from the form int index = 1; String suppliedName = request.getParameter("supplied-name-" + index); while (suppliedName != null) { String systemId = request.getParameter("systemId-" + index); sOut.write(suppliedName.getBytes()); sOut.write("\t".getBytes()); if (systemId != null) sOut.write(systemId.getBytes()); sOut.write("\n".getBytes()); index++; suppliedName = request.getParameter("supplied-name-" + index); } return null; } return super.handleRequestInternal(request, response); }