Search in sources :

Example 1 with ClassPathScanningCandidateComponentProvider

use of org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider in project opennms by OpenNMS.

the class Upgrade method getUpgradeObjects.

/**
     * Gets the upgrade objects.
     *
     * @return the upgrade objects
     * @throws OnmsUpgradeException the OpenNMS upgrade exception
     */
protected List<OnmsUpgrade> getUpgradeObjects() throws OnmsUpgradeException {
    List<OnmsUpgrade> upgrades = new ArrayList<OnmsUpgrade>();
    try {
        ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true);
        provider.addIncludeFilter(new AssignableTypeFilter(OnmsUpgrade.class));
        Set<BeanDefinition> components = provider.findCandidateComponents(getClassScope());
        for (BeanDefinition component : components) {
            if (component.isAbstract()) {
                continue;
            }
            Class<?> cls = Class.forName(component.getBeanClassName());
            if (cls.getAnnotation(Ignore.class) != null) {
                continue;
            }
            OnmsUpgrade upgrade = (OnmsUpgrade) cls.newInstance();
            upgrades.add(upgrade);
            log("Found upgrade task %s\n", upgrade.getId());
        }
        Collections.sort(upgrades, new OnmsUpgradeComparator());
    } catch (Exception e) {
        throw new OnmsUpgradeException("  Can't find the upgrade classes because: " + e.getMessage(), e);
    }
    return upgrades;
}
Also used : Ignore(org.opennms.upgrade.api.Ignore) ClassPathScanningCandidateComponentProvider(org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider) ArrayList(java.util.ArrayList) OnmsUpgrade(org.opennms.upgrade.api.OnmsUpgrade) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) OnmsUpgradeComparator(org.opennms.upgrade.api.OnmsUpgradeComparator) OnmsUpgradeException(org.opennms.upgrade.api.OnmsUpgradeException) OnmsUpgradeException(org.opennms.upgrade.api.OnmsUpgradeException) AssignableTypeFilter(org.springframework.core.type.filter.AssignableTypeFilter)

Example 2 with ClassPathScanningCandidateComponentProvider

use of org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider in project opennms by OpenNMS.

the class JaxbUtils method getClassForElement.

public static Class<?> getClassForElement(final String elementName) {
    if (elementName == null)
        return null;
    final Class<?> existing = m_elementClasses.get(elementName);
    if (existing != null)
        return existing;
    final ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
    scanner.addIncludeFilter(new AnnotationTypeFilter(XmlRootElement.class));
    for (final BeanDefinition bd : scanner.findCandidateComponents("org.opennms")) {
        final String className = bd.getBeanClassName();
        try {
            final Class<?> clazz = Class.forName(className);
            final XmlRootElement annotation = clazz.getAnnotation(XmlRootElement.class);
            if (annotation == null) {
                LOG.warn("Somehow found class {} but it has no @XmlRootElement annotation! Skipping.", className);
                continue;
            }
            if (elementName.equalsIgnoreCase(annotation.name())) {
                LOG.trace("Found class {} for element name {}", className, elementName);
                m_elementClasses.put(elementName, clazz);
                return clazz;
            }
        } catch (final ClassNotFoundException e) {
            LOG.warn("Unable to get class object from class name {}. Skipping.", className, e);
        }
    }
    return null;
}
Also used : AnnotationTypeFilter(org.springframework.core.type.filter.AnnotationTypeFilter) XmlRootElement(javax.xml.bind.annotation.XmlRootElement) ClassPathScanningCandidateComponentProvider(org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition)

Example 3 with ClassPathScanningCandidateComponentProvider

use of org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider in project camel by apache.

the class UnitTestCommand method executeTest.

