List of usage examples for javax.servlet ServletRequest getParameter
public String getParameter(String name);
String
, or null
if the parameter does not exist. From source file:org.apache.unomi.web.ContextServlet.java
@Override public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { final Date timestamp = new Date(); if (request.getParameter("timestamp") != null) { timestamp.setTime(Long.parseLong(request.getParameter("timestamp"))); }/*from w w w . ja v a 2 s .com*/ // first we must retrieve the context for the current visitor, and build a Javascript object to attach to the // script output. String profileId; HttpServletRequest httpServletRequest = (HttpServletRequest) request; String httpMethod = httpServletRequest.getMethod(); // logger.debug(HttpUtils.dumpRequestInfo(httpServletRequest)); // set up CORS headers as soon as possible so that errors are not misconstrued on the client for CORS errors HttpUtils.setupCORSHeaders(httpServletRequest, response); if ("options".equals(httpMethod.toLowerCase())) { response.flushBuffer(); return; } Profile profile = null; String cookieProfileId = null; Cookie[] cookies = httpServletRequest.getCookies(); for (Cookie cookie : cookies) { if (profileIdCookieName.equals(cookie.getName())) { cookieProfileId = cookie.getValue(); } } Session session = null; String personaId = request.getParameter("personaId"); if (personaId != null) { PersonaWithSessions personaWithSessions = profileService.loadPersonaWithSessions(personaId); if (personaWithSessions == null) { logger.error("Couldn't find persona with id=" + personaId); profile = null; } else { profile = personaWithSessions.getPersona(); session = personaWithSessions.getLastSession(); } } String sessionId = request.getParameter("sessionId"); if (cookieProfileId == null && sessionId == null && personaId == null) { ((HttpServletResponse) response).sendError(HttpServletResponse.SC_BAD_REQUEST); return; } boolean profileCreated = false; ContextRequest contextRequest = null; String scope = null; String stringPayload = HttpUtils.getPayload(httpServletRequest); if (stringPayload != null) { ObjectMapper mapper = CustomObjectMapper.getObjectMapper(); JsonFactory factory = mapper.getFactory(); try { contextRequest = mapper.readValue(factory.createParser(stringPayload), ContextRequest.class); } catch (Exception e) { logger.error("Cannot read payload " + stringPayload, e); return; } scope = contextRequest.getSource().getScope(); } int changes = EventService.NO_CHANGE; if (profile == null) { if (sessionId != null) { session = profileService.loadSession(sessionId, timestamp); if (session != null) { profileId = session.getProfileId(); profile = profileService.load(profileId); profile = checkMergedProfile(response, profile, session); } } if (profile == null) { // profile not stored in session if (cookieProfileId == null) { // no profileId cookie was found, we generate a new one and create the profile in the profile service profile = createNewProfile(null, response, timestamp); profileCreated = true; } else { profile = profileService.load(cookieProfileId); if (profile == null) { // this can happen if we have an old cookie but have reset the server, // or if we merged the profiles and somehow this cookie didn't get updated. profile = createNewProfile(null, response, timestamp); profileCreated = true; HttpUtils.sendProfileCookie(profile, response, profileIdCookieName, profileIdCookieDomain); } else { profile = checkMergedProfile(response, profile, session); } } } else if ((cookieProfileId == null || !cookieProfileId.equals(profile.getItemId())) && !profile.isAnonymousProfile()) { // profile if stored in session but not in cookie HttpUtils.sendProfileCookie(profile, response, profileIdCookieName, profileIdCookieDomain); } // associate profile with session if (sessionId != null && session == null) { session = new Session(sessionId, profile, timestamp, scope); changes |= EventService.SESSION_UPDATED; Event event = new Event("sessionCreated", session, profile, scope, null, session, timestamp); event.getAttributes().put(Event.HTTP_REQUEST_ATTRIBUTE, request); event.getAttributes().put(Event.HTTP_RESPONSE_ATTRIBUTE, response); logger.debug("Received event " + event.getEventType() + " for profile=" + profile.getItemId() + " session=" + session.getItemId() + " target=" + event.getTarget() + " timestamp=" + timestamp); changes |= eventService.send(event); } } if (profileCreated) { changes |= EventService.PROFILE_UPDATED; Event profileUpdated = new Event("profileUpdated", session, profile, scope, null, profile, timestamp); profileUpdated.setPersistent(false); profileUpdated.getAttributes().put(Event.HTTP_REQUEST_ATTRIBUTE, request); profileUpdated.getAttributes().put(Event.HTTP_RESPONSE_ATTRIBUTE, response); logger.debug("Received event {} for profile={} {} target={} timestamp={}", profileUpdated.getEventType(), profile.getItemId(), session != null ? " session=" + session.getItemId() : "", profileUpdated.getTarget(), timestamp); changes |= eventService.send(profileUpdated); } ContextResponse data = new ContextResponse(); data.setProfileId(profile.isAnonymousProfile() ? cookieProfileId : profile.getItemId()); if (privacyService.isRequireAnonymousBrowsing(profile.getItemId())) { profile = privacyService.getAnonymousProfile(); session.setProfile(profile); changes = EventService.SESSION_UPDATED; } if (contextRequest != null) { changes |= handleRequest(contextRequest, profile, session, data, request, response, timestamp); } if ((changes & EventService.PROFILE_UPDATED) == EventService.PROFILE_UPDATED && profile != null) { profileService.save(profile); } if ((changes & EventService.SESSION_UPDATED) == EventService.SESSION_UPDATED && session != null) { profileService.saveSession(session); } String extension = httpServletRequest.getRequestURI() .substring(httpServletRequest.getRequestURI().lastIndexOf(".") + 1); boolean noScript = "json".equals(extension); String contextAsJSONString = CustomObjectMapper.getObjectMapper().writeValueAsString(data); Writer responseWriter; if (noScript) { response.setCharacterEncoding("UTF-8"); responseWriter = response.getWriter(); response.setContentType("application/json"); IOUtils.write(contextAsJSONString, responseWriter); } else { responseWriter = response.getWriter(); responseWriter.append("window.digitalData = window.digitalData || {};\n").append("var cxs = ") .append(contextAsJSONString).append(";\n"); // now we copy the base script source code InputStream baseScriptStream = getServletContext().getResourceAsStream( profile instanceof Persona ? IMPERSONATE_BASE_SCRIPT_LOCATION : BASE_SCRIPT_LOCATION); IOUtils.copy(baseScriptStream, responseWriter); } responseWriter.flush(); }
From source file:com.spshop.web.ShoppingController.java
private int retriveQty(ServletRequest request) { int quantity = 1; try {//from w w w .ja va 2s .co m quantity = Integer.parseInt(request.getParameter(QTY)); } catch (NumberFormatException e) { //e.printStackTrace(); } if (quantity < 1) { quantity = 1; } return quantity; }
From source file:edu.wisc.my.stats.web.filter.RelativeDateQueryFilter.java
/** * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) *///from www.j a va 2s . c om public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { throw new ClassCastException("RelativeDateQueryFilter can only filter HttpServletRequests"); } boolean useWrapper = false; final WritableHttpServletRequestWrapper wrappedRequestWrapper = new WritableHttpServletRequestWrapper( (HttpServletRequest) request); for (final String dateParameter : this.dateParameters) { final String value = request.getParameter(dateParameter); if (StringUtils.isBlank(value)) { continue; } try { final int dayOffset = Integer.parseInt(value); final Calendar now = Calendar.getInstance(); now.add(Calendar.DAY_OF_YEAR, -1 * dayOffset); final String newValue = this.dateFormat.format(now.getTime()); useWrapper = true; wrappedRequestWrapper.putParameter(dateParameter, newValue); } catch (NumberFormatException nfe) { //Isn't a single number, assume it is a valid Date and just ignore it. } } if (useWrapper) { chain.doFilter(wrappedRequestWrapper, response); } else { chain.doFilter(request, response); } }
From source file:org.egov.restapi.filter.ApiFilter.java
@Override public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException { final MultiReadHttpServletRequest multiReadRequest = new MultiReadHttpServletRequest( (HttpServletRequest) servletRequest); if (!validateRequest(multiReadRequest)) throw new ApplicationRuntimeException("RESTAPI.001"); String ulbCode = null;/*from w ww. jav a 2 s. c o m*/ final byte[] b = new byte[5000]; ulbCode = servletRequest.getParameter("ulbCode"); if (ulbCode == null) { JSONObject jsonObject = null; String jb = new String(); try { final ServletInputStream inputStream = multiReadRequest.getInputStream(); inputStream.read(b); jb = new String(b); } catch (final Exception e) { // Throw error } try { jsonObject = JSONObject.fromObject(jb.toString()); } catch (final Exception e) { throw new RuntimeException("Invalid Json"); } if (jsonObject != null) ulbCode = jsonObject.getString("ulbCode"); else throw new RuntimeException("Invalid Json ULB Code is not Passed"); } if (StringUtils.isNotBlank(ulbCode)) { if (!ulbCode.equals(ApplicationThreadLocals.getCityCode())) { LOG.info("Request Reached Different city. Need to change domain details"); final String cityName = RestRedirectConstants.getCode_ulbNames().get(ulbCode).toLowerCase(); ApplicationThreadLocals.setTenantID(cityName); final City city = cityService.getCityByCode(ulbCode); ApplicationThreadLocals.setDomainName(city.getDomainURL()); ApplicationThreadLocals.setCityCode(ulbCode); } else LOG.info("ULB code resolved to be same, continueing normal request flow"); } else { LOG.error("ULB Code missing in request"); throw new ApplicationRuntimeException("ULB Code missing in request"); } filterChain.doFilter(multiReadRequest, servletResponse); }
From source file:no.sesat.search.http.filters.SiteLocatorFilter.java
private static void logAccessRequest(final ServletRequest request) { final StringBuilder url = new StringBuilder(); final String referer; final String method; final String ip = request.getRemoteAddr(); final String userAgent; final String sesamId; final String sesamUser; if (request instanceof HttpServletRequest) { final HttpServletRequest req = (HttpServletRequest) request; url.append(req.getRequestURI() + (null != req.getQueryString() ? '?' + req.getQueryString() : "")); referer = req.getHeader("Referer"); method = req.getMethod();/*from w w w. j av a 2s . c o m*/ userAgent = req.getHeader("User-Agent"); sesamId = getCookieValue(req, "SesamID"); sesamUser = getCookieValue(req, "SesamUser"); } else { for (@SuppressWarnings("unchecked") Enumeration<String> en = request.getParameterNames(); en.hasMoreElements();) { final String param = en.nextElement(); url.append(param + '=' + request.getParameter(param)); if (en.hasMoreElements()) { url.append('&'); } } referer = method = userAgent = sesamId = sesamUser = UNKNOWN; } ACCESS_LOG.info("<request>" + "<url method=\"" + method + "\">" + StringEscapeUtils.escapeXml(url.toString()) + "</url>" + (null != referer ? "<referer>" + StringEscapeUtils.escapeXml(referer) + "</referer>" : "") + "<browser ipaddress=\"" + ip + "\">" + StringEscapeUtils.escapeXml(userAgent) + "</browser>" + "<user id=\"" + sesamId + "\">" + sesamUser + "</user>" + "</request>"); }
From source file:com.assignment4.security.ValidateSaltFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // Assume its HTTP HttpServletRequest httpReq = (HttpServletRequest) request; // Get the salt sent with the request String salt = (String) httpReq.getParameter("randId"); // Validate that the salt is in the cache Cache<String, Boolean> csrfPreventionSaltCache = (Cache<String, Boolean>) httpReq.getSession() .getAttribute("csrfPreventionSaltCache"); if (csrfPreventionSaltCache != null && salt == null && (null != request.getParameter("activationtoken") || null != request.getParameter("crypt"))) { csrfPreventionSaltCache = CacheBuilder.newBuilder().maximumSize(5000) .expireAfterWrite(20, TimeUnit.MINUTES).build(); httpReq.getSession().setAttribute("csrfPreventionSaltCache", csrfPreventionSaltCache); // Generate the salt and store it in the users cache salt = RandomStringUtils.random(20, 0, 0, true, true, null, new SecureRandom()); csrfPreventionSaltCache.put(salt, Boolean.TRUE); // Add the salt to the current request so it can be used // by the page rendered in this request httpReq.setAttribute("randId", salt); }//from ww w .j a v a 2 s .c om if (csrfPreventionSaltCache != null && salt != null && csrfPreventionSaltCache.getIfPresent(salt) != null) { // If the salt is in the cache, we move on chain.doFilter(request, response); } else { // Otherwise we throw an exception aborting the request flow throw new ServletException("Potential CSRF detected!! Inform a scary sysadmin ASAP."); } }
From source file:com.easyshop.common.web.filter.SetCommonDataFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { ///*from w w w. java 2 s .c o m*/ HttpServletRequest httpServletRequest = (HttpServletRequest) request; if (request.getAttribute(Constants.CONTEXT_PATH) == null) { request.setAttribute(Constants.CONTEXT_PATH, httpServletRequest.getContextPath()); } if (request.getAttribute(Constants.WEB_BASE) == null) { request.setAttribute(Constants.WEB_BASE, webBase); } //? String currentPageStr = request.getParameter(currentPageParamKey); if (StringUtils.isNotBlank(currentPageStr)) { try { Integer currentPage = Integer.valueOf(currentPageStr); PageContext.setCurrentPage(currentPage); } catch (NumberFormatException e) { //e.printStackTrace(); LOGGER.warn( "?'currentPage'?,???,?{}", currentPageStr); } } String pageSizeStr = request.getParameter(pageSizeParamKey); if (StringUtils.isNotBlank(pageSizeStr)) { try { Integer pageSize = Integer.valueOf(pageSizeStr); PageContext.setPageSize(pageSize); } catch (NumberFormatException e) { //e.printStackTrace(); LOGGER.warn( "?'pageSize'?,???,?{}", pageSizeStr); } } try { chain.doFilter(request, response); } finally { PageContext.clear(); } }
From source file:com.wikipy.security.AuthenticationFilter.java
/** * Run the authentication filter/*from w w w . java2 s .com*/ * * @param req ServletRequest * @param resp ServletResponse * @param chain FilterChain * @exception ServletException * @exception IOException */ public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { // Assume it's an HTTP request HttpServletRequest httpReq = (HttpServletRequest) req; HttpServletResponse httpResp = (HttpServletResponse) resp; // Get the user details object from the session String user = (String) httpReq.getSession().getAttribute(AUTHENTICATION_USER); if (user == null) { String ticket = getCookieTicket(httpReq); if (ticket == null) { ticket = req.getParameter(ARG_TICKET); } if (ticket != null) { Cache cookieCache = cacheService.getCookieCache(); Element element = cookieCache.get(ticket); if (element != null) { String cachedUser = (String) element.getValue(); httpReq.getSession().setAttribute(AUTHENTICATION_USER, cachedUser); AuthenticationUtil.setCurrentUser(cachedUser); chain.doFilter(req, resp); return; } } httpReq.getSession().setAttribute(AuthenticationFilter.LOGIN_REFERER, httpReq.getRequestURI()); httpResp.sendRedirect("/login.jsp"); return; } else { AuthenticationUtil.setCurrentUser(user); chain.doFilter(req, resp); } }
From source file:org.kuali.rice.krad.util.KRADUtils.java
/** * Retrieves value for the given parameter name in the request and attempts to convert to a Boolean using * the <code>BooleanFormatter</code> * * @param request - servlet request containing parameters * @param parameterName - name of parameter to retrieve value for * @return Boolean set to value of parameter, or null if parameter was not found in request */// w w w . j a v a2 s . c om public static Boolean getRequestParameterAsBoolean(ServletRequest request, String parameterName) { Boolean parameterValue = null; String parameterValueStr = request.getParameter(parameterName); if (StringUtils.isNotBlank(parameterValueStr)) { parameterValue = (Boolean) new BooleanFormatter().convertFromPresentationFormat(parameterValueStr); } return parameterValue; }
From source file:org.eclipse.skalli.view.internal.filter.AbstractSearchFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // retrieve the logged-in user String userId = (String) request.getAttribute(Consts.ATTRIBUTE_USERID); User user = (User) request.getAttribute(Consts.ATTRIBUTE_USER); // calculate start param int start = toInt(request.getParameter(Consts.PARAM_START), 0, -1); // calculate count size param int count = toInt(request.getParameter(Consts.PARAM_COUNT), 10, 50); // retrieve search hits and based on that parent projects and subprojects SearchResult<Project> searchResult = getSearchHits(user, request, response, start, count); List<SearchHit<Project>> searchHits = searchResult.getResult(); Map<String, String> natures = getProjectNatures(searchHits); Map<String, Project> parents = getParents(searchHits); Map<String, List<Project>> parentChains = getParentChains(searchHits); Map<String, List<SearchHit<Project>>> subprojects = getSubprojects(searchHits); Map<String, List<String>> sourceLinks = getSourceLinks(userId, searchHits); // retrieve the favorites of the user Favorites favorites = getFavorites(user); // calculate params for pager int resultSize = searchResult.getResultCount(); int pages = (int) Math.ceil((double) resultSize / (double) count); int currentPage = (int) Math.floor((double) start / (double) count) + 1; long duration = searchResult.getDuration(); // set the request attributes request.setAttribute(ATTRIBUTE_TITLE, getTitle(user)); request.setAttribute(ATTRIBUTE_PROJECTS, searchHits); request.setAttribute(ATTRIBUTE_NATURES, natures); request.setAttribute(ATTRIBUTE_PARENTS, parents); request.setAttribute(ATTRIBUTE_PARENTCHAINS, parentChains); request.setAttribute(ATTRIBUTE_SUBPROJETS, subprojects); request.setAttribute(ATTRIBUTE_SOURCELINKS, sourceLinks); request.setAttribute(Consts.ATTRIBUTE_FAVORITES, favorites.asMap()); request.setAttribute(ATTRIBUTE_DURATION, duration); request.setAttribute(ATTRIBUTE_START, start); request.setAttribute(ATTRIBUTE_VIEWSIZE, count); request.setAttribute(ATTRIBUTE_RESULTSIZE, resultSize); request.setAttribute(ATTRIBUTE_CURRENTPAGE, currentPage); request.setAttribute(ATTRIBUTE_PAGES, pages); request.setAttribute(Consts.ATTRIBUTE_USER, user); if (((HttpServletRequest) request).getPathInfo() == null) { request.getRequestDispatcher(Consts.JSP_SEARCHRESULT).forward(request, response); return;//from ww w .j av a 2s. co m } // proceed along the chain chain.doFilter(request, response); }