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:com.apress.prospringintegration.customadapters.outbound.ShellMessageWritingMessageEndpoint.java

@Override
protected void handleMessageInternal(Message<?> message) throws Exception {

    Assert.isInstanceOf(String.class, message.getPayload(), "the payload must be a String");

    String msg = (String) message.getPayload();

    MessageHeaders headers = message.getHeaders();

    try {/*from   w  ww .ja  va2  s  .  co m*/
        if (headers.containsKey(USERID_HEADER)) {
            String ptys = headers.containsKey(TERMINALS_HEADER) ? (String) headers.get(TERMINALS_HEADER) : null;
            String userid = (String) headers.get(USERID_HEADER);
            write(userid, msg, ptys);
        } else {
            wall(msg);
        }
    } catch (Throwable throwable) {
        throw new RuntimeException(throwable);
    }
}

From source file:com.capinfo.common.security.authentication.dao.SecurityDaoAuthenticationProvider.java

/**
 * ?org.springframework.security.authentication.dao.
 * AbstractUserDetailsAuthenticationProvider.authenticate
 * /*from w  w w  . j ava2 s .c  om*/
 */
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
            messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports",
                    "Only UsernamePasswordAuthenticationToken is supported"));

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

    boolean cacheWasUsed = true;
    UserDetails user = getUserCache().getUserFromCache(username);
    // Ehcache?UserDetailspasswordnull.usernamepassword?
    // boolean userOutCache=user == null;
    boolean userOutCache = user == null || StringUtils.isBlank(user.getUsername())
            || StringUtils.isBlank(user.getPassword());
    if (userOutCache) {
        cacheWasUsed = false;

        try {
            user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication);

            if (!authentication.getCredentials().toString().equals(user.getPassword())) {
                throw new BadCredentialsException(messages.getMessage(
                        "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
            }
        } 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 {
        getPreAuthenticationChecks().check(user);
    } 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);
            getPreAuthenticationChecks().check(user);
        } else {
            throw exception;
        }
    }

    getPostAuthenticationChecks().check(user);

    if (!cacheWasUsed) {
        getUserCache().putUserInCache(user);
        UserDetails user2 = getUserCache().getUserFromCache(username);
    }

    Object principalToReturn = user;

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

    return createSuccessAuthentication(principalToReturn, authentication, user);
}

From source file:org.jasig.springframework.web.portlet.context.ContribXmlPortletApplicationContext.java

/**
 * TODO this gets moved into ConfigurablePortletApplicationContext
 *//*w  w w.ja va 2  s  .  co  m*/
@Override
public ConfigurablePortletEnvironment getEnvironment() {
    ConfigurableEnvironment env = super.getEnvironment();
    Assert.isInstanceOf(ConfigurablePortletEnvironment.class, env,
            "ConfigurablePortletApplicationContext environment must be of type "
                    + "ConfigurablePortletEnvironment");
    return (ConfigurablePortletEnvironment) env;
}

From source file:it.reply.orchestrator.dto.deployment.SlaPlacementPolicy.java

/**
 * Set the SLA id from a {@link AbstractPropertyValue}.
 * /*w w  w  .  j a  v  a2 s . co  m*/
 * @param slaId
 *          the SLA id
 */
public void setSlaId(AbstractPropertyValue slaId) {
    Objects.requireNonNull(slaId, "slaId must not be null");
    Assert.isInstanceOf(ScalarPropertyValue.class, slaId, "slaId must be a scalar value");
    this.slaId = ((ScalarPropertyValue) slaId).getValue();
}

From source file:org.juiser.spring.security.user.SecurityContextUser.java

@Override
protected User findUser() {
    Authentication authc = getValidAuthentication();
    Assert.notNull(authc, "Current SecurityContext Authentication cannot be null.");
    Object value = authc.getPrincipal();
    Assert.isInstanceOf(ForwardedUserDetails.class, value,
            "securityContext.getAuthentication().getPrincipal() must contain a ForwardedUserDetails instance.");
    User user = null;/*from www. j  av a 2 s .co m*/
    if (value instanceof ForwardedUserDetails) {
        ForwardedUserDetails details = (ForwardedUserDetails) value;
        user = details.getUser();
    }
    if (user != null) {
        return user;
    }
    String msg = "Unable to acquire required " + User.class.getName()
            + " instance from the current SecurityContext Authentication.";
    throw new IllegalStateException(msg);
}

