Example usage for javax.servlet ServletRequest getAttribute

List of usage examples for javax.servlet ServletRequest getAttribute

Introduction

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

Prototype

public Object getAttribute(String name);

Source Link

Document

Returns the value of the named attribute as an Object, or null if no attribute of the given name exists.

Usage

From source file:org.kuali.rice.krad.web.bind.UifServletRequestDataBinder.java

/**
 * Calls {@link org.kuali.rice.krad.web.form.UifFormBase#preBind(HttpServletRequest)}, Performs data binding
 * from servlet request parameters to the form, initializes view object, then calls
 * {@link org.kuali.rice.krad.web.form.UifFormBase#postBind(javax.servlet.http.HttpServletRequest)}
 *
 * <p>/*from w  w  w  .j  a va2s.  c o  m*/
 * The view is initialized by first looking for the {@code viewId} parameter in the request. If found, the view is
 * retrieved based on this id. If the id is not present, then an attempt is made to find a view by type. In order
 * to retrieve a view based on type, the view request parameter {@code viewTypeName} must be present. If all else
 * fails and the viewId is populated on the form (could be populated from a previous request), this is used to
 * retrieve the view.
 * </p>
 *
 * @param request - HTTP Servlet Request instance
 */
@Override
public void bind(ServletRequest request) {
    UifFormBase form = (UifFormBase) UifServletRequestDataBinder.this.getTarget();

    request.setAttribute(UifConstants.REQUEST_FORM, form);

    form.preBind((HttpServletRequest) request);

    _bind(request);

    request.setAttribute(UifConstants.PROPERTY_EDITOR_REGISTRY, this.bindingResult.getPropertyEditorRegistry());

    executeAutomaticLinking(request, form);

    if (!form.isUpdateNoneRequest()) {
        // attempt to retrieve a view by unique identifier first, either as request attribute or parameter
        String viewId = (String) request.getAttribute(UifParameters.VIEW_ID);
        if (StringUtils.isBlank(viewId)) {
            viewId = request.getParameter(UifParameters.VIEW_ID);
        }

        View view = null;
        if (StringUtils.isNotBlank(viewId)) {
            view = getViewService().getViewById(viewId);
        }

        // attempt to get view instance by type parameters
        if (view == null) {
            view = getViewByType(request, form);
        }

        // if view not found attempt to find one based on the cached form
        if (view == null) {
            view = getViewFromPreviousModel(form);

            if (view != null) {
                LOG.warn("Obtained viewId from cached form, this may not be safe!");
            }
        }

        if (view != null) {
            form.setViewId(view.getId());

        } else {
            form.setViewId(null);
        }

        form.setView(view);
    }

    // invoke form callback for custom binding
    form.postBind((HttpServletRequest) request);
}

From source file:org.aludratest.cloud.selenium.impl.SeleniumHttpProxy.java

@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
    if (LOG.isTraceEnabled()) {
        // give a random ID for this request
        String id = Integer.toHexString((int) (Math.random() * Integer.MAX_VALUE));
        while (id.length() < 8) {
            id = "0" + id;
        }//from  w  w  w . ja va 2s  .c  o  m
        LOG.trace("service() enter for " + resource + ", unique request code " + id);
        req.setAttribute("selenium.requestId", id);
    }

    // wait for update proxy if in progress
    synchronized (SeleniumHttpProxy.class) {
    }

    super.service(req, res);

    if (Boolean.TRUE.equals(req.getAttribute("selenium.connectFailed"))) {
        ((HttpServletResponse) res).sendError(HttpServletResponse.SC_GATEWAY_TIMEOUT);
    }
}

From source file:org.codice.ddf.security.filter.login.LoginFilter.java