@Override
public UnitTestResult executeTest(final ITestConfig config, String component) throws Exception {
    logger.info("Spring-Boot test configuration {}", config);
    Pattern pattern = Pattern.compile(config.getUnitTestInclusionPattern());
    logger.info("Scaning the classpath for test classes");
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
    scanner.addIncludeFilter(new RegexPatternTypeFilter(pattern));
    Set<BeanDefinition> defs = scanner.findCandidateComponents(config.getUnitTestBasePackage());
    List<String> testClasses = new LinkedList<>();
    for (BeanDefinition bd : defs) {
        testClasses.add(bd.getBeanClassName());
    }
    if (config.getUnitTestExclusionPattern() != null) {
        Pattern exclusionPattern = Pattern.compile(config.getUnitTestExclusionPattern());
        for (Iterator<String> it = testClasses.iterator(); it.hasNext(); ) {
            String cn = it.next();
            if (exclusionPattern.matcher(cn).matches()) {
                logger.warn("Excluding Test Class: {}", cn);
                it.remove();
            }
        }
    }
    final List<Class<?>> classes = new ArrayList<>();
    for (String cn : testClasses) {
        try {
            Class<?> clazz = Class.forName(cn);
            if (isAdmissible(clazz)) {
                logger.info("Found admissible test class: {}", cn);
                classes.add(clazz);
            }
        } catch (Throwable t) {
            logger.warn("Test class {} has thrown an exception during initialization", cn);
            logger.debug("Exception for test cass " + cn + " is:", t);
        }
    }
    logger.info("Run JUnit tests on {} test classes", classes.size());
    JUnitCore runner = new JUnitCore();
    runner.addListener(new RunListener() {

        @Override
        public void testStarted(Description description) throws Exception {
            disableJmx(config.getJmxDisabledNames());
        }
    });
    Result result = runner.run(classes.toArray(new Class[] {}));
    logger.info(config.getModuleName() + " unit tests. " + "Success: " + result.wasSuccessful() + " - Test Run: " + result.getRunCount() + " - Failures: " + result.getFailureCount() + " - Ignored Tests: " + result.getIgnoreCount());
    for (Failure f : result.getFailures()) {
        logger.warn("Failed test description: {}", f.getDescription());
        logger.warn("Message: {}", f.getMessage());
        if (f.getException() != null) {
            logger.warn("Exception thrown from test", f.getException());
        }
    }
    if (!result.wasSuccessful()) {
        Assert.fail("Some unit tests failed (" + result.getFailureCount() + "/" + result.getRunCount() + "), check the logs for more details");
    }
    if (result.getRunCount() == 0 && config.getUnitTestsExpectedNumber() == null) {
        Assert.fail("No tests have been found");
    }
    Integer expectedTests = config.getUnitTestsExpectedNumber();
    if (expectedTests != null && expectedTests != result.getRunCount()) {
        Assert.fail("Wrong number of tests: expected " + expectedTests + " found " + result.getRunCount());
    }
    return new UnitTestResult(result);
}
Also used : Pattern(java.util.regex.Pattern) Description(org.junit.runner.Description) JUnitCore(org.junit.runner.JUnitCore) ArrayList(java.util.ArrayList) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) RegexPatternTypeFilter(org.springframework.core.type.filter.RegexPatternTypeFilter) LinkedList(java.util.LinkedList) RunListener(org.junit.runner.notification.RunListener) Result(org.junit.runner.Result) ClassPathScanningCandidateComponentProvider(org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider) Failure(org.junit.runner.notification.Failure)

Example 4 with ClassPathScanningCandidateComponentProvider

use of org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider in project jOOQ by jOOQ.

the class JPADatabase method create0.

