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

The following examples show how to use javax.servlet.ServletRequest#setAttribute() . 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: CognitoIdentityFilter.java    From aws-serverless-java-container with Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    Object apiGwContext = servletRequest.getAttribute(RequestReader.API_GATEWAY_CONTEXT_PROPERTY);
    if (apiGwContext == null) {
        log.warn("API Gateway context is null");
        filterChain.doFilter(servletRequest, servletResponse);
    }
    if (!AwsProxyRequestContext.class.isAssignableFrom(apiGwContext.getClass())) {
        log.warn("API Gateway context object is not of valid type");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    AwsProxyRequestContext ctx = (AwsProxyRequestContext)apiGwContext;
    if (ctx.getIdentity() == null) {
        log.warn("Identity context is null");
        filterChain.doFilter(servletRequest, servletResponse);
    }
    String cognitoIdentityId = ctx.getIdentity().getCognitoIdentityId();
    if (cognitoIdentityId == null || "".equals(cognitoIdentityId.trim())) {
        log.warn("Cognito identity id in request is null");
    }
    servletRequest.setAttribute(COGNITO_IDENTITY_ATTRIBUTE, cognitoIdentityId);
    filterChain.doFilter(servletRequest, servletResponse);
}
 
Example 2
Source File: SSLInformationAssociationHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    ServletRequest request = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY).getServletRequest();
    SSLSessionInfo ssl = exchange.getConnection().getSslSessionInfo();
    if (ssl != null) {
        String cipherSuite = ssl.getCipherSuite();
        request.setAttribute("javax.servlet.request.cipher_suite", cipherSuite);
        request.setAttribute("javax.servlet.request.key_size", getKeyLength(cipherSuite));
        request.setAttribute("javax.servlet.request.ssl_session_id", ssl.getSessionId());
        X509Certificate[] certs = getCerts(ssl);
        if (certs != null) {
            request.setAttribute("javax.servlet.request.X509Certificate", certs);
        }

    }
    next.handleRequest(exchange);
}
 
Example 3
Source File: QuarkusExceptionHandler.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public boolean handleThrowable(HttpServerExchange exchange, ServletRequest request, ServletResponse response, Throwable t) {
    String uid = BASE_ID + ERROR_COUNT.incrementAndGet();
    request.setAttribute(ERROR_ID, uid);
    ExceptionLog log = t.getClass().getAnnotation(ExceptionLog.class);
    if (log != null) {
        Logger.Level level = log.value();
        Logger.Level stackTraceLevel = log.stackTraceLevel();
        String category = log.category();
        handleCustomLog(exchange, t, level, stackTraceLevel, category, uid);
    } else if (t instanceof IOException) {
        //we log IOExceptions at a lower level
        //because they can be easily caused by malicious remote clients in at attempt to DOS the server by filling the logs
        UndertowLogger.REQUEST_IO_LOGGER.debugf(t, "Exception handling request %s to %s", uid, exchange.getRequestURI());
    } else {
        UndertowLogger.REQUEST_IO_LOGGER.errorf(t, "Exception handling request %s to %s", uid, exchange.getRequestURI());
    }
    return false;
}
 
Example 4
Source File: RcCaptchaValidateFilter.java    From mumu with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
		throws Exception {
	// 1、设置验证码是否开启属性,页面可以根据该属性来决定是否显示验证码
	request.setAttribute("captchaEbabled", captchaEbabled);

	HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
	// 2、判断验证码是否禁用 或不是表单提交(允许访问)
	if (captchaEbabled == false || !"post".equalsIgnoreCase(httpServletRequest.getMethod())) {
		return true;
	}
	// 3、此时是表单提交,验证验证码是否正确
	// 获取页面提交的验证码
	String submitCaptcha = httpServletRequest.getParameter(captchaParam);
	// 获取session中的验证码
	String captcha = (String) httpServletRequest.getSession().getAttribute("rcCaptcha");
	if (submitCaptcha.equals(captcha)) {
		return true;
	}
	return false;
}
 
Example 5
Source File: SearcherTag.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 {
		String word = request.getParameter("search");
		SearcherTagHelper helper = new SearcherTagHelper();
		List<String> result = helper.executeSearch(word, reqCtx);
		this.pageContext.setAttribute(this.getListName(), result);
		request.setAttribute("search", word);
	} catch (Throwable t) {
		_logger.error("error in do start tag", t);
		//ApsSystemUtils.logThrowable(e, this, "doStartTag");
		throw new JspException("Error detected while initialising the tag", t);
	}
	return SKIP_BODY;
}
 
Example 6
Source File: Log4jServletFilter.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    if (request.getAttribute(ALREADY_FILTERED_ATTRIBUTE) != null) {
        chain.doFilter(request, response);
    } else {
        request.setAttribute(ALREADY_FILTERED_ATTRIBUTE, Boolean.TRUE);

        try {
            this.initializer.setLoggerContext();
            CURRENT_REQUEST.set(request);
            chain.doFilter(request, response);
        } finally {
            this.initializer.clearLoggerContext();
            CURRENT_REQUEST.remove();
        }
    }
}
 
Example 7
Source File: RestAuthFilter.java    From opencps-v2 with GNU Affero General Public License v3.0 5 votes vote down vote up
private void authOK(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain, long userId)
			throws IOException, ServletException {
		servletRequest.setAttribute(USER_ID, userId);
//	    HttpServletRequest  httpRequest  = (HttpServletRequest)  servletRequest;
	    HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
//	    String gzipFilterProperty = PropsUtil.get(OPENCPS_GZIP_FILTER);
//	    String liferayGzipProperty = PropsUtil.get(LIFERAY_GZIP_FILTER);
	    
//	    boolean gzipFilterEnable = Validator.isNotNull(gzipFilterProperty) ? Boolean.parseBoolean(PropsUtil.get(OPENCPS_GZIP_FILTER)) : false;
//	    if (Validator.isNotNull(liferayGzipProperty) && Boolean.parseBoolean(liferayGzipProperty)) {
//	    	gzipFilterEnable = false;
//	    }
//	    gzipFilterEnable = false;
//	    if (gzipFilterEnable) {
//		    if ( acceptsGZipEncoding(httpRequest)) {
//		    	if (!httpResponse.containsHeader("Content-Encoding")
//		    		|| httpResponse.getHeader("Content-Encoding").indexOf("gzip") == -1) {
//		    		httpResponse.addHeader("Content-Encoding", "gzip");
//		    		httpResponse.setCharacterEncoding("UTF-8");
//			        GZipServletResponseWrapper gzipResponse =
//			        		new GZipServletResponseWrapper(httpResponse);
//			        filterChain.doFilter(servletRequest, gzipResponse);
//			        gzipResponse.close();
//		    	}
//		    	else {
//		    		filterChain.doFilter(servletRequest, httpResponse);
//		    	}
//		    } else {
//		    	filterChain.doFilter(servletRequest, httpResponse);
//		    }
//	    }
//	    else {
	    	filterChain.doFilter(servletRequest, httpResponse);
//	    }
	}
 
Example 8
Source File: WebAsyncUtils.java    From lams with GNU General Public License v2.0 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 9
Source File: ExceptionHandlerFilter.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
	throws IOException, ServletException {

	try {
		chain.doFilter(request, response);
	} catch (Exception e) {
		logger.info("{} 捕捉到异常", this.getClass().getName());
		Throwable rootCause = e;

		while (rootCause.getCause() != null) {
			rootCause = rootCause.getCause();
		}

		String message = rootCause.getMessage();

		message = message == null ? "异常:" + rootCause.getClass().getName() : message;

		request.setAttribute("message", message);
		request.setAttribute("e", e);

		if (rootCause instanceof AccountException) {
			request.getRequestDispatcher("/views/jsp/accountException.jsp").forward(request, response);
		} else if (rootCause instanceof BusinessException) {
			request.getRequestDispatcher("/views/jsp/businessException.jsp").forward(request, response);
		} else {
			request.getRequestDispatcher("/views/jsp/exception.jsp").forward(request, response);
		}
	}
}
 
Example 10
Source File: CommonUtils.java    From jsets-shiro-spring-boot-starter with Apache License 2.0 4 votes vote down vote up
/**
 * 设置信息
 */
public static void setAuthMessage(ServletRequest request, String message) {
	request.setAttribute(ShiroProperties.ATTRIBUTE_REQUEST_AUTH_MESSAGE, message);
}
 
Example 11
Source File: AuthFilter.java    From ms-identity-java-webapp with MIT License 4 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response,
                     FilterChain chain) throws IOException, ServletException {

    if (request instanceof HttpServletRequest) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        try {
            String currentUri = httpRequest.getRequestURL().toString();
            String path = httpRequest.getServletPath();
            String queryStr = httpRequest.getQueryString();
            String fullUrl = currentUri + (queryStr != null ? "?" + queryStr : "");

            // exclude home page
            if(excludedUrls.contains(path)){
                chain.doFilter(request, response);
                return;
            }

            if(containsAuthenticationCode(httpRequest)){
                // response should have authentication code, which will be used to acquire access token
                authHelper.processAuthenticationCodeRedirect(httpRequest, currentUri, fullUrl);

                chain.doFilter(request, response);
                return;
            }

            // check if user has a AuthData in the session
            if (!isAuthenticated(httpRequest)) {
                    // not authenticated, redirecting to login.microsoft.com so user can authenticate
                    authHelper.sendAuthRedirect(
                            httpRequest,
                            httpResponse,
                            null,
                            authHelper.getRedirectUriSignIn());
                    return;
            }

            if (isAccessTokenExpired(httpRequest)) {
                updateAuthDataUsingSilentFlow(httpRequest, httpResponse);
            }
        } catch (MsalException authException) {
            // something went wrong (like expiration or revocation of token)
            // we should invalidate AuthData stored in session and redirect to Authorization server
            SessionManagementHelper.removePrincipalFromSession(httpRequest);
            authHelper.sendAuthRedirect(
                    httpRequest,
                    httpResponse,
                    null,
                    authHelper.getRedirectUriSignIn());
            return;
        } catch (Throwable exc) {
            httpResponse.setStatus(500);
            System.out.println(exc.getMessage());
            request.setAttribute("error", exc.getMessage());
            request.getRequestDispatcher("/error").forward(request, response);
            return;
        }
    }
    chain.doFilter(request, response);
}
 