/**
 * Validates an attached SAML assertion, or exchanges any other incoming
 * token for a SAML assertion via the STS.
 *
 * @param request//from w w w. j a v  a 2 s  . c o m
 * @param response
 * @param chain
 * @throws IOException
 * @throws ServletException
 */
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    LOGGER.debug("Performing doFilter() on LoginFilter");
    HttpServletRequest httpRequest = (HttpServletRequest) request;

    String path = StringUtils.isNotBlank(httpRequest.getContextPath()) ? httpRequest.getContextPath()
            : httpRequest.getServletPath() + StringUtils.defaultString(httpRequest.getPathInfo());

    if (request.getAttribute(ContextPolicy.NO_AUTH_POLICY) != null) {
        LOGGER.debug("NO_AUTH_POLICY header was found, skipping login filter.");
        chain.doFilter(request, response);
    } else {
        // perform validation
        final Subject subject = validateRequest(httpRequest);
        if (subject != null) {
            httpRequest.setAttribute(SecurityConstants.SECURITY_SUBJECT, subject);
            LOGGER.debug("Now performing request as user {} for {}", subject.getPrincipal(),
                    StringUtils.isNotBlank(httpRequest.getContextPath()) ? httpRequest.getContextPath()
                            : httpRequest.getServletPath());
            SecurityLogger.audit("Executing request {} on {} as user.", subject, httpRequest.getMethod(), path);
            subject.execute(() -> {
                PrivilegedExceptionAction<Void> action = () -> {
                    chain.doFilter(request, response);
                    return null;
                };
                SecurityAssertion securityAssertion = subject.getPrincipals()
                        .oneByType(SecurityAssertion.class);
                if (null != securityAssertion) {
                    HashSet emptySet = new HashSet();
                    javax.security.auth.Subject javaSubject = new javax.security.auth.Subject(true,
                            securityAssertion.getPrincipals(), emptySet, emptySet);
                    javax.security.auth.Subject.doAs(javaSubject, action);
                } else {
                    LOGGER.debug("Subject had no security assertion.");
                }
                return null;
            });

        } else {
            LOGGER.debug("Could not attach subject to http request.");
        }
    }

}

