Example usage for javax.servlet ServletRequest setAttribute

List of usage examples for javax.servlet ServletRequest setAttribute

Introduction

In this page you can find the example usage for javax.servlet ServletRequest setAttribute.

Prototype

public void setAttribute(String name, Object o);

Source Link

Document

Stores an attribute in this request.

Usage

From source file:com.iflytek.edu.cloud.frame.web.filter.CheckOpenServiceFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    MainError mainError = null;/*from   www  .ja v a 2  s .  co  m*/
    Locale locale = getLocale(request);

    String format = request.getParameter(Constants.SYS_PARAM_KEY_FORMAT);
    if (!StringUtils.hasText(format)) {
        format = Constants.DATA_FORMAT_XML;
    }

    request.setAttribute(Constants.SYS_PARAM_KEY_LOCALE, locale);
    request.setAttribute(Constants.SYS_PARAM_KEY_FORMAT, format);

    String appkey = request.getParameter(Constants.SYS_PARAM_KEY_APPKEY);
    if (!StringUtils.hasText(appkey)) {
        mainError = MainErrors.getError(MainErrorType.MISSING_APPKEY, locale);
    } else {
        RestContextHolder.getContext().addParam(Constants.SYS_PARAM_KEY_APPKEY, appkey);
    }

    //??GET, POST
    if (mainError == null) {
        String httpMethod = httpServletRequest.getMethod();
        if (!Constants.HTTP_METHOD_GET.equals(httpMethod) && !Constants.HTTP_METHOD_POST.equals(httpMethod)) {
            mainError = MainErrors.getError(MainErrorType.HTTP_ACTION_NOT_ALLOWED, locale);
        }
    }

    //service method?version?
    if (mainError == null) {
        String method = request.getParameter(Constants.SYS_PARAM_KEY_METHOD);
        if (!StringUtils.hasText(method)) {
            //method?
            mainError = MainErrors.getError(MainErrorType.MISSING_METHOD, locale);
        } else {
            if (methodVersionMap.containsKey(method)) {
                String version = request.getParameter(Constants.SYS_PARAM_KEY_VERSION);

                if (!StringUtils.hasText(version)) {
                    //?
                    mainError = MainErrors.getError(MainErrorType.MISSING_VERSION, locale);
                } else {
                    if (!methodVersionMap.get(method).contains(version)) {
                        //??
                        mainError = MainErrors.getError(MainErrorType.UNSUPPORTED_VERSION, locale);
                    }
                }
            } else {
                //method?
                mainError = MainErrors.getError(MainErrorType.INVALID_METHOD, locale);
            }
        }
    }

    //access_token?
    if (mainError == null) {
        if (EnvUtil.oauthEnabled()) {
            String accessToken = request.getParameter(Constants.SYS_PARAM_KEY_ACCESS_TOKEN);
            if (!checkHeaderToken(httpServletRequest) && !StringUtils.hasText(accessToken)) {
                mainError = MainErrors.getError(MainErrorType.MISSING_ACCESS_TOKEN, locale);
            }
        }
    }

    //jsonp
    String callback = httpServletRequest.getParameter(Constants.SYS_PARAM_KEY_CALLBACK);
    if (StringUtils.hasText(callback))
        RestContextHolder.getContext().addParam(Constants.SYS_PARAM_KEY_CALLBACK, callback);

    if (mainError != null) {
        request.setAttribute(Constants.MAIN_ERROR_CODE, mainError.getCode());
        httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        messageConverter.convertData(httpServletRequest, httpServletResponse, mainError);
    } else {
        chain.doFilter(request, response);
    }

    requestLogging.recoredLog(httpServletRequest, httpServletResponse);
    RestContextHolder.clearContext();
}

From source file:org.xwiki.container.servlet.filters.internal.SavedRequestRestorerFilter.java

/**
 * {@inheritDoc}/* w w  w . j a v a 2s  . c  om*/
 * 
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse,
 *      javax.servlet.FilterChain)
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    ServletRequest filteredRequest = request;
    // This filter works only for HTTP requests, because they are the only ones with a session.
    if (request instanceof HttpServletRequest
            && !Boolean.valueOf((String) request.getAttribute(ATTRIBUTE_APPLIED))) {
        // Get the saved request, if any (returns null if not applicable)
        SavedRequest savedRequest = getSavedRequest((HttpServletRequest) request);
        // Merge the new and the saved request
        filteredRequest = new SavedRequestWrapper((HttpServletRequest) request, savedRequest);
        filteredRequest.setAttribute(ATTRIBUTE_APPLIED, "true");
    }
    // Forward the request
    chain.doFilter(filteredRequest, response);
    // Allow multiple calls to this filter as long as they are not nested.
    filteredRequest.removeAttribute(ATTRIBUTE_APPLIED);
}

