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.eclipse.skalli.view.internal.filter.LoginFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { long timeBeginnProcessing = System.currentTimeMillis(); HttpServletRequest httpRequest = (HttpServletRequest) request; String pathInfo = httpRequest.getPathInfo(); String requestURL = httpRequest.getRequestURL().toString(); // servletUrl = schema://host:port/contextPath/servletPath String servletURL = StringUtils.removeEnd(requestURL, pathInfo); request.setAttribute(Consts.ATTRIBUTE_SERVLET_URL, servletURL); // baseUrl = schema://host:port/contextPath String baseURL = StringUtils.removeEnd(servletURL, httpRequest.getServletPath()); request.setAttribute(Consts.ATTRIBUTE_BASE_URL, baseURL); // webLocator = schema://host:port String webLocator = StringUtils.removeEnd(requestURL, httpRequest.getRequestURI()); request.setAttribute(Consts.ATTRIBUTE_WEBLOCATOR, webLocator); String paramProjectId = request.getParameter(Consts.PARAM_ID); // determine the project from the URL Project project = null;/*from w ww . j ava2 s . c o m*/ ProjectService projectService = ((ProjectService) EntityServices.getByEntityClass(Project.class)); // first check if project can be deduced from pathInfo if (StringUtils.isNotBlank(pathInfo)) { if (pathInfo.startsWith(FilterUtil.PATH_SEPARATOR)) { pathInfo = pathInfo.replaceFirst(FilterUtil.PATH_SEPARATOR, StringUtils.EMPTY); } if (pathInfo.contains(FilterUtil.PATH_SEPARATOR)) { pathInfo = pathInfo.substring(0, pathInfo.indexOf(FilterUtil.PATH_SEPARATOR)); } project = projectService.getProjectByProjectId(pathInfo); // project not found by name, search by UUID if (project == null && UUIDUtils.isUUID(pathInfo)) { UUID uuid = UUIDUtils.asUUID(pathInfo); project = projectService.getByUUID(uuid); // project not found by UUID, search for deleted project by UUID if (project == null) { project = projectService.getDeletedProject(uuid); } } if (project == null) { request.setAttribute(Consts.ATTRIBUTE_WINDOWNAME, httpRequest.getPathInfo()); } } // project not found by pathInfo, check if project is provided via URL parameter if (project == null && StringUtils.isNotBlank(paramProjectId)) { project = projectService.getProjectByProjectId(paramProjectId); if (project == null) { // currently we don't support a scenario where projects are passed via UUID FilterUtil.handleException(request, response, new FilterException(String.format("Invalid project identifier '%s' specified in query '%s'", paramProjectId, Consts.PARAM_ID))); return; } } if (project != null) { request.setAttribute(Consts.ATTRIBUTE_PROJECT, project); request.setAttribute(Consts.ATTRIBUTE_PROJECTID, project.getProjectId()); request.setAttribute(Consts.ATTRIBUTE_PROJECTUUID, project.getUuid().toString()); } else { // do nothing if project is null since this filter runs during // creation of projects and displaying of search results, too } // login and ensure that the user is allowed to access PermitService permitService = Services.getRequiredService(PermitService.class); String userId = permitService.login(httpRequest, project); User user = null; boolean isAnonymousUser = StringUtils.isBlank(userId); if (isAnonymousUser && rejectAnonymousUsers) { FilterUtil.handleACException(httpRequest, response, new AccessControlException("Forbidden for anonymous users")); return; } if (!isAnonymousUser) { request.setAttribute(Consts.ATTRIBUTE_USERID, userId); String userDisplayName = userId; user = UserServices.getUser(userId); if (user != null) { userDisplayName = user.getDisplayName(); request.setAttribute(Consts.ATTRIBUTE_USER, user); } request.setAttribute(Consts.ATTRIBUTE_USER_DISPLAY_NAME, userDisplayName); } boolean isProjectAdmin = !isAnonymousUser && project != null && (GroupUtils.isAdministrator(userId) || Permits.isAllowed(Permit.ACTION_PUT, project)); boolean isProjectAdminInParentChain = !isAnonymousUser && project != null && ProjectUtils.isProjectAdminInParentChain(userId, project); request.setAttribute(Consts.ATTRIBUTE_ANONYMOUS_USER, isAnonymousUser); request.setAttribute(Consts.ATTRIBUTE_PROJECTADMIN, isProjectAdmin); request.setAttribute(Consts.ATTRIBUTE_PARENTPROJECTADMIN, isProjectAdminInParentChain); // track the access Statistics statistics = Statistics.getDefault(); if (user != null) { statistics.trackUser(userId, user.getDepartment(), user.getLocation()); } else if (StringUtils.isNotBlank(userId)) { statistics.trackUser(userId, null, null); } String referer = httpRequest.getHeader("Referer"); //$NON-NLS-1$ if (StringUtils.isBlank(referer)) { referer = request.getParameter("referer"); //$NON-NLS-1$ } if (StringUtils.isNotBlank(referer)) { statistics.trackReferer(userId, referer); } String requestLine = MessageFormat.format("{0} {1}", //$NON-NLS-1$ httpRequest.getMethod(), httpRequest.getRequestURI()); if (project != null) { requestLine = MessageFormat.format("{0} /projects/{1}", //$NON-NLS-1$ httpRequest.getMethod(), project.getProjectId()); } statistics.trackUsage(userId, requestLine, referer); String browser = httpRequest.getHeader("User-Agent"); //$NON-NLS-1$ if (StringUtils.isNotBlank(browser)) { statistics.trackBrowser(userId, browser); } // proceed along the chain chain.doFilter(request, response); // track the overall response time long responseTime = System.currentTimeMillis() - timeBeginnProcessing; statistics.trackResponseTime(userId, requestLine, responseTime); LOG.info(MessageFormat.format("{0}: responseTime={1} milliseconds)", requestLine, Long.toString(responseTime))); }
From source file:org.agnitas.util.AgnUtils.java
/** * Getter for property parameterMap./*from www. ja va2 s .co m*/ * * @return Value of property parameterMap. */ public static Map<String, String> getRequestParameterMap(ServletRequest req) { Map<String, String> parameterMap = new HashMap<String, String>(); @SuppressWarnings("unchecked") Enumeration<String> e = req.getParameterNames(); while (e.hasMoreElements()) { String parameterName = e.nextElement(); String paremeterValue = req.getParameter(parameterName); parameterMap.put(parameterName, paremeterValue); } return parameterMap; }
From source file:org.sakaiproject.portlets.PortletIFrame.java
public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException { response.setContentType("text/html"); // System.out.println("==== doView called ===="); // Grab that underlying request to get a GET parameter ServletRequest req = (ServletRequest) ThreadLocalManager.get(CURRENT_HTTP_REQUEST); String popupDone = req.getParameter("sakai.popup"); PrintWriter out = response.getWriter(); Context context = new VelocityContext(); Placement placement = ToolManager.getCurrentPlacement(); Properties config = getAllProperties(placement); response.setTitle(placement.getTitle()); String source = config.getProperty(SOURCE); if (source == null) source = ""; String height = config.getProperty(HEIGHT); if (height == null) height = "1200px"; String sakaiPropertiesUrlKey = config.getProperty(SAKAI_PROPERTIES_URL_KEY); String hideOptions = config.getProperty(HIDE_OPTIONS); String special = getSpecial(config); // Handle the situation where we are displaying the worksite information if (SPECIAL_WORKSITE.equals(special)) { try {//from w w w . j a v a 2 s. c om // If the site does not have an info url, we show description or title Site s = SiteService.getSite(placement.getContext()); String rv = StringUtils.trimToNull(s.getInfoUrlFull()); if (rv == null) { String siteInfo = StringUtils.trimToNull(s.getDescription()); if (siteInfo == null) { siteInfo = StringUtils.trimToNull(s.getTitle()); } StringBuilder alertMsg = new StringBuilder(); if (siteInfo != null) siteInfo = validator.processFormattedText(siteInfo, alertMsg); context.put("siteInfo", siteInfo); vHelper.doTemplate(vengine, "/vm/info.vm", context, out); return; } } catch (Exception any) { any.printStackTrace(); } } boolean popup = "true".equals(placement.getPlacementConfig().getProperty(POPUP)); boolean maximize = "true".equals(placement.getPlacementConfig().getProperty(MAXIMIZE)); // set the pass_pid parameter String passPidStr = config.getProperty(PASS_PID, "false"); boolean passPid = "true".equalsIgnoreCase(passPidStr); // Set the macro expansion String macroExpansionStr = config.getProperty(MACRO_EXPANSION, "true"); boolean macroExpansion = !("false".equalsIgnoreCase(macroExpansionStr)); // Compute the URL String url = sourceUrl(special, source, placement.getContext(), macroExpansion, passPid, placement.getId(), sakaiPropertiesUrlKey); //System.out.println("special="+special+" source="+source+" pgc="+placement.getContext()+" macroExpansion="+macroExpansion+" passPid="+passPid+" PGID="+placement.getId()+" sakaiPropertiesUrlKey="+sakaiPropertiesUrlKey+" url="+url); if (url != null && url.trim().length() > 0) { url = sanitizeHrefURL(url); if (url == null || !validateURL(url)) { M_log.warn("invalid URL suppressed placement=" + placement.getId() + " site=" + placement.getContext() + " url=" + url); url = "about:blank"; } // Check if the site sets X-Frame options popup = popup || popupXFrame(request, placement, url); Session session = SessionManager.getCurrentSession(); String csrfToken = (String) session.getAttribute(UsageSessionService.SAKAI_CSRF_SESSION_ATTRIBUTE); if (csrfToken != null) context.put("sakai_csrf_token", csrfToken); context.put("tlang", rb); context.put("includeLatestJQuery", PortalUtils.includeLatestJQuery("PortletIFrame")); context.put("validator", validator); context.put("source", url); context.put("height", height); sendAlert(request, context); context.put("popup", Boolean.valueOf(popup)); context.put("popupdone", Boolean.valueOf(popupDone != null)); context.put("maximize", Boolean.valueOf(maximize)); context.put("placement", placement.getId().replaceAll("[^a-zA-Z0-9]", "_")); context.put("loadTime", new Long(xframeLoad)); // SAK-23566 capture the view calendar events if (placement != null && placement.getContext() != null && placement.getId() != null) { EventTrackingService ets = (EventTrackingService) ComponentManager.get(EventTrackingService.class); if (ets != null) { String eventRef = "/web/" + placement.getContext() + "/id/" + placement.getId() + "/url/" + URLEncoder.encode(url, "UTF-8"); eventRef = StringUtils.abbreviate(eventRef, 240); // ensure the ref won't pass 255 chars String etsProperty = (StringUtils .trimToNull(config.getProperty(EVENT_ACCESS_WEB_CONTENT)) != null) ? config.getProperty(EVENT_ACCESS_WEB_CONTENT) : EVENT_ACCESS_WEB_CONTENT; ets.post(ets.newEvent(etsProperty, eventRef, false)); } } // TODO: state.setAttribute(TARGETPAGE_URL,config.getProperty(TARGETPAGE_URL)); // TODO: state.setAttribute(TARGETPAGE_NAME,config.getProperty(TARGETPAGE_NAME)); vHelper.doTemplate(vengine, "/vm/main.vm", context, out); } else { out.println("Not yet configured"); } // TODO: state.setAttribute(EVENT_ACCESS_WEB_CONTENT, config.getProperty(EVENT_ACCESS_WEB_CONTENT)); // TODO: state.setAttribute(EVENT_REVISE_WEB_CONTENT, config.getProperty(EVENT_REVISE_WEB_CONTENT)); // System.out.println("==== doView complete ===="); }
From source file:com.springsource.hq.plugin.tcserver.serverconfig.web.support.HqAuthenticationFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); /**/*from w w w . j a v a2 s . c o m*/ * If authentication isn't empty, look for the chance that the user was authenticated by * AnonymousAuthenticationProvider. If this is the case, there will be security credentials, but no session role * granted yet. The filter pulls sessionId from the session, and checks against HQ. If successful, it replaces * the existing token with an HQ-specific one. * * If there is already an HqAuthenticationToken then grab the token's sessionId, and re-verify that the session * is active. If the sessionId is null (which only happens when manually entering URLs), send user down the * filter stack. * * If there is no HqAuthenticationToken at all (which should only happen if there is a faulty change in * configuration), then go down the filter stack, allowing Spring Security to fail on lack of security * credentials. Spring Security tends to throw some sort of meaningful error indicating what is missing. */ if (auth != null) { logger.debug("Authentication exists => " + auth); String sessionId = request.getParameter("sessionId"); if (sessionId != null) { logger.debug("SessionId found => " + sessionId); if (!sessionIdExpired(request, sessionId)) { UsernamePasswordAuthenticationToken newToken = createHqAuthenticationToken(auth, sessionId); logger.debug("Replacing existing authentication with new one => " + newToken); SecurityContextHolder.getContext().setAuthentication(newToken); } } else { if (auth instanceof HqAuthenticationToken) { HqAuthenticationToken token = (HqAuthenticationToken) auth; if (sessionIdExpired(request, token.getSessionId())) { throw new BadCredentialsException("Session has expired. Re-login."); } } else { logger.debug("sessionId not found at all. Unable to check against Hyperic."); } } } else { logger.debug("Authentication is currently empty. Unable to check against Hyperic."); } chain.doFilter(request, response); }
From source file:com.adito.vfs.webdav.DAVTransaction.java
/** * <p>//from w ww .j a v a2 s.c om * Create a new {@link DAVTransaction} instance. * </p> * * @throws URISyntaxException */ public DAVTransaction(ServletRequest request, ServletResponse response) // throws ServletException, DAVAuthenticationRequiredException { throws ServletException, URISyntaxException { if (request == null) throw new NullPointerException("Null request"); if (response == null) throw new NullPointerException("Null response"); this.req = (HttpServletRequest) request; this.res = (HttpServletResponse) response; this.resourceCache = new HashMap(); /* * First see if the launch ID has been provided as a parameter. If it * has we can just get the resource session directly. This should happen * for web folders that are first launched from an active user session * or from a file download from the network place HTML file browser. */ String launchId = request.getParameter(LaunchSession.LAUNCH_ID); if (launchId != null) { LaunchSession launchSession = LaunchSessionFactory.getInstance().getLaunchSession(launchId); if (launchSession != null) { sessionInfo = launchSession.getSession(); LogonControllerFactory.getInstance().addCookies( new ServletRequestAdapter((HttpServletRequest) request), new ServletResponseAdapter((HttpServletResponse) response), launchSession.getSession().getLogonTicket(), launchSession.getSession()); sessionInfo.access(); } else if (log.isDebugEnabled()) log.debug("Could not locate session using ticket"); } sessionInfo = LogonControllerFactory.getInstance().getSessionInfo(req); configureFromRequest(); }
From source file:org.xwiki.wysiwyg.filter.ConversionFilter.java
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { // Take the list of request parameters that require HTML conversion. String[] parametersRequiringHTMLConversion = req.getParameterValues(REQUIRES_HTML_CONVERSION); if (parametersRequiringHTMLConversion != null) { MutableServletRequestFactory mreqFactory = Utils.getComponent((Type) MutableServletRequestFactory.class, req.getProtocol());/* w w w .j av a 2 s .c o m*/ // Wrap the current request in order to be able to change request parameters. MutableServletRequest mreq = mreqFactory.newInstance(req); // Remove the list of request parameters that require HTML conversion to avoid recurrency. mreq.removeParameter(REQUIRES_HTML_CONVERSION); // Try to convert each parameter from the list and save caught exceptions. Map<String, Throwable> errors = new HashMap<String, Throwable>(); // Save also the output to prevent loosing data in case of conversion exceptions. Map<String, String> output = new HashMap<String, String>(); for (int i = 0; i < parametersRequiringHTMLConversion.length; i++) { String parameterName = parametersRequiringHTMLConversion[i]; String html = req.getParameter(parameterName); // Remove the syntax parameter from the request to avoid interference with further request processing. String syntax = mreq.removeParameter(parameterName + "_syntax"); if (html == null || syntax == null) { continue; } try { HTMLConverter converter = Utils.getComponent((Type) HTMLConverter.class); mreq.setParameter(parameterName, converter.fromHTML(html, syntax)); } catch (Exception e) { LOGGER.error(e.getLocalizedMessage(), e); errors.put(parameterName, e); } // If the conversion fails the output contains the value before the conversion. output.put(parameterName, mreq.getParameter(parameterName)); } if (!errors.isEmpty()) { handleConversionErrors(errors, output, mreq, res); } else { chain.doFilter(mreq, res); } } else { chain.doFilter(req, res); } }
From source file:org.nuxeo.ecm.platform.ui.web.auth.NuxeoAuthenticationFilter.java
protected boolean handleLogout(ServletRequest request, ServletResponse response, CachableUserIdentificationInfo cachedUserInfo) throws ServletException { logLogout(cachedUserInfo.getUserInfo()); // invalidate Session ! service.invalidateSession(request);/*from w ww .ja va2 s . co m*/ request.setAttribute(DISABLE_REDIRECT_REQUEST_KEY, Boolean.TRUE); Map<String, String> parameters = new HashMap<String, String>(); String securityError = request.getParameter(SECURITY_ERROR); if (securityError != null) { parameters.put(SECURITY_ERROR, securityError); } if (cachedUserInfo.getPrincipal().getName().equals(getAnonymousId())) { parameters.put(FORCE_ANONYMOUS_LOGIN, "true"); } String requestedUrl = request.getParameter(REQUESTED_URL); if (requestedUrl != null) { parameters.put(REQUESTED_URL, requestedUrl); } // Reset JSESSIONID Cookie HttpServletResponse httpResponse = (HttpServletResponse) response; Cookie cookie = new Cookie("JSESSIONID", null); cookie.setMaxAge(0); cookie.setPath("/"); httpResponse.addCookie(cookie); String pluginName = cachedUserInfo.getUserInfo().getAuthPluginName(); NuxeoAuthenticationPlugin authPlugin = service.getPlugin(pluginName); NuxeoAuthenticationPluginLogoutExtension logoutPlugin = null; if (authPlugin instanceof NuxeoAuthenticationPluginLogoutExtension) { logoutPlugin = (NuxeoAuthenticationPluginLogoutExtension) authPlugin; } boolean redirected = false; if (logoutPlugin != null) { redirected = Boolean.TRUE.equals( logoutPlugin.handleLogout((HttpServletRequest) request, (HttpServletResponse) response)); } HttpServletRequest httpRequest = (HttpServletRequest) request; if (!redirected && !XMLHTTP_REQUEST_TYPE.equalsIgnoreCase(httpRequest.getHeader("X-Requested-With"))) { String baseURL = service.getBaseURL(request); try { String url = baseURL + LoginScreenHelper.getStartupPagePath(); url = URIUtils.addParametersToURIQuery(url, parameters); ((HttpServletResponse) response).sendRedirect(url); redirected = true; } catch (IOException e) { log.error("Unable to redirect to default start page after logout : " + e.getMessage()); } } try { cachedUserInfo.getLoginContext().logout(); } catch (LoginException e) { log.error("Unable to logout " + e.getMessage()); } return redirected; }
From source file:org.apache.nifi.web.security.x509.X509AuthenticationFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final HttpServletResponse httpResponse = (HttpServletResponse) response; // determine if this request is attempting to create a new account if (isNewAccountRequest((HttpServletRequest) request)) { // determine if this nifi supports new account requests if (properties.getSupportNewAccountRequests()) { // ensure there is a certificate in the request X509Certificate certificate = certificateExtractor .extractClientCertificate((HttpServletRequest) request); if (certificate != null) { // extract the principal from the certificate Object certificatePrincipal = principalExtractor.extractPrincipal(certificate); String principal = certificatePrincipal.toString(); // log the new user account request logger.info("Requesting new user account for " + principal); try { // get the justification String justification = request.getParameter("justification"); if (justification == null) { justification = StringUtils.EMPTY; }/*from w w w . j av a2s . co m*/ // create the pending user account userService.createPendingUserAccount(principal, justification); // generate a response httpResponse.setStatus(HttpServletResponse.SC_CREATED); httpResponse.setContentType("text/plain"); // write the response message PrintWriter out = response.getWriter(); out.println("Not authorized. User account created. Authorization pending."); } catch (IllegalArgumentException iae) { handleUserServiceError((HttpServletRequest) request, httpResponse, HttpServletResponse.SC_BAD_REQUEST, iae.getMessage()); } catch (AdministrationException ae) { handleUserServiceError((HttpServletRequest) request, httpResponse, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ae.getMessage()); } } else { // can this really happen? handleMissingCertificate((HttpServletRequest) request, httpResponse); } } else { handleUserServiceError((HttpServletRequest) request, httpResponse, HttpServletResponse.SC_NOT_FOUND, "This NiFi does not support new account requests."); } } else { try { // this not a request to create a user account - try to authorize super.doFilter(request, response, chain); } catch (AuthenticationException ae) { // continue the filter chain since anonymous access should be supported if (!properties.getNeedClientAuth()) { chain.doFilter(request, response); } else { // create an appropriate response for the given exception handleUnsuccessfulAuthentication((HttpServletRequest) request, httpResponse, ae); } } } }
From source file:org.eclipse.skalli.view.internal.filter.ProjectPermitsFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; // retrieve userId and project instance from previous filters in chain String userId = (String) request.getAttribute(Consts.ATTRIBUTE_USERID); Project project = (Project) request.getAttribute(Consts.ATTRIBUTE_PROJECT); boolean isAnonymousUser = BooleanUtils .toBoolean((Boolean) request.getAttribute(Consts.ATTRIBUTE_ANONYMOUS_USER)); boolean isProjectAdmin = BooleanUtils .toBoolean((Boolean) request.getAttribute(Consts.ATTRIBUTE_PROJECTADMIN)); String servletPath = httpRequest.getServletPath(); String pathInfo = httpRequest.getPathInfo(); if (servletPath.startsWith(Consts.URL_PROJECTS)) { // handle access to project detail page if (project != null && !Permits.hasProjectPermit(Permit.ALLOW, Permit.ACTION_GET, project)) { AccessControlException e = new AccessControlException(MessageFormat.format( "User ''{0}'' is not authorized to view project ''{1}''", userId, project.getProjectId())); FilterUtil.handleACException(httpRequest, response, e); return; }/* www . j ava2 s . c o m*/ // handle URL starting with /projects String actionValue = request.getParameter(Consts.PARAM_ACTION); if (project != null && Consts.PARAM_VALUE_EDIT.equals(actionValue)) { // handle /projects/{projectId}?action=edit if (!isProjectAdmin) { AccessControlException e = new AccessControlException( MessageFormat.format("User ''{0}'' is not authorized to edit project ''{1}''", userId, project.getProjectId())); FilterUtil.handleACException(httpRequest, response, e); return; } } else if (project == null && StringUtils.isNotBlank(pathInfo)) { // handle /projects/{projectId} with unknown projectId => project creation dialog if (isAnonymousUser) { AccessControlException e = new AccessControlException( "Anonymous users are not authorized to create new projects"); FilterUtil.handleACException(httpRequest, response, e); return; } } } else { // handle all other URLs not starting with /projects if (isAnonymousUser) { AccessControlException e = new AccessControlException( "Anonymous users are not authorized to view this page"); FilterUtil.handleACException(request, response, e); return; } if (StringUtils.isNotBlank(pathInfo)) { if (project == null) { FilterException e = new FilterException(MessageFormat .format("No project instance available although servlet path is {0}.", servletPath)); FilterUtil.handleException(request, response, e); return; } else if (!isProjectAdmin) { AccessControlException e = new AccessControlException( "User is not authorized to view this page"); FilterUtil.handleACException(request, response, e); return; } } } // proceed along the chain chain.doFilter(request, response); }