All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.hibernate.validator.internal.util.privilegedactions.GetInstancesFromServiceLoader Maven / Gradle / Ivy

Go to download

JSR 380's RI, Hibernate Validator version ${hibernate-validator.version} and its dependencies repackaged as OSGi bundle

There is a newer version: 5.1.0
Show newest version
/*
 * Hibernate Validator, declare and validate application constraints
 *
 * License: Apache License, Version 2.0
 * See the license.txt file in the root directory or .
 */
package org.hibernate.validator.internal.util.privilegedactions;

import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;

/**
 * @author Guillaume Smet
 */
public class GetInstancesFromServiceLoader implements PrivilegedAction> {

	private final ClassLoader primaryClassLoader;

	private final Class clazz;

	private GetInstancesFromServiceLoader(ClassLoader primaryClassLoader, Class clazz) {
		this.primaryClassLoader = primaryClassLoader;
		this.clazz = clazz;
	}

	public static  GetInstancesFromServiceLoader action(ClassLoader primaryClassLoader, Class serviceClass) {
		return new GetInstancesFromServiceLoader( primaryClassLoader, serviceClass );
	}

	@Override
	public List run() {
		// Option #1: try the primary class loader first (either the thread context class loader or the external class
		// loader that has been defined)
		List instances = loadInstances( primaryClassLoader );

		// Option #2: if we cannot find any service files within the primary class loader, use the current class loader
		if ( instances.isEmpty() && GetInstancesFromServiceLoader.class.getClassLoader() != primaryClassLoader ) {
			instances = loadInstances( GetInstancesFromServiceLoader.class.getClassLoader() );
		}

		return instances;
	}

	private List loadInstances(ClassLoader classloader) {
		ServiceLoader loader = ServiceLoader.load( clazz, classloader );
		Iterator iterator = loader.iterator();
		List instances = new ArrayList();
		while ( iterator.hasNext() ) {
			try {
				instances.add( iterator.next() );
			}
			catch (ServiceConfigurationError e) {
				// ignore, because it can happen when multiple
				// services are present and some of them are not class loader
				// compatible with our API.
			}
		}
		return instances;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy