Example usage for org.springframework.util Assert state

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

Introduction

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

Prototype

public static void state(boolean expression, Supplier<String> messageSupplier) 

Source Link

Document

Assert a boolean expression, throwing an IllegalStateException if the expression evaluates to false .

Usage

From source file:org.cloudfoundry.identity.uaa.oauth.ClientAdminEndpoints.java

@RequestMapping(value = "/oauth/clients/{client}", method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.OK)/*from w  ww. ja  va2s  .co m*/
@ResponseBody
public ClientDetails updateClientDetails(@RequestBody BaseClientDetails client,
        @PathVariable("client") String clientId) throws Exception {
    Assert.state(clientId.equals(client.getClientId()),
            String.format("The client id (%s) does not match the URL (%s)", client.getClientId(), clientId));
    ClientDetails details = client;
    try {
        ClientDetails existing = getClientDetails(clientId);
        if (existing == null) {
            //TODO - should we proceed? Previous code did by throwing a NPE and logging a warning
            logger.warn("Couldn't fetch client config, null, for client_id: " + clientId);
        } else {
            details = syncWithExisting(existing, client);
        }
    } catch (Exception e) {
        logger.warn("Couldn't fetch client config for client_id: " + clientId, e);
    }
    details = validateClient(details, false);
    clientRegistrationService.updateClientDetails(details);
    clientUpdates.incrementAndGet();
    return removeSecret(client);
}

From source file:org.cloudfoundry.identity.uaa.oauth.RemoteTokenServices.java

@Override
public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException {

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    formData.add("token", accessToken);
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", getAuthorizationHeader(clientId, clientSecret));
    Map<String, Object> map = postForMap(checkTokenEndpointUrl, formData, headers);

    if (map.containsKey("error")) {
        logger.debug("check_token returned error: " + map.get("error"));
        throw new InvalidTokenException(accessToken);
    }/*from www .  j ava2  s  .  c o m*/

    Assert.state(map.containsKey("client_id"), "Client id must be present in response from auth server");
    String remoteClientId = (String) map.get("client_id");

    Set<String> scope = new HashSet<String>();
    if (map.containsKey("scope")) {
        @SuppressWarnings("unchecked")
        Collection<String> values = (Collection<String>) map.get("scope");
        scope.addAll(values);
    }
    AuthorizationRequest clientAuthentication = new AuthorizationRequest(remoteClientId, scope);

    if (map.containsKey("resource_ids") || map.containsKey("client_authorities")) {
        Set<String> resourceIds = new HashSet<String>();
        if (map.containsKey("resource_ids")) {
            @SuppressWarnings("unchecked")
            Collection<String> values = (Collection<String>) map.get("resource_ids");
            resourceIds.addAll(values);
        }
        Set<GrantedAuthority> clientAuthorities = new HashSet<GrantedAuthority>();
        if (map.containsKey("client_authorities")) {
            @SuppressWarnings("unchecked")
            Collection<String> values = (Collection<String>) map.get("client_authorities");
            clientAuthorities.addAll(getAuthorities(values));
        }
        BaseClientDetails clientDetails = new BaseClientDetails();
        clientDetails.setClientId(remoteClientId);
        clientDetails.setResourceIds(resourceIds);
        clientDetails.setAuthorities(clientAuthorities);
        clientAuthentication.setResourceIdsAndAuthoritiesFromClientDetails(clientDetails);
    }
    Map<String, String> requestParameters = new HashMap<>();
    if (isStoreClaims()) {
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getValue() != null && entry.getValue() instanceof String) {
                requestParameters.put(entry.getKey(), (String) entry.getValue());
            }
        }
    }

    if (map.containsKey(ClaimConstants.ADDITIONAL_AZ_ATTR)) {
        try {
            requestParameters.put(ClaimConstants.ADDITIONAL_AZ_ATTR,
                    JsonUtils.writeValueAsString(map.get(ClaimConstants.ADDITIONAL_AZ_ATTR)));
        } catch (JsonUtils.JsonUtilException e) {
            throw new IllegalStateException("Cannot convert access token to JSON", e);
        }
    }
    clientAuthentication.setRequestParameters(Collections.unmodifiableMap(requestParameters));

    Authentication userAuthentication = getUserAuthentication(map, scope);

    clientAuthentication.setApproved(true);
    return new OAuth2Authentication(clientAuthentication.createOAuth2Request(), userAuthentication);
}

From source file:org.cloudfoundry.identity.uaa.oauth.SignerProvider.java

/**
 * Sets the JWT signing key and corresponding key for verifying siugnatures produced by this class.
 *
 * The signing key can be either a simple MAC key or an RSA
 * key. RSA keys should be in OpenSSH format,
 * as produced by <tt>ssh-keygen</tt>.
 *
 * @param signingKey the key to be used for signing JWTs.
 *//*from www.  j  a  v  a  2 s  . com*/
public void setSigningKey(String signingKey) {
    Assert.hasText(signingKey);
    signingKey = signingKey.trim();

    this.signingKey = signingKey;

    if (isAssymetricKey(signingKey)) {
        KeyPair keyPair = parseKeyPair(signingKey);
        signer = new RsaSigner(signingKey);

        pemEncodePublicKey(keyPair);

        logger.debug("Configured with RSA signing key");
        try {
            verifier = new RsaVerifier(verifierKey);
        } catch (Exception e) {
            throw new RuntimeException("Unable to create an RSA verifier from verifierKey", e);
        }

        byte[] test = "test".getBytes();
        try {
            verifier.verify(test, signer.sign(test));
            logger.debug("Signing and verification RSA keys match");
        } catch (InvalidSignatureException e) {
            throw new RuntimeException("Signing and verification RSA keys do not match", e);
        }
        type = "RSA";
    } else {
        // Assume it's an HMAC key
        this.verifierKey = signingKey;
        MacSigner macSigner = new MacSigner(signingKey);
        signer = macSigner;
        verifier = macSigner;

        Assert.state(this.verifierKey == null || this.signingKey == this.verifierKey,
                "For MAC signing you do not need to specify the verifier key separately, and if you do it must match the signing key");
        type = "MAC";
    }
}

From source file:org.cloudfoundry.identity.uaa.oauth.token.SignerProvider.java

@Override
public void afterPropertiesSet() throws Exception {
    if (signer instanceof RsaSigner) {
        type = "RSA";
        RsaVerifier verifier;/*  w  w w .j  av a 2s. co  m*/
        try {
            verifier = new RsaVerifier(verifierKey);
        } catch (Exception e) {
            throw new RuntimeException("Unable to create an RSA verifier from verifierKey", e);
        }

        byte[] test = "test".getBytes();
        try {
            verifier.verify(test, signer.sign(test));
            logger.debug("Signing and verification RSA keys match");
        } catch (InvalidSignatureException e) {
            throw new RuntimeException("Signing and verification RSA keys do not match", e);
        }
    } else {
        Assert.state(this.signingKey == this.verifierKey,
                "For MAC signing you do not need to specify the verifier key separately, and if you do it must match the signing key");
    }
}

From source file:org.cloudfoundry.identity.uaa.test.TestAccountSetup.java

private void initializeUserAccount(RestOperations client) {

    if (this.user == null) {

        UaaUser user = testAccounts.getUserWithRandomID();
        @SuppressWarnings("rawtypes")
        ResponseEntity<Map> results = client.getForEntity(
                serverRunning.getUserUri() + "?filter=userName eq \"" + user.getUsername() + "\"", Map.class);
        assertEquals(HttpStatus.OK, results.getStatusCode());
        @SuppressWarnings("unchecked")
        List<Map<String, ?>> resources = (List<Map<String, ?>>) results.getBody().get("resources");
        Map<String, ?> map;
        if (!resources.isEmpty()) {
            map = resources.get(0);/*from w  w  w.  j a v a 2s .  co  m*/
        } else {
            map = getUserAsMap(user);
            @SuppressWarnings("rawtypes")
            ResponseEntity<Map> response = client.postForEntity(serverRunning.getUserUri(), map, Map.class);
            Assert.state(response.getStatusCode() == HttpStatus.CREATED,
                    "User account not created: status was " + response.getStatusCode());
            @SuppressWarnings("unchecked")
            Map<String, ?> value = response.getBody();
            map = value;
        }
        this.user = getUserFromMap(map);

    }

}

