Example usage for org.springframework.util Assert isInstanceOf

List of usage examples for org.springframework.util Assert isInstanceOf

Introduction

In this page you can find the example usage for org.springframework.util Assert isInstanceOf.

Prototype

public static void isInstanceOf(Class<?> type, @Nullable Object obj, Supplier<String> messageSupplier) 

Source Link

Document

Assert that the provided object is an instance of the provided class.

Usage

From source file:org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.java

public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
            () -> messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports",
                    "Only UsernamePasswordAuthenticationToken is supported"));

    // Determine username
    String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" : authentication.getName();

    boolean cacheWasUsed = true;
    UserDetails user = this.userCache.getUserFromCache(username);

    if (user == null) {
        cacheWasUsed = false;/*w  ww .jav  a2  s. c om*/

        try {
            user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication);
        } catch (UsernameNotFoundException notFound) {
            logger.debug("User '" + username + "' not found");

            if (hideUserNotFoundExceptions) {
                throw new BadCredentialsException(messages.getMessage(
                        "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
            } else {
                throw notFound;
            }
        }

        Assert.notNull(user, "retrieveUser returned null - a violation of the interface contract");
    }

    try {
        preAuthenticationChecks.check(user);
        additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken) authentication);
    } catch (AuthenticationException exception) {
        if (cacheWasUsed) {
            // There was a problem, so try again after checking
            // we're using latest data (i.e. not from the cache)
            cacheWasUsed = false;
            user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication);
            preAuthenticationChecks.check(user);
            additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken) authentication);
        } else {
            throw exception;
        }
    }

    postAuthenticationChecks.check(user);

    if (!cacheWasUsed) {
        this.userCache.putUserInCache(user);
    }

    Object principalToReturn = user;

    if (forcePrincipalAsString) {
        principalToReturn = user.getUsername();
    }

    return createSuccessAuthentication(principalToReturn, authentication, user);
}

From source file:org.springframework.security.extensions.portlet.PortletSessionContextIntegrationInterceptor.java

private boolean preHandle(PortletRequest request, PortletResponse response, Object handler) throws Exception {

    PortletSession portletSession = null;
    boolean portletSessionExistedAtStartOfRequest = false;

    // see if the portlet session already exists (or should be eagerly created)
    try {//w  ww . j av  a2  s.  c o m
        portletSession = request.getPortletSession(forceEagerSessionCreation);
    } catch (IllegalStateException ignored) {
    }

    // if there is a session, then see if there is a contextClass to bring in
    if (portletSession != null) {

        // remember that the session already existed
        portletSessionExistedAtStartOfRequest = true;

        // attempt to retrieve the contextClass from the session
        Object contextFromSessionObject = portletSession.getAttribute(SPRING_SECURITY_CONTEXT_KEY,
                portletSessionScope());

        // if we got a contextClass then place it into the holder
        if (contextFromSessionObject != null) {

            // if we are supposed to clone it, then do so
            if (cloneFromPortletSession) {
                Assert.isInstanceOf(Cloneable.class, contextFromSessionObject,
                        "Context must implement Clonable and provide a Object.clone() method");
                try {
                    Method m = contextFromSessionObject.getClass().getMethod("clone", new Class[] {});
                    if (!m.isAccessible()) {
                        m.setAccessible(true);
                    }
                    contextFromSessionObject = m.invoke(contextFromSessionObject, new Object[] {});
                } catch (Exception ex) {
                    ReflectionUtils.handleReflectionException(ex);
                }
            }

            // if what we got is a valid contextClass then place it into the holder, otherwise create a new one
            if (contextFromSessionObject instanceof SecurityContext) {
                if (logger.isDebugEnabled())
                    logger.debug("Obtained from SPRING_SECURITY_CONTEXT a valid SecurityContext and "
                            + "set to SecurityContextHolder: '" + contextFromSessionObject + "'");
                SecurityContextHolder.setContext((SecurityContext) contextFromSessionObject);
            } else {
                if (logger.isWarnEnabled())
                    logger.warn("SPRING_SECURITY_CONTEXT did not contain a SecurityContext but contained: '"
                            + contextFromSessionObject
                            + "'; are you improperly modifying the PortletSession directly "
                            + "(you should always use SecurityContextHolder) or using the PortletSession attribute "
                            + "reserved for this class? - new SecurityContext instance associated with "
                            + "SecurityContextHolder");
                SecurityContextHolder.setContext(generateNewContext());
            }

        } else {

            // there was no contextClass in the session, so create a new contextClass and put it in the holder
            if (logger.isDebugEnabled())
                logger.debug("PortletSession returned null object for SPRING_SECURITY_CONTEXT - new "
                        + "SecurityContext instance associated with SecurityContextHolder");
            SecurityContextHolder.setContext(generateNewContext());
        }

    } else {

        // there was no session, so create a new contextClass and place it in the holder
        if (logger.isDebugEnabled())
            logger.debug("No PortletSession currently exists - new SecurityContext instance "
                    + "associated with SecurityContextHolder");
        SecurityContextHolder.setContext(generateNewContext());

    }

    // place attributes onto the request to remember if the session existed and the hashcode of the contextClass
    request.setAttribute(SESSION_EXISTED, new Boolean(portletSessionExistedAtStartOfRequest));
    request.setAttribute(CONTEXT_HASHCODE, new Integer(SecurityContextHolder.getContext().hashCode()));

    return true;
}

