List of usage examples for javax.servlet ServletOutputStream print
public void print(double d) throws IOException
double
value to the client, with no carriage return-line feed (CRLF) at the end. From source file:com.chaosinmotion.securechat.server.MessageServlet.java
/** * Handle POST commands. This uses the cookie mechanism for Java * servlets to track users for security reasons, and handles the * commands for getting a token, for verifying server status, and for * logging in and changing a password.//from w w w .j a v a2 s. c o m */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ReturnResult retVal = null; /* * Step 1: determine the path element after the api/1/ URL. This * determines the command */ String path = req.getPathInfo(); if (path == null) { resp.sendError(404); return; } if (path.startsWith("/")) path = path.substring(1); try { /* * All commands require authentication. This determines if we have * it or not. */ HttpSession session = req.getSession(); Login.UserInfo userinfo = (Login.UserInfo) session.getAttribute("userinfo"); if (userinfo == null) { retVal = new ReturnResult(Errors.ERROR_UNAUTHORIZED, "Not authorized"); } else { if (path.equalsIgnoreCase("sendmessages")) { /* * Process the send messages request. This takes an array * of device IDs and messages. The assumption is that each * messages. */ JSONTokener tokener = new JSONTokener(req.getInputStream()); JSONObject requestParams = new JSONObject(tokener); retVal = SendMessages.processRequest(userinfo, requestParams); } else if (path.equalsIgnoreCase("getmessages")) { /* * Process the get messages request. This gets the messages * associated with the device provided, so long as it is * tied to the username that we've logged into. This will * pull the data and delete the messages from the back * end as they are pulled. */ JSONTokener tokener = new JSONTokener(req.getInputStream()); JSONObject requestParams = new JSONObject(tokener); retVal = GetMessages.processRequest(userinfo, requestParams); } else if (path.equalsIgnoreCase("dropmessages")) { /* * Process the get messages request. This gets the messages * associated with the device provided, so long as it is * tied to the username that we've logged into. This will * pull the data and delete the messages from the back * end as they are pulled. */ JSONTokener tokener = new JSONTokener(req.getInputStream()); JSONObject requestParams = new JSONObject(tokener); DropMessages.processRequest(userinfo, requestParams); retVal = new ReturnResult(); } else if (path.equalsIgnoreCase("notifications")) { /* * Process notification endpoint; this returns the * port of the network connection endpoint the user * can use for immediate notifications. This may also * return failure if we were unable to open a port * to receive connections. */ NotificationService n = NotificationService.getShared(); if (n.isRunning()) { SimpleReturnResult r = new SimpleReturnResult(); r.put("port", n.getServerPort()); r.put("host", n.getServerAddress()); r.put("ssl", n.getSSLFlag()); retVal = r; } else { retVal = new ReturnResult(Errors.ERROR_NOTIFICATION, "No notification service"); } } } } catch (Throwable th) { retVal = new ReturnResult(th); } /* * If we get here and we still haven't initialized return value, * set to a 404 error. We assume this reaches here with a null * value because the path doesn't exist. */ if (retVal == null) { resp.sendError(404); } else { /* * We now have a return result. Formulate the response */ ServletOutputStream stream = resp.getOutputStream(); resp.setContentType("application/json"); stream.print(retVal.toString()); } }
From source file:org.rhq.coregui.server.gwt.FileUploadServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(); session.setMaxInactiveInterval(MAX_INACTIVE_INTERVAL); if (ServletFileUpload.isMultipartContent(req)) { DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); if (tmpDir == null) { tmpDir = LookupUtil.getCoreServer().getJBossServerTempDir(); }/*from w w w . j a v a 2 s .c om*/ fileItemFactory.setRepository(tmpDir); //fileItemFactory.setSizeThreshold(0); ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory); List<FileItem> fileItemsList; try { fileItemsList = servletFileUpload.parseRequest(req); } catch (FileUploadException e) { writeExceptionResponse(resp, "File upload failed", e); return; } List<FileItem> actualFiles = new ArrayList<FileItem>(); Map<String, String> formFields = new HashMap<String, String>(); boolean retrieve = false; boolean obfuscate = false; Subject authenticatedSubject = null; for (FileItem fileItem : fileItemsList) { if (fileItem.isFormField()) { if (fileItem.getFieldName() != null) { formFields.put(fileItem.getFieldName(), fileItem.getString()); } if ("retrieve".equals(fileItem.getFieldName())) { retrieve = true; } else if ("obfuscate".equals(fileItem.getFieldName())) { obfuscate = Boolean.parseBoolean(fileItem.getString()); } else if ("sessionid".equals(fileItem.getFieldName())) { int sessionid = Integer.parseInt(fileItem.getString()); SubjectManagerLocal subjectManager = LookupUtil.getSubjectManager(); try { authenticatedSubject = subjectManager.getSubjectBySessionId(sessionid); } catch (Exception e) { throw new ServletException("Cannot authenticate request", e); } } fileItem.delete(); } else { // file item contains an actual uploaded file actualFiles.add(fileItem); log("file was uploaded: " + fileItem.getName()); } } if (authenticatedSubject == null) { for (FileItem fileItem : actualFiles) { fileItem.delete(); } throw new ServletException("Cannot process unauthenticated request"); } if (retrieve && actualFiles.size() == 1) { // sending in "retrieve" form element with a single file means the client just wants the content echoed back resp.setContentType("text/html"); FileItem fileItem = actualFiles.get(0); ServletOutputStream outputStream = resp.getOutputStream(); outputStream.print("<html>"); InputStream inputStream = fileItem.getInputStream(); try { // we have to HTML escape inputStream before writing it to outputStream StreamUtil.copy(inputStream, outputStream, false, true); } finally { inputStream.close(); } outputStream.print("</html>"); outputStream.flush(); fileItem.delete(); } else { Map<String, File> allUploadedFiles = new HashMap<String, File>(); // maps form field name to the actual file Map<String, String> allUploadedFileNames = new HashMap<String, String>(); // maps form field name to upload file name for (FileItem fileItem : actualFiles) { File theFile = forceToFile(fileItem); if (obfuscate) { // The commons fileupload API has a file tracker that deletes the file when the File object is garbage collected (huh?). // Because we will be using these files later, and because they are going to be obfuscated, we don't want this to happen, // so just rename the file to move it away from the file tracker and thus won't get // prematurely deleted before we get a chance to use it. File movedFile = new File(theFile.getAbsolutePath() + ".temp"); if (theFile.renameTo(movedFile)) { theFile = movedFile; } try { FileUtil.compressFile(theFile); // we really just compress it with our special compressor since its faster than obsfucation } catch (Exception e) { throw new ServletException("Cannot obfuscate uploaded files", e); } } allUploadedFiles.put(fileItem.getFieldName(), theFile); allUploadedFileNames.put(fileItem.getFieldName(), (fileItem.getName() != null) ? fileItem.getName() : theFile.getName()); } processUploadedFiles(authenticatedSubject, allUploadedFiles, allUploadedFileNames, formFields, req, resp); } } }
From source file:org.sakaiproject.kernel.rest.me.RestMeProvider.java
/** * @param response/*from w w w.j av a 2 s . co m*/ * @param anonMeFile * @throws JCRNodeFactoryServiceException * @throws RepositoryException * @throws IOException */ private void sendOutput(HttpServletResponse response, Locale locale, User user, String path) throws RepositoryException, JCRNodeFactoryServiceException, IOException { response.setContentType(RestProvider.CONTENT_TYPE); ServletOutputStream outputStream = response.getOutputStream(); outputStream.print("{ \"locale\" :"); outputStream.print(beanConverter.convertToString(UserLocale.localeToMap(locale))); sendFile("preferences", path, outputStream); outputPathPrefix(user.getUuid(), outputStream); outputStream.print(", \"profile\" : {}"); outputStream.print("}"); }
From source file:org.sakaiproject.kernel.rest.me.RestMeProvider.java
/** * @param response/*from w w w. j av a2 s. c om*/ * @param anonMeFile * @throws JCRNodeFactoryServiceException * @throws RepositoryException * @throws IOException */ private void sendOutput(HttpServletResponse response, Locale locale, User user, UserEnvironment userEnvironment) throws RepositoryException, JCRNodeFactoryServiceException, IOException { response.setContentType(RestProvider.CONTENT_TYPE); ServletOutputStream outputStream = response.getOutputStream(); outputStream.print("{ \"locale\" :"); outputStream.print(beanConverter.convertToString(UserLocale.localeToMap(locale))); outputStream.print(", \"preferences\" :"); userEnvironment.setProtected(true); String json = beanConverter.convertToString(userEnvironment); userEnvironment.setProtected(false); outputStream.print(json); outputPathPrefix(user.getUuid(), outputStream); outputUserProfile(user.getUuid(), outputStream); outputStream.print("}"); }
From source file:org.sakaiproject.kernel.rest.me.RestMeProvider.java
/** * @param response/*from www . j a v a 2 s .c om*/ * @param anonMeFile * @throws JCRNodeFactoryServiceException * @throws RepositoryException * @throws IOException */ private void sendDefaultUserOutput(HttpServletResponse response, Locale locale, User user) throws RepositoryException, JCRNodeFactoryServiceException, IOException { response.setContentType(RestProvider.CONTENT_TYPE); ServletOutputStream outputStream = response.getOutputStream(); outputStream.print("{ \"locale\" :"); outputStream.print(beanConverter.convertToString(UserLocale.localeToMap(locale))); outputStream.print(", \"preferences\" :"); Map<String, Object> m = new HashMap<String, Object>(); m.put("uuid", user.getUuid()); m.put("superUser", false); m.put("subjects", new String[0]); outputStream.print(beanConverter.convertToString(m)); outputPathPrefix(user.getUuid(), outputStream); outputUserProfile(user.getUuid(), outputStream); outputStream.print("}"); }
From source file:org.sakaiproject.kernel.rest.me.RestMeProvider.java
/** * Output another user, limited information set. * * @param elements//from w ww.ja v a 2 s. c o m * the path elements of the request. * @param request * the request object. * @param response * the response object. * @throws IOException * if there was a problem sending the output. * @throws RepositoryException * the there was a problem with the repository. */ private void doOtherUser(String[] elements, HttpServletRequest request, HttpServletResponse response) throws IOException, RepositoryException { String[] userIds = StringUtils.split(elements[1], ','); response.setContentType(RestProvider.CONTENT_TYPE); ServletOutputStream outputStream = response.getOutputStream(); outputStream.print("{ \"users\" : [ "); boolean first = true; if (userIds != null) { for (String userId : userIds) { if (!first) { outputStream.print(","); } User user = userResolverService.resolveWithUUID(userId); if (user == null) { outputStream.print( beanConverter.convertToString(ImmutableMap.of("statusCode", "404", "userId", userId))); } else { outputStream.print("{ \"statusCode\": \"200\", \"restricted\": true"); outputPathPrefix(user.getUuid(), outputStream); outputUserProfile(user.getUuid(), outputStream); outputStream.print("}"); } first = false; } } outputStream.print("]}"); }
From source file:net.urosk.reportEngine.ReportsServlet.java
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String reportDesign = request.getParameter("__report"); String type = request.getParameter("__format"); String outputFilename = request.getParameter("__filename"); String attachment = request.getParameter("attachment"); //check parameters StringBuffer msg = new StringBuffer(); // checkers/* w w w. ja v a 2 s . co m*/ if (isEmpty(reportDesign)) { msg.append("<BR>__report can not be empty"); } OutputType outputType = null; try { outputType = OutputType.valueOf(type.toUpperCase()); } catch (Exception e) { msg.append("Undefined report __format: " + type + ". Set __format=" + OutputType.values()); } // checkers if (isEmpty(outputFilename)) { msg.append("<BR>__filename can not be empty"); } try { ServletOutputStream out = response.getOutputStream(); ServletContext context = request.getSession().getServletContext(); // output error if (StringUtils.isNotEmpty(msg.toString())) { out.print(msg.toString()); return; } ReportDef def = new ReportDef(); def.setDesignFileName(reportDesign); def.setOutputType(outputType); @SuppressWarnings("unchecked") Map<String, String[]> params = request.getParameterMap(); Iterator<String> i = params.keySet().iterator(); while (i.hasNext()) { String key = i.next(); String value = params.get(key)[0]; def.getParameters().put(key, value); } try { String createdFile = birtReportEngine.createReport(def); File file = new File(createdFile); String mimetype = context.getMimeType(file.getAbsolutePath()); String inlineOrAttachment = (attachment != null) ? "attachment" : "inline"; response.setContentType((mimetype != null) ? mimetype : "application/octet-stream"); response.setContentLength((int) file.length()); response.setHeader("Content-Disposition", inlineOrAttachment + "; filename=\"" + outputFilename + "\""); DataInputStream in = new DataInputStream(new FileInputStream(file)); byte[] bbuf = new byte[1024]; int length; while ((in != null) && ((length = in.read(bbuf)) != -1)) { out.write(bbuf, 0, length); } in.close(); } catch (Exception e) { logger.error(e, e); out.print(e.getMessage()); } finally { out.flush(); out.close(); } logger.info("Free memory: " + (Runtime.getRuntime().freeMemory() / 1024L * 1024L)); } catch (Exception e) { logger.error(e, e); } finally { } }
From source file:org.bigbluebuttonproject.fileupload.web.FileUploadController.java
/** * This handler method overwriting the method in MultiActionController. * Its purpose is to stream slide XML from server to the HTTP response. * It writes the response using HttpServletResponse. * // w w w .ja v a2 s . c o m * @param request HttpServletRequest * @param response HttpServletResponse where the Slide XML is sent * * @return the xml slides * * @throws Exception the exception */ public ModelAndView getXmlSlides(HttpServletRequest request, HttpServletResponse response) throws Exception { Integer room = new Integer(request.getParameterValues("room")[0]); logger.info("Getting XML Slides [" + room + "]"); logger.info("Servlet Path = [" + request.getServletPath() + "]"); logger.info("Host = [" + request.getServerName() + ":" + request.getServerPort() + "]"); logger.info("Request URI = [" + request.getRequestURI() + "]"); logger.info("Request URL = [" + request.getRequestURL() + "]"); // get URL from client request int lastIndex = request.getRequestURL().lastIndexOf("/"); String url = request.getRequestURL().substring(0, lastIndex); // create slide presentation descriptor XML String slidesXml = createXml(url, getSlidesForRoom(room)); // String slidesXml = this.slideDatabase.getSlidesInXml(room); logger.info("XML Slides = " + slidesXml); // before sending the xml string to the client, // set content type and header response.setContentType("text/xml"); //Ask browser not to chache images response.setHeader("Cache-Control", "no-cache"); // get ServletOutputStream from HttpServletResponse ServletOutputStream out = response.getOutputStream(); // send the xml string to client out.print(slidesXml); out.flush(); out.close(); return null; }
From source file:org.openmrs.web.servlet.SampleFlowsheetServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Getting sample flowsheet"); response.setContentType("text/html"); HttpSession session = request.getSession(); String pid = request.getParameter("pid"); if (pid == null || pid.length() == 0) { session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "error.null"); return;//from w ww. java 2s. co m } if (!Context.isAuthenticated() || !Context.hasPrivilege(PrivilegeConstants.GET_PATIENTS) || !Context.hasPrivilege(PrivilegeConstants.GET_OBS)) { session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Privileges required: " + PrivilegeConstants.GET_PATIENTS + " and " + PrivilegeConstants.GET_OBS); session.setAttribute(WebConstants.OPENMRS_LOGIN_REDIRECT_HTTPSESSION_ATTR, request.getRequestURI() + "?" + request.getQueryString()); response.sendRedirect(request.getContextPath() + "/login.htm"); return; } ServletOutputStream out = response.getOutputStream(); Integer patientId = Integer.parseInt(pid); Patient patient = Context.getPatientService().getPatient(patientId); List<Obs> obsList = Context.getObsService().getObservationsByPerson(patient); if (obsList == null || obsList.size() < 1) { out.print("No observations found"); return; } out.println("<style>"); out.println(".header { font-family:Arial; font-weight:bold; text-align: center; font-size: 1.5em;}"); out.println( ".label { font-family:Arial; text-align:right; color:#808080; font-style:italic; font-size: 0.6em; vertical-align: top;}"); out.println(".value { font-family:Arial; text-align:left; vertical-align:top; }"); out.println("</style>"); out.println("<table cellspacing=0 cellpadding=3>"); Locale locale = Context.getLocale(); Calendar date = Calendar.getInstance(); date.set(1900, Calendar.JANUARY, 1); Calendar obsDate = Calendar.getInstance(); for (Obs obs : obsList) { obsDate.setTime(obs.getObsDatetime()); if (Math.abs(obsDate.getTimeInMillis() - date.getTimeInMillis()) > 86400000) { date = obsDate; out.println("<tr><td class=header colspan=2>" + Context.getDateFormat().format(date.getTime()) + "</td></tr>"); } StringBuilder s = new StringBuilder("<tr><td class=label>"); s.append(getName(obs, locale)); s.append("</td><td class=value>"); s.append(getValue(obs, locale)); s.append("</td></tr>"); out.println(s.toString()); } out.println("</table>"); }
From source file:org.sakaiproject.kernel.rest.me.RestMeProvider.java
private void outputPathPrefix(String uuid, ServletOutputStream outputStream) throws IOException { String pathPrefix = userFactoryService.getUserPathPrefix(uuid); outputStream.print(", \"userStoragePrefix\":\""); outputStream.print(pathPrefix);//from w w w . ja va 2 s. c o m outputStream.print("\""); }