From source file:com.denksoft.springstarter.util.security.CustomAclEntryAfterInvocationProvider.java

private Serializable getIdentity(Object object) throws IdentityUnavailableException {
    Assert.notNull(object, "object cannot be null");
    Serializable identifier;//from   w w w  . j av  a  2 s.  c  o m
    Class javaType = ClassUtils.getUserClass(object.getClass());

    Object result;

    try {
        Method method = javaType.getMethod("getId", new Class[] {});
        result = method.invoke(object, new Object[] {});
    } catch (Exception e) {
        throw new IdentityUnavailableException("Could not extract identity from object " + object, e);
    }

    Assert.notNull(result, "getId() is required to return a non-null value");
    Assert.isInstanceOf(Serializable.class, result, "Getter must provide a return value of type Serializable");
    return (Serializable) result;
}

From source file:org.codehaus.groovy.grails.plugins.searchable.compass.search.DefaultStringQuerySearchableCompassQueryBuilder.java

public CompassQuery buildQuery(GrailsApplication grailsApplication, CompassSession compassSession, Map options,
        Object query) {//from w w  w  . j a v a2 s.  c o  m
    Assert.notNull(query, "query cannot be null");
    Assert.isInstanceOf(String.class, query,
            "query must be a String but is [" + query.getClass().getName() + "]");

    String analyzer = (String) getOption(ANALYZER_NAMES, options);
    String parser = (String) getOption(PARSER_NAMES, options);
    String defaultSearchProperty = (String) getOption(DEFAULT_PROPERTY_NAMES, options);
    Collection properties = (Collection) getOption(PROPERTIES_NAMES, options);
    Boolean useAndDefaultOperator = (Boolean) getOption(USE_AND_DEFAULT_OPERATOR_NAMES, options);
    Boolean escape = MapUtils.getBoolean(options, "escape", Boolean.FALSE);

    Assert.isTrue(!(properties != null && defaultSearchProperty != null),
            "The " + DefaultGroovyMethods.join(DEFAULT_PROPERTY_NAMES, "/") + " and "
                    + DefaultGroovyMethods.join(PROPERTIES_NAMES, "/") + " options cannot be combined");

    String queryString = (String) query;
    if (escape.booleanValue()) {
        queryString = CompassQueryParser.escape(queryString);
    }

    CompassQueryBuilder compassQueryBuilder = compassSession.queryBuilder();
    CompassQueryBuilder.ToCompassQuery stringBuilder;
    if (properties != null && !properties.isEmpty()) {
        stringBuilder = compassQueryBuilder.multiPropertyQueryString(queryString);
        for (Iterator iter = properties.iterator(); iter.hasNext();) {
            ((CompassQueryBuilder.CompassMultiPropertyQueryStringBuilder) stringBuilder)
                    .add((String) iter.next());
        }
    } else {
        stringBuilder = compassQueryBuilder.queryString(queryString);
    }

    if (analyzer != null) {
        InvokerHelper.invokeMethod(stringBuilder, "setAnalyzer", analyzer);
    }
    if (parser != null) {
        InvokerHelper.invokeMethod(stringBuilder, "setQueryParser", parser);
    }
    if (defaultSearchProperty != null) {
        InvokerHelper.invokeMethod(stringBuilder, "setDefaultSearchProperty", defaultSearchProperty);
    }
    if (useAndDefaultOperator != null && useAndDefaultOperator.booleanValue()) {
        InvokerHelper.invokeMethod(stringBuilder, "useAndDefaultOperator", null);
    }
    return stringBuilder.toQuery();
}

From source file:fr.mby.portal.coreimpl.auth.MinimalPortalUserAuthenticationProvider.java

@Override
public IAuthentication authenticate(final IAuthentication authentication) throws AuthenticationException {
    Assert.notNull(authentication, "No authentication supplied !");
    Assert.isInstanceOf(PortalUserAuthentication.class, authentication,
            "IAuthentication shoud be a PortalUserAuthentication type !");

    if (authentication.isAuthenticated()) {
        throw new AuthenticationException(authentication,
                "Already authenticated IAuthentication token supplied !");
    }// w w w . j ava  2 s.c o  m

    final PortalUserAuthentication auth = (PortalUserAuthentication) authentication;

    IAuthentication resultingAuth = null;

    final String login = authentication.getName();
    switch (login) {
    case "admin":
        resultingAuth = this.performAuthentication(auth, "admin123", BasicAclManager.ADMIN);
        break;
    case "user":
        resultingAuth = this.performAuthentication(auth, "user123", BasicAclManager.LOGGED);
        break;
    default:
        break;
    }

    if (resultingAuth == null) {
        throw new AuthenticationException(authentication, "Unable to authenticate supplied authentication !");
    }

    return resultingAuth;
}

