List of usage examples for javax.servlet.http HttpServletRequest setCharacterEncoding
public void setCharacterEncoding(String env) throws UnsupportedEncodingException;
From source file:com.wx.CustomerWXServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*w w w . j a v a2s . c o m*/ * @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 { String sToken = "testToken"; String sCorpID = "wxe706b25abb1216c0"; String sEncodingAESKey = "AWdjbue1y51jzlAMwBCSm9GDt7zW6zuIbNqGEPcqsRR"; request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); String msg_signature = request.getParameter("msg_signature"); String timestamp = request.getParameter("timestamp"); String nonce = request.getParameter("nonce"); InputStream inputStream = request.getInputStream(); String postData = IOUtils.toString(inputStream, "UTF-8"); System.out.println(postData); String msg = ""; WXBizMsgCrypt wxcpt = null; try { wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); //? msg = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, postData); } catch (AesException e) { e.printStackTrace(); } System.out.println("msg=" + msg); BaseMessage respMessage = CoreService.processRequest(msg, classService); String resMsg = null; /** if (request.getSession().getAttribute("accessToken") == null) { try { String accessToken = CoreService.getAccessToken(config.getInitParameter("corpid"), config.getInitParameter("corpsecret")); request.getSession().setAttribute("accessToken", accessToken); QyWxURLUtil.applyAccessToken(accessToken); } catch (Exception ex) { Logger.getLogger(TestWXServlet.class.getName()).log(Level.SEVERE, null, ex); } } **/ /** * UploadMediaReturnMessage uploadMediaReturnMsg; try { * uploadMediaReturnMsg = WXUtils.send("image", * "/root/WXMedia/anranhui520/1.jpg"); * if("null".equals(uploadMediaReturnMsg.getErrcode())){ * System.out.println("Media_id:"+uploadMediaReturnMsg.getMedia_id()); * }else{ System.out.println("Upload error * message:"+uploadMediaReturnMsg.getErrmsg()+" error * code:"+uploadMediaReturnMsg.getErrcode()); * * } * } catch (Exception ex) { * Logger.getLogger(TestWXServlet.class.getName()).log(Level.SEVERE, * null, ex); } * */ if (respMessage instanceof TextMessage) { /*try { TextMessage txtMsg = (TextMessage) respMessage; String command = txtMsg.getContent(); CheckCommandReturnMessage ccReturnMsg = CMDService.processCheckingCommand(command); Set<UserInfo> userInfoSet = ccReturnMsg.getUserInfos(); UserInfo userif = null; for (UserInfo userInfo : userInfoSet) { userif = userInfo; } System.out.println("msgContent:" + ccReturnMsg.getContent()); System.out.println("weixinid:" + userif.getWeixinid()); try { UploadMediaReturnMessage uploadMediaReturnMsg = null; try { QRCodeGenerator.encode(ccReturnMsg.getContent(), "/root/WXMedia/"+userif.getWeixinid()); uploadMediaReturnMsg = WXUtils.send("image", "/root/WXMedia/"+userif.getWeixinid()+"/qrcode.jpg"); if ("null".equals(uploadMediaReturnMsg.getErrcode())) { System.out.println("Media_id:" + uploadMediaReturnMsg.getMedia_id()); } else { System.out.println("Upload error message:" + uploadMediaReturnMsg.getErrmsg() + " error code:" + uploadMediaReturnMsg.getErrcode()); } } catch (Exception ex) { Logger.getLogger(CustomerWXServlet.class.getName()).log(Level.SEVERE, null, ex); }*/ /** * TextSendMessage textMsg = new TextSendMessage(); String * msgtxt = ccReturnMsg.getContent(); * textMsg.setTextContent(msgtxt); * textMsg.setMsgtype("text"); * textMsg.setTouser(userif.getWeixinid()); * textMsg.setAgentid(Long.parseLong(config.getInitParameter("checkingAgentId"))); * */ /* ImageSendMessage imgMsg = new ImageSendMessage(); imgMsg.setImageMedia(uploadMediaReturnMsg.getMedia_id()); imgMsg.setMsgtype("image"); imgMsg.setTouser(userif.getWeixinid()); imgMsg.setAgentid(Long.parseLong(config.getInitParameter("checkingAgentId"))); AccessTokenReturnMessage returnMsg = CoreService.sendMessage(imgMsg); } catch (Exception ex) { Logger.getLogger(CustomerWXServlet.class.getName()).log(Level.SEVERE, null, ex); } } catch (Exception ex) { Logger.getLogger(CustomerWXServlet.class.getName()).log(Level.SEVERE, null, ex); }*/ } else if (respMessage instanceof NewsMessage) { System.out.println("enter NewsMessage."); NewsMessage newsMsg = (NewsMessage) respMessage; resMsg = MessageUtil.newsMessageToXml(newsMsg); System.out.println("ResMsg:" + resMsg); } PrintWriter out = response.getWriter(); out.print(resMsg); out.flush(); out.close(); }
From source file:org.jlibrary.web.servlet.JLibraryContentLoaderServlet.java
private void processContent(HttpServletRequest req, HttpServletResponse resp) { try {/* w ww. j a v a 2 s . com*/ resp.setCharacterEncoding("ISO-8859-1"); req.setCharacterEncoding("ISO-8859-1"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } String appURL = req.getContextPath(); String uri = req.getRequestURI(); String path = StringUtils.difference(appURL + "/repositories", uri); if (path.equals("") || path.equals("/")) { // call to /repositories try { Ticket ticket = TicketService.getTicketService().getSystemTicket(); List repoInfo = repositoryService.findAllRepositoriesInfo(ticket); Iterator it = repoInfo.iterator(); List<RepositoryInfo> repositories = new ArrayList<RepositoryInfo>(); while (it.hasNext()) { RepositoryInfo info = (RepositoryInfo) it.next(); if (info.getName().equals("system") || info.getName().equals("default")) { continue; } repositories.add(info); } RequestDispatcher rd = getServletContext().getRequestDispatcher("/repositories.jsp"); req.setAttribute("repositories", repositories); rd.forward(req, resp); return; } catch (Exception e) { logger.error(e.getMessage(), e); //TODO: mandar a una pgina de error esttica } } String[] pathElements = StringUtils.split(path, "/"); String repositoryName = getRepositoryName(req); Ticket ticket = TicketService.getTicketService().getTicket(req, repositoryName); Repository repository = null; try { repository = loadRepository(repositoryName, ticket); if (pathElements.length > 1) { if (pathElements[1].equals("categories")) { String categoryPath = StringUtils .difference(appURL + "/repositories/" + repositoryName + "/categories", uri); Category category = findCategory(repository, pathElements); if (category == null) { resp.setStatus(HttpServletResponse.SC_NOT_FOUND); resp.flushBuffer(); } else { String output = exportCategory(req, resp, ticket, repository, category); resp.getOutputStream().write(output.getBytes()); resp.flushBuffer(); } return; } } Node node = null; String nodePath = StringUtils.difference(appURL + "/repositories/" + repositoryName, uri); if (pathElements.length == 1) { node = repository.getRoot(); } else { node = findNode(ticket, repositoryService, nodePath); } if (node == null) { logger.debug("Node could not be found"); } else { req.setAttribute("node", node); /* resp.setDateHeader("Last-Modified", node.getDate().getTime()); resp.setDateHeader("Age", 86400); // cache a day */ if (node.isDocument()) { Document document = (Document) node; byte[] output; if ("true".equals(req.getParameter("download"))) { output = repositoryService.loadDocumentContent(document.getId(), ticket); if (document.isImage()) { resp.setContentType( Types.getMimeTypeForExtension(FileUtils.getExtension(document.getPath()))); } else { resp.setContentType("application/octet-stream"); } } else { output = exportDocument(req, ticket, repository, node).getBytes(); } resp.getOutputStream().write(output); resp.flushBuffer(); } else if (node.isDirectory()) { // Search for a root document (index.html) String output = exportDirectory(req, resp, ticket, repository, node); resp.getOutputStream().write(output.getBytes()); resp.flushBuffer(); } else if (node.isResource()) { exportResouce(req, resp, repositoryService, ticket, node); } } } catch (NodeNotFoundException nnfe) { logErrorAndForward(req, resp, repositoryName, nnfe, "The requested page could not be found."); } catch (SecurityException se) { logErrorAndForward(req, resp, repositoryName, se, "You do not have enough rights for accessing to the requested page."); } catch (Exception e) { //TODO:mandar a pgina de error esttica e.printStackTrace(); } }
From source file:edu.umd.lib.servlets.permissions.PermissionsServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // explicitly set character encoding req.setCharacterEncoding("UTF-8"); res.setCharacterEncoding("UTF-8"); if (!BasicAuth.hasAuthorizationHeader(req)) { BasicAuth.setRequestAuthorizationHeaders(res, "Repository"); return;/*from ww w . j a v a 2s . c om*/ } // Use user id from credentials as default userid. SimpleCredentials creds = BasicAuth.parseAuthorizationHeader(req); String userId = creds.getUserID(); log.debug("userId={}", userId); Session jcrSession = null; Session impersonateSession = null; Map<String, Object> templateParams = new HashMap<String, Object>(); String defaultJcrPath = "/"; templateParams.put("jcrUserId", userId); templateParams.put("jcrPath", defaultJcrPath); try { renderTemplatePage(req, res, getRenderTemplate(req), templateParams); } catch (TemplateException te) { log.warn("Failed to render freemarker template.", te); } }
From source file:com.openkm.servlet.frontend.ConverterServlet.java
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("service({}, {})", request, response); request.setCharacterEncoding("UTF-8"); String uuid = WebUtils.getString(request, "uuid"); boolean inline = WebUtils.getBoolean(request, "inline"); boolean print = WebUtils.getBoolean(request, "print"); boolean toPdf = WebUtils.getBoolean(request, "toPdf"); boolean toSwf = WebUtils.getBoolean(request, "toSwf"); CharsetDetector detector = new CharsetDetector(); File tmp = null;/*from w ww. j a v a 2 s .c o m*/ InputStream is = null; ConverterListener listener = new ConverterListener(ConverterListener.STATUS_LOADING); updateSessionManager(request); try { // Now an document can be located by UUID if (!uuid.equals("")) { // Saving listener to session request.getSession().setAttribute(FILE_CONVERTER_STATUS, listener); String path = OKMRepository.getInstance().getNodePath(null, uuid); Document doc = OKMDocument.getInstance().getProperties(null, path); String fileName = PathUtils.getName(doc.getPath()); // Save content to temporary file tmp = File.createTempFile("okm", "." + FileUtils.getFileExtension(fileName)); if (Config.REPOSITORY_NATIVE) { // If is used to preview, it should workaround the DOWNLOAD extended permission. is = new DbDocumentModule().getContent(null, path, false, !(toSwf)); } else { is = new JcrDocumentModule().getContent(null, path, false); } // Text files may need encoding conversion if (doc.getMimeType().startsWith("text/")) { detector.setText(new BufferedInputStream(is)); CharsetMatch cm = detector.detect(); Reader rd = cm.getReader(); FileUtils.copy(rd, tmp); IOUtils.closeQuietly(is); IOUtils.closeQuietly(rd); } else { FileUtils.copy(is, tmp); IOUtils.closeQuietly(is); } // Prepare conversion ConversionData cd = new ConversionData(); cd.uuid = uuid; cd.fileName = fileName; cd.mimeType = doc.getMimeType(); cd.file = tmp; if (toPdf && !cd.mimeType.equals(MimeTypeConfig.MIME_PDF)) { try { listener.setStatus(ConverterListener.STATUS_CONVERTING_TO_PDF); toPDF(cd); listener.setStatus(ConverterListener.STATUS_CONVERTING_TO_PDF_FINISHED); } catch (ConversionException e) { log.error(e.getMessage(), e); listener.setError(e.getMessage()); InputStream tis = ConverterServlet.class.getResourceAsStream("conversion_problem.pdf"); FileUtils.copy(tis, cd.file); } } else if (toSwf && !cd.mimeType.equals(MimeTypeConfig.MIME_SWF)) { try { listener.setStatus(ConverterListener.STATUS_CONVERTING_TO_SWF); toSWF(cd); listener.setStatus(ConverterListener.STATUS_CONVERTING_TO_SWF_FINISHED); } catch (ConversionException e) { log.error(e.getMessage(), e); listener.setError(e.getMessage()); InputStream tis = ConverterServlet.class.getResourceAsStream("conversion_problem.swf"); FileUtils.copy(tis, cd.file); } } if (toPdf && print) { cd.file = PDFUtils.markToPrint(cd.file); } // Send back converted document listener.setStatus(ConverterListener.STATUS_SENDING_FILE); WebUtils.sendFile(request, response, cd.fileName, cd.mimeType, inline, cd.file); } else { log.error("Missing Conversion Parameters"); response.setContentType(MimeTypeConfig.MIME_TEXT); PrintWriter out = response.getWriter(); out.print("Missing Conversion Parameters"); out.flush(); out.close(); } } catch (PathNotFoundException e) { log.warn(e.getMessage(), e); listener.setError(e.getMessage()); throw new ServletException(new OKMException( ErrorCode.get(ErrorCode.ORIGIN_OKMDownloadService, ErrorCode.CAUSE_PathNotFound), e.getMessage())); } catch (AccessDeniedException e) { log.warn(e.getMessage(), e); listener.setError(e.getMessage()); throw new ServletException(new OKMException( ErrorCode.get(ErrorCode.ORIGIN_OKMDownloadService, ErrorCode.CAUSE_AccessDenied), e.getMessage())); } catch (RepositoryException e) { log.warn(e.getMessage(), e); listener.setError(e.getMessage()); throw new ServletException( new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDownloadService, ErrorCode.CAUSE_Repository), e.getMessage())); } catch (IOException e) { log.error(e.getMessage(), e); listener.setError(e.getMessage()); throw new ServletException(new OKMException( ErrorCode.get(ErrorCode.ORIGIN_OKMDownloadService, ErrorCode.CAUSE_IO), e.getMessage())); } catch (DatabaseException e) { log.error(e.getMessage(), e); listener.setError(e.getMessage()); throw new ServletException(new OKMException( ErrorCode.get(ErrorCode.ORIGIN_OKMDownloadService, ErrorCode.CAUSE_Database), e.getMessage())); } catch (Exception e) { log.error(e.getMessage(), e); listener.setError(e.getMessage()); throw new ServletException(new OKMException( ErrorCode.get(ErrorCode.ORIGIN_OKMDownloadService, ErrorCode.CAUSE_General), e.getMessage())); } finally { listener.setConversionFinish(true); org.apache.commons.io.FileUtils.deleteQuietly(tmp); } log.debug("service: void"); }
From source file:Controlador.Contr_Seleccion.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* w w w .j a v a2 s . c om*/ * * @param request servlet request * @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 { /*Se detalla el contenido que tendra el servlet*/ response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); /*Se crea una variable para la sesion*/ HttpSession session = request.getSession(true); boolean b; try { /*Se declaran las variables necesarias*/ Cls_Seleccion sel = new Cls_Seleccion(); String Codigo = "", Mensaje = "", Nombre = "", Tipo = "", Imagen = "", url, Peti; String urlsalidaimg; urlsalidaimg = "/media/santiago/Santiago/IMGTE/"; //urlsalidaimg = "D:\\IMGTE\\"; String urlimgservidor = this.getServletContext().getRealPath("/Libs/Customs/images/Seleccion"); /*FileItemFactory es una interfaz para crear FileItem*/ FileItemFactory file_factory = new DiskFileItemFactory(); /*ServletFileUpload esta clase convierte los input file a FileItem*/ ServletFileUpload servlet_up = new ServletFileUpload(file_factory); /*sacando los FileItem del ServletFileUpload en una lista */ servlet_up.setHeaderEncoding("UTF-8"); List items = servlet_up.parseRequest(request); Iterator it = items.iterator(); /*Se evalua cada una de las posibles peticiones y los posibles campos que envien*/ while (it.hasNext()) { FileItem item = (FileItem) it.next(); if (item.isFormField()) { //Plain request parameters will come here. String name = item.getFieldName(); if (name.equals("Codigo")) { /*Se guarda el campo en la clase*/ sel.setCodigo(item.getString()); } else if (name.equals("Nombre")) { /** * Se guarda el campo en la clase */ sel.setNombre(item.getString()); } else if (name.equals("Tipo")) { /** * Se guarda el campo en la clase */ sel.setTipo(item.getString()); } else if (name.equals("Estado")) { /** * Se guarda el campo en la clase */ sel.setEstado(item.getString()); } else if (name.equals("RegistrarSeleccion")) { /*Se evalua si se mando una iamgen, cuando se va a registrar un evento*/ if (!sel.getImagen().equals("")) { /*Si se envia una imagen obtiene la imagen para guardarla en el server luego*/ File img = new File(sel.getImagen()); /*Se ejecuta el metodo de registrar usuario que se encuentra, en la clase modelo con los datos que se encuentran en la clase*/ b = sel.setRegistrarSeleccion(sel.getNombre(), sel.getTipo(), sel.getTypeImg()); if (b) { /*Se guarda un mensaje mediante las sesiones y se redirecciona*/ File imagedb = new File(urlimgservidor + "/" + sel.getCodigo() + sel.getTypeImg()); img.renameTo(imagedb); session.setAttribute("Mensaje", "El gusto o ambiente ha sido registrado correctamente."); session.setAttribute("TipoMensaje", "Dio"); url = "View/ConsultaSeleccion.jsp"; response.sendRedirect(url); } else { img.delete(); /*Se guarda un mensaje de error mediante las sesiones y se redirecciona*/ session.setAttribute("Mensaje", sel.getMensaje()); session.setAttribute("TipoMensaje", "NODio"); url = "View/ConsultaSeleccion.jsp"; response.sendRedirect(url); } } else { /*Se guarda un mensaje de error mediante las sesiones y se redirecciona*/ session.setAttribute("Mensaje", "Seleccione una imagen, para registrar el ambiente o gusto."); session.setAttribute("TipoMensaje", "NODio"); } } else if (name.equals("ModificarSeleccion")) { if (sel.getImagen().equals("")) { /*Se ejecuta el metodo de actualizar los datos de la seleccion usuario que se encuentra, en la clase modelo con los datos que se encuentran en la clase*/ b = sel.actualizardatosSeleccion(sel.getCodigo(), sel.getNombre(), sel.getTipo(), sel.getEstado()); if (b) { /*Se guarda un mensaje mediante las sesiones y se redirecciona*/ session.setAttribute("Mensaje", "El gusto o ambiente ha sido registrada correctamente."); session.setAttribute("TipoMensaje", "Dio"); url = "View/ConsultaSeleccion.jsp"; response.sendRedirect(url); } else { /*Se guarda un mensaje mediante las sesiones y se redirecciona*/ session.setAttribute("Mensaje", sel.getMensaje()); session.setAttribute("TipoMensaje", "NODio"); url = "View/ConsultaSeleccion.jsp"; response.sendRedirect(url); } } else { /*Se ejecuta el metodo de actualizar los datos de la seleccion usuario que se encuentra, en la clase modelo con los datos que se encuentran en la clase*/ File img = new File(sel.getImagen()); b = sel.actualizardatosSeleccion(sel.getCodigo(), sel.getNombre(), sel.getTipo(), sel.getTypeImg(), sel.getEstado()); if (b) { File imagedb = new File(urlimgservidor + "/" + sel.getCodigo() + sel.getTypeImg()); img.renameTo(imagedb); /*Se guarda un mensaje mediante las sesiones y se redirecciona*/ session.setAttribute("Mensaje", "El gusto o ambiente ha sido modificado correctamente."); session.setAttribute("TipoMensaje", "Dio"); url = "View/ConsultaSeleccion.jsp"; response.sendRedirect(url); } else { img.delete(); /*Se guarda un mensaje mediante las sesiones y se redirecciona*/ session.setAttribute("Mensaje", sel.getMensaje()); session.setAttribute("TipoMensaje", "NODio"); url = "View/ConsultaSeleccion.jsp"; response.sendRedirect(url); } } } } else { if (!item.getName().equals("")) { //uploaded files will come here. FileItem file = item; String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); if (sizeInBytes > 1000000) { /*Se muestra un mensaje en caso de pesar mas de 3 MB*/ session.setAttribute("Mensaje", "El tamao lmite de la imagen es: 1 MB"); session.setAttribute("TipoMensaje", "NODio"); /*Se redirecciona*/ response.sendRedirect("View/ConsultaSeleccion.jsp"); } else { if (contentType.indexOf("jpeg") > 0 || contentType.indexOf("png") > 0) { if (contentType.indexOf("jpeg") > 0) { contentType = ".jpg"; } else { contentType = ".png"; } /*Se crea la imagne*/ File archivo_server = new File(urlimgservidor + "/" + item.getName()); /*Se guardael nombre y tipo de imagen en la clase*/ sel.setImagen(urlimgservidor + "/" + item.getName()); sel.setTypeImg(contentType); /*Se guarda la imagen*/ item.write(archivo_server); } else { session.setAttribute("Mensaje", "Solo se pueden registrar imagenes JPG o PNG"); session.setAttribute("TipoMensaje", "NODio"); } } } else { /*Se guarda el url de la imagen en la clase*/ sel.setImagen(""); } } } /*Se redirecciona sino se recive ninguna peticion*/ response.sendRedirect("View/index.jsp"); } catch (FileUploadException ex) { /*Se muestra un mensaje en caso de error*/ System.out.print(ex.getMessage().toString()); } catch (Exception ex) { /*Se muestra un mensaje en caso de error*/ Logger.getLogger(Contr_Seleccion.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.apache.pluto.driver.PortalDriverServlet.java
/** * Handle all requests. All POST requests are passed to this method. * // w w w . j av a2s.c om * @param request * the incoming HttpServletRequest. * @param response * the incoming HttpServletResponse. * @throws ServletException * if an internal error occurs. * @throws IOException * if an error occurs writing to the response. */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (LOG.isDebugEnabled()) { LOG.debug("Start of PortalDriverServlet.doGet() to process portlet request . . ."); } if (charset != null) { request.setCharacterEncoding(charset); } PortalRequestContext portalRequestContext = new PortalRequestContext(getServletContext(), request, response); PortalURL portalURL = null; try { portalURL = portalRequestContext.getRequestedPortalURL(); } catch (Exception ex) { String msg = "Cannot handle request for portal URL. Problem: " + ex.getMessage(); LOG.error(msg, ex); throw new ServletException(msg, ex); } // Add by xiejj for support multispace Resource resource = functions.getSavedViewPort(request); VWBContext context = VWBContext.createContext(request, PortalCommand.VIEW, resource); if (!context.hasAccess(response)) { return; } // end xiejj String actionWindowId = portalURL.getActionWindow(); String resourceWindowId = portalURL.getResourceWindow(); PortletWindowConfig actionWindowConfig = null; PortletWindowConfig resourceWindowConfig = null; if (resourceWindowId != null) { resourceWindowConfig = PortletWindowConfig.fromId(resourceWindowId); } else if (actionWindowId != null) { actionWindowConfig = PortletWindowConfig.fromId(actionWindowId); } // ????? // ??? if (resourceWindowConfig == null) { if (!"".equals(contentType)) { response.setContentType(contentType); } } // Action window config will only exist if there is an action request. if (actionWindowConfig != null) { PortletWindowImpl portletWindow = new PortletWindowImpl(container, actionWindowConfig, portalURL); if (LOG.isDebugEnabled()) { LOG.debug("Processing action request for window: " + portletWindow.getId().getStringId()); } try { container.doAction(portletWindow, request, response); } catch (PortletContainerException ex) { LOG.error(ex.getMessage(), ex); throw new ServletException(ex); } catch (PortletException ex) { LOG.error(ex.getMessage(), ex); throw new ServletException(ex); } if (LOG.isDebugEnabled()) { LOG.debug("Action request processed.\n\n"); } } // Resource request else if (resourceWindowConfig != null) { try { if (request.getParameterNames().hasMoreElements()) setPublicRenderParameter(request, portalURL, portalURL.getResourceWindow()); } catch (PortletContainerException e) { LOG.error(e); throw new ServletException(e); } PortletWindowImpl portletWindow = new PortletWindowImpl(container, resourceWindowConfig, portalURL); if (LOG.isDebugEnabled()) { LOG.debug("Processing resource Serving request for window: " + portletWindow.getId().getStringId()); } try { container.doServeResource(portletWindow, request, response); } catch (PortletContainerException ex) { LOG.error(ex.getMessage(), ex); throw new ServletException(ex); } catch (PortletException ex) { LOG.error(ex.getMessage(), ex); throw new ServletException(ex); } if (LOG.isDebugEnabled()) { LOG.debug("Resource serving request processed.\n\n"); } } // Otherwise (actionWindowConfig == null), handle the render request. else { if (LOG.isDebugEnabled()) { LOG.debug("Processing render request."); } PageConfig pageConfig = portalURL.getPageConfig(request); if (pageConfig == null) { String renderPath = (portalURL == null ? "" : portalURL.getRenderPath()); String msg = "PageConfig for render path [" + renderPath + "] could not be found."; LOG.error(msg); throw new ServletException(msg); } request.setAttribute(AttributeKeys.CURRENT_PAGE, pageConfig); String uri = (pageConfig.getUri() != null) ? pageConfig.getUri() : DEFAULT_PAGE_URI; if (LOG.isDebugEnabled()) { LOG.debug("Dispatching to: " + uri); } functions.layout(request, response, context); if (LOG.isDebugEnabled()) { LOG.debug("Render request processed.\n\n"); } } }
From source file:com.ikon.servlet.admin.ConfigServlet.java
@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.debug("doGet({}, {})", request, response); request.setCharacterEncoding("UTF-8"); String action = WebUtils.getString(request, "action"); String filter = WebUtils.getString(request, "filter"); String userId = request.getRemoteUser(); updateSessionManager(request);//from ww w. j a v a2s . com try { if (action.equals("create")) { create(userId, types, request, response); } else if (action.equals("edit")) { edit(userId, types, request, response); } else if (action.equals("delete")) { delete(userId, types, request, response); } else if (action.equals("check")) { check(userId, request, response); } else if (action.equals("export")) { export(userId, request, response); } else { list(userId, filter, request, response); } } catch (DatabaseException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } }
From source file:org.apache.openmeetings.servlet.outputhandler.DownloadHandler.java
@Override protected void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { try {/* w ww . j a v a2s .c om*/ httpServletRequest.setCharacterEncoding("UTF-8"); log.debug("\nquery = " + httpServletRequest.getQueryString()); log.debug("\n\nfileName = " + httpServletRequest.getParameter("fileName")); log.debug("\n\nparentPath = " + httpServletRequest.getParameter("parentPath")); String queryString = httpServletRequest.getQueryString(); if (queryString == null) { queryString = ""; } String sid = httpServletRequest.getParameter("sid"); if (sid == null) { sid = "default"; } log.debug("sid: " + sid); Long users_id = getBean(SessiondataDao.class).checkSession(sid); Long user_level = getBean(UserManager.class).getUserLevelByID(users_id); if (user_level != null && user_level > 0) { String room_id = httpServletRequest.getParameter("room_id"); if (room_id == null) { room_id = "default"; } String moduleName = httpServletRequest.getParameter("moduleName"); if (moduleName == null) { moduleName = "nomodule"; } String parentPath = httpServletRequest.getParameter("parentPath"); if (parentPath == null) { parentPath = "nomodule"; } String requestedFile = httpServletRequest.getParameter("fileName"); if (requestedFile == null) { requestedFile = ""; } String fileExplorerItemIdParam = httpServletRequest.getParameter("fileExplorerItemId"); Long fileExplorerItemId = null; if (fileExplorerItemIdParam != null) { fileExplorerItemId = Long.parseLong(fileExplorerItemIdParam); } // make a complete name out of domain(organisation) + roomname String roomName = room_id; // trim whitespaces cause it is a directory name roomName = StringUtils.deleteWhitespace(roomName); // Get the current User-Directory File working_dir; // Add the Folder for the Room if (moduleName.equals("lzRecorderApp")) { working_dir = OmFileHelper.getStreamsHibernateDir(); } else if (moduleName.equals("videoconf1")) { working_dir = OmFileHelper.getUploadRoomDir(roomName); if (parentPath.length() != 0 && !parentPath.equals("/")) { working_dir = new File(working_dir, parentPath); } } else if (moduleName.equals("userprofile")) { working_dir = OmFileHelper.getUploadProfilesUserDir(users_id); logNonExistentFolder(working_dir); } else if (moduleName.equals("remoteuserprofile")) { String remoteUser_id = httpServletRequest.getParameter("remoteUserid"); working_dir = OmFileHelper .getUploadProfilesUserDir(remoteUser_id == null ? "0" : remoteUser_id); logNonExistentFolder(working_dir); } else if (moduleName.equals("remoteuserprofilebig")) { String remoteUser_id = httpServletRequest.getParameter("remoteUserid"); working_dir = OmFileHelper .getUploadProfilesUserDir(remoteUser_id == null ? "0" : remoteUser_id); logNonExistentFolder(working_dir); requestedFile = getBigProfileUserName(working_dir); } else if (moduleName.equals("chat")) { String remoteUser_id = httpServletRequest.getParameter("remoteUserid"); working_dir = OmFileHelper .getUploadProfilesUserDir(remoteUser_id == null ? "0" : remoteUser_id); logNonExistentFolder(working_dir); requestedFile = getChatUserName(working_dir); } else { working_dir = OmFileHelper.getUploadRoomDir(roomName); } if (!moduleName.equals("nomodule")) { log.debug("requestedFile: " + requestedFile + " current_dir: " + working_dir); File full_path = new File(working_dir, requestedFile); // If the File does not exist or is not readable show/load a // place-holder picture if (!full_path.exists() || !full_path.canRead()) { if (!full_path.canRead()) { log.debug("LOG DownloadHandler: The request file is not readable "); } else { log.debug( "LOG DownloadHandler: The request file does not exist / has already been deleted"); } log.debug("LOG ERROR requestedFile: " + requestedFile); // replace the path with the default picture/document if (requestedFile.endsWith(".jpg")) { log.debug("LOG endsWith d.jpg"); log.debug("LOG moduleName: " + moduleName); requestedFile = DownloadHandler.defaultImageName; if (moduleName.equals("remoteuserprofile")) { requestedFile = DownloadHandler.defaultProfileImageName; } else if (moduleName.equals("remoteuserprofilebig")) { requestedFile = DownloadHandler.defaultProfileImageNameBig; } else if (moduleName.equals("userprofile")) { requestedFile = DownloadHandler.defaultProfileImageName; } else if (moduleName.equals("chat")) { requestedFile = DownloadHandler.defaultChatImageName; } } else if (requestedFile.endsWith(".swf")) { requestedFile = DownloadHandler.defaultSWFName; } else { requestedFile = DownloadHandler.defaultImageName; } full_path = new File(OmFileHelper.getDefaultDir(), requestedFile); } log.debug("full_path: " + full_path); if (!full_path.exists() || !full_path.canRead()) { if (!full_path.canRead()) { log.debug( "DownloadHandler: The request DEFAULT-file does not exist / has already been deleted"); } else { log.debug( "DownloadHandler: The request DEFAULT-file does not exist / has already been deleted"); } // no file to handle abort processing return; } // Requested file is outside OM webapp folder File curDirFile = OmFileHelper.getOmHome(); if (!full_path.getCanonicalPath().startsWith(curDirFile.getCanonicalPath())) { throw new Exception("Invalid file requested: f2.cp == " + full_path.getCanonicalPath() + "; curDir.cp == " + curDirFile.getCanonicalPath()); } // Default type - Explorer, Chrome and others int browserType = 0; // Firefox and Opera browsers if (httpServletRequest.getHeader("User-Agent") != null) { if ((httpServletRequest.getHeader("User-Agent").contains("Firefox")) || (httpServletRequest.getHeader("User-Agent").contains("Opera"))) { browserType = 1; } } log.debug("Detected browser type:" + browserType); httpServletResponse.reset(); httpServletResponse.resetBuffer(); OutputStream out = httpServletResponse.getOutputStream(); if (requestedFile.endsWith(".swf")) { // trigger download to SWF => THIS is a workaround for // Flash Player 10, FP 10 does not seem // to accept SWF-Downloads with the Content-Disposition // in the Header httpServletResponse.setContentType("application/x-shockwave-flash"); httpServletResponse.setHeader("Content-Length", "" + full_path.length()); } else { httpServletResponse.setContentType("APPLICATION/OCTET-STREAM"); String fileNameResult = requestedFile; if (fileExplorerItemId != null && fileExplorerItemId > 0) { FileExplorerItem fileExplorerItem = getBean(FileExplorerItemDao.class) .getFileExplorerItemsById(fileExplorerItemId); if (fileExplorerItem != null) { fileNameResult = fileExplorerItem.getFileName().substring(0, fileExplorerItem.getFileName().length() - 4) + fileNameResult.substring(fileNameResult.length() - 4, fileNameResult.length()); } } if (browserType == 0) { httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileNameResult, "UTF-8")); } else { httpServletResponse.setHeader("Content-Disposition", "attachment; filename*=UTF-8'en'" + java.net.URLEncoder.encode(fileNameResult, "UTF-8")); } httpServletResponse.setHeader("Content-Length", "" + full_path.length()); } OmFileHelper.copyFile(full_path, out); out.flush(); out.close(); } } else { log.error("ERROR DownloadHandler: not authorized FileDownload "); } } catch (ServerNotInitializedException e) { return; } catch (Exception er) { log.error("Error downloading: ", er); } }
From source file:controlador.CPersona.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w ww . ja va2 s . c om*/ * * @param request servlet request * @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 { response.setContentType("text/html;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); }
From source file:org.lainsoft.forge.flow.control.GenericFlowController.java
/** * Receives standard HTTP requests from the public <code>service</code> method and * dispatches them to the <code>do</code>XXX methods defined in this class. * This method is an HTTP-specific version of the * <code>Servlet.service(javax.servlet.ServletRequest, * javax.servlet.ServletResponse)</code> * method. There's no need to override this method. * * @param request the <code>HttpServletRequest</code> object that contains the * request the client made of the servlet. * @param response the <code>HttpServletResponse</code> object that contains the * response the servlet returns to the client. * @throws IOException if an input or output error occurs while the servlet is * handling the HTTP request.//from ww w .ja va 2s.c o m * @throws ServletException if the HTTP request cannot be handled. */ public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { GenericViewHelper helper = new GenericViewHelper(request, response, getServletContext()); try { String charset; if (!helper.is_empty(charset = getServletContext().getInitParameter("character_encoding"))) { request.setCharacterEncoding(charset); } Map flow_request = processRequest(helper); render(flow_request, flow(flow_request, helper), helper); } catch (CommandException ce) { throw new ServletException(ce); } }