From source file:org.cloudfoundry.identity.uaa.test.TestAccountSetup.java

private List<? extends GrantedAuthority> extractAuthorities(Collection<Map<String, String>> groups) {
    List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
    for (Map<String, String> group : groups) {
        String role = group.get("display");
        Assert.state(role != null, "Role is null in this group: " + group);
        authorities.add(new SimpleGrantedAuthority(role));
    }/*from w  w  w. j  ava  2s .com*/
    return authorities;
}

From source file:org.codehaus.groovy.grails.commons.spring.GrailsRuntimeConfigurator.java

public void reconfigure(GrailsApplicationContext current, ServletContext servletContext,
        boolean loadExternalBeans) {
    RuntimeSpringConfiguration springConfig = parent != null ? new DefaultRuntimeSpringConfiguration(parent)
            : new DefaultRuntimeSpringConfiguration();
    Assert.state(pluginManager.isInitialised(),
            "Cannot re-configure Grails application when it hasn't even been configured yet!");

    pluginManager.doRuntimeConfiguration(springConfig);

    List<String> beanNames = springConfig.getBeanNames();
    for (Object beanName : beanNames) {
        String name = (String) beanName;
        if (LOG.isDebugEnabled()) {
            LOG.debug("Re-creating bean definition [" + name + "]");
        }//w ww  . j  av  a 2 s .  com
        current.registerBeanDefinition(name, springConfig.createBeanDefinition(name));
        // force initialisation
        current.getBean(name);
    }
    pluginManager.doDynamicMethods();
    pluginManager.doPostProcessing(current);

    if (loadExternalBeans) {
        doPostResourceConfiguration(application, springConfig);
    }

    reset();
}

From source file:org.codehaus.groovy.grails.plugins.AbstractGrailsPluginManager.java

protected void checkInitialised() {
    Assert.state(initialised,
            "Must call loadPlugins() before invoking configurational methods on GrailsPluginManager");
}

From source file:org.codehaus.groovy.grails.web.pages.GroovyPageResourceLoader.java

@Override
public Resource getResource(String location) {
    Assert.hasLength(location, "Argument [location] cannot be null or blank");

    // deal with plug-in resolving
    if (location.startsWith(PLUGINS_PATH)) {
        Assert.state(pluginSettings != null, "'pluginsettings' has not been initialised.");
        List<String> pluginBaseDirectories = pluginSettings.getPluginBaseDirectories();
        DefaultGroovyPageLocator.PluginViewPathInfo pluginViewPathInfo = DefaultGroovyPageLocator
                .getPluginViewPathInfo(location);
        String path = pluginViewPathInfo.basePath;
        String pluginName = pluginViewPathInfo.pluginName;
        String pathRelativeToPlugin = pluginViewPathInfo.path;

        for (String pluginBaseDirectory : pluginBaseDirectories) {
            String pathToResource = pluginBaseDirectory + File.separatorChar + path;
            Resource r = super.getResource("file:" + pathToResource);
            if (r.exists()) {
                return r;
            }//  w  w w.  j a va2s .  c  o  m

            pathToResource = buildPluginViewPath(pluginBaseDirectory, pluginName, pathRelativeToPlugin);
            r = super.getResource(pathToResource);
            if (r.exists())
                return r;
        }

        Resource r = findInInlinePlugin(pluginName, pathRelativeToPlugin);
        if (r != null && r.exists()) {
            return r;
        }
    }

    Resource resource = super.getResource(location);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Resolved GSP location [" + location + "] to resource [" + resource + "] (exists? ["
                + resource.exists() + "]) using base resource [" + localBaseResource + "]");
    }
    return resource;
}

From source file:org.codehaus.groovy.grails.web.pages.GroovyPagesTemplateEngine.java

private GroovyPageScriptSource getResourceWithinContext(String uri) {
    Assert.state(groovyPageLocator != null,
            "TemplateEngine not initialised correctly, no [groovyPageLocator] specified!");
    GroovyPageScriptSource scriptSource = groovyPageLocator.findPage(uri);
    if (scriptSource != null) {
        return scriptSource;
    }/*ww  w.j  a va  2  s .  c  o  m*/
    return null;
}