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:sk.lazyman.gizmo.security.SimpleBindAunthenticator.java

@Override
public DirContextOperations authenticate(Authentication authentication) {
    DirContextOperations user = null;//from   w w  w .  j  a  v  a  2  s  .  com
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
            "Can only process UsernamePasswordAuthenticationToken objects");

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

    if (StringUtils.isEmpty(password)) {
        LOG.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);
    }

    try {
        if (user != null && StringUtils.isNotEmpty(gizmoGroup)) {
            BaseLdapPathContextSource ctxSource = (BaseLdapPathContextSource) getContextSource();
            DirContext ctx = ctxSource.getReadOnlyContext();

            DistinguishedName userDn = new DistinguishedName(user.getDn());
            userDn.prepend(ctxSource.getBaseLdapPath());

            SearchControls controls = new SearchControls();
            controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            String filter = String.format(GROUP_SEARCH_QUERY, gizmoGroup, userDn.toCompactString());
            NamingEnumeration en = ctx.search("", filter, controls);
            if (!en.hasMore()) {
                throw new BadCredentialsException(
                        messages.getMessage("BindAuthenticator.badCredentials", "Bad credentials"));
            }
        }
    } catch (javax.naming.NamingException ex) {
        throw new BadCredentialsException("Couldn't check group membership");
    }

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

    return user;
}

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

/**
 * TODO this gets moved into ConfigurablePortletApplicationContext
 *//*from  w w w.  jav  a 2 s. c  o  m*/
@Override
public void setEnvironment(ConfigurableEnvironment environment) {
    Assert.isInstanceOf(ConfigurablePortletEnvironment.class, environment,
            "ContribDispatcherPortlet environment must be of type " + "ConfigurablePortletEnvironment");

    super.setEnvironment(environment);
}

From source file:com.orangeleap.common.security.OrangeLeapBindAuthenticator.java

@SuppressWarnings("unchecked")
public DirContextOperations authenticate(Authentication authentication) {

    logger.debug("OrangeLeapBindAuthenticator invoked with " + authentication.getClass().getName());

    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
            "Can only process UsernamePasswordAuthenticationToken objects");

    logger.debug("Attempting to authenticate with OrangeLeapBindAuthenticator...");

    String[] principal = authentication.getPrincipal().toString().split("@");
    if (principal.length != 2)
        throw new RuntimeException("Invalid principal: " + principal);
    String username = principal[0];
    String site = principal[1];/* w  w w.ja v a2 s.c  o m*/
    String password = (String) authentication.getCredentials();

    // If DN patterns are configured, try authenticating with them directly
    Iterator dns = getUserDns(username).iterator();

    DirContextOperations user = null;
    while (dns.hasNext() && user == null) {
        user = bindWithDn((String) dns.next(), username, password);
    }

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

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

    Map<String, Object> info = OrangeLeapUsernamePasswordLocal.getOrangeLeapAuthInfo();
    info.put(OrangeLeapUsernamePasswordLocal.SITE, site);
    info.put(OrangeLeapUsernamePasswordLocal.USER_NAME, username);
    info.put(OrangeLeapUsernamePasswordLocal.PASSWORD, password);

    logger.debug("Authenticated with OrangeLeapBindAuthenticator.");

    return user;
}

From source file:org.openmrs.web.controller.observation.handler.WebTextHandler.java

/**
 * Returns the ComplexData for an Obs depending on the view.
 * Currently, the views implemented are those supported by ancestor plus the following:
 * <ul>/*from  w  w w  . ja  v a  2  s .c  om*/
 * <li>{@link ComplexObsHandler#URI_VIEW}: a lightweight alternative to returning the
 * ComplexData from the parent class since this does not require access to the service layer.
 * Gives a link to the ComplexServlet for this obs
 * </ul>
 * 
 * @see org.openmrs.obs.handler.TextHandler#getObs(Obs, String)
 */
@Override
public Obs getObs(Obs obs, String view) {
    if (ComplexObsHandler.URI_VIEW.equals(view)) {
        Locale locale = Context.getLocale();
        ComplexData cd = new ComplexData(obs.getValueAsString(locale),
                WebHandlerUtils.getHyperlink(obs, ComplexObsHandler.RAW_VIEW));
        obs.setComplexData(cd);
        return obs;
    }

    if (ComplexObsHandler.HTML_VIEW.equals(view)) {
        obs = super.getObs(obs, ComplexObsHandler.TEXT_VIEW);

        ComplexData cd = obs.getComplexData();
        Assert.notNull(cd, "TextHandler failed to provide text complex data");
        Assert.isInstanceOf(String.class, cd.getData(), "TextHandler doesn't provide text as string");

        Locale locale = Context.getLocale();
        cd = new ComplexData(obs.getValueAsString(locale), "<pre>" + cd.getData() + "</pre>");
        obs.setComplexData(cd);
        return obs;
    }

    return super.getObs(obs, view);
}

From source file:net.shibboleth.idp.oidc.util.OIDCUtils.java

/**
 * Gets the http servlet response from the context.
 *
 * @param context the context//from  w ww  . java2s.co  m
 * @return the http servlet response
 */
public static HttpServletResponse getHttpServletResponse(final RequestContext context) {
    Assert.isInstanceOf(ServletExternalContext.class, context.getExternalContext(),
            "Cannot obtain HttpServletResponse from event of type: "
                    + context.getExternalContext().getClass().getName());
    return (HttpServletResponse) context.getExternalContext().getNativeResponse();
}

From source file:es.osoco.grails.plugins.otp.authentication.OneTimePasswordAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    Assert.isInstanceOf(OneTimePasswordAuthenticationToken.class, authentication,
            messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports",
                    "Only OneTimePasswordAuthenticationToken is supported"));

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

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

    if (user == null) {
        cacheWasUsed = false;/*from w w  w.  j  a  v a2s . c  o m*/

        try {
            user = retrieveUser(username, (OneTimePasswordAuthenticationToken) authentication);
        } catch (UsernameNotFoundException notFound) {

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

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

    try {
        getPreAuthenticationChecks().check(user);
        additionalAuthenticationChecks(user, (OneTimePasswordAuthenticationToken) 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, (OneTimePasswordAuthenticationToken) authentication);
            getPreAuthenticationChecks().check(user);
            additionalAuthenticationChecks(user, (OneTimePasswordAuthenticationToken) authentication);
        } else {
            throw exception;
        }
    }

    getPostAuthenticationChecks().check(user);

    if (!cacheWasUsed) {
        getUserCache().putUserInCache(user);
    }

    Object principalToReturn = user;

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

    return createSuccessAuthentication(principalToReturn, authentication, user);
}