From source file:org.springframework.security.ldap.authentication.AbstractLdapAuthenticationProvider.java

public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
            messages.getMessage("LdapAuthenticationProvider.onlySupports",
                    "Only UsernamePasswordAuthenticationToken is supported"));

    final UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken) authentication;

    String username = userToken.getName();
    String password = (String) authentication.getCredentials();

    if (logger.isDebugEnabled()) {
        logger.debug("Processing authentication request for user: " + username);
    }// w  w  w .  ja  va  2  s  . c o m

    if (!StringUtils.hasLength(username)) {
        throw new BadCredentialsException(
                messages.getMessage("LdapAuthenticationProvider.emptyUsername", "Empty Username"));
    }

    if (!StringUtils.hasLength(password)) {
        throw new BadCredentialsException(
                messages.getMessage("AbstractLdapAuthenticationProvider.emptyPassword", "Empty Password"));
    }

    Assert.notNull(password, "Null password was supplied in authentication token");

    DirContextOperations userData = doAuthentication(userToken);

    UserDetails user = userDetailsContextMapper.mapUserFromContext(userData, authentication.getName(),
            loadUserAuthorities(userData, authentication.getName(), (String) authentication.getCredentials()));

    return createSuccessfulAuthentication(userToken, user);
}

From source file:org.springframework.security.ldap.authentication.BindAuthenticator.java

public DirContextOperations authenticate(Authentication authentication) {
    DirContextOperations user = null;/*from ww w . j av  a  2  s  .c o m*/
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
            "Can only process UsernamePasswordAuthenticationToken objects");

    String username = authentication.getName();
    String password = (String) authentication.getCredentials();

    if (!StringUtils.hasLength(password)) {
        logger.debug("Rejecting empty password for user " + username);
        throw new BadCredentialsException(
                messages.getMessage("BindAuthenticator.emptyPassword", "Empty Password"));
    }

    // If DN patterns are configured, try authenticating with them directly
    for (String dn : getUserDns(username)) {
        user = bindWithDn(dn, username, password);

        if (user != null) {
            break;
        }
    }

    // Otherwise use the configured search object to find the user and authenticate
    // with the returned DN.
    if (user == null && getUserSearch() != null) {
        DirContextOperations userFromSearch = getUserSearch().searchForUser(username);
        user = bindWithDn(userFromSearch.getDn().toString(), username, password,
                userFromSearch.getAttributes());
    }

    if (user == null) {
        throw new BadCredentialsException(
                messages.getMessage("BindAuthenticator.badCredentials", "Bad credentials"));
    }

    return user;
}

From source file:org.springframework.security.ldap.authentication.LdapAuthenticationProvider.java