@SuppressWarnings("serial")
@Override
protected DSLContext create0() {
    if (connection == null) {
        String packages = getProperties().getProperty("packages");
        if (isBlank(packages)) {
            packages = "";
            log.warn("No packages defined", "It is highly recommended that you provide explicit packages to scan");
        }
        try {
            connection = DriverManager.getConnection("jdbc:h2:mem:jooq-meta-extensions", "sa", "");
            MetadataSources metadata = new MetadataSources(new StandardServiceRegistryBuilder().applySetting("hibernate.dialect", "org.hibernate.dialect.H2Dialect").applySetting("javax.persistence.schema-generation-connection", connection).applySetting(AvailableSettings.CONNECTION_PROVIDER, new ConnectionProvider() {

                @SuppressWarnings("rawtypes")
                @Override
                public boolean isUnwrappableAs(Class unwrapType) {
                    return false;
                }

                @Override
                public <T> T unwrap(Class<T> unwrapType) {
                    return null;
                }

                @Override
                public Connection getConnection() {
                    return connection;
                }

                @Override
                public void closeConnection(Connection conn) throws SQLException {
                }

                @Override
                public boolean supportsAggressiveRelease() {
                    return true;
                }
            }).build());
            ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
            scanner.addIncludeFilter(new AnnotationTypeFilter(Entity.class));
            // [#5845] Use the correct ClassLoader to load the jpa entity classes defined in the user project
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            for (String pkg : packages.split(",")) for (BeanDefinition def : scanner.findCandidateComponents(defaultIfBlank(pkg, "").trim())) metadata.addAnnotatedClass(Class.forName(def.getBeanClassName(), true, cl));
            // This seems to be the way to do this in idiomatic Hibernate 5.0 API
            // See also: http://stackoverflow.com/q/32178041/521799
            // SchemaExport export = new SchemaExport((MetadataImplementor) metadata.buildMetadata(), connection);
            // export.create(true, true);
            // Hibernate 5.2 broke 5.0 API again. Here's how to do this now:
            SchemaExport export = new SchemaExport();
            export.create(EnumSet.of(TargetType.DATABASE), metadata.buildMetadata());
        } catch (Exception e) {
            throw new DataAccessException("Error while exporting schema", e);
        }
    }
    return DSL.using(connection);
}
Also used : AnnotationTypeFilter(org.springframework.core.type.filter.AnnotationTypeFilter) Entity(javax.persistence.Entity) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) SQLException(java.sql.SQLException) MetadataSources(org.hibernate.boot.MetadataSources) Connection(java.sql.Connection) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) SQLException(java.sql.SQLException) DataAccessException(org.jooq.exception.DataAccessException) ConnectionProvider(org.hibernate.engine.jdbc.connections.spi.ConnectionProvider) ClassPathScanningCandidateComponentProvider(org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider) DataAccessException(org.jooq.exception.DataAccessException) SchemaExport(org.hibernate.tool.hbm2ddl.SchemaExport)

Example 5 with ClassPathScanningCandidateComponentProvider

use of org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider in project spring-boot by spring-projects.

the class EntityScanner method scan.

/**
	 * Scan for entities with the specified annotations.
	 * @param annotationTypes the annotation types used on the entities
	 * @return a set of entity classes
	 * @throws ClassNotFoundException if an entity class cannot be loaded
	 */
@SafeVarargs
public final Set<Class<?>> scan(Class<? extends Annotation>... annotationTypes) throws ClassNotFoundException {
    List<String> packages = getPackages();
    if (packages.isEmpty()) {
        return Collections.<Class<?>>emptySet();
    }
    Set<Class<?>> entitySet = new HashSet<>();
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
    scanner.setEnvironment(this.context.getEnvironment());
    scanner.setResourceLoader(this.context);
    for (Class<? extends Annotation> annotationType : annotationTypes) {
        scanner.addIncludeFilter(new AnnotationTypeFilter(annotationType));
    }
    for (String basePackage : packages) {
        if (StringUtils.hasText(basePackage)) {
            for (BeanDefinition candidate : scanner.findCandidateComponents(basePackage)) {
                entitySet.add(ClassUtils.forName(candidate.getBeanClassName(), this.context.getClassLoader()));
            }
        }
    }
    return entitySet;
}
Also used : AnnotationTypeFilter(org.springframework.core.type.filter.AnnotationTypeFilter) ClassPathScanningCandidateComponentProvider(org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) HashSet(java.util.HashSet)

Aggregations

ClassPathScanningCandidateComponentProvider (org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider)7 BeanDefinition (org.springframework.beans.factory.config.BeanDefinition)6 AnnotationTypeFilter (org.springframework.core.type.filter.AnnotationTypeFilter)4 ArrayList (java.util.ArrayList)2 ManagedConnector (com.evolveum.midpoint.provisioning.ucf.api.ManagedConnector)1 ObjectNotFoundException (com.evolveum.midpoint.util.exception.ObjectNotFoundException)1 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)1 Connection (java.sql.Connection)1 SQLException (java.sql.SQLException)1 HashSet (java.util.HashSet)1 LinkedList (java.util.LinkedList)1 Pattern (java.util.regex.Pattern)1 Entity (javax.persistence.Entity)1 XmlRootElement (javax.xml.bind.annotation.XmlRootElement)1 MetadataSources (org.hibernate.boot.MetadataSources)1 StandardServiceRegistryBuilder (org.hibernate.boot.registry.StandardServiceRegistryBuilder)1 ConnectionProvider (org.hibernate.engine.jdbc.connections.spi.ConnectionProvider)1 SchemaExport (org.hibernate.tool.hbm2ddl.SchemaExport)1 DataAccessException (org.jooq.exception.DataAccessException)1 Description (org.junit.runner.Description)1