List of usage examples for javax.servlet.http HttpServletRequest getServletContext
public ServletContext getServletContext();
From source file:net.swas.explorer.servlet.ms.WriteMSConfig.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) *//* ww w . j a v a 2s . co m*/ @SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Map<String, String[]> params = request.getParameterMap(); String status = "", msg = ""; PrintWriter out = response.getWriter(); JSONObject respJson = new JSONObject(); JSONObject messageJson = new JSONObject(); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); messageJson.put("action", "writeMSConfig"); if (FormFieldValidator.isLogin(request.getSession())) { for (String key : params.keySet()) { if (params.get(key) == null) { messageJson.put(key, ""); } else if (params.get(key)[0].equals("")) { messageJson.put(key, ""); } else { messageJson.put(key, params.get(key)[0]); } } log.info("Sending Json : " + messageJson.toJSONString()); this.prod.send(messageJson.toJSONString()); String revMsg = this.cons.getReceivedMessage(request.getServletContext()); log.info("Received Message :" + revMsg); if (revMsg != null) { JSONParser parser = new JSONParser(); JSONObject revJson = null; try { revJson = (JSONObject) parser.parse(revMsg); respJson = revJson; } catch (ParseException e) { status = "1"; msg = "Unable to reach modsercurity service. Please try later"; e.printStackTrace(); } } else { status = "1"; msg = "Unable to reach modsercurity service. Please try later"; log.info("Message is not received......"); } if (!status.equals("")) { respJson.put("status", status); respJson.put("message", msg); } } else { status = "2"; msg = "User Session Expired"; respJson.put("status", status); respJson.put("message", msg); } try { log.info("Sending Json : " + respJson.toString()); out.print(respJson.toString()); } finally { out.close(); } }
From source file:password.pwm.http.filter.RequestInitializationFilter.java
private void initializeServletRequest(final HttpServletRequest req, final HttpServletResponse resp, final FilterChain filterChain) throws IOException, ServletException { try {/*from w w w.j a v a 2s . c om*/ checkAndInitSessionState(req); PwmRequest.forRequest(req, resp); } catch (Throwable e) { LOGGER.error("can't load application: " + e.getMessage(), e); if (!(new PwmURL(req).isResourceURL())) { ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_APP_UNAVAILABLE); try { final ContextManager contextManager = ContextManager.getContextManager(req.getServletContext()); if (contextManager != null) { errorInformation = contextManager.getStartupErrorInformation(); } } catch (Throwable e2) { e2.getMessage(); } req.setAttribute(PwmRequestAttribute.PwmErrorInfo.toString(), errorInformation); final String url = JspUrl.APP_UNAVAILABLE.getPath(); req.getServletContext().getRequestDispatcher(url).forward(req, resp); } return; } try { final PwmRequest pwmRequest = PwmRequest.forRequest(req, resp); checkIfSessionRecycleNeeded(pwmRequest); handleRequestInitialization(pwmRequest); addPwmResponseHeaders(pwmRequest); checkIdleTimeout(pwmRequest); try { handleRequestSecurityChecks(pwmRequest); } catch (PwmUnrecoverableException e) { LOGGER.error(pwmRequest, e.getErrorInformation()); pwmRequest.respondWithError(e.getErrorInformation()); if (PwmError.ERROR_INTRUDER_SESSION != e.getError()) { pwmRequest.invalidateSession(); } return; } } catch (Throwable e) { final String logMsg = "can't init request: " + e.getMessage(); if (e instanceof PwmException && ((PwmException) e).getError() != PwmError.ERROR_UNKNOWN) { LOGGER.error(logMsg); } else { LOGGER.error(logMsg, e); } if (!(new PwmURL(req).isResourceURL())) { ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_APP_UNAVAILABLE); try { final ContextManager contextManager = ContextManager.getContextManager(req.getServletContext()); if (contextManager != null) { errorInformation = contextManager.getStartupErrorInformation(); } } catch (Throwable e2) { e2.getMessage(); } req.setAttribute(PwmRequestAttribute.PwmErrorInfo.toString(), errorInformation); final String url = JspUrl.APP_UNAVAILABLE.getPath(); req.getServletContext().getRequestDispatcher(url).forward(req, resp); } return; } filterChain.doFilter(req, resp); }
From source file:cpabe.controladores.UploadDecriptacaoServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<CaminhoArquivo> lista = new ArrayList<CaminhoArquivo>(); List<File> lista2 = new ArrayList<File>(); CaminhoArquivo c = new CaminhoArquivo(); if (!ServletFileUpload.isMultipartContent(request)) { throw new ServletException("Content type is not multipart/form-data"); }//from w ww.ja v a 2s .com // response.setContentType("text/html"); // PrintWriter out = response.getWriter(); // out.write("<html><head></head><body>"); try { List<FileItem> fileItemsList = uploader.parseRequest(request); Iterator<FileItem> fileItemsIterator = fileItemsList.iterator(); while (fileItemsIterator.hasNext()) { FileItem fileItem = fileItemsIterator.next(); System.out.println("FieldName=" + fileItem.getFieldName()); System.out.println("FileName=" + fileItem.getName()); System.out.println("ContentType=" + fileItem.getContentType()); System.out.println("Size in bytes=" + fileItem.getSize()); File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + fileItem.getName()); //setar no objeto CaminhoArquivo os dados do arquivo anexado String caminho = file.getAbsolutePath(); String nome = fileItem.getName(); c.setNome(nome); c.setWay(caminho); System.out.println("caminho=" + caminho); System.out.println("nome=" + nome); System.out.println("Absolute Path at server=" + file.getAbsolutePath()); fileItem.write(file); lista2.add(file); // out.write("File " + fileItem.getName() + " uploaded successfully."); // out.write("<br>"); // out.write("<a href=\"UploadDownloadFileServlet?fileName=" + fileItem.getName() + "\">Download " + fileItem.getName() + "</a>"); } } catch (FileUploadException e) { // out.write("Exception in uploading file."); } catch (Exception e) { // out.write("Exception in uploading file."); } // out.write("</body></html>"); //lendo a lista dos arquivos adicionados e pegando os caminhos do arquivo e da chave c.setWay(lista2.get(0).getAbsolutePath()); c.setNome(lista2.get(0).getName()); System.out.println("arquivo=" + lista2.get(0).getAbsolutePath()); c.setChave(lista2.get(1).getAbsolutePath()); System.out.println("chave=" + lista2.get(1).getAbsolutePath()); request.setAttribute("caminho", c); request.getRequestDispatcher("/formularios/decriptar/decriptar2.jsp").forward(request, response); }
From source file:com.dlshouwen.jspc.zwpc.controller.SelfEvaluateController.java
/** * ?// w w w. java 2s.co m * * @param expId_itemType * @param request * @return AJAX? * @throws Exception */ @RequestMapping(value = "/{expId_itemType}/refreshItems", method = RequestMethod.POST) @ResponseBody @Transactional public AjaxResponse refreshItems(@PathVariable String expId_itemType, HttpServletRequest request) throws Exception { // AJAX? AjaxResponse aresp = new AjaxResponse(); String expId = null; String itemType = null; if (StringUtils.isNotEmpty(expId_itemType)) { expId = expId_itemType.split("_")[0]; itemType = expId_itemType.split("_")[1]; } List<EvalItem> etList = new ArrayList<EvalItem>(); if (StringUtils.isNotEmpty(expId) && StringUtils.isNotEmpty(itemType)) { etList = dao.getByExpIdAndItemType(expId, itemType); } String html = getItemForHtml(etList, request.getServletContext()); Map map = new HashMap(); map.put("ITEM_DATE", html); map.put("ITEM_TYPE", itemType); aresp.setSuccess(true); aresp.setSuccessMessage("??"); aresp.setExtParam(map); return aresp; }
From source file:com.github.cxt.Myjersey.jerseycore.FileResource.java
@Path("upload") @POST//from w w w. ja va 2s. co m @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.APPLICATION_JSON) public String uploadFile(FormDataMultiPart form, @Context HttpServletRequest request) throws IOException { //??,httpclent? System.out.println(request.getCharacterEncoding()); Map<String, List<FormDataBodyPart>> map = form.getFields(); for (String key : map.keySet()) { FormDataBodyPart filePart = form.getField(key); //? InputStream inputStream = filePart.getValueAs(InputStream.class); FormDataContentDisposition disposition = filePart.getFormDataContentDisposition(); System.out.println(filePart.getMediaType()); if (disposition.getFileName() == null) {// System.out.println(key + "!" + filePart.getValue()); } else { String fileName = new String(disposition.getFileName().getBytes("ISO8859-1"), CHARSET); if (fileName != null && !fileName.trim().equals("")) { String name = Calendar.getInstance().getTimeInMillis() + fileName; String path = request.getServletContext().getRealPath("/"); path += File.separator + "data" + File.separator + name; File file = new File(path); try { FileUtils.copyInputStreamToFile(inputStream, file); } catch (IOException ex) { ex.printStackTrace(); return "{\"success\": false}"; } } } } return "{\"success\": true}"; }
From source file:BSxSB.Controllers.StudentController.java
@RequestMapping(method = RequestMethod.GET) public void doDownload(HttpServletRequest request, HttpServletResponse response) throws IOException { int BUFFER_SIZE = 4096; String filePath = "/WEB-INF/jsp/studentviewgenerated.jsp"; // get absolute path of the application ServletContext context = request.getServletContext(); String appPath = context.getRealPath(""); System.out.println("appPath = " + appPath); // construct the complete absolute path of the file String fullPath = appPath + filePath; File downloadFile = new File(fullPath); FileInputStream inputStream = new FileInputStream(downloadFile); // get MIME type of the file String mimeType = context.getMimeType(fullPath); if (mimeType == null) { // set to binary type if MIME mapping not found mimeType = "application/octet-stream"; }// w w w . ja v a 2s. co m System.out.println("MIME type: " + mimeType); // set content attributes for the response response.setContentType(mimeType); response.setContentLength((int) downloadFile.length()); // set headers for the response String headerKey = "Content-Disposition"; String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName()); response.setHeader(headerKey, headerValue); // get output stream of the response OutputStream outStream = response.getOutputStream(); byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1; // write bytes read from the input stream into the output stream while ((bytesRead = inputStream.read(buffer)) != -1) { outStream.write(buffer, 0, bytesRead); } inputStream.close(); outStream.close(); }
From source file:com.arcadian.loginservlet.StudentAssignmentServlet.java
/** * Handles the HTTP/*from w w w .j ava 2s .c o m*/ * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!ServletFileUpload.isMultipartContent(request)) { throw new ServletException("Content type is not multipart/form-data"); } response.setContentType("text/html"); PrintWriter out = response.getWriter(); try { List<FileItem> fileItemsList = uploader.parseRequest(request); Iterator<FileItem> fileItemsIterator = fileItemsList.iterator(); String assignmentid = ""; String filename = ""; while (fileItemsIterator.hasNext()) { FileItem fileItem = fileItemsIterator.next(); System.out.println(fileItem); if (fileItem.isFormField()) { String name = fileItem.getFieldName(); String value = fileItem.getString(); if (name.equalsIgnoreCase("assignmentid")) { assignmentid = value; } System.out.println("Assignment id==" + assignmentid); } if (fileItem.getName() != null) { File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + fileItem.getName()); System.out.println("Absolute Path at server=" + file.getAbsolutePath()); fileItem.write(file); filename = fileItem.getName(); } } assignmentFoldetService = new AssignmentFolderService(); assignmentFoldetService.updateAssignmentFolder(username, assignmentid, filename); } catch (FileUploadException e) { System.out.println("Exception in file upload" + e); } catch (Exception ex) { Logger.getLogger(CourseContentServlet.class.getName()).log(Level.SEVERE, null, ex); } processRequest(request, response); }
From source file:org.debux.webmotion.server.WebMotionServer.java
/** * Static resources management/*from w w w .j a v a2 s . co m*/ */ protected void doResource(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Suppress the static in path HttpServletRequest requestWrapper = new HttpServletRequestWrapper(request) { @Override public String getServletPath() { String servletPath = super.getServletPath(); if (servletPath != null) { return servletPath.replaceFirst(PATH_STATIC, ""); } return null; } @Override public String getPathInfo() { String pathInfo = super.getPathInfo(); if (pathInfo != null) { return pathInfo.replaceFirst(PATH_STATIC, ""); } return null; } @Override public String getRequestURI() { String requestURI = super.getRequestURI(); if (requestURI != null) { return requestURI.replaceFirst(PATH_STATIC, ""); } return null; } }; // Dispatch on default servlet ServletContext servletContext = request.getServletContext(); RequestDispatcher dispatcher = servletContext.getNamedDispatcher("default"); DispatcherType dispatcherType = request.getDispatcherType(); if (dispatcherType == DispatcherType.INCLUDE) { dispatcher.include(requestWrapper, response); } else { dispatcher.forward(requestWrapper, response); } }
From source file:org.flowerplatform.core.file.upload.UploadServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { return;/*from w w w .java 2 s. co m*/ } // entire URL displayed after servlet name ("servlet/upload") -> /uploadId/file_to_upload_name String uploadId = request.getPathInfo().substring(1, request.getPathInfo().lastIndexOf("/")); UploadService uploadService = ((UploadService) CorePlugin.getInstance().getServiceRegistry() .getService("uploadService")); UploadInfo uploadInfo = uploadService.getUploadInfo(uploadId); if (uploadInfo.getTmpLocation() == null) { return; } logger.trace("Uploading {}", uploadInfo); // create temporary upload location file for archive that needs to be unzipped after File file = new File(uploadInfo.getTmpLocation()); if (!file.exists() && uploadInfo.unzipFile()) { file.createNewFile(); } // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(uploadService.getTemporaryUploadDirectory()); factory.setFileCleaningTracker(FileCleanerCleanup.getFileCleaningTracker(request.getServletContext())); // Create a new file upload handler ServletFileUpload uploadHandler = new ServletFileUpload(factory); File uploadedFile = null; try { // Parse the request List<FileItem> items = uploadHandler.parseRequest(request); // Process the uploaded items Iterator<FileItem> it = items.iterator(); while (it.hasNext()) { FileItem item = it.next(); if (!item.isFormField()) { // uploaded file uploadedFile = new File(uploadInfo.unzipFile() ? uploadInfo.getTmpLocation() : (uploadInfo.getTmpLocation() + "/" + item.getName())); item.write(uploadedFile); } } if (uploadInfo.unzipFile()) { // unzip file if requested CoreUtils.unzipArchive(uploadedFile, new File(uploadInfo.getLocation())); } } catch (Exception e) { // something happened or user cancelled the upload while in progress if (uploadedFile != null) { CoreUtils.delete(uploadedFile); } } }
From source file:com.dlshouwen.core.api.controller.ApiController.java
/** * ???//from w w w . j a v a2 s . c o m * * @param request * @param response * @throws Exception */ @RequestMapping(value = "/getUser") public void getUser(HttpServletRequest request, HttpServletResponse response) throws Exception { String loginName = request.getParameter("username"); JSONObject obj = new JSONObject(); if (loginName != null && loginName.trim().length() > 0) { User user = userDao.getUserByCode(loginName); if (user != null) { obj.put("userName", user.getUser_code()); if (StringUtils.isNotEmpty(user.getImgpath())) { String ipath = ""; try { ipath = user.getImgpath().substring(user.getImgpath().lastIndexOf("/") + 1, user.getImgpath().lastIndexOf(".")); } catch (Exception e) { ipath = ""; } obj.put("avatar", ipath); } else { obj.put("avatar", ""); } obj.put("emailbox", user.getEmail()); obj.put("mobilephone", user.getPhone()); obj.put("telephone", user.getPhone()); if (user.getImgpath() != null && user.getImgpath().trim().length() > 0) { String recordNumberStr = AttributeUtils.getAttributeContent(request.getServletContext(), "source_webapp_file_postion"); obj.put("avatarData", GetImageStr(recordNumberStr + user.getImgpath())); } } } response.setContentType("text/html;charset=utf-8"); response.getWriter().write(obj.toString()); }