public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
            messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports",
                    "Only UsernamePasswordAuthenticationToken is supported"));

    final UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken) authentication;

    String username = userToken.getName();
    String password = (String) authentication.getCredentials();

    if (logger.isDebugEnabled()) {
        logger.debug("Processing authentication request for user: " + username);
    }//from   www. ja  v  a 2  s  .c o  m

    if (!StringUtils.hasLength(username)) {
        throw new BadCredentialsException(
                messages.getMessage("LdapAuthenticationProvider.emptyUsername", "Empty Username"));
    }

    Assert.notNull(password, "Null password was supplied in authentication token");

    try {
        DirContextOperations userData = getAuthenticator().authenticate(authentication);

        Collection<GrantedAuthority> extraAuthorities = loadUserAuthorities(userData, username, password);

        UserDetails user = userDetailsContextMapper.mapUserFromContext(userData, username, extraAuthorities);

        return createSuccessfulAuthentication(userToken, user);
    } catch (PasswordPolicyException ppe) {
        // The only reason a ppolicy exception can occur during a bind is that the account is locked.
        throw new LockedException(
                messages.getMessage(ppe.getStatus().getErrorCode(), ppe.getStatus().getDefaultMessage()));
    } catch (UsernameNotFoundException notFound) {
        if (hideUserNotFoundExceptions) {
            throw new BadCredentialsException(
                    messages.getMessage("LdapAuthenticationProvider.badCredentials", "Bad credentials"));
        } else {
            throw notFound;
        }
    } catch (NamingException ldapAccessFailure) {
        throw new AuthenticationServiceException(ldapAccessFailure.getMessage(), ldapAccessFailure);
    }
}

From source file:org.springframework.security.ldap.authentication.PasswordComparisonAuthenticator.java

public DirContextOperations authenticate(final Authentication authentication) {
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
            "Can only process UsernamePasswordAuthenticationToken objects");
    // locate the user and check the password

    DirContextOperations user = null;//from   www.  j a va 2 s  . c  om
    String username = authentication.getName();
    String password = (String) authentication.getCredentials();

    SpringSecurityLdapTemplate ldapTemplate = new SpringSecurityLdapTemplate(getContextSource());

    for (String userDn : getUserDns(username)) {
        try {
            user = ldapTemplate.retrieveEntry(userDn, getUserAttributes());
        } catch (NameNotFoundException ignore) {
        }
        if (user != null) {
            break;
        }
    }

    if (user == null && getUserSearch() != null) {
        user = getUserSearch().searchForUser(username);
    }

    if (user == null) {
        throw new UsernameNotFoundException("User not found: " + username);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Performing LDAP compare of password attribute '" + passwordAttributeName + "' for user '"
                + user.getDn() + "'");
    }

    if (usePasswordAttrCompare && isPasswordAttrCompare(user, password)) {
        return user;
    } else if (isLdapPasswordCompare(user, ldapTemplate, password)) {
        return user;
    }
    throw new BadCredentialsException(
            messages.getMessage("PasswordComparisonAuthenticator.badCredentials", "Bad credentials"));
}

From source file:org.springframework.springfaces.internal.WrapperHandler.java

/**
 * Wrap the specified delegate by consulting all {@link FacesWrapperFactory factories} registered with Spring.
 * @param externalContext the external context
 * @param delegate the root delegate//from w w w . j  a  v a  2  s  . c om
 * @return a wrapped implementation
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
private T wrap(ExternalContext externalContext, T delegate) {
    if (!SpringFacesIntegration.isInstalled(externalContext)) {
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("SpringFacesSupport is not yet installed, wrapping will be deferred");
        }
        if (this.logger.isWarnEnabled() && this.warnOnMissingSpringFaces) {
            this.logger.warn(
                    "SpringFacesSupport is not installed, full Spring/JSF integration may not be availble");
        }
        return delegate;
    }

    ApplicationContext applicationContext = SpringFacesIntegration.getCurrentInstance(externalContext)
            .getApplicationContext();

    List<Map.Entry<String, FacesWrapperFactory>> orderdBeans = new ArrayList<Map.Entry<String, FacesWrapperFactory>>();
    orderdBeans.addAll(BeanFactoryUtils
            .beansOfTypeIncludingAncestors(applicationContext, FacesWrapperFactory.class).entrySet());
    Collections.sort(orderdBeans, new OrderedMapEntryComparator());
    T rtn = delegate;
    for (Map.Entry<String, FacesWrapperFactory> entry : orderdBeans) {
        FacesWrapperFactory factory = entry.getValue();
        if (isFactorySupported(factory)) {
            T wrapper = (T) factory.newWrapper(this.typeClass, rtn);
            if (wrapper != null) {
                Assert.isInstanceOf(this.typeClass, wrapper,
                        "FacesWrapperFactory " + entry.getValue() + " returned incorrect type ");
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Wrapping " + this.typeClass.getSimpleName() + " with "
                            + wrapper.getClass() + " obtained from FacesWrapperFactory " + entry.getValue());
                }
                postProcessWrapper(wrapper);
                rtn = wrapper;
            }
        }
    }
    return rtn;
}

From source file:org.springframework.web.servlet.HttpServletBean.java

/**
 * Set the {@code Environment} that this servlet runs in.
 * <p>Any environment set here overrides the {@link StandardServletEnvironment}
 * provided by default.//from  w  ww  .ja v a2  s.c o m
 * @throws IllegalArgumentException if environment is not assignable to
 * {@code ConfigurableEnvironment}
 */
