use of org.openmrs.annotation.Handler in project openmrs-core by openmrs.
the class HandlerUtil method getHandlersForType.
/**
* Retrieves a List of all registered components from the Context that are of the passed
* handlerType and one or more of the following is true:
* <ul>
* <li>The handlerType is annotated as a {@link Handler} that supports the passed type</li>
* <li>The passed type is null - this effectively returns all components of the passed
* handlerType</li>
* </ul>
* The returned handlers are ordered in the list based upon the order property.
*
* @param handlerType Indicates the type of class to return
* @param type Indicates the type that the given handlerType must support (or null for any)
* @return a List of all matching Handlers for the given parameters, ordered by Handler#order
* @should return a list of all classes that can handle the passed type
* @should return classes registered in a module
* @should return an empty list if no classes can handle the passed type
*/
public static <H, T> List<H> getHandlersForType(Class<H> handlerType, Class<T> type) {
List<?> list = cachedHandlers.get(new Key(handlerType, type));
if (list != null) {
return (List<H>) list;
}
List<H> handlers = new ArrayList<>();
// First get all registered components of the passed class
log.debug("Getting handlers of type " + handlerType + (type == null ? "" : " for class " + type.getName()));
for (H handler : Context.getRegisteredComponents(handlerType)) {
Handler handlerAnnotation = handler.getClass().getAnnotation(Handler.class);
// Only consider those that have been annotated as Handlers
if (handlerAnnotation != null) {
// If no type is passed in return all handlers
if (type == null) {
log.debug("Found handler " + handler.getClass());
handlers.add(handler);
} else // Otherwise, return all handlers that support the passed type
{
for (int i = 0; i < handlerAnnotation.supports().length; i++) {
Class<?> clazz = handlerAnnotation.supports()[i];
if (clazz.isAssignableFrom(type)) {
log.debug("Found handler: " + handler.getClass());
handlers.add(handler);
}
}
}
}
}
// Return the list of handlers based on the order specified in the Handler annotation
handlers.sort(Comparator.comparing(o -> getOrderOfHandler(o.getClass())));
Map<Key, List<?>> newCachedHandlers = new WeakHashMap<>(cachedHandlers);
newCachedHandlers.put(new Key(handlerType, type), handlers);
cachedHandlers = newCachedHandlers;
return handlers;
}
Aggregations