From source file:de.highbyte_le.weberknecht.security.filters.LoginPageForwardFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (logger.isDebugEnabled())
        logger.debug("doFilter() - start");

    boolean forward = true;

    if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) {
        logger.error("servlet request is no HTTP servlet request");
    } else {//from  w w w. j  ava  2s . c o m
        HttpSession session = ((HttpServletRequest) request).getSession();

        UserAuthentication userAuthentication = (UserAuthentication) session.getAttribute("user_auth");
        if (userAuthentication != null && userAuthentication.isAuthenticated())
            forward = false;
    }

    if (forward) {
        request.setAttribute("de.highbyte_le.weberknecht.login.status", "failed");

        logger.debug("doFilter() - forward to login page");
        RequestDispatcher rd = request.getRequestDispatcher(loginPage);
        rd.forward(request, response);
    } else {
        logger.debug("doFilter() - Continue with filter chain");
        chain.doFilter(request, response);
    }
}

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;//www.  j a va 2 s  . co  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.xwiki.portlet.controller.DispatchFilter.java

/**
 * {@inheritDoc}//from  w w  w . j  a v a2  s  . c  o m
 * 
 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (request instanceof HttpServletRequest
            && !Boolean.valueOf((String) request.getAttribute(ATTRIBUTE_APPLIED))) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        RequestType requestType = (RequestType) request.getAttribute(DispatchPortlet.ATTRIBUTE_REQUEST_TYPE);
        if (requestType != null) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            // Prevent nested calls to this filter.
            request.setAttribute(ATTRIBUTE_APPLIED, "true");
            switch (requestType) {
            case ACTION:
                doAction(httpRequest, httpResponse, chain);
                break;
            case RENDER:
                doRender(httpRequest, httpResponse, chain);
                break;
            case RESOURCE:
                doResource(httpRequest, httpResponse, chain);
                break;
            default:
                // We should never get here.
                break;
            }
            // Allow multiple calls to this filter, as long as they are not nested. We need this because we
            // transform redirects into dispatches and thus a request can be dispatched multiple times, but these
            // dispatches shouldn't be nested.
            request.removeAttribute(ATTRIBUTE_APPLIED);
            return;
        }
    }
    chain.doFilter(request, response);
}

From source file:no.sesat.search.http.filters.SiteLocatorFilter.java

private void doBeforeProcessing(final ServletRequest request, final ServletResponse response)
        throws IOException, ServletException {

    LOG.trace("doBeforeProcessing()");

    final Site site = getSite(request);

    if (null != site) {

        request.setAttribute(Site.NAME_KEY, site);
        request.setAttribute("startTime", FindResource.START_TIME);
        MDC.put(Site.NAME_KEY, site.getName());
        MDC.put("UNIQUE_ID", getRequestId(request));

        /* Setting default encoding */
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

    } else {//from ww w .j a va2s  .  c om
        throw new ServletException("SiteLocatorFilter with no Site :-(");
    }
}

From source file:org.codehaus.groovy.grails.web.servlet.DefaultGrailsApplicationAttributes.java

public FlashScope getFlashScope(ServletRequest request) {
    if (!(request instanceof HttpServletRequest)) {
        return null;
    }//from w w w.  j a  v  a2s.  co  m

    HttpServletRequest servletRequest = (HttpServletRequest) request;
    HttpSession session = servletRequest.getSession(false);
    FlashScope fs;
    if (session != null) {
        fs = (FlashScope) session.getAttribute(FLASH_SCOPE);
    } else {
        fs = (FlashScope) request.getAttribute(FLASH_SCOPE);
    }
    if (fs == null) {
        fs = new GrailsFlashScope();
        if (session != null) {
            session.setAttribute(FLASH_SCOPE, fs);
        } else {
            request.setAttribute(FLASH_SCOPE, fs);
        }
    }
    return fs;
}

From source file:org.sonar.plugins.openid.OpenIdValidationFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    ParameterList responseParameters = new ParameterList(request.getParameterMap());
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    String receivingURL = requestUrl(httpRequest);
    UserDetails user;//  w w w.  ja v  a  2 s  .  c  o m
    try {
        user = openIdClient.verify(receivingURL, responseParameters);
    } catch (RuntimeException e) {
        LoggerFactory.getLogger(OpenIdValidationFilter.class).error("Fail to verify OpenId request", e);
        throw e;
    }
    if (user == null) {
        httpResponse.sendRedirect("/openid/unauthorized");
    } else {
        request.setAttribute(USER_ATTRIBUTE, user);
        filterChain.doFilter(request, response);
    }
}

From source file:com.opensymphony.able.filter.TransactionServletFilter.java

public void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain filterChain) throws IOException, ServletException {
    // TODO we could get clever and figure out what URIs are read only transactions etc
    TransactionTemplate transactionTemplate = (TransactionTemplate) context.getBean("transactionTemplate");
    transactionTemplate.setReadOnly(false);

    if (log.isDebugEnabled()) {
        log.debug("Starting a transaction");
    }//from   w w w.j  a  va 2s. c o  m

    PlatformTransactionManager transactionManager = transactionTemplate.getTransactionManager();
    TransactionStatus status = transactionManager.getTransaction(transactionTemplate);
    TransactionOutcome outcome = new TransactionOutcome(status, transactionTemplate);
    request.setAttribute(TRANSACTION_OUTCOME, outcome);

    Exception exception = null;
    try {
        filterChain.doFilter(request, response);
        status = transactionManager.getTransaction(transactionTemplate);
    } catch (Exception e) {
        exception = e;
        log.warn("Caught: " + e, e);
    }

    if (outcome.isRollbackOnly() || exception != null) {
        status.setRollbackOnly();
    }

    try {
        if (status.isRollbackOnly()) {
            log.debug("Rolling back transaction");
            transactionManager.rollback(status);
        } else {
            log.debug("Committing transaction");
            transactionManager.commit(status);
        }
    } catch (TransactionException e) {
        if (exception == null) {
            exception = e;
        } else {
            log.debug("Failed to rollback transaction: " + e, e);
        }
    }

    if (exception instanceof IOException) {
        throw (IOException) exception;
    } else if (exception instanceof ServletException) {
        throw (ServletException) exception;
    } else if (exception != null) {
        throw new ServletException(exception);
    }
}

From source file:au.org.paperminer.main.UserFilter.java

/**
 * Set values and update persistent user store. If the email has changed, reset status
 * and issue verification email if requested.
 * @param id User ID/*www.  j  av a  2s . c  o m*/
 * @param req
 * @param resp
 */
private void resetUserData(String id, ServletRequest req, ServletResponse resp) {
    UserHelper helper = new UserHelper(id);

    if (helper.isKnownUser()) {
        String email = req.getParameter("em");
        String troveKey = req.getParameter("tk");
        String verify = req.getParameter("vfy");
        m_logger.debug(email + "," + troveKey + "," + verify);
        if (!isValidEmailAddress(email)) {
            req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e101");
        } else if (!isValidTroveKey(troveKey)) {
            req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e102");
        } else {
            boolean emailChanged = !email.equals(helper.get(UserHelper.EMAIL));
            if (email.equals(helper.get(UserHelper.EMAIL))
                    && troveKey.equals(helper.get(UserHelper.TROVE_KEY))) {
                m_logger.debug("update ignored, no change: " + email + "," + troveKey + "," + verify);
            } else {
                String status = emailChanged ? Integer.toString(PaperMinerConstants.USER_CREATED)
                        : helper.get(UserHelper.STATUS);
                helper.set(UserHelper.EMAIL, email);
                helper.set(UserHelper.STATUS, status);
                helper.set(UserHelper.TROVE_KEY, troveKey);
                m_logger.debug("Updating user " + id + " to " + email + "/" + troveKey + " status " + status);
                try {
                    helper.update();
                } catch (PaperMinerException ex) {
                    m_logger.error("error updating user", ex);
                    req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e108");
                }
            }
            //if ((emailChanged || helper.get(UserHelper.STATUS).equals(PaperMinerConstants.USER_CREATED)) && (verify != null) && verify.equals('y')) {
            if ((verify != null) && verify.equals("y")) {
                sendVerificationEmail(id, email, req);
            }
        }
    }
}