Example 12
Source File: FilterUtil.java    From two-token-sw with Apache License 2.0 4 votes vote down vote up
public static void setSessionInfoInRequestAttributeAfterLogin(
    ServletRequest request, User user, SessionInfo sessionInfo) {
  request.setAttribute(REQUEST_USER, user);
  request.setAttribute(REQUEST_SESSION_INFO, sessionInfo);
}
 
Example 13
Source File: DelegatingFilterProxyTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
		throws IOException, ServletException {

	request.setAttribute("called", Boolean.TRUE);
}
 
Example 14
Source File: ServletCategory.java    From groovy with Apache License 2.0 4 votes vote down vote up
public static void putAt(ServletRequest request, String key, Object value) {
    request.setAttribute(key, value);
}
 
Example 15
Source File: RequestContextHolderTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
	request.setAttribute(FROM_REQUEST_FILTER, FROM_REQUEST_FILTER);
	chain.doFilter(request, response);
}
 
Example 16
Source File: LogsearchKRBAuthenticationFilter.java    From ambari-logsearch with Apache License 2.0 4 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain filterChain) throws IOException, ServletException {
  HttpServletRequest httpRequest = (HttpServletRequest) request;
  if (requestMatcher.matches(httpRequest)) {
    logger.debug("LogsearchKRBAuthenticationFilter public filter path >>>>" + httpRequest.getPathInfo());
    SecurityContextImpl securityContextImpl = (SecurityContextImpl) httpRequest.getSession(true).getAttribute("SPRING_SECURITY_CONTEXT");
    Authentication existingAuth = null;
    if (securityContextImpl != null) {
      existingAuth = securityContextImpl.getAuthentication();
    }
    if (!isLoginRequest(httpRequest) && spnegoEnable
      && (existingAuth == null || !existingAuth.isAuthenticated())) {
      KerberosName.setRules(logSearchSpnegoConfig.getNameRules());
      String userName = getUsernameFromRequest(httpRequest);
      if ((existingAuth == null || !existingAuth.isAuthenticated())
        && (StringUtils.isNotEmpty(userName))) {
        // --------------------------- To Create Logsearch Session--------------------------------------
        // if we get the userName from the token then log into logsearch using the same user
        final List<GrantedAuthority> grantedAuths = new ArrayList<>();
        grantedAuths.add(new SimpleGrantedAuthority(DEFAULT_USER_ROLE));
        final UserDetails principal = new User(userName, "", grantedAuths);
        final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(
          principal, "", grantedAuths);
        WebAuthenticationDetails webDetails = new WebAuthenticationDetails(
          httpRequest);
        ((AbstractAuthenticationToken) finalAuthentication)
          .setDetails(webDetails);
        Authentication authentication = this
          .authenticate(finalAuthentication);
        authentication = getGrantedAuthority(authentication);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        request.setAttribute("spnegoEnabled", true);
        logger.info("Logged into Logsearch as = " + userName);
      } else {
        try {
          super.doFilter(request, response, filterChain);
        } catch (Exception e) {
          logger.error("Error LogsearchKRBAuthenticationFilter : " + e.getMessage());
        }
      }
    } else {
      filterChain.doFilter(request, response);
    }
  } else {
    filterChain.doFilter(request, response);
  }
}
 
Example 17
Source File: AirportServlet.java    From Project with Apache License 2.0 4 votes vote down vote up
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
    req.setAttribute("list", airportService.show());
    req.getRequestDispatcher("index.jsp").forward(req, res);
}
 
Example 18
Source File: ShallowEtagHeaderFilter.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * This method can be used to disable the content caching response wrapper
 * of the ShallowEtagHeaderFilter. This can be done before the start of HTTP
 * streaming for example where the response will be written to asynchronously
 * and not in the context of a Servlet container thread.
 * @since 4.2
 */
public static void disableContentCaching(ServletRequest request) {
	Assert.notNull(request, "ServletRequest must not be null");
	request.setAttribute(STREAMING_ATTRIBUTE, true);
}
 
Example 19
Source File: WebUtils.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * Expose the specified request attribute if not already present.
 * @param request current servlet request
 * @param name the name of the attribute
 * @param value the suggested value of the attribute
 */
private static void exposeRequestAttributeIfNotPresent(ServletRequest request, String name, Object value) {
	if (request.getAttribute(name) == null) {
		request.setAttribute(name, value);
	}
}
 
Example 20
Source File: FilterTest.java    From piranha with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * Process the filter.
 *
 * @param request the request.
 * @param response the response.
 * @param chain the chain.
 * @throws IOException when an I/O error occurs.
 * @throws ServletException when a servlet error occurs.
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    request.setAttribute("TestMultiple1Filter", "true");
    chain.doFilter(request, response);
}