List of usage examples for javax.servlet.http HttpServletRequest setCharacterEncoding
public void setCharacterEncoding(String env) throws UnsupportedEncodingException;
From source file:ua.aits.sdolyna.controller.SystemController.java
@RequestMapping(value = "/Sdolyna/system/do/editdata", method = RequestMethod.POST) public ModelAndView editArticle(HttpServletRequest request) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedEncodingException, IOException { request.setCharacterEncoding("UTF-8"); String id = request.getParameter("article_id"); String titleEN = request.getParameter("titleEN"); String titleRU = request.getParameter("titleRU"); String textEN = request.getParameter("textEN"); String textRU = request.getParameter("textRU"); String date = request.getParameter("date"); String date_end = request.getParameter("act-date"); String category = request.getParameter("category"); String files_data = request.getParameter("gallery-items"); if (files_data != "" && files_data != null) { List<GalleryModel> items = new LinkedList<>(); String[] itm = files_data.split("\\|"); for (String i : itm) { String[] row = i.split("\\,"); GalleryModel imag = Articles.new GalleryModel(); imag.setImage_url(row[0].replace("path:", "")); imag.setImage_title_ru(row[1].replace("textRU:", "")); imag.setImage_title_en(row[2].replace("textEN:", "")); imag.setImage_article_id(Integer.parseInt(id)); items.add(imag);/* w w w . j a va 2 s . co m*/ } Articles.cleanGallery(id); Articles.insertGalImages(items); } else { Articles.cleanGallery(id); } Articles.updateArticle(id, titleEN, titleRU, textEN, textRU, category, date, date_end); return new ModelAndView("redirect:" + "/system/index/" + category); }
From source file:edu.lafayette.metadb.web.controlledvocab.ShowVocab.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) *//*from www . j ava2 s . co m*/ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String vocabName = request.getParameter("vocab-name"); //MetaDbHelper.note("Vocab Name in Servlet: "+vocabName); PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF8"), true); response.setCharacterEncoding("utf-8"); request.setCharacterEncoding("utf-8"); JSONArray vocab = new JSONArray(); try { Set<String> vocabList = ControlledVocabDAO.getControlledVocab(vocabName); Iterator<String> itr = vocabList.iterator(); String[] term = request.getParameterValues("term"); boolean autocomplete = term != null && !(term[0].equals("")); while (itr.hasNext()) { String entry = itr.next(); if (autocomplete) { //MetaDbHelper.note("Entry: "+entry+", query: "+term[0]); if (entry.toLowerCase().startsWith(term[0].toLowerCase())) vocab.put(entry); } else vocab.put(entry); } out.print(vocab); } catch (Exception e) { MetaDbHelper.logEvent(e); } out.flush(); }
From source file:org.kawanfw.sql.servlet.ServerSqlManager.java
/** * Get request./* w w w. ja v a 2 s. c o m*/ */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { request.setCharacterEncoding("UTF-8"); // Store the host info in RequestInfoStore RequestInfoStore.init(request); response.setContentType("text/html"); PrintWriter out = response.getWriter(); String servletName = this.getServletName(); if (commonsConfigurator != null) { debug("doGet commonsConfigurator: " + commonsConfigurator.getClass().getName()); } else { debug("doGet commonsConfigurator is null"); } if (fileConfigurator != null) { debug("doGet fileConfigurator : " + fileConfigurator.getClass().getName()); } else { debug("doGet fileConfigurator is null"); } if (sqlConfigurator != null) { debug("doGet sqlConfigurator : " + sqlConfigurator.getClass().getName()); } else { debug("doGet sqlConfigurator is null"); } // Must be done in doPost() and do Get() because we need // request.getServerName() // That is not available in init... // checkOnceLicenseInfo(request, commonsConfigurator); ServerSqlManagerDoGetTester serverSqlManagerDoGetTester = new ServerSqlManagerDoGetTester(); serverSqlManagerDoGetTester.doGetTest(servletName, out, exception, commonsConfigurator, fileConfigurator, sqlConfigurator); }
From source file:org.kawanfw.sql.servlet.ServerSqlManager.java
/** * Post request./*w ww .ja va 2 s .com*/ */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { request.setCharacterEncoding("UTF-8"); // Store the host info in RequestInfoStore RequestInfoStore.init(request); // If init fail, say it cleanly to client, instead of bad 500 Servlet // Error if (exception != null) { OutputStream out = response.getOutputStream(); writeLine(out, TransferStatus.SEND_FAILED); writeLine(out, exception.getClass().getName()); // Exception class // name writeLine(out, initErrrorMesage + " Reason: " + exception.getMessage()); // Exception // message writeLine(out, ExceptionUtils.getStackTrace(exception)); return; } debug("after RequestInfoStore.init(request);"); debug(request.getRemoteAddr()); // Configure a repository (to ensure a secure temp location is used) ServletContext servletContext = this.getServletConfig().getServletContext(); File servletContextTempDir = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); // Wrap the HttpServletRequest with HttpServletRequestEncrypted for // parameters decryption HttpServletRequestConvertor requestEncrypted = new HttpServletRequestConvertor(request, commonsConfigurator); ServerSqlDispatch dispatch = new ServerSqlDispatch(); debug("before dispatch.executeRequest()"); dispatch.executeRequest(requestEncrypted, response, servletContextTempDir, commonsConfigurator, fileConfigurator, sqlConfigurator); }
From source file:com.salesmanager.core.util.www.SalesManagerInterceptor.java
public String intercept(ActionInvocation invoke) throws Exception { try {/*from w w w. j a v a 2 s . c o m*/ HttpServletRequest req = (HttpServletRequest) ServletActionContext.getRequest(); HttpServletResponse resp = (HttpServletResponse) ServletActionContext.getResponse(); req.setCharacterEncoding("UTF-8"); // get cookies Map cookiesMap = new HashMap(); Cookie[] cookies = req.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; cookiesMap.put(cookie.getName(), cookie); } } /** * MERCHANT ID */ // look at merchantId in url parameter String merchantId = (String) req.getParameter("merchantId"); Cookie storeCookie = (Cookie) cookiesMap.get("STORE"); int iMerchantId = Constants.DEFAULT_MERCHANT_ID; MerchantStore store = null; if (StringUtils.isBlank(merchantId)) {// no merchantId in the // request // check for store store = (MerchantStore) req.getSession().getAttribute("STORE"); if (merchantId == null) { if (store != null) { iMerchantId = store.getMerchantId(); } else { // check for cookie Cookie c = (Cookie) cookiesMap.get("STORE"); if (c != null && !StringUtils.isBlank(c.getValue())) { String v = c.getValue(); iMerchantId = Integer.valueOf(v); } else { // assign defaultMerchantId iMerchantId = Constants.DEFAULT_MERCHANT_ID; } // set store store = this.setMerchantStore(req, resp, merchantId); if (store == null) { return "NOSTORE"; } } } } else {// merchantId in the request // check for store in the session store = (MerchantStore) req.getSession().getAttribute("STORE"); if (store != null) { // check if both match if (!merchantId.equals(String.valueOf(store.getMerchantId()))) {// if they differ store = this.setMerchantStore(req, resp, merchantId); } else { iMerchantId = store.getMerchantId(); } } else { // set store store = this.setMerchantStore(req, resp, merchantId); if (store == null) { return "NOSTORE"; } } } req.setAttribute("STORE", store); if (StringUtils.isBlank(store.getTemplateModule())) { return "NOSTORE"; } req.setAttribute("templateId", store.getTemplateModule()); ActionContext ctx = ActionContext.getContext(); LocaleUtil.setLocaleForRequest(req, resp, ctx, store); HttpSession session = req.getSession(); Principal p = (Principal) session.getAttribute("PRINCIPAL"); if (p != null) { try { SalesManagerPrincipalProxy proxy = new SalesManagerPrincipalProxy(p); BaseActionAware action = ((BaseActionAware) invoke.getAction()); action.setPrincipalProxy(proxy); } catch (Exception e) { log.error("The current action does not implement PrincipalAware " + invoke.getAction().getClass()); } } String r = baseIntercept(invoke, req, resp); if (r != null) { return r; } return invoke.invoke(); } catch (Exception e) { log.error(e); ActionSupport action = (ActionSupport) invoke.getAction(); action.addActionError(action.getText("errors.technical") + " " + e.getMessage()); if (e instanceof ActionException) { return Action.ERROR; } else { return "GENERICERROR"; } } }
From source file:org.guanxi.idp.service.AuthHandler.java
/** * Looks for an existing GuanxiPrincipal referenced by a request cookie. When a cookie is created after * a successful authentication at the IdP, either via the login page or an application cookie handler, * the corresponding GuanxiPrincipal is stored in the servlet context against the cookie value. * The new GuanxiPrincipal that is created after successful authentication is stored in the servlet * context under GuanxiPrincipal.id/*from w ww.j ava2 s.co m*/ * * @param request Standard HttpServletRequest * @param response Standard HttpServletResponse * @param object handler * @return true * @throws Exception if an error occurs */ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception { request.setCharacterEncoding("UTF-8"); String missingParams = checkRequestParameters(request); if (missingParams != null) { logger.info("Missing param(s) : " + missingParams); request.setAttribute("message", messageSource.getMessage("missing.param", new Object[] { missingParams }, request.getLocale())); request.getRequestDispatcher(errorPage).forward(request, response); return false; } IdpDocument.Idp idpConfig = (IdpDocument.Idp) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_CONFIG); boolean spSupported = false; EntityFarm farm = (EntityFarm) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_ENTITY_FARM); EntityManager manager = farm.getEntityManagerForID(request.getParameter(spIDRequestParam)); if (manager != null) { SPMetadata metadata = (SPMetadata) manager.getMetadata(request.getParameter(spIDRequestParam)); // Apply the trust rules to the SP if (metadata != null) { if (manager.getTrustEngine().trustEntity(metadata, request.getParameter("shire"))) { spSupported = true; } else { logger.error("Trust failure for " + request.getParameter(spIDRequestParam) + " --> " + request.getParameter("shire")); } } else { logger.error("No Metadata Manager found for " + request.getParameter(spIDRequestParam)); } } else { logger.error("No Metadata Manager"); } // Check the locally registered SPs if (!spSupported) { ServiceProvider[] spList = idpConfig.getServiceProviderArray(); for (int c = 0; c < spList.length; c++) { if (spList[c].getName().equals(request.getParameter(spIDRequestParam))) { // If it's in here, we trust it explicitly spSupported = true; } } } // Did we find the service provider? if (!spSupported) { logger.error( "Service Provider providerId " + request.getParameter(spIDRequestParam) + " not supported"); request.setAttribute("message", messageSource.getMessage("sp.not.supported", new Object[] { request.getParameter(spIDRequestParam) }, request.getLocale())); request.getRequestDispatcher(errorPage).forward(request, response); return false; } // Look for our cookie. This is after any application cookie handler has authenticated the user String cookieName = getCookieName(); Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int c = 0; c < cookies.length; c++) { if (cookies[c].getName().equals(cookieName)) { // Retrieve the principal from the servlet context if (servletContext.getAttribute(cookies[c].getValue()) == null) { // Out of date cookie value, so remove the cookie cookies[c].setMaxAge(0); response.addCookie(cookies[c]); } else { // Found the principal from a previously established authentication request.setAttribute(Guanxi.REQUEST_ATTR_IDP_PRINCIPAL, (GuanxiPrincipal) servletContext.getAttribute(cookies[c].getValue())); return true; } } } } // Are we getting an authentication request from the login page? if (request.getParameter("guanxi:mode") != null) { if (request.getParameter("guanxi:mode").equalsIgnoreCase("authenticate")) { // Get a new GuanxiPrincipal... GuanxiPrincipal principal = gxPrincipalFactory.createNewGuanxiPrincipal(request); if (authenticator.authenticate(principal, request.getParameter("userid"), request.getParameter("password"))) { // ...associate it with a login name... if (principal.getName() == null) { //The login name from the authenticator page principal.setName(request.getParameter("userid")); } // ...store it in the request for the SSO to use... request.setAttribute(Guanxi.REQUEST_ATTR_IDP_PRINCIPAL, principal); // ...and store it in application scope for the rest of the profile to use servletContext.setAttribute(principal.getUniqueId(), principal); // Get a new cookie ready to reference the principal in the servlet context Cookie cookie = new Cookie(getCookieName(), principal.getUniqueId()); cookie.setDomain((String) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_DOMAIN)); cookie.setPath(idpConfig.getCookie().getPath()); if (((Integer) (servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_AGE))) .intValue() != -1) cookie.setMaxAge( ((Integer) (servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_AGE))) .intValue()); response.addCookie(cookie); return true; } // if (authenticator.authenticate... else { logger.error("Authentication error : " + authenticator.getErrorMessage()); request.setAttribute("message", messageSource.getMessage("authentication.error", null, request.getLocale())); request.getRequestDispatcher(errorPage).forward(request, response); return false; } } } // No embedded cookie authentication or local auth, so show the login page String authPage = null; AuthPage[] authPages = idpConfig.getAuthenticatorPages().getAuthPageArray(); for (int c = 0; c < authPages.length; c++) { // We'll use the default auth page if none is specified for this service provider if (authPages[c].getProviderId().equals(Guanxi.DEFAULT_AUTH_PAGE_MARKER)) { authPage = authPages[c].getUrl(); } // Customised auth page for this service provider if (authPages[c].getProviderId().equals(request.getParameter(spIDRequestParam))) { authPage = authPages[c].getUrl(); } } addRequiredParamsAsPrefixedAttributes(request); request.getRequestDispatcher(authPage).forward(request, response); return false; }
From source file:com.glaf.base.utils.upload.FileUploadBackGroundServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { processFileUpload(request, response); } else {/* ww w . j a v a 2s.co m*/ request.setCharacterEncoding("UTF-8"); if (request.getParameter("uploadStatus") != null) { responseStatusQuery(request, response); } if (request.getParameter("cancelUpload") != null) { processCancelFileUpload(request, response); } if (request.getParameter("download") != null) { processDownload(request, response); } } }
From source file:net.nan21.dnet.core.web.controller.ui.extjs.AbstractUiExtjsController.java
protected void _prepare(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); if (logger.isInfoEnabled()) { logger.info("Handling request for ui.extjs: ", request.getPathInfo()); }/*from w w w .j ava 2 s . c o m*/ String server = request.getServerName(); int port = request.getServerPort(); // String contextPath = request.getContextPath(); // String path = request.getServletPath(); String userRolesStr = null; try { ISessionUser su = (ISessionUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); IUser user = su.getUser(); IUserSettings prefs = user.getSettings(); Session.user.set(user); model.put("constantsJsFragment", this.getConstantsJsFragment()); model.put("user", user); DateFormatAttribute[] masks = DateFormatAttribute.values(); Map<String, String> dateFormatMasks = new HashMap<String, String>(); for (int i = 0, len = masks.length; i < len; i++) { DateFormatAttribute mask = masks[i]; if (mask.isForJs()) { dateFormatMasks.put(mask.name().replace("EXTJS_", ""), prefs.getDateFormat(mask.name())); } } model.put("dateFormatMasks", dateFormatMasks); model.put("modelDateFormat", this.getSettings().get(Constants.PROP_EXTJS_MODEL_DATE_FORMAT)); model.put("decimalSeparator", prefs.getDecimalSeparator()); model.put("thousandSeparator", prefs.getThousandSeparator()); StringBuffer sb = new StringBuffer(); int i = 0; for (String role : user.getProfile().getRoles()) { if (i > 0) { sb.append(","); } sb.append("\"" + role + "\""); i++; } userRolesStr = sb.toString(); } catch (ClassCastException e) { // not authenticated } String hostUrl = ((request.isSecure()) ? "https" : "http") + "://" + server + ((port != 80) ? (":" + port) : "");// + contextPath; model.put("productName", this.getSettings().getProductName()); model.put("productVersion", this.getSettings().getProductVersion()); model.put("hostUrl", hostUrl); // themes model.put("urlUiExtjsThemes", getUiExtjsSettings().getUrlThemes()); // DNet extjs components in core and modules model.put("urlUiExtjsCore", getUiExtjsSettings().getUrlCore()); model.put("urlUiExtjsModules", getUiExtjsSettings().getUrlModules()); model.put("urlUiExtjsModuleSubpath", getUiExtjsSettings().getModuleSupath()); // translations for core and modules model.put("urlUiExtjsCoreI18n", getUiExtjsSettings().getUrlCoreI18n()); model.put("urlUiExtjsModulesI18n", getUiExtjsSettings().getUrlModulesI18n()); model.put("shortLanguage", this.resolveLang(request, response)); model.put("theme", this.resolveTheme(request, response)); model.put("sysCfg_workingMode", this.getSettings().get(Constants.PROP_WORKING_MODE)); model.put("userRolesStr", userRolesStr); }
From source file:eu.earthobservatory.org.StrabonEndpoint.QueryBean.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); // check connection details if (strabonWrapper.getStrabon() == null) { RequestDispatcher dispatcher = request.getRequestDispatcher("/connection.jsp"); // pass the current details of the connection request.setAttribute("username", strabonWrapper.getUsername()); request.setAttribute("password", strabonWrapper.getPassword()); request.setAttribute("dbname", strabonWrapper.getDatabaseName()); request.setAttribute("hostname", strabonWrapper.getHostName()); request.setAttribute("port", strabonWrapper.getPort()); request.setAttribute("dbengine", strabonWrapper.getDBEngine()); // pass the other parameters as well request.setAttribute("query", request.getParameter("query")); if (request.getParameter("format").equalsIgnoreCase("PIECHART") || request.getParameter("format").equalsIgnoreCase("AREACHART") || request.getParameter("format").equalsIgnoreCase("COLUMNCHART")) { request.setAttribute("format", "CHART"); } else {/*from w w w .jav a 2s.c o m*/ request.setAttribute("format", request.getParameter("format")); } request.setAttribute("handle", request.getParameter("handle")); // forward the request dispatcher.forward(request, response); } else { if (Common.VIEW_TYPE.equals(request.getParameter(Common.VIEW))) { // HTML visual interface processVIEWRequest(request, response); } else {// invoked as a service processRequest(request, response); } } }