@Override
public void setEnvironment(Environment environment) {
    Assert.isInstanceOf(ConfigurableEnvironment.class, environment, "ConfigurableEnvironment required");
    this.environment = (ConfigurableEnvironment) environment;
}

From source file:org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.java

/**
 * Create a {@link UriComponentsBuilder} by invoking a "mock" controller method.
 * The controller method and the supplied argument values are then used to
 * delegate to {@link #fromMethod(Class, Method, Object...)}.
 * <p>For example, given this controller:
 * <pre class="code">/*from   w w w.j  av  a  2 s.  c  om*/
 * &#064;RequestMapping("/people/{id}/addresses")
 * class AddressController {
 *
 *   &#064;RequestMapping("/{country}")
 *   public HttpEntity<Void> getAddressesForCountry(&#064;PathVariable String country) { ... }
 *
 *   &#064;RequestMapping(value="/", method=RequestMethod.POST)
 *   public void addAddress(Address address) { ... }
 * }
 * </pre>
 * A UriComponentsBuilder can be created:
 * <pre class="code">
 * // Inline style with static import of "MvcUriComponentsBuilder.on"
 *
 * MvcUriComponentsBuilder.fromMethodCall(
 *       on(AddressController.class).getAddressesForCountry("US")).buildAndExpand(1);
 *
 * // Longer form useful for repeated invocation (and void controller methods)
 *
 * AddressController controller = MvcUriComponentsBuilder.on(AddressController.class);
 * controller.addAddress(null);
 * builder = MvcUriComponentsBuilder.fromMethodCall(controller);
 * controller.getAddressesForCountry("US")
 * builder = MvcUriComponentsBuilder.fromMethodCall(controller);
 * </pre>
 *
 * <p><strong>Note:</strong> This method extracts values from "Forwarded"
 * and "X-Forwarded-*" headers if found. See class-level docs.
 *
 * @param info either the value returned from a "mock" controller
 * invocation or the "mock" controller itself after an invocation
 * @return a UriComponents instance
 */
public static UriComponentsBuilder fromMethodCall(Object info) {
    Assert.isInstanceOf(MethodInvocationInfo.class, info, "MethodInvocationInfo required");
    MethodInvocationInfo invocationInfo = (MethodInvocationInfo) info;
    Class<?> controllerType = invocationInfo.getControllerType();
    Method method = invocationInfo.getControllerMethod();
    Object[] arguments = invocationInfo.getArgumentValues();
    return fromMethodInternal(null, controllerType, method, arguments);
}

From source file:org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.java

/**
 * An alternative to {@link #fromMethodCall(Object)} that accepts a
 * {@code UriComponentsBuilder} representing the base URL. This is useful
 * when using MvcUriComponentsBuilder outside the context of processing a
 * request or to apply a custom baseUrl not matching the current request.
 * <p><strong>Note:</strong> This method extracts values from "Forwarded"
 * and "X-Forwarded-*" headers if found. See class-level docs.
 * @param builder the builder for the base URL; the builder will be cloned
 * and therefore not modified and may be re-used for further calls.
 * @param info either the value returned from a "mock" controller
 * invocation or the "mock" controller itself after an invocation
 * @return a UriComponents instance//w  ww.  j  ava 2 s  . c  om
 */
public static UriComponentsBuilder fromMethodCall(UriComponentsBuilder builder, Object info) {
    Assert.isInstanceOf(MethodInvocationInfo.class, info, "MethodInvocationInfo required");
    MethodInvocationInfo invocationInfo = (MethodInvocationInfo) info;
    Class<?> controllerType = invocationInfo.getControllerType();
    Method method = invocationInfo.getControllerMethod();
    Object[] arguments = invocationInfo.getArgumentValues();
    return fromMethodInternal(builder, controllerType, method, arguments);
}