From source file:ch.rasc.wampspring.config.WebMvcWampEndpointRegistry.java

private static SubProtocolWebSocketHandler unwrapSubProtocolWebSocketHandler(WebSocketHandler wsHandler) {
    WebSocketHandler actual = WebSocketHandlerDecorator.unwrap(wsHandler);
    Assert.isInstanceOf(SubProtocolWebSocketHandler.class, actual,
            "No SubProtocolWebSocketHandler in " + wsHandler);
    return (SubProtocolWebSocketHandler) actual;
}

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

public CompassQuery buildQuery(GrailsApplication grailsApplication, CompassSession compassSession, Map options,
        Object args) {//ww  w  .  j  a  va 2  s . com
    Object query = SearchableMethodUtils.getQueryArgument(args);
    Assert.notNull(query, "Missing String or Closure query argument");

    CompassQuery compassQuery;
    if (query instanceof String) {
        compassQuery = stringQueryBuilder.buildQuery(grailsApplication, compassSession, options, query);
    } else {
        Assert.isInstanceOf(Closure.class, query,
                "query is neither String nor Closure: must be one of these but is ["
                        + query.getClass().getName() + "]");
        Object closureQueryBuilder = InvokerHelper.invokeConstructorOf(closureQueryBuilderClass,
                compassSession.queryBuilder());
        compassQuery = (CompassQuery) InvokerHelper.invokeMethod(closureQueryBuilder, "buildQuery", query);
    }
    //        Object clazz = options.get("class");
    //        if (clazz != null) {
    //            LOG.warn("The 'class' option for the Searchable Plugin search method is deprecated. Please use 'match' instead");
    //            System.out.println("WARN: The 'class' option for the Searchable Plugin search method is deprecated. Please use 'match' instead");
    //            if (!options.containsKey("match")) {
    //                options.put("match", )
    //            }
    //        }
    if (!options.containsKey("class") && options.containsKey("match")) {
        options.put("class", options.get("match"));
    }
    return applyOptions(grailsApplication, getCompass(), compassSession, compassQuery, options);
}

From source file:com.gewara.web.support.OpenMemberAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Assert.isInstanceOf(OpenMemberAuthenticationToken.class, authentication,
            "OpenMemberAuthenticationProvider only supports OpenMemberAuthenticationToken");
    OpenMemberAuthenticationToken auth = (OpenMemberAuthenticationToken) authentication;
    Member member = daoService.getObject(Member.class, auth.getMemberid());
    if (StringUtils.equals(auth.getSource(), MemberConstant.SOURCE_DYNCODE)) {
        if (!StringUtils.equals(member.getMobile(), auth.getIdentity())
                || !ValidateUtil.isMobile(auth.getIdentity())) {
            dbLogger.warn("" + auth.getIdentity());
            throw new IllegalArgumentException("!");
        }// www.  j  av  a  2 s.  c  o  m
    } else {
        MemberInfo info = daoService.getObject(MemberInfo.class, auth.getMemberid());
        String mSource = VmUtils.getJsonValueByKey(info.getOtherinfo(), "openMember");
        if (!StringUtils.contains(mSource, auth.getSource())) {
            //TODO:openMember
            //if(!StringUtils.equals(mSource, auth.getSource())){
            dbLogger.warn("" + auth.getSource() + ", memberid=" + auth.getMemberid());
            throw new IllegalArgumentException("");
        }
    }
    Assert.notNull(member, "");
    preAuthenticationChecks.check(member);
    postAuthenticationChecks.check(member);
    Assert.notNull(member, "");
    return createSuccessAuthentication(auth, member);
}

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

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