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;
}
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;
}
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);
}
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);
}
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;
}
Aggregations