Java Code Examples for javax.servlet.ServletRequest#getAttribute()

The following examples show how to use javax.servlet.ServletRequest#getAttribute() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CatalogWorker.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
public static String getCatalogName(ServletRequest request, String prodCatalogId) {
    if (UtilValidate.isEmpty(prodCatalogId)) return null;
    Delegator delegator = (Delegator) request.getAttribute("delegator");

    try {
        GenericValue prodCatalog = EntityQuery.use(delegator).from("ProdCatalog").where("prodCatalogId", prodCatalogId).cache().queryOne();

        if (prodCatalog != null) {
            return prodCatalog.getString("catalogName");
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, "Error looking up name for prodCatalog with id " + prodCatalogId, module);
    }

    return null;
}
 
Example 2
Source File: X509AuthenticationFilter.java    From nifi-minifi with Apache License 2.0 6 votes vote down vote up
private void authenticateIfPossible(ServletRequest request) {
    if (!request.isSecure()) {
        return;
    }

    X509Certificate[] certs = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");

    if (certs == null || certs.length == 0) {
        if (logger.isDebugEnabled()) {
            logger.debug("Unable to get certificates in request from " + HttpRequestUtil.getClientString(request));
        }
        return;
    }

    Authentication authentication = authenticationManager.authenticate(new X509AuthenticationToken(certs));
    if (authentication.isAuthenticated()) {
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }
}
 
Example 3
Source File: HTMLUtils.java    From xdocreport.samples with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void generateHTMLOption( String optionValue, String optionLabel, ServletRequest request,
                                       Writer writer, String parameterName )
    throws IOException
{
    writer.write( "<option value=\"" );
    writer.write( optionValue );
    writer.write( "\"" );
    String parameterValue = request.getParameter( parameterName );
    if ( StringUtils.isEmpty( parameterValue ) )
    {
        parameterValue = (String) request.getAttribute( parameterName );
    }
    if ( optionValue.equals( parameterValue ) )
    {
        writer.write( " selected=\"true\" " );
    }
    writer.write( " >" );
    writer.write( optionLabel );
    writer.write( "</option>" );
}
 
Example 4
Source File: FacetNavTreeTag.java    From entando-components with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public int doStartTag() throws JspException {
	ServletRequest request =  this.pageContext.getRequest();
	RequestContext reqCtx = (RequestContext) request.getAttribute(RequestContext.REQCTX);
	try {
		List<String> requiredFacets = this.getRequiredFacets();

		IFacetNavHelper facetNavHelper = (IFacetNavHelper) ApsWebApplicationUtils.getBean(JpFacetNavSystemConstants.CONTENT_FACET_NAV_HELPER, this.pageContext);
		Map<String, Integer> occurrences = facetNavHelper.getOccurences(requiredFacets, reqCtx);

		List<ITreeNode> facetsForTree = this.getFacetRootNodes(reqCtx);
		this.pageContext.setAttribute(this.getFacetsTreeParamName(), facetsForTree);
		request.setAttribute(this.getOccurrencesParamName(), occurrences);
		request.setAttribute(this.getRequiredFacetsParamName(), requiredFacets);
	} catch (Throwable t) {
		_logger.error("Error in doStartTag", t);
		throw new JspException("Error initialization tag", t);
	}
	return super.doStartTag();
}
 
Example 5
Source File: ApplicationRequest.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Set the request that we are wrapping.
 *
 * @param request The new wrapped request
 */
@Override
public void setRequest(ServletRequest request) {

    super.setRequest(request);

    // Initialize the attributes for this request
    synchronized (attributes) {
        attributes.clear();
        Enumeration<String> names = request.getAttributeNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            Object value = request.getAttribute(name);
            attributes.put(name, value);
        }
    }

}
 
Example 6
Source File: ExtendedServletRequestDataBinder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Merge URI variables into the property values to use for data binding.
 */
