List of usage examples for javax.servlet.http HttpServletRequest setCharacterEncoding
public void setCharacterEncoding(String env) throws UnsupportedEncodingException;
From source file:com.github.thorqin.webapi.FileManager.java
public List<FileInfo> saveUploadFiles(HttpServletRequest request, int maxSize) throws ServletException, IOException, FileUploadException { List<FileInfo> uploadList = new LinkedList<>(); request.setCharacterEncoding("utf-8"); ServletFileUpload upload = new ServletFileUpload(); upload.setHeaderEncoding("UTF-8"); if (!ServletFileUpload.isMultipartContent(request)) { return uploadList; }/*from w w w .ja v a 2 s . co m*/ upload.setSizeMax(maxSize); FileItemIterator iter; iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); try (InputStream stream = item.openStream()) { if (!item.isFormField()) { FileInfo info = new FileInfo(); info.setFileName(item.getName()); if (getFileMIME(info.getExtName()) == null) { logger.log(Level.WARNING, "Upload file's MIME type isn't permitted."); continue; } info = store(stream, info.fileName); uploadList.add(info); } } } return uploadList; }
From source file:net.sf.ginp.GinpServlet.java
/** * Central Processor of HTTP Methods. This method gets the model for the * users session, extracts the Command Parameters and preforms the command * specified in the request. It then redirects or if cookies are used * forwards the response to the JSP govened by the new state. If a * significant error occurs it should be throwned up to here so that a * debug page can be displayed. If a user sees a debug page then that is * bad so lets try to find out about it and so we can fix it. * *@param req HTTP Request *@param res HTTP Response *@exception IOException Description of the Exception *//*from ww w . java2s. co m*/ public final void doHttpMethod(final HttpServletRequest req, final HttpServletResponse res) throws IOException { // Set the Character Encoding. Do this first before access ing the req // and res objects, otherwise they take the system default. try { req.setCharacterEncoding(Configuration.getCharacterEncoding()); //res.setCharacterEncoding(Configuration.getCharacterEncoding()); res.setContentType("text/html; charset=\"" + Configuration.getCharacterEncoding() + "\""); setNoCache(res); // Debug log.debug("req.getContentType(): " + req.getContentType()); log.debug("Request Charactor Encoding:" + req.getCharacterEncoding()); } catch (java.io.UnsupportedEncodingException e) { log.error("Error setting Character Encoding. Check Configuration", e); } try { //Retrieve the model for this web app GinpModel model = ModelUtil.getModel(req); //This controller modifies the model via commands executeCommand(req, model); // The updated model is now available in the request, // go to the view page String url = model.getCurrentPage(); // debug to log if (log.isDebugEnabled()) { log.debug("doHttpMethod url=" + url + " " + model.getDebugInfo()); } // Forward to New URL forwardToPage(req, res, url); // debug to log if (log.isDebugEnabled()) { log.debug("DONE"); } } catch (Exception ex) { log.error("doHttpMethod", ex); handleError(req, res, ex); } }
From source file:com.stratelia.silverpeas.versioningPeas.servlets.DragAndDrop.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { SilverTrace.info("versioningPeas", "DragAndDrop.doPost", "root.MSG_GEN_ENTER_METHOD"); if (!FileUploadUtil.isRequestMultipart(req)) { res.getOutputStream().println("SUCCESS"); return;//ww w.j a v a2 s . c o m } try { req.setCharacterEncoding("UTF-8"); String componentId = req.getParameter("ComponentId"); SilverTrace.info("versioningPeas", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "componentId = " + componentId); String id = req.getParameter("Id"); SilverTrace.info("versioningPeas", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "id = " + id); int userId = Integer.parseInt(req.getParameter("UserId")); SilverTrace.info("versioningPeas", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "userId = " + userId); int versionType = Integer.parseInt(req.getParameter("Type")); boolean bIndexIt = StringUtil.getBooleanValue(req.getParameter("IndexIt")); String documentId = req.getParameter("DocumentId"); List<FileItem> items = FileUploadUtil.parseRequest(req); VersioningImportExport vie = new VersioningImportExport(); int majorNumber = 0; int minorNumber = 0; String fullFileName = null; for (FileItem item : items) { if (!item.isFormField()) { String fileName = item.getName(); if (fileName != null) { fileName = fileName.replace('\\', File.separatorChar); fileName = fileName.replace('/', File.separatorChar); SilverTrace.info("versioningPeas", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "file = " + fileName); long size = item.getSize(); SilverTrace.info("versioningPeas", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "item #" + fullFileName + " size = " + size); String mimeType = AttachmentController.getMimeType(fileName); String physicalName = saveFileOnDisk(item, componentId, vie); DocumentPK documentPK = new DocumentPK(-1, componentId); if (StringUtil.isDefined(documentId)) { documentPK.setId(documentId); } DocumentVersionPK versionPK = new DocumentVersionPK(-1, documentPK); ForeignPK foreignPK = new ForeignPK(id, componentId); Document document = new Document(documentPK, foreignPK, fileName, null, Document.STATUS_CHECKINED, userId, null, null, componentId, null, null, 0, 0); DocumentVersion version = new DocumentVersion(versionPK, documentPK, majorNumber, minorNumber, userId, new Date(), null, versionType, DocumentVersion.STATUS_VALIDATION_NOT_REQ, physicalName, fileName, mimeType, new Long(size).intValue(), componentId); List<DocumentVersion> versions = new ArrayList<DocumentVersion>(); versions.add(version); VersionsType versionsType = new VersionsType(); versionsType.setListVersions(versions); document.setVersionsType(versionsType); List<Document> documents = new ArrayList<Document>(); documents.add(document); try { vie.importDocuments(foreignPK, documents, userId, bIndexIt); } catch (Exception e) { // storing data into DB failed, delete file just added on disk deleteFileOnDisk(physicalName, componentId, vie); throw e; } } else { SilverTrace.info("versioningPeas", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "item " + item.getFieldName() + "=" + item.getString()); } } } } catch (Exception e) { SilverTrace.error("versioningPeas", "DragAndDrop.doPost", "ERREUR", e); res.getOutputStream().println("ERROR"); return; } res.getOutputStream().println("SUCCESS"); }
From source file:net.nan21.dnet.core.web.controller.ui.extjs.UiExtjsFrameController.java
/** * Handler to return the cached js file with the dependent components. * //from www. jav a 2 s . c om * @param bundle * @param frame * @param request * @param response * @return * @throws Exception */ @RequestMapping(value = "/{bundle}/{frame}.js", method = RequestMethod.GET) @ResponseBody public String frameCmpJs(@PathVariable("bundle") String bundle, @PathVariable("frame") String frame, HttpServletRequest request, HttpServletResponse response) throws Exception { try { @SuppressWarnings("unused") ISessionUser su = (ISessionUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); } catch (java.lang.ClassCastException e) { throw new NotAuthorizedRequestException("Not authenticated"); } request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); String fileName = frame + ".js"; File f = new File(this.cacheFolder + "/" + bundle + "." + fileName); if (!f.exists()) { DependencyLoader loader = this.getDependencyLoader(); loader.packFrameCmp(bundle, frame, f); } this.sendFile(f, response.getOutputStream()); return null; }
From source file:com.concursive.connect.web.controller.servlets.URLControllerServlet.java
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException { LOG.debug("service called"); LOG.debug("requestCharacterEncoding=" + request.getCharacterEncoding()); try {/* w w w . j av a2 s. c o m*/ request.setCharacterEncoding("UTF-8"); } catch (Exception e) { LOG.warn("Unsupported encoding"); } // Check the preferences to see if the correct domain name is being used, else do a redirect ApplicationPrefs prefs = (ApplicationPrefs) request.getSession().getServletContext() .getAttribute("applicationPrefs"); boolean redirect = false; String contextPath = request.getContextPath(); String uri = request.getRequestURI(); String queryString = request.getQueryString(); String path = uri.substring(contextPath.length()) + (queryString == null ? "" : "?" + queryString); LOG.debug("path: " + path); request.setAttribute("requestedURL", path); // It's important the user is using the correct URL for accessing content; // The portal has it's own redirect scheme, this is a another catch all // to see if an old domain name or context is used PortalBean bean = new PortalBean(request); String expectedDomainName = prefs.get(ApplicationPrefs.WEB_DOMAIN_NAME); LOG.debug("expectedDomainName: " + expectedDomainName); LOG.debug("domainName: " + bean.getServerName()); String expectedContext = prefs.get(ApplicationPrefs.WEB_CONTEXT); LOG.debug("expectedContextPath: " + expectedContext); LOG.debug("contextPath: " + contextPath); if (StringUtils.hasText(expectedContext) && !expectedContext.equals(contextPath) || (expectedDomainName != null && path.length() > 0 && !"127.0.0.1".equals(bean.getServerName()) && !"127.0.0.1".equals(expectedDomainName) && !"localhost".equals(bean.getServerName()) && !"localhost".equals(expectedDomainName) && !bean.getServerName().startsWith("10.") && !bean.getServerName().startsWith("172.") && !bean.getServerName().startsWith("192.") && !bean.getServerName().equals(expectedDomainName))) { if (uri.length() > 0 && !uri.substring(1).equals(prefs.get("PORTAL.INDEX"))) { String newUrl = URLFactory.createURL(prefs.getPrefs()) + path; request.setAttribute("redirectTo", newUrl); LOG.debug("redirectTo: " + newUrl); request.removeAttribute(Constants.REQUEST_PAGE_LAYOUT); redirect = true; } } if (redirect) { try { RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/redirect301.jsp"); dispatcher.forward(request, response); } catch (Exception e) { } } else { mapToMVCAction(request, response); } }
From source file:net.nan21.dnet.core.web.controller.ui.extjs.UiExtjsFrameController.java
/** * Handler to return the cached js file with the dependent translations. * /*from w w w.j a v a 2 s.c om*/ * @param bundle * @param frame * @param language * @param request * @param response * @return * @throws Exception */ @RequestMapping(value = "/{bundle}/{language}/{frame}.js", method = RequestMethod.GET) @ResponseBody public String frameTrlJs(@PathVariable("bundle") String bundle, @PathVariable("frame") String frame, @PathVariable("language") String language, HttpServletRequest request, HttpServletResponse response) throws Exception { try { @SuppressWarnings("unused") ISessionUser su = (ISessionUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); } catch (java.lang.ClassCastException e) { throw new NotAuthorizedRequestException("Not authenticated"); } request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); String fileName = frame + "-" + language + ".js"; File f = new File(this.cacheFolder + "/" + bundle + "." + fileName); if (!f.exists()) { DependencyLoader loader = this.getDependencyLoader(); loader.packFrameTrl(bundle, frame, language, f); } this.sendFile(f, response.getOutputStream()); return null; }
From source file:mercury.JsonController.java
/** * */// w ww. j a v a2s .co m protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.log.debug("processRequest start: " + this.getMemoryInfo()); String submitButton = null; String thisPage = null; HttpSession session = request.getSession(); JSONObject jsonResponse = null; Integer status = null; request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); try { submitButton = request.getParameter("submitButton"); thisPage = request.getParameter("thisPage"); AuthorizationPoints atps = (AuthorizationPoints) request.getSession().getAttribute("LOGGED_USER_ATPS"); if (atps == null) { atps = new AuthorizationPoints(null); request.getSession().setAttribute("LOGGED_USER_ATPS", atps); } AuthorizationBO authBO = new AuthorizationBO(); String handlerName = JsonController.targetJsonHandlers.getProperty(thisPage); if (thisPage.equals("ping") && submitButton.equals("ping")) { jsonResponse = new SuccessDTO("OK") .toJSONObject(BaseHandler.getI18nProperties(session, "biblivre3")); } else if (authBO.authorize(atps, handlerName, submitButton)) { RootJsonHandler handler = (RootJsonHandler) Class.forName(handlerName).newInstance(); jsonResponse = handler.process(request, response); } else { if (atps == null) { status = 403; } jsonResponse = this.jsonFailure(session, "warning", "ERROR_NO_PERMISSION"); } } catch (ClassNotFoundException e) { System.out.println("====== [mercury.Controller.processRequest()] Exception 1: " + e); jsonResponse = this.jsonFailure(session, "error", "DIALOG_VOID"); } catch (ExceptionUser e) { System.out.println("====== [mercury.Controller.processRequest()] Exception 2: " + e.getKeyText()); jsonResponse = this.jsonFailure(session, "error", e.getKeyText()); } catch (Exception e) { System.out.println("====== [mercury.Controller.processRequest()] Exception 3: " + e); e.printStackTrace(); jsonResponse = this.jsonFailure(session, "error", "DIALOG_VOID"); } finally { // Print response to browser if (status != null) { response.setStatus(status); } if (jsonResponse != null) { try { jsonResponse.putOnce("success", true); // Only put success on response if not already present. } catch (JSONException e) { } response.getWriter().print(jsonResponse.toString()); } } }
From source file:com.ikon.servlet.admin.OmrServlet.java
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 userId = request.getRemoteUser(); updateSessionManager(request);/*from w w w. ja v a2 s . c om*/ try { if (action.equals("create")) { create(userId, request, response); } else if (action.equals("edit")) { edit(userId, request, response); } else if (action.equals("delete")) { delete(userId, request, response); } else if (action.equals("downloadFile")) { downloadFile(userId, request, response); } else if (action.equals("editAsc")) { editAscFile(userId, request, response); } else if (action.equals("editFields")) { editFieldsFile(userId, request, response); } else if (action.equals("check")) { check(userId, request, response); } else { list(userId, request, response); } } catch (DatabaseException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (Exception e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } }
From source file:com.ikon.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 toPdf = WebUtils.getBoolean(request, "toPdf"); boolean toSwf = WebUtils.getBoolean(request, "toSwf"); CharsetDetector detector = new CharsetDetector(); File tmp = null;//from w w w.j av a 2 s. com 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); } } // 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:com.asual.summer.core.RequestFilter.java
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { requestHolder.set(request);/*from w w w . j ava 2s . c om*/ HttpServletRequest defaultRequest = new DefaultRequest(request); if (multipartResolver != null && multipartResolver.isMultipart(request)) { defaultRequest = multipartResolver.resolveMultipart(defaultRequest); } try { long time = System.currentTimeMillis(); requestHolder.set(defaultRequest); if (defaultRequest.getCharacterEncoding() == null) { defaultRequest.setCharacterEncoding((String) ResourceUtils.getProperty("app.encoding")); } if (RequestUtils.isTrident()) { response.setHeader("X-UA-Compatible", "IE=Edge,chrome=1"); } filterChain.doFilter(requestHolder.get(), response); logger.debug("The request for '" + defaultRequest.getRequestURI() + "' took " + (System.currentTimeMillis() - time) + "ms."); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (multipartResolver != null && defaultRequest instanceof MultipartHttpServletRequest) { multipartResolver.cleanupMultipart((MultipartHttpServletRequest) defaultRequest); } requestHolder.set(null); } }