ObjectBasedListenerObjectCreator.java

/*
 * Copyright (C) 2012-2024 RRiBbit.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.rribbit.creation;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.CopyOnWriteArrayList;

import org.rribbit.Listener;
import org.rribbit.ListenerObject;
import org.rribbit.creation.notification.ListenerObjectCreationObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This {@link ListenerObjectCreator} creates {@link ListenerObject}s from objects. Users can pass in {@link Object}s and this class will scan the {@link Object}'s
 * class and create {@link ListenerObject}s for the public methods that are annotated with {@link Listener}. This includes all public methods that are declared in superclasses.
 * <p />
 * Please note that in Java, method annotations are NOT inherited. This means that, if you override/implement a method in a subclass or subinterface, and the overriding/implementing method
 * does not have the annotation, then that method will not inherit it. If a class or interface just inherits a method, without overriding it, then the annotation WILL exist.
 * <p />
 * Subclasses of this class are required to call {@link #notifyObserversOnClassAdded(Class)} whenever a class is scanned and its listeners are created.
 *
 * @author G.J. Schouten
 *
 */
public class ObjectBasedListenerObjectCreator implements ListenerObjectCreator {

	private static final Logger log = LoggerFactory.getLogger(ObjectBasedListenerObjectCreator.class);

	/**
	 * Subclasses are recommended to use this {@link Collection} to store the {@link ListenerObject}s in.
	 */
	protected Collection<ListenerObject> listenerObjects;

	protected Collection<ListenerObjectCreationObserver> observers;

	/**
	 * Initializes the {@link Collection} of {@link ListenerObject}s and calls {@link #addObject(Object)} for each given {@link Object}.
	 *
	 * @param objects
	 */
	public ObjectBasedListenerObjectCreator(Object... objects) {

		listenerObjects = new CopyOnWriteArrayList<>();
		observers = new CopyOnWriteArrayList<>();

		for(Object object : objects) {
			this.addObject(object);
		}
	}

	/**
	 * Scans all public methods of the dynamic runtime {@link Class} of the given {@link Object} (the {@link Class} returned by {@link #getClass()}) and creates {@link ListenerObject}s
	 * for them if they have a {@link Listener} annotation, then initializes those {@link ListenerObject}s with the given {@link Object} as execution target.
	 *
	 * @param object
	 */
	public void addObject(Object object) {

		log.debug("Processing Object");
		Collection<ListenerObject> incompleteListenerObjects = this.getIncompleteListenerObjectsFromClass(object.getClass());
		for(ListenerObject listenerObject : incompleteListenerObjects) {
			listenerObject.setTarget(object);
		}
		listenerObjects.addAll(incompleteListenerObjects);
		this.notifyObserversOnClassAdded(object.getClass());
	}

	/**
	 * Scans all public methods in the given {@link Class}, including those inherited from superclasses / superinterfaces and creates {@link ListenerObject}s for them if they have a
	 * {@link Listener} annotation. These {@link ListenerObject} have their target {@link Object} NOT YET SET! This is the responsibility of the caller of this method.
	 *
	 * @param clazz	the class to scan
	 * @return a {@link Collection} of incomplete {@link ListenerObject}s that have their target {@link Object} not yet set.
	 */
	protected Collection<ListenerObject> getIncompleteListenerObjectsFromClass(Class<?> clazz) {

		Collection<ListenerObject> incompleteListenerObjects = new ArrayList<>();
		for(Method method : clazz.getMethods()) {
			Listener listener = method.getAnnotation(Listener.class);
			if(listener != null) {
				log.debug("Listener annotation found for method '{}', instantiating ListenerObject", method);
				ListenerObject listenerObject = new ListenerObject();
				listenerObject.setHints(Arrays.asList(listener.hint()));
				listenerObject.setMethod(method);
				listenerObject.setReturnType(method.getReturnType());
				incompleteListenerObjects.add(listenerObject);
			}
		}
		return incompleteListenerObjects;
	}

	/**
	 * Notifies all registered {@link ListenerObjectCreationObserver}s that a class is scanned and its listeners created.
	 *
	 * @param addedClass
	 */
	protected void notifyObserversOnClassAdded(Class<?> addedClass) {

		for(ListenerObjectCreationObserver listenerObjectCreationObserver : observers) {
			listenerObjectCreationObserver.onClassAdded(addedClass);
		}
	}

	@Override
	public Collection<ListenerObject> getListenerObjects() {
		return listenerObjects;
	}

	@Override
	public void registerObserver(ListenerObjectCreationObserver listenerObjectCreationObserver) {
		observers.add(listenerObjectCreationObserver);
	}
}