@Override
@SuppressWarnings("unchecked")
protected void addBindValues(MutablePropertyValues mpvs, ServletRequest request) {
	String attr = HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE;
	Map<String, String> uriVars = (Map<String, String>) request.getAttribute(attr);
	if (uriVars != null) {
		for (Entry<String, String> entry : uriVars.entrySet()) {
			if (mpvs.contains(entry.getKey())) {
				if (logger.isWarnEnabled()) {
					logger.warn("Skipping URI variable '" + entry.getKey() +
							"' since the request contains a bind value with the same name.");
				}
			}
			else {
				mpvs.addPropertyValue(entry.getKey(), entry.getValue());
			}
		}
	}
}
 
Example 7
Source File: RequestTracingFilter.java    From wingtips with Apache License 2.0 6 votes vote down vote up
/**
 * Wrapper around {@link #doFilterInternal(HttpServletRequest, HttpServletResponse, FilterChain)} to make sure this
 * filter's logic is only executed once per request.
 */
@Override
public void doFilter(ServletRequest request,
                     ServletResponse response,
                     FilterChain filterChain) throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) {
        throw new ServletException(this.getClass().getName() + " only supports HTTP requests");
    }
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    boolean filterHasAlreadyExecuted = request.getAttribute(FILTER_HAS_ALREADY_EXECUTED_ATTRIBUTE) != null;
    if (filterHasAlreadyExecuted || skipDispatch(httpRequest)) {

        // Already executed or we're supposed to skip, so continue the filter chain without doing the
        //      distributed tracing work.
        filterChain.doFilter(request, response);
    }
    else {
        // Time to execute the distributed tracing logic.
        request.setAttribute(FILTER_HAS_ALREADY_EXECUTED_ATTRIBUTE, Boolean.TRUE);
        doFilterInternal(httpRequest, httpResponse, filterChain);
    }
}
 
Example 8
Source File: SelectableColumnTag.java    From spacewalk with GNU General Public License v2.0 5 votes vote down vote up
private static void addPostScript(String script, String listName,
                                            ServletRequest request) {
    String key  = makePostScriptKey(listName);
    StringBuilder test = (StringBuilder)request.getAttribute(key);
    if (test == null) {
        test = new StringBuilder();
        request.setAttribute(key, test);
    }
    test.append(script);
}
 
Example 9
Source File: OncePerRequestFilter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * This {@code doFilter} implementation stores a request attribute for
 * "already filtered", proceeding without filtering again if the
 * attribute is already there.
 * @see #getAlreadyFilteredAttributeName
 * @see #shouldNotFilter
 * @see #doFilterInternal
 */
@Override
public final void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
		throws ServletException, IOException {

	if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) {
		throw new ServletException("OncePerRequestFilter just supports HTTP requests");
	}
	HttpServletRequest httpRequest = (HttpServletRequest) request;
	HttpServletResponse httpResponse = (HttpServletResponse) response;

	String alreadyFilteredAttributeName = getAlreadyFilteredAttributeName();
	boolean hasAlreadyFilteredAttribute = request.getAttribute(alreadyFilteredAttributeName) != null;

	if (hasAlreadyFilteredAttribute || skipDispatch(httpRequest) || shouldNotFilter(httpRequest)) {

		// Proceed without invoking this filter...
		filterChain.doFilter(request, response);
	}
	else {
		// Do invoke this filter...
		request.setAttribute(alreadyFilteredAttributeName, Boolean.TRUE);
		try {
			doFilterInternal(httpRequest, httpResponse, filterChain);
		}
		finally {
			// Remove the "already filtered" request attribute for this request.
			request.removeAttribute(alreadyFilteredAttributeName);
		}
	}
}
 
Example 10
Source File: SessionHelpers.java    From HttpSessionReplacer with MIT License 5 votes vote down vote up
/**
 * This method is called from {@link SessionFilter} or from {@link Filter} implementations modified by SessionAgent.
 * The method wraps {@link ServletRequest} in {@link HttpRequestWrapper}.
 * <p>
 * The method will wrap request at most once per request and will only wrap instances of {@link HttpServletRequest}.
 *
 * @param request
 *          request received by filter
 * @param response
 *          response received by filter
 * @param originalServletContext
 *          {@link ServletContext} used when filter was initialized
 * @return wrapped or original request
 */
public ServletRequest prepareRequest(ServletRequest request, ServletResponse response,
    ServletContext originalServletContext) {
  // Only execute this code once per request
  if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
    HttpRequestWrapper wrappedRequest = (HttpRequestWrapper)request.getAttribute(REQUEST_WRAPPED_ATTRIBUTE);
    ServletContext servletContext = originalServletContext;
    if (servletContext == null) {
      logger.info("ServletContext was null when prepareRequest() was called from Filter. "
          + "This means that filter's init() method was not called at initialization time. "
          + "This may result in unexpected behavior if this filter was invoked after"
          + "servlet dispatch forward() and include() calls.");
      servletContext = ((HttpServletRequest)request).getServletContext();
    }

    // for following we actually test that servlet context points to same
    // references, and so we don't use equals() method
    if (wrappedRequest == null || servletContext != wrappedRequest.getServletContext()) { // NOSONAR
      if (interceptListeners) {
        findListenersByIntercepting(servletContext, (HttpServletRequest)request);
      }
      wrappedRequest = wrapRequest(request, servletContext);
      wrappedRequest.setResponse(wrapResponse(response, wrappedRequest));
      request.setAttribute(REQUEST_WRAPPED_ATTRIBUTE, wrappedRequest);
      return wrappedRequest;
    }
  }
  return request;
}
 
Example 11
Source File: AutoIndexingTagHelper.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Return the current tabindex.
 * @param tag The tag containing the tabindex property. 
 * @param request The request.
 * @return The current request.
 */
public static String getCurrentIndex(IAutoIndexingTag tag, ServletRequest request) {
	if (null == tag.getUseTabindexAutoIncrement() || !tag.getUseTabindexAutoIncrement().booleanValue()) {
		return null;
	}
	String currentCounter = (String) request.getAttribute(COUNTER_KEY);
	int currentCounterValue = 1;
	if (null != currentCounter) {
		currentCounterValue = Integer.parseInt(currentCounter);
	}
	int step = (null != tag.getStep()) ? tag.getStep().intValue() : 0;
	int nextValue = currentCounterValue + step;
	request.setAttribute(COUNTER_KEY, String.valueOf(nextValue));
	return String.valueOf(currentCounterValue);
}
 
Example 12
Source File: SysUserFilter.java    From es with Apache License 2.0 5 votes vote down vote up
protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
    User user = (User) request.getAttribute(Constants.CURRENT_USER);
    String url = null;
    if (Boolean.TRUE.equals(user.getDeleted())) {
        url = getUserNotfoundUrl();
    } else if (user.getStatus() == UserStatus.blocked) {
        url = getUserBlockedUrl();
    } else {
        url = getUserUnknownErrorUrl();
    }

    WebUtils.issueRedirect(request, response, url);
}
 
Example 13
Source File: PagerTagHelper.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected int getMaxElementForItem(int maxItems, ServletRequest request) {
	if (maxItems == 0) {
		RequestContext reqCtx = (RequestContext) request.getAttribute(RequestContext.REQCTX);
		if (reqCtx != null) {
			Widget widget = (Widget) reqCtx.getExtraParam(SystemConstants.EXTRAPAR_CURRENT_WIDGET);
			ApsProperties config = widget.getConfig();
			String stringMax = (null != config) ? (String) config.get("maxElemForItem") : null;
			if (stringMax != null && stringMax.length() > 0) {
				maxItems = Integer.parseInt(stringMax);
			}
		}
	}
	return maxItems;
}
 
Example 14
Source File: WebAsyncUtils.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Obtain the {@link WebAsyncManager} for the current request, or if not
 * found, create and associate it with the request.
 */
public static WebAsyncManager getAsyncManager(ServletRequest servletRequest) {
	WebAsyncManager asyncManager = null;
	Object asyncManagerAttr = servletRequest.getAttribute(WEB_ASYNC_MANAGER_ATTRIBUTE);
	if (asyncManagerAttr instanceof WebAsyncManager) {
		asyncManager = (WebAsyncManager) asyncManagerAttr;
	}
	if (asyncManager == null) {
		asyncManager = new WebAsyncManager();
		servletRequest.setAttribute(WEB_ASYNC_MANAGER_ATTRIBUTE, asyncManager);
	}
	return asyncManager;
}
 
Example 15
Source File: KeycloakSecurityContextRequestFilter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
    if (request.getAttribute(FILTER_APPLIED) != null) {
        filterChain.doFilter(request, response);
        return;
    }

    request.setAttribute(FILTER_APPLIED, Boolean.TRUE);

    KeycloakSecurityContext keycloakSecurityContext = getKeycloakSecurityContext();

    if (keycloakSecurityContext instanceof RefreshableKeycloakSecurityContext) {
        RefreshableKeycloakSecurityContext refreshableSecurityContext = (RefreshableKeycloakSecurityContext) keycloakSecurityContext;
        KeycloakDeployment deployment = resolveDeployment(request, response);

        // just in case session got serialized
        if (refreshableSecurityContext.getDeployment()==null) {
            log.trace("Recreating missing deployment and related fields in deserialized context");
            AdapterTokenStore adapterTokenStore = adapterTokenStoreFactory.createAdapterTokenStore(deployment, (HttpServletRequest) request,
                    (HttpServletResponse) response);
            refreshableSecurityContext.setCurrentRequestInfo(deployment, adapterTokenStore);
        }

        if (!refreshableSecurityContext.isActive() || deployment.isAlwaysRefreshToken()) {
            if (refreshableSecurityContext.refreshExpiredToken(false)) {
                request.setAttribute(KeycloakSecurityContext.class.getName(), refreshableSecurityContext);
            } else {
                clearAuthenticationContext();
            }
        }

        request.setAttribute(KeycloakSecurityContext.class.getName(), keycloakSecurityContext);
    }

    filterChain.doFilter(request, response);
}
 
Example 16
Source File: AnonymousFilter.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void afterCompletion(final ServletRequest request, final ServletResponse response, final Exception exception)
    throws Exception
{
  Subject subject = (Subject) request.getAttribute(ORIGINAL_SUBJECT);
  if (subject != null) {
    log.trace("Binding original subject: {}", subject);
    ThreadContext.bind(subject);
  }
}
 
Example 17
Source File: CheckHeadInfoOutputterTag.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
public int doStartTag() throws JspException {
	ServletRequest request =  this.pageContext.getRequest();
	RequestContext reqCtx = (RequestContext) request.getAttribute(RequestContext.REQCTX);
	HeadInfoContainer headInfo = (HeadInfoContainer) reqCtx.getExtraParam(SystemConstants.EXTRAPAR_HEAD_INFO_CONTAINER);
	List<Object> infos = headInfo.getInfos(this.getType());
	if (infos == null || infos.size() == 0) {
		return SKIP_BODY;
	} else {
		return EVAL_BODY_INCLUDE;
	}
}
 
Example 18
Source File: OnlineSessionFilter.java    From es with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
    Subject subject = getSubject(request, response);
    if (subject == null || subject.getSession() == null) {
        return true;
    }
    Session session = onlineSessionDAO.readSession(subject.getSession().getId());
    if (session != null && session instanceof OnlineSession) {
        OnlineSession onlineSession = (OnlineSession) session;
        request.setAttribute(ShiroConstants.ONLINE_SESSION, onlineSession);
        //把user id设置进去
        boolean isGuest = onlineSession.getUserId() == null || onlineSession.getUserId() == 0L;
        if (isGuest == true) {
            User user = (User) request.getAttribute(Constants.CURRENT_USER);
            if (user != null) {
                onlineSession.setUserId(user.getId());
                onlineSession.setUsername(user.getUsername());
                onlineSession.markAttributeChanged();
            }
        }

        if (onlineSession.getStatus() == OnlineSession.OnlineStatus.force_logout) {
            return false;
        }
    }
    return true;
}
 
