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.bremersee.common.security.acls.jdbc.BasicLookupStrategy.java

/**
 * Looks up a batch of <code>ObjectIdentity</code>s directly from the database.
 * <p>/*www  .  j  a  v a2s. c  o m*/
 * The caller is responsible for optimization issues, such as selecting the identities
 * to lookup, ensuring the cache doesn't contain them already, and adding the returned
 * elements to the cache etc.
 * <p>
 * This subclass is required to return fully valid <code>Acl</code>s, including
 * properly-configured parent ACLs.
 *
 */
private Map<ObjectIdentity, Acl> lookupObjectIdentities(final Collection<ObjectIdentity> objectIdentities,
        List<Sid> sids) {
    Assert.notEmpty(objectIdentities, "Must provide identities to lookup");

    final Map<Serializable, Acl> acls = new HashMap<>(); // contains
    // Acls
    // with
    // StubAclParents

    // Make the "acls" map contain all requested objectIdentities
    // (including markers to each parent in the hierarchy)
    String sql = computeRepeatingSql(lookupObjectIdentitiesWhereClause, objectIdentities.size());

    Set<Long> parentsToLookup = jdbcTemplate.query(sql, new PreparedStatementSetter() { // NOSONAR
        @Override
        public void setValues(PreparedStatement ps) throws SQLException {
            int i = 0;
            for (ObjectIdentity oid : objectIdentities) {
                // Determine prepared statement values for this iteration
                String type = oid.getType();

                // No need to check for nulls, as guaranteed non-null by
                // ObjectIdentity.getIdentifier() interface contract
                String identifier = oid.getIdentifier().toString();
                // Changed by Christian Bremer (cbr)
                //long id = (Long.valueOf(identifier)).longValue(); // NOSONAR

                // Inject values
                //ps.setString((2 * i) + 1, id); // NOSONAR
                ps.setString((2 * i) + 1, identifier);
                ps.setString((2 * i) + 2, type);
                i++;
            }
        }
    }, new ProcessResultSet(acls, sids));

    // Lookup the parents, now that our JdbcTemplate has released the database
    // connection (SEC-547)
    if (!parentsToLookup.isEmpty()) {
        lookupPrimaryKeys(acls, parentsToLookup, sids);
    }

    // Finally, convert our "acls" containing StubAclParents into true Acls
    Map<ObjectIdentity, Acl> resultMap = new HashMap<>();

    for (Acl inputAcl : acls.values()) {
        Assert.isInstanceOf(AclImpl.class, inputAcl, "Map should have contained an AclImpl");
        Assert.isInstanceOf(Long.class, ((AclImpl) inputAcl).getId(), "Acl.getId() must be Long");

        Acl result = convert(acls, (Long) ((AclImpl) inputAcl).getId());
        resultMap.put(result.getObjectIdentity(), result);
    }

    return resultMap;
}

From source file:org.bremersee.common.security.acls.jdbc.BasicLookupStrategy.java

/**
 * The final phase of converting the <code>Map</code> of <code>AclImpl</code>
 * instances which contain <code>StubAclParent</code>s into proper, valid
 * <code>AclImpl</code>s with correct ACL parents.
 *
 * @param inputMap the unconverted <code>AclImpl</code>s
 * @param currentIdentity the current<code>Acl</code> that we wish to convert (this
 * may be/*from   w w w .j a  v a 2  s  .com*/
 *
 */
private AclImpl convert(Map<Serializable, Acl> inputMap, Long currentIdentity) {
    Assert.notEmpty(inputMap, "InputMap required");
    Assert.notNull(currentIdentity, "CurrentIdentity required");

    // Retrieve this Acl from the InputMap
    Acl uncastAcl = inputMap.get(currentIdentity);
    Assert.isInstanceOf(AclImpl.class, uncastAcl, "The inputMap contained a non-AclImpl");

    AclImpl inputAcl = (AclImpl) uncastAcl;

    Acl parent = inputAcl.getParentAcl();

    if ((parent != null) && parent instanceof StubAclParent) {
        // Lookup the parent
        StubAclParent stubAclParent = (StubAclParent) parent;
        parent = convert(inputMap, stubAclParent.getId());
    }

    // Now we have the parent (if there is one), create the true AclImpl
    AclImpl result = new AclImpl(inputAcl.getObjectIdentity(), inputAcl.getId(), aclAuthorizationStrategy,
            grantingStrategy, parent, null, inputAcl.isEntriesInheriting(), inputAcl.getOwner());

    // Copy the "aces" from the input to the destination

    // Obtain the "aces" from the input ACL
    List<AccessControlEntryImpl> aces = readAces(inputAcl);

    // Create a list in which to store the "aces" for the "result" AclImpl instance
    List<AccessControlEntryImpl> acesNew = new ArrayList<>();

    // Iterate over the "aces" input and replace each nested
    // AccessControlEntryImpl.getAcl() with the new "result" AclImpl instance
    // This ensures StubAclParent instances are removed, as per SEC-951
    for (AccessControlEntryImpl ace : aces) {
        setAclOnAce(ace, result);
        acesNew.add(ace);
    }

    // Finally, now that the "aces" have been converted to have the "result" AclImpl
    // instance, modify the "result" AclImpl instance
    setAces(result, acesNew);

    return result;
}

From source file:com.wavemaker.tools.project.LocalStudioFileSystem.java

public static void setWaveMakerHome(Resource wmHome) throws FileAccessException {
    Assert.isInstanceOf(FileSystemResource.class, wmHome, "Expected a FileSystemResource");

    try {//  w  ww.ja  v  a 2s . com
        ConfigurationStore.setVersionedPreference(LocalStudioConfiguration.class, WMHOME_KEY,
                wmHome.getFile().getCanonicalPath());
    } catch (IOException ex) {
        throw new WMRuntimeException(ex);
    }

    if (!wmHome.exists()) {
        ((FileSystemResource) wmHome).getFile().mkdirs();
    }
}

From source file:com.wavemaker.tools.project.LocalStudioFileSystem.java

@Override
public Resource createPath(Resource resource, String path) {
    Assert.isInstanceOf(FileSystemResource.class, resource, "Expected a FileSystemResource");
    try {/* w w w. j a  v a2  s . c om*/
        if (!resource.exists()) {
            File rootFile = resource.getFile();
            while (rootFile.getAbsolutePath().length() > 1 && !rootFile.exists()) {
                rootFile = rootFile.getParentFile();
            }
            IOUtils.makeDirectories(resource.getFile(), rootFile);
        }
        FileSystemResource relativeResource = (FileSystemResource) resource.createRelative(path);
        if (!relativeResource.exists()) {
            if (relativeResource.getPath().endsWith("/")) {
                IOUtils.makeDirectories(relativeResource.getFile(), resource.getFile());
            } else {
                IOUtils.makeDirectories(relativeResource.getFile().getParentFile(), resource.getFile());
            }
        }
        return relativeResource;
    } catch (IOException ex) {
        throw new WMRuntimeException(ex);
    }
}

From source file:com.wavemaker.tools.project.LocalStudioFileSystem.java

@Override
public Resource copyFile(Resource root, InputStream source, String filePath) {
    Assert.isInstanceOf(FileSystemResource.class, root, "Expected a FileSystemResource");
    try {/* w w  w .j  a  v  a  2 s. c  om*/
        FileSystemResource targetFile = (FileSystemResource) root.createRelative(filePath);
        FileCopyUtils.copy(source, getOutputStream(targetFile));
        return targetFile;
    } catch (IOException ex) {
        throw new WMRuntimeException(ex);
    }
}

From source file:com.wavemaker.tools.project.LocalStudioFileSystem.java

@Override
public void rename(Resource oldResource, Resource newResource) {
    Assert.isInstanceOf(FileSystemResource.class, oldResource, "Expected a FileSystemResource");
    Assert.isInstanceOf(FileSystemResource.class, newResource, "Expected a FileSystemResource");
    try {/*from   w ww  .  j a va 2 s  .c o m*/
        oldResource.getFile().renameTo(newResource.getFile());
    } catch (IOException ex) {
        throw new WMRuntimeException(ex);
    }

}

From source file:com.wavemaker.tools.project.LocalStudioFileSystem.java

@Override
public boolean deleteFile(Resource resource) {
    Assert.isInstanceOf(FileSystemResource.class, resource, "Expected a FileSystemResource");
    FileSystemResource fileResource = (FileSystemResource) resource;
    if (fileResource.getFile().isDirectory()) {
        try {/*from  w w w .j  av a 2s . c o  m*/
            FileUtils.forceDelete(fileResource.getFile());
            return true;
        } catch (IOException ex) {
            throw new WMRuntimeException(ex);
        }
    } else {
        return fileResource.getFile().delete();
    }

}

From source file:de.hybris.platform.acceleratorservices.email.impl.DefaultEmailGenerationService.java