From source file:grails.plugin.searchable.internal.compass.search.DefaultStringQuerySearchableCompassQueryBuilder.java

public CompassQuery buildQuery(GrailsApplication grailsApplication, CompassSession compassSession, Map options,
        Object query) {//from   w  ww.ja va 2  s .c  o  m
    Assert.notNull(query, "query cannot be null");
    Assert.isInstanceOf(String.class, query,
            "query must be a String but is [" + query.getClass().getName() + "]");

    String analyzer = (String) getOption(ANALYZER_NAMES, options);
    String parser = (String) getOption(PARSER_NAMES, options);
    String defaultSearchProperty = (String) getOption(DEFAULT_PROPERTY_NAMES, options);
    Collection properties = (Collection) getOption(PROPERTIES_NAMES, options);
    Boolean useAndDefaultOperator = (Boolean) getOption(USE_AND_DEFAULT_OPERATOR_NAMES, options);
    String defaultOperator = (String) getOption(DEFAULT_OPERATOR_NAMES, options);
    Boolean escape = MapUtils.getBoolean(options, "escape", false);

    Assert.isTrue(!(properties != null && defaultSearchProperty != null),
            "The " + DefaultGroovyMethods.join(DEFAULT_PROPERTY_NAMES, "/") + " and "
                    + DefaultGroovyMethods.join(PROPERTIES_NAMES, "/") + " options cannot be combined");
    Assert.isTrue(!(defaultOperator != null && useAndDefaultOperator != null),
            "The [" + DefaultGroovyMethods.join(USE_AND_DEFAULT_OPERATOR_NAMES, ", ") + "] and ["
                    + DEFAULT_PROPERTY_NAMES[0]
                    + "] options indicate the same thing so cannot be used together: [" + DEFAULT_PROPERTY_NAMES
                    + "] is better");

    String queryString = (String) query;
    if (escape) {
        queryString = CompassQueryParser.escape(queryString);
    }

    CompassQueryBuilder compassQueryBuilder = compassSession.queryBuilder();
    CompassQueryBuilder.ToCompassQuery stringBuilder;
    if (properties != null && !properties.isEmpty()) {
        stringBuilder = compassQueryBuilder.multiPropertyQueryString(queryString);
        for (Iterator iter = properties.iterator(); iter.hasNext();) {
            ((CompassQueryBuilder.CompassMultiPropertyQueryStringBuilder) stringBuilder)
                    .add((String) iter.next());
        }
    } else {
        stringBuilder = compassQueryBuilder.queryString(queryString);
    }

    if (analyzer != null) {
        InvokerHelper.invokeMethod(stringBuilder, "setAnalyzer", analyzer);
    }
    if (parser != null) {
        InvokerHelper.invokeMethod(stringBuilder, "setQueryParser", parser);
    }
    if (defaultSearchProperty != null) {
        InvokerHelper.invokeMethod(stringBuilder, "setDefaultSearchProperty", defaultSearchProperty);
    }
    // todo deprecate "useAndDefaultOperator" - "defaultOperator" is better
    if (useAndDefaultOperator != null) {
        if (useAndDefaultOperator) {
            InvokerHelper.invokeMethod(stringBuilder, "useAndDefaultOperator", null);
        } else {
            InvokerHelper.invokeMethod(stringBuilder, "useOrDefaultOperator", null);
        }
    }
    if (defaultOperator != null) {
        if (defaultOperator.equalsIgnoreCase("and")) {
            InvokerHelper.invokeMethod(stringBuilder, "useAndDefaultOperator", null);
        } else if (defaultOperator.equalsIgnoreCase("or")) {
            InvokerHelper.invokeMethod(stringBuilder, "useOrDefaultOperator", null);
        } else {
            throw new IllegalArgumentException("The [" + DEFAULT_OPERATOR_NAMES[0]
                    + "] option only accepts 'and' or 'or' values but [" + defaultOperator + "] was supplied");
        }
    }
    return stringBuilder.toQuery();
}