List of usage examples for javax.servlet ServletOutputStream write
public abstract void write(int b) throws IOException;
From source file:net.sf.jsog.spring.JsogViewTest.java
@Test public void testRenderMergedOutputModelCustomEncodingCharset() throws Exception { // TODO: Make this test more robust // Setup/*from w w w . j a v a 2s .c om*/ String encoding = "UTF-8"; JSOG expected = new JSOG("foobar"); MediaType contentType = MediaType.APPLICATION_JSON; // Setup the model Map<String, Object> model = new HashMap<String, Object>(); model.put("JSOG", expected); // Setup the output stream ServletOutputStream sos = createMock(ServletOutputStream.class); expect(response.getOutputStream()).andReturn(sos); Capture<byte[]> out = new Capture<byte[]>(); sos.write(capture(out)); expectLastCall(); sos.flush(); expectLastCall(); sos.close(); expectLastCall(); response.setContentType(contentType.toString()); expectLastCall(); response.setCharacterEncoding(encoding); expectLastCall(); response.setContentLength(expected.toString().getBytes(encoding).length); expectLastCall(); expect(request.getParameter("callback")).andReturn(null); // Execution replay(request, response, sos); instance.setEncoding(Charset.forName(encoding)); instance.renderMergedOutputModel(model, request, response); // Verification verify(request, response, sos); assertTrue(out.hasCaptured()); // Parse the resulting value JSOG actual = JSOG.parse(new String(out.getValue(), encoding)); assertEquals(actual, expected); }
From source file:net.sf.jsog.spring.JsogViewTest.java
@Test public void testRenderMergedOutputModelJSONP() throws Exception { // TODO: Make this test more robust // Setup//from w ww.jav a 2 s . c om String encoding = "ISO-8859-1"; // Default encoding String callback = "foo"; JSOG expectedJson = new JSOG("foobar"); String expected = callback + "(" + expectedJson + ")"; MediaType contentType = MediaType.APPLICATION_JSON; // Setup the model Map<String, Object> model = new HashMap<String, Object>(); model.put("JSOG", expectedJson); // Setup the output stream ServletOutputStream sos = createMock(ServletOutputStream.class); expect(response.getOutputStream()).andReturn(sos); Capture<byte[]> out = new Capture<byte[]>(); sos.write(capture(out)); expectLastCall(); sos.flush(); expectLastCall(); sos.close(); expectLastCall(); response.setContentType(contentType.toString()); expectLastCall(); response.setCharacterEncoding(encoding); expectLastCall(); response.setContentLength(expected.toString().getBytes(encoding).length); expectLastCall(); expect(request.getParameter("callback")).andReturn(callback); // Execution replay(request, response, sos); instance.renderMergedOutputModel(model, request, response); // Verification verify(request, response, sos); assertTrue(out.hasCaptured()); // Parse the resulting value String actual = new String(out.getValue(), encoding); assertEquals(actual, expected); }
From source file:net.sf.jsog.spring.JsogViewTest.java
/** * This tests that complex models can be rendered properly. * A complex model is one that doesn't have "JSOG" as it's only key (excepting BindingResult values). * @throws Exception//from ww w . jav a 2 s .co m */ @Test public void testRenderMergedOutputModelComplex() throws Exception { // TODO: Make this test more robust // Setup String encoding = "ISO-8859-1"; // Default encoding JSOG expected = JSOG.object("foo", "foovalue").put("bar", "barvalue").put("obj", JSOG.object()); MediaType contentType = MediaType.APPLICATION_JSON; // Setup the model Map<String, Object> model = new HashMap<String, Object>(); model.put("foo", "foovalue"); model.put("bar", "barvalue"); model.put("obj", JSOG.object()); // Setup the output stream ServletOutputStream sos = createMock(ServletOutputStream.class); expect(response.getOutputStream()).andReturn(sos); Capture<byte[]> out = new Capture<byte[]>(); sos.write(capture(out)); expectLastCall(); sos.flush(); expectLastCall(); sos.close(); expectLastCall(); response.setContentType(contentType.toString()); expectLastCall(); response.setCharacterEncoding(encoding); expectLastCall(); response.setContentLength(expected.toString().getBytes(encoding).length); expectLastCall(); expect(request.getParameter("callback")).andReturn(null); // Execution replay(request, response, sos); instance.renderMergedOutputModel(model, request, response); // Verification verify(request, response, sos); assertTrue(out.hasCaptured()); // Parse the resulting value JSOG actual = JSOG.parse(new String(out.getValue(), encoding)); assertEquals(actual, expected); }
From source file:net.sf.jsog.spring.JsogViewTest.java
@Test public void testRenderMergedOutputModelJSONPCustomCallback() throws Exception { // TODO: Make this test more robust // Setup//from w w w .j a va2 s . c om String encoding = "ISO-8859-1"; // Default encoding String callback = "foo"; String callbackParamName = "bar"; JSOG expectedJson = new JSOG("foobar"); String expected = callback + "(" + expectedJson + ")"; MediaType contentType = MediaType.APPLICATION_JSON; // Setup the model Map<String, Object> model = new HashMap<String, Object>(); model.put("JSOG", expectedJson); // Setup the output stream ServletOutputStream sos = createMock(ServletOutputStream.class); expect(response.getOutputStream()).andReturn(sos); Capture<byte[]> out = new Capture<byte[]>(); sos.write(capture(out)); expectLastCall(); sos.flush(); expectLastCall(); sos.close(); expectLastCall(); response.setContentType(contentType.toString()); expectLastCall(); response.setCharacterEncoding(encoding); expectLastCall(); response.setContentLength(expected.toString().getBytes(encoding).length); expectLastCall(); expect(request.getParameter(callbackParamName)).andReturn(callback); // Execution replay(request, response, sos); instance.setJsonpCallbackParam(callbackParamName); instance.renderMergedOutputModel(model, request, response); // Verification verify(request, response, sos); assertTrue(out.hasCaptured()); // Parse the resulting value String actual = new String(out.getValue(), encoding); assertEquals(actual, expected); }
From source file:net.sf.jsog.spring.JsogViewTest.java
@Test public void testRenderMergedOutputModelBeanCustomBeanJsogFactory() throws Exception { // Setup/*from ww w.ja v a2 s . co m*/ String encoding = "ISO-8859-1"; // Default encoding JSOG beanJsog = JSOG.object("foo", "foovalue").put("bar", "barvalue"); JSOG expected = JSOG.object("bean", beanJsog); MediaType contentType = MediaType.APPLICATION_JSON; BeanJsogFactory bjf = createMock(BeanJsogFactory.class); instance.setBeanJsogFactory(bjf); expect(bjf.create(isA(TestBean.class))).andReturn(beanJsog); // Setup the model Map<String, Object> model = new HashMap<String, Object>(); model.put("bean", new TestBean()); // Setup the output stream ServletOutputStream sos = createMock(ServletOutputStream.class); expect(response.getOutputStream()).andReturn(sos); Capture<byte[]> out = new Capture<byte[]>(); sos.write(capture(out)); expectLastCall(); sos.flush(); expectLastCall(); sos.close(); expectLastCall(); response.setContentType(contentType.toString()); expectLastCall(); response.setCharacterEncoding(encoding); expectLastCall(); response.setContentLength(expected.toString().getBytes(encoding).length); expectLastCall(); expect(request.getParameter("callback")).andReturn(null); // Execution replay(request, response, sos, bjf); instance.renderMergedOutputModel(model, request, response); // Verification verify(request, response, sos, bjf); assertTrue(out.hasCaptured()); // Parse the resulting value JSOG actual = JSOG.parse(new String(out.getValue(), encoding)); assertEquals(actual, expected); }
From source file:com.jd.survey.web.survey.PublicSurveyController.java
/** * Returns the survey logo image binary * @param departmentId/* ww w . jav a2 s . c om*/ * @param uiModel * @param httpServletRequest * @return */ @RequestMapping(value = "/logo/{id}", produces = "text/html") public void getSurveyLogo(@PathVariable("id") Long surveyDefinitionId, Model uiModel, Principal principal, HttpServletRequest httpServletRequest, HttpServletResponse response) { try { uiModel.asMap().clear(); //Check if the user is authorized SurveyDefinition surveyDefinition = surveySettingsService.surveyDefinition_findById(surveyDefinitionId); if (!surveyDefinition.getIsPublic()) {//survey definition not open to the public //attempt to access a private survey definition from a public open url log.warn(SURVEY_NOT_PUBLIC_WARNING_MESSAGE + httpServletRequest.getPathInfo() + FROM_IP_WARNING_MESSAGE + httpServletRequest.getLocalAddr()); throw (new RuntimeException("Unauthorized access to logo")); } else { //response.setContentType("image/png"); ServletOutputStream servletOutputStream = response.getOutputStream(); servletOutputStream.write(surveyDefinition.getLogo()); servletOutputStream.flush(); } } catch (Exception e) { log.error(e.getMessage(), e); throw (new RuntimeException(e)); } }
From source file:net.sourceforge.fenixedu.presentationTier.Action.student.onlineTests.StudentTestsAction.java
public ActionForward exportChecksum(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { final String logId = request.getParameter("logId"); final User userView = getUserView(request); if (logId != null && logId.length() != 0) { StudentTestLog studentTestLog = FenixFramework.getDomainObject(logId); if (studentTestLog.getStudent().getPerson().equals(userView.getPerson())) { List<StudentTestLog> studentTestLogs = new ArrayList<StudentTestLog>(); studentTestLogs.add(studentTestLog); byte[] data = ReportsUtils.exportToPdfFileAsByteArray( "net.sourceforge.fenixedu.domain.onlineTests.StudentTestLog.checksumReport", null, studentTestLogs);//from w ww . ja v a 2 s. c om response.setContentType("application/pdf"); response.addHeader("Content-Disposition", "attachment; filename=" + studentTestLog.getStudent().getNumber() + ".pdf"); response.setContentLength(data.length); ServletOutputStream writer = response.getOutputStream(); writer.write(data); writer.flush(); writer.close(); response.flushBuffer(); return mapping.findForward(""); } } return null; }
From source file:com.seer.datacruncher.spring.ExtraCheckCustomCodeValidator.java
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String code = request.getParameter("value"); String name = request.getParameter("name"); String addReq = request.getParameter("addReq"); //TODO: take the result message from "locale" String result = null;//w ww. j a v a 2s. c om ObjectMapper mapper = new ObjectMapper(); ServletOutputStream out = null; response.setContentType("application/json"); out = response.getOutputStream(); if (StringUtils.isEmpty(code) || StringUtils.isEmpty(name)) { result = I18n.getMessage("error.extracheck.invaliddata"); } else { name = name.trim(); if (addReq.equalsIgnoreCase("true")) { ReadList list = checksTypeDao.findCustomCodeByName(name); if (list != null && CollectionUtils.isNotEmpty(list.getResults())) { result = I18n.getMessage("error.extracheck.name.alreadyexist"); out.write(mapper.writeValueAsBytes(result)); out.flush(); out.close(); return null; } } try { File sourceDir = new File(System.getProperty("java.io.tmpdir"), "DataCruncher/src"); sourceDir.mkdirs(); String classNamePack = name.replace('.', File.separatorChar); String srcFilePath = sourceDir + "" + File.separatorChar + classNamePack + ".java"; File sourceFile = new File(srcFilePath); if (sourceFile.exists()) { sourceFile.delete(); } FileUtils.writeStringToFile(new File(srcFilePath), code); DynamicClassLoader dynacode = DynamicClassLoader.getInstance(); dynacode.addSourceDir(sourceDir); CustomCodeValidator customCodeValidator = (CustomCodeValidator) dynacode .newProxyInstance(CustomCodeValidator.class, name); boolean isValid = false; if (customCodeValidator != null) { Class clazz = dynacode.getLoadedClass(name); if (clazz != null) { Class[] interfaces = clazz.getInterfaces(); if (ArrayUtils.isNotEmpty(interfaces)) { for (Class clz : interfaces) { if ((clz.getName().equalsIgnoreCase( "com.seer.datacruncher.utils.validation.SingleValidation"))) { isValid = true; } } } } } if (isValid) { result = "Success"; } else { result = I18n.getMessage("error.extracheck.wrongimpl"); } } catch (Exception e) { result = "Failed. Reason:" + e.getMessage(); } } out.write(mapper.writeValueAsBytes(result)); out.flush(); out.close(); return null; }
From source file:org.fenixedu.academic.ui.struts.action.student.onlineTests.StudentTestsAction.java
public ActionForward exportChecksum(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { final String logId = request.getParameter("logId"); final User userView = getUserView(request); if (logId != null && logId.length() != 0) { StudentTestLog studentTestLog = FenixFramework.getDomainObject(logId); if (studentTestLog.getStudent().getPerson().equals(userView.getPerson())) { List<StudentTestLog> studentTestLogs = new ArrayList<StudentTestLog>(); studentTestLogs.add(studentTestLog); byte[] data = ReportsUtils .generateReport("org.fenixedu.academic.domain.onlineTests.StudentTestLog.checksumReport", null, studentTestLogs) .getData();//from w w w . ja v a 2s . c om response.setContentType("application/pdf"); response.addHeader("Content-Disposition", "attachment; filename=" + studentTestLog.getStudent().getNumber() + ".pdf"); response.setContentLength(data.length); ServletOutputStream writer = response.getOutputStream(); writer.write(data); writer.flush(); writer.close(); response.flushBuffer(); return mapping.findForward(""); } } return null; }
From source file:SendMp3.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String fileName = (String) request.getParameter("file"); if (fileName == null || fileName.equals("")) throw new ServletException("Invalid or non-existent file parameter in SendMp3 servlet."); if (fileName.indexOf(".mp3") == -1) fileName = fileName + ".mp3"; String mp3Dir = getServletContext().getInitParameter("mp3-dir"); if (mp3Dir == null || mp3Dir.equals("")) throw new ServletException("Invalid or non-existent mp3Dir context-param."); ServletOutputStream stream = null; BufferedInputStream buf = null; try {/*from w w w. j av a 2 s. co m*/ stream = response.getOutputStream(); File mp3 = new File(mp3Dir + "/" + fileName); //set response headers response.setContentType("audio/mpeg"); response.addHeader("Content-Disposition", "attachment; filename=" + fileName); response.setContentLength((int) mp3.length()); FileInputStream input = new FileInputStream(mp3); buf = new BufferedInputStream(input); int readBytes = 0; //read from the file; write to the ServletOutputStream while ((readBytes = buf.read()) != -1) stream.write(readBytes); } catch (IOException ioe) { throw new ServletException(ioe.getMessage()); } finally { if (stream != null) stream.close(); if (buf != null) buf.close(); } }