@Override
public EmailMessageModel generate(final BusinessProcessModel businessProcessModel,
        final EmailPageModel emailPageModel) throws RuntimeException {
    ServicesUtil.validateParameterNotNull(emailPageModel, "EmailPageModel cannot be null");
    Assert.isInstanceOf(EmailPageTemplateModel.class, emailPageModel.getMasterTemplate(),
            "MasterTemplate associated with EmailPageModel should be EmailPageTemplate");

    final EmailPageTemplateModel emailPageTemplateModel = (EmailPageTemplateModel) emailPageModel
            .getMasterTemplate();//from w w w . java2  s.  c  om
    final RendererTemplateModel bodyRenderTemplate = emailPageTemplateModel.getHtmlTemplate();
    Assert.notNull(bodyRenderTemplate,
            "HtmlTemplate associated with MasterTemplate of EmailPageModel cannot be null");
    final RendererTemplateModel subjectRenderTemplate = emailPageTemplateModel.getSubject();
    Assert.notNull(subjectRenderTemplate,
            "Subject associated with MasterTemplate of EmailPageModel cannot be null");

    final EmailMessageModel emailMessageModel;
    //This call creates the context to be used for rendering of subject and body templates.  
    final AbstractEmailContext<BusinessProcessModel> emailContext = getEmailContextFactory()
            .create(businessProcessModel, emailPageModel, bodyRenderTemplate);

    if (emailContext == null) {
        LOG.error("Failed to create email context for businessProcess [" + businessProcessModel + "]");
        throw new RuntimeException(
                "Failed to create email context for businessProcess [" + businessProcessModel + "]");
    } else {
        if (!validate(emailContext)) {
            LOG.error("Email context for businessProcess [" + businessProcessModel + "] is not valid: "
                    + ReflectionToStringBuilder.toString(emailContext));
            throw new RuntimeException("Email context for businessProcess [" + businessProcessModel
                    + "] is not valid: " + ReflectionToStringBuilder.toString(emailContext));
        }

        final StringWriter subject = new StringWriter();
        getRendererService().render(subjectRenderTemplate, emailContext, subject);

        final StringWriter body = new StringWriter();
        getRendererService().render(bodyRenderTemplate, emailContext, body);

        emailMessageModel = createEmailMessage(subject.toString(), body.toString(), emailContext);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Email Subject: " + emailMessageModel.getSubject());
            LOG.debug("Email Body: " + emailMessageModel.getBody());
        }

    }

    return emailMessageModel;
}

From source file:de.thm.arsnova.security.CustomBindAuthenticator.java

public DirContextOperations authenticate(Authentication authentication) {
    DirContextOperations user = null;/*from  ww  w .ja  v a2 s  .co  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);
    }

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

    return user;
}

From source file:de.thorstenberger.examServer.ws.remoteusermanager.HTTPAuthAuthenticationProvider.java

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

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

    if (!configManager.isStudentsLoginEnabled()) {
        throw new AuthenticationServiceException("Login disabled for student role.");
    }//  w  ww .j av a  2 s  .  c o m

    if (configManager.getHTTPAuthURL() != null && configManager.getHTTPAuthURL().length() > 0) {

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

        UserBean userBean;
        try {

            // verify url
            URL url = null;
            try {
                url = new URL(configManager.getHTTPAuthURL());
            } catch (final MalformedURLException e1) {
                throw new AuthenticationServiceException("URL-Error for HTTP-Auth.");
            }

            userBean = getRemoteUserInfos(url, username, password);

            if (!userBean.getRole().equals("student")) {
                throw new AuthenticationServiceException("Only student role allowed.");
            }

            try {

                userManager.getUserByUsername(userBean.getLogin());

            } catch (final UsernameNotFoundException e) {
                final User user = new User();
                user.setEnabled(true);
                user.setUsername(userBean.getLogin());
                user.setFirstName(userBean.getFirstName() == null ? "" : userBean.getFirstName());
                user.setLastName(userBean.getName() == null ? "" : userBean.getName());
                user.setEmail(userBean.getEmail() == null ? "" : userBean.getEmail());
                user.setPassword(StringUtil.encodePassword(userBean.getPassword(), "SHA"));
                user.addRole(roleManager.getRole("student"));
                try {
                    userManager.saveUser(user);
                } catch (final UserExistsException e2) {
                    // should not happen
                    throw new RuntimeException(e2);
                }
            }
        } catch (final AuthenticationServiceException e) {
            throw new BadCredentialsException(
                    messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials",
                            "Invalid username or password."));
        }

        final UserDetails userDetails = userManager.getUserByUsername(username);

        Object principalToReturn = userDetails;

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

        return createSuccessAuthentication(principalToReturn, authentication, userDetails);

    }

    return null;

}