From source file:org.unitime.timetable.filter.QueryLogFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws ServletException, IOException {

    String sessionId = null;/*from  w  w w .  ja v  a 2s  . c  om*/
    String userId = null;
    try {
        if (request instanceof HttpServletRequest) {
            HttpServletRequest r = (HttpServletRequest) request;
            sessionId = r.getSession().getId();
            UserContext user = getUser();
            if (user != null)
                userId = user.getTrueExternalUserId();
        }
    } catch (IllegalStateException e) {
    }

    long t0 = JProf.currentTimeMillis();
    Throwable exception = null;
    try {
        chain.doFilter(request, response);
    } catch (Throwable t) {
        exception = t;
    }
    long t1 = JProf.currentTimeMillis();

    if (exception == null) {
        Object ex = request.getAttribute("__exception");
        if (ex != null && ex instanceof Throwable)
            exception = (Throwable) ex;
    }

    if (request instanceof HttpServletRequest) {
        HttpServletRequest r = (HttpServletRequest) request;
        QueryLog q = new QueryLog();
        String uri = r.getRequestURI();
        if (uri.indexOf('/') >= 0)
            uri = uri.substring(uri.lastIndexOf('/') + 1);
        if (uri.endsWith(".do"))
            q.setType(QueryLog.Type.STRUCTS.ordinal());
        else if (uri.endsWith(".gwt"))
            q.setType(QueryLog.Type.GWT.ordinal());
        else
            q.setType(QueryLog.Type.OTHER.ordinal());
        q.setUri(uri);
        q.setTimeStamp(new Date());
        q.setTimeSpent(t1 - t0);
        q.setSessionId(sessionId);
        q.setUid(userId);
        try {
            if (sessionId == null)
                q.setSessionId(r.getSession().getId());
            if (userId == null) {
                UserContext user = getUser();
                if (user != null)
                    q.setUid(user.getTrueExternalUserId());
            }
        } catch (IllegalStateException e) {
        }
        GwtCallInfo callInfo = GwtDispatcherServlet.getLastQuery();
        if (callInfo != null) {
            q.setQuery(callInfo.getQuery());
            q.setUri(q.getUri() + ": " + callInfo.getTarget());
        } else if (ApplicationProperty.QueryLogJSON.isTrue()) {
            try {
                Map<String, Object> params = new HashMap<String, Object>();
                for (Map.Entry<String, String[]> e : r.getParameterMap().entrySet()) {
                    if ("password".equals(e.getKey()) || "noCacheTS".equals(e.getKey()))
                        continue;
                    if (e.getValue() == null || e.getValue().length == 0)
                        continue;
                    if (e.getValue().length == 1)
                        params.put(e.getKey(), e.getValue()[0]);
                    else
                        params.put(e.getKey(), e.getValue());
                }
                q.setQuery(iGson.toJson(params));
            } catch (Throwable t) {
            }
        } else {
            String params = "";
            for (Enumeration e = r.getParameterNames(); e.hasMoreElements();) {
                String n = (String) e.nextElement();
                if ("password".equals(n) || "noCacheTS".equals(n))
                    continue;
                if (!params.isEmpty())
                    params += "&";
                params += n + "=" + r.getParameter(n);
            }
            if (!params.isEmpty())
                q.setQuery(params);
        }
        if (exception != null) {
            Throwable t = exception;
            String ex = "";
            while (t != null) {
                String clazz = t.getClass().getName();
                if (clazz.indexOf('.') >= 0)
                    clazz = clazz.substring(1 + clazz.lastIndexOf('.'));
                if (!ex.isEmpty())
                    ex += "\n";
                ex += clazz + ": " + t.getMessage();
                if (t.getStackTrace() != null && t.getStackTrace().length > 0)
                    ex += " (at " + t.getStackTrace()[0].getFileName() + ":"
                            + t.getStackTrace()[0].getLineNumber() + ")";
                t = t.getCause();
            }
            if (!ex.isEmpty())
                q.setException(ex);
        }
        if (!iExclude.contains(q.getUri()) || q.getException() != null) {
            if (iSaver != null)
                iSaver.add(q);
        }
    }

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

From source file:org.apache.solr.security.GenericHadoopAuthPlugin.java

@Override
public boolean doAuthenticate(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws Exception {
    final HttpServletResponse frsp = (HttpServletResponse) response;

    // Workaround until HADOOP-13346 is fixed.
    HttpServletResponse rspCloseShield = new HttpServletResponseWrapper(frsp) {
        @SuppressForbidden(reason = "Hadoop DelegationTokenAuthenticationFilter uses response writer, this"
                + "is providing a CloseShield on top of that")
        @Override//  w w w .j a  v  a 2 s  . c om
        public PrintWriter getWriter() throws IOException {
            final PrintWriter pw = new PrintWriterWrapper(frsp.getWriter()) {
                @Override
                public void close() {
                };
            };
            return pw;
        }
    };
    authFilter.doFilter(request, rspCloseShield, filterChain);

    if (authFilter instanceof HadoopAuthFilter) { // delegation token mgmt.
        String requestContinuesAttr = (String) request.getAttribute(REQUEST_CONTINUES_ATTR);
        if (requestContinuesAttr == null) {
            log.warn("Could not find " + REQUEST_CONTINUES_ATTR);
            return false;
        } else {
            return Boolean.parseBoolean(requestContinuesAttr);
        }
    }

    return true;
}

From source file:org.ajax4jsf.webapp.BaseFilter.java

/**
 * Execute the filter.//  w  w w.  j  av  a2 s  .  c  o m
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    long startTimeMills = 0;
    // Detect case of request - normal, AJAX, AJAX - JavaScript
    // TODO - detect first processing in filter.
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;
    if (log.isDebugEnabled()) {
        startTimeMills = System.currentTimeMillis();
        log.debug(Messages.getMessage(Messages.FILTER_START_INFO, new Date(startTimeMills),
                httpServletRequest.getRequestURI()));
    }

    if (request.getAttribute(FILTER_PERFORMED) != Boolean.TRUE) {
        // mark - and not processing same request twice.
        try {
            request.setAttribute(FILTER_PERFORMED, Boolean.TRUE);
            String ajaxPushHeader = httpServletRequest.getHeader(AJAX_PUSH_KEY_HEADER);
            // check for a push check request.
            if (httpServletRequest.getMethod().equals("HEAD") && null != ajaxPushHeader) {
                PushEventsCounter listener = eventsManager.getListener(ajaxPushHeader);
                // To avoid XmlHttpRequest parsing exceptions.
                httpServletResponse.setContentType("text/plain");
                if (listener.isPerformed()) {
                    listener.processed();
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                    httpServletResponse.setHeader(AJAX_PUSH_STATUS_HEADER, AJAX_PUSH_READY);
                    if (log.isDebugEnabled()) {
                        log.debug("Occurs event for a id " + ajaxPushHeader);
                    }
                } else {
                    // Response code - 'No content'
                    httpServletResponse.setStatus(HttpServletResponse.SC_ACCEPTED);
                    if (log.isDebugEnabled()) {
                        log.debug("No event for a id " + ajaxPushHeader);
                    }
                }
                httpServletResponse.setContentLength(0);
            } else
            // check for resource request
            if (!getResourceService().serviceResource(httpServletRequest, httpServletResponse)) {
                // Not request to resource - perform filtering.
                // first stage - detect/set encoding of request. Same as in
                // Myfaces External Context.
                setupRequestEncoding(httpServletRequest);

                processUploadsAndHandleRequest(httpServletRequest, httpServletResponse, chain);
            }
        } finally {
            // Remove filter marker from response, to enable sequence calls ( for example, forward to error page )
            request.removeAttribute(FILTER_PERFORMED);
            Object ajaxContext = request.getAttribute(AjaxContext.AJAX_CONTEXT_KEY);
            if (null != ajaxContext && ajaxContext instanceof AjaxContext) {
                ((AjaxContext) ajaxContext).release();
                request.removeAttribute(AjaxContext.AJAX_CONTEXT_KEY);
            }
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug(Messages.getMessage(Messages.FILTER_NO_XML_CHAIN_2));
        }
        chain.doFilter(request, response);

    }
    if (log.isDebugEnabled()) {
        startTimeMills = System.currentTimeMillis() - startTimeMills;
        log.debug(Messages.getMessage(Messages.FILTER_STOP_INFO, "" + startTimeMills,
                httpServletRequest.getRequestURI()));
    }
}

From source file:com.hp.autonomy.frontend.find.hod.web.SsoController.java

@RequestMapping(value = SSO_PAGE, method = RequestMethod.GET)
public ModelAndView sso(final ServletRequest request) throws JsonProcessingException, HodErrorException {
    final Map<String, Object> ssoConfig = new HashMap<>();
    ssoConfig.put(SsoMvcConstants.AUTHENTICATE_PATH.value(), SSO_AUTHENTICATION_URI);
    ssoConfig.put(SsoMvcConstants.COMBINED_REQUEST_API.value(), HodCombinedRequestController.COMBINED_REQUEST);
    ssoConfig.put(SsoMvcConstants.ERROR_PAGE.value(),
            DispatcherServletConfiguration.CLIENT_AUTHENTICATION_ERROR_PATH);
    ssoConfig.put(SsoMvcConstants.LIST_APPLICATION_REQUEST.value(),
            hodAuthenticationRequestService.getListApplicationRequest());
    ssoConfig.put(SsoMvcConstants.LIST_APPLICATION_REQUEST_API.value(),
            HodCombinedRequestController.LIST_APPLICATION_REQUEST);
    ssoConfig.put(SsoMvcConstants.SSO_PAGE.value(), ssoPage);
    ssoConfig.put(SsoMvcConstants.SSO_ENTRY_PAGE.value(), SSO_PAGE);

    final Map<String, Object> attributes = new HashMap<>();
    attributes.put(MvcConstants.GIT_COMMIT.value(), gitCommit);
    attributes.put(MvcConstants.CONFIG.value(), controllerUtils.convertToJson(ssoConfig));
    attributes.put(ControllerUtils.SPRING_CSRF_ATTRIBUTE,
            request.getAttribute(ControllerUtils.SPRING_CSRF_ATTRIBUTE));

    return new ModelAndView(ViewNames.SSO.viewName(), attributes);
}

From source file:org.apache.solr.security.KerberosPlugin.java

@Override
public boolean doAuthenticate(ServletRequest req, ServletResponse rsp, FilterChain chain) throws Exception {
    log.debug("Request to authenticate using kerberos: " + req);

    final HttpServletResponse frsp = (HttpServletResponse) rsp;

    // kerberosFilter may close the stream and write to closed streams,
    // see HADOOP-13346.  To work around, pass a PrintWriter that ignores
    // closes/*from  w w w.j ava  2 s. c om*/
    HttpServletResponse rspCloseShield = new HttpServletResponseWrapper(frsp) {
        @SuppressForbidden(reason = "Hadoop DelegationTokenAuthenticationFilter uses response writer, this"
                + "is providing a CloseShield on top of that")
        @Override
        public PrintWriter getWriter() throws IOException {
            final PrintWriter pw = new PrintWriterWrapper(frsp.getWriter()) {
                @Override
                public void close() {
                };
            };
            return pw;
        }
    };
    kerberosFilter.doFilter(req, rspCloseShield, chain);
    String requestContinuesAttr = (String) req
            .getAttribute(RequestContinuesRecorderAuthenticationHandler.REQUEST_CONTINUES_ATTR);
    if (requestContinuesAttr == null) {
        log.warn("Could not find " + RequestContinuesRecorderAuthenticationHandler.REQUEST_CONTINUES_ATTR);
        return false;
    } else {
        return Boolean.parseBoolean(requestContinuesAttr);
    }
}

From source file:io.starter.datamodel.ContentData.java

/**
 * do the work of deleting all existing acls for content, inserting a new
 * owner acl, and optionally inserting necessary new ACL(s) based on the
 * OP_TYPE//from  w w  w  .ja  v a  2 s . co m
 * 
 * @param optype
 * @param servletRequest
 * @param id
 * @return
 * @throws ServletException
 */
private String resetAclsForContent(int optype, ServletRequest servletRequest, Integer id)
        throws ServletException {
    // DELETE all ACLs except the User's OWNER ACL
    Object u = servletRequest.getAttribute(SESSION_VAR_USER);

    if (u == null)
        throw new ServletException("No User in Request -- Anonymous users cannot modify content permissions.");

    User user = (User) u;
    int uid = user.getId();

    user.clearCachedAuthorizationForAllUsers();

    SqlSession session = (SqlSession) servletRequest.getAttribute(SESSION_VAR_SQLSESSION);
    int rowsDeleted = 0;

    // delete content acls
    AclExample ax = new AclExample();
    Criteria c = ax.createCriteria();
    c.andTargetIdEqualTo(id);
    c.andTargetTypeEqualTo(SECURITY_TARGET_TYPE_CONTENT);
    session.delete("io.starter.dao.AclMapper.deleteByExample", ax);
    session.commit();

    Acl a = new Acl();
    // give permission to current session user -- only one allowed to do
    // this
    a.setPrincipleId(user.getId());
    a.setPrincipleType(SECURITY_PRINCIPAL_TYPE_USER);

    // allow them to
    a.setPermission(SECURITY_ACL_OWNER);

    // to this thing
    a.setTargetId(id);
    a.setTargetType(SECURITY_TARGET_TYPE_CONTENT);

    int rowsInserted = session.insert("io.starter.dao.AclMapper.insert", a);

    if (rowsInserted < 1)
        throw new ServletException("Could not make Content object private: setting Owner ACL failed.");

    if (optype == OPTYPE_SET_PUBLIC) { // make public

        Acl ae = new Acl();
        // give permission to current session user -- only one allowed
        // to do
        // this
        ae.setPrincipleId(SECURITY_ROLE_EVERYONE);
        ae.setPrincipleType(SECURITY_PRINCIPAL_TYPE_ROLE);

        // allow them to
        ae.setPermission(SystemConstants.SECURITY_ACL_APPEND); // required
        // to allow
        // comments/rating

        // to this thing
        ae.setTargetId(id);
        ae.setTargetType(SECURITY_TARGET_TYPE_CONTENT);

        rowsInserted = session.insert("io.starter.dao.AclMapper.insert", ae);
        session.commit();

        ae = new Acl();
        ae.setPrincipleId(SECURITY_ROLE_EVERYONE);
        ae.setPrincipleType(SECURITY_PRINCIPAL_TYPE_ROLE);

        // allow them to
        ae.setPermission(SystemConstants.SECURITY_ACL_READ); // need to see

        // to this thing
        ae.setTargetId(id);
        ae.setTargetType(SECURITY_TARGET_TYPE_CONTENT);

        rowsInserted += session.insert("io.starter.dao.AclMapper.insert", ae);
        session.commit();
        if (rowsInserted < 2)
            throw new ServletException(
                    "Could not make Content object private: setting Everyone READ-ONLY and APPEND ACLs failed.");

    } else if (optype == OPTYPE_SET_TAKEOVER_OWNERSHIP) { // take over
        // ownership
        // (administrators)
        if (!user.isAdmin())
            throw new ServletException(
                    "Could not take over Content object ownership: Only Administrators can do this.");

        Acl ax1 = new Acl();
        // give permission to current session user -- only one allowed
        // to do
        // this
        ax1.setPrincipleId(1);
        ax1.setPrincipleType(SECURITY_PRINCIPAL_TYPE_USER);

        // allow them to
        ax1.setPermission(SECURITY_ACL_OWNER);

        // to this thing
        ax1.setTargetId(id);
        ax1.setTargetType(SECURITY_TARGET_TYPE_CONTENT);

        rowsInserted = session.insert("io.starter.dao.AclMapper.insert", ax1);

        if (rowsInserted < 1)
            throw new ServletException(
                    "Could not take over Content object ownership: setting Owner ACL failed.");

    }
    session.commit();

    // return the result
    return "true";
}

From source file:gov.nih.nci.cabig.caaers.web.security.FabricatedAuthenticationFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest)) {
        throw new ServletException("Can only process HttpServletRequest");
    }/*from  ww  w. j a v  a2 s . co  m*/
    if (!(response instanceof HttpServletResponse)) {
        throw new ServletException("Can only process HttpServletResponse");
    }

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    HttpSession httpSession = httpRequest.getSession();
    final SecurityContext contextBeforeExec = SecurityContextHolder.getContext();
    Authentication authBeforeExec = contextBeforeExec.getAuthentication();

    OriginalAuthenticationHolder.setAuthentication(authBeforeExec);

    try {
        if (request.getAttribute(FILTER_APPLIED) == null) {
            doProcessing(httpRequest, httpResponse, chain);
            request.setAttribute(FILTER_APPLIED, true);
        }

        Authentication fabricatedAuth = SecurityContextHolder.getContext().getAuthentication();
        if (fabricatedAuth != null) {
            GrantedAuthority[] fabAuthorities = fabricatedAuth.getAuthorities();
            if (fabAuthorities == null || fabAuthorities.length < 1) {
                throw new AccessDeniedException(
                        "Your account permissions do not provide you access to this page.");
            }
        }

        prepareRolesCollections(httpRequest);
        chain.doFilter(httpRequest, httpResponse);
    } finally {
        request.removeAttribute(FILTER_APPLIED);
        SecurityContextHolder.setContext(contextBeforeExec);
        SecurityContextHolder.getContext().setAuthentication(authBeforeExec);
        if (httpSession != null) {
            httpSession.setAttribute(HttpSessionContextIntegrationFilter.ACEGI_SECURITY_CONTEXT_KEY,
                    SecurityContextHolder.getContext());
        }
        OriginalAuthenticationHolder.setAuthentication(null);
        CurrentEntityHolder.setEntity(null);
    }
    return;
}