Example 19
Source File: RangerPDPKnoxFilter.java    From ranger with Apache License 2.0 4 votes vote down vote up
public void doFilter(ServletRequest request, ServletResponse response,
		FilterChain chain) throws IOException, ServletException {

	String sourceUrl = (String) request
			.getAttribute(AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME);
	String topologyName = getTopologyName(sourceUrl);
	String serviceName = getServiceName();

	RangerPerfTracer perf = null;

	if(RangerPerfTracer.isPerfTraceEnabled(PERF_KNOXAUTH_REQUEST_LOG)) {
		perf = RangerPerfTracer.getPerfTracer(PERF_KNOXAUTH_REQUEST_LOG, "RangerPDPKnoxFilter.doFilter(url=" + sourceUrl + ", topologyName=" + topologyName + ")");
	}

	Subject subject = Subject.getSubject(AccessController.getContext());

	Principal primaryPrincipal = (Principal) subject.getPrincipals(
			PrimaryPrincipal.class).toArray()[0];
	String primaryUser = primaryPrincipal.getName();

	String impersonatedUser = null;
	Object[] impersonations = subject.getPrincipals(
			ImpersonatedPrincipal.class).toArray();
	if (impersonations != null && impersonations.length > 0) {
		impersonatedUser = ((Principal) impersonations[0]).getName();
	}

	String user = (impersonatedUser != null) ? impersonatedUser
			: primaryUser;
	if (LOG.isDebugEnabled()) {
		LOG.debug("Checking access primaryUser: " + primaryUser + ", impersonatedUser: "
				+ impersonatedUser + ", effectiveUser: " + user);
	}

	Object[] groupObjects = subject.getPrincipals(GroupPrincipal.class)
			.toArray();
	Set<String> groups = new HashSet<String>();
	for (Object obj : groupObjects) {
		groups.add(((Principal) obj).getName());
	}

	String clientIp = request.getRemoteAddr();
	List<String> forwardedAddresses = getForwardedAddresses(request);

	if (LOG.isDebugEnabled()) {
		LOG.debug("Checking access primaryUser: " + primaryUser
				+ ", impersonatedUser: " + impersonatedUser
				+ ", effectiveUser: " + user + ", groups: " + groups
				+ ", clientIp: " + clientIp + ", remoteIp: " + clientIp + ", forwardedAddresses: " + forwardedAddresses);
	}

	RangerAccessRequest accessRequest = new RequestBuilder()
		.service(serviceName)
		.topology(topologyName)
		.user(user)
		.groups(groups)
		.clientIp(clientIp)
		.remoteIp(clientIp)
		.forwardedAddresses(forwardedAddresses)
		.build();

	boolean accessAllowed = false;

	if (plugin != null) {
		RangerAccessResult result = plugin.isAccessAllowed(accessRequest);

		accessAllowed = result != null && result.getIsAllowed();
	}

	if (LOG.isDebugEnabled()) {
		LOG.debug("Access allowed: " + accessAllowed);
	}

	RangerPerfTracer.log(perf);

	if (accessAllowed) {
		chain.doFilter(request, response);
	} else {
		sendForbidden((HttpServletResponse) response);
	}
}
 
Example 20
Source File: TracingFilter.java    From java-web-servlet-filter with Apache License 2.0 2 votes vote down vote up
/**
 * Get context of server span.
 *
 * @param servletRequest request
 * @return server span context
 */
public static SpanContext serverSpanContext(ServletRequest servletRequest) {
    return (SpanContext) servletRequest.getAttribute(SERVER_SPAN_CONTEXT);
}