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

host.anzo.core.startup.StartModule Maven / Gradle / Ivy

There is a newer version: 1.29
Show newest version
package host.anzo.core.startup;

import host.anzo.commons.utils.ClassUtils;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.stream.Stream;

/**
 * @author ANZO
 * @since 20.04.2018
 */
public class StartModule> {
	private final List> dependency = new ArrayList<>(0);
	private @Getter final Map> beforeMethods = new HashMap<>();
	private @Getter final Map> afterMethods = new HashMap<>();

	private @Getter final SL startLevel;
	private @Getter final Class clazz;
	private @Getter Object instance;

	public StartModule(SL startLevel, @NotNull Class clazz) {
		this.startLevel = startLevel;
		this.clazz = clazz;
		for (Method method : Stream.concat(Arrays.stream(clazz.getDeclaredMethods()), Arrays.stream(clazz.getSuperclass().getDeclaredMethods())).toList()) {
			if (method.isAnnotationPresent(StartupRun.class)) {
				final StartupRun startupRun = method.getAnnotation(StartupRun.class);
				if (!StringUtils.isEmpty(startupRun.after())) {
					afterMethods.computeIfAbsent(startupRun.after(), k -> new ArrayList<>()).add(new StartupMethodInfo(clazz, method, startupRun.isAsync()));
				}
				else if (!StringUtils.isEmpty(startupRun.before())) {
					beforeMethods.computeIfAbsent(startupRun.before(), k -> new ArrayList<>()).add(new StartupMethodInfo(clazz, method, startupRun.isAsync()));
				}
			}
		}
	}

	public void addDependency(StartModule module) {
		dependency.add(module);
	}

	public void init() {
		if(instance != null) {
			// Cannot allow to secondary init
			return;
		}

		for(StartModule depend : dependency) {
			depend.init();
		}

		instance = ClassUtils.singletonInstance(clazz);

		final Collection scheduledMethods = ClassUtils.getMethodsAnnotatedWith(clazz, Scheduled.class);
		for (Method scheduledMethod : scheduledMethods) {
			if (!Modifier.isPublic(scheduledMethod.getModifiers())) {
				throw new IllegalStateException("Method annotated with @Scheduled must be public!");
			}
			ScheduledService.getInstance().addScheduledMethod(clazz, scheduledMethod);
		}
	}

	@Override
	public String toString() {
		return clazz.getSimpleName();
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy