11package com .marginallyclever .nodegraphcore ;
22
33import org .json .JSONException ;
4+ import org .reflections .Reflections ;
45import org .slf4j .Logger ;
56import org .slf4j .LoggerFactory ;
67
7- import java .util .HashMap ;
8- import java .util .Map ;
9- import java .util .ServiceLoader ;
10- import java .util .Set ;
8+ import java .lang .reflect .InvocationTargetException ;
9+ import java .util .*;
1110
1211/**
1312 * Maintains a map of Classes and their {@link DAO4JSON}.
@@ -40,7 +39,9 @@ public static void registerDAO(DAO4JSON<?> dao) {
4039 */
4140 public static Object toJSON (Class <?> aClass ,Object object ) throws JSONException {
4241 DAO4JSON <?> dao = daoRegistry .get (aClass );
43- if (dao ==null ) throw new JSONException ("no DAO for " +aClass .getName ());
42+ if (dao ==null ) {
43+ throw new JSONException ("no DAO for " +aClass .getName ());
44+ }
4445 return dao .toJSON (object );
4546 }
4647
@@ -71,7 +72,6 @@ public static void loadRegistries() {
7172 loadRegistries (helper .getExtensionClassLoader ());
7273 }
7374
74-
7575 public static void loadRegistries (ClassLoader classLoader ) {
7676 ServiceLoader <DAORegistry > serviceLoader = ServiceLoader .load (DAORegistry .class , classLoader );
7777 for (DAORegistry registry : serviceLoader ) {
@@ -88,4 +88,28 @@ public static String[] getNames() {
8888 }
8989 return names ;
9090 }
91+
92+ public static void registerAllDAOInPackage (String packageName ) throws GraphException {
93+ // Use Reflections to find all subtypes of Node in the package
94+ Reflections reflections = new Reflections (packageName );
95+ Set <Class <? extends DAO4JSON >> subTypes = reflections .getSubTypesOf (DAO4JSON .class );
96+ var list = new ArrayList <>();
97+ subTypes .stream ().sorted (Comparator .comparing (Class ::getName )).forEach (typeFound ->{
98+ if (!typeFound .getName ().startsWith (packageName )) return ;
99+ list .add (typeFound .getName ().substring (packageName .length () + 1 ));
100+ });
101+ String str = packageName + " contains DAO " + Arrays .toString (list .toArray ());
102+ logger .info (str );
103+
104+ for (var typeFound : subTypes ) {
105+ if (!typeFound .getName ().startsWith (packageName )) continue ;
106+
107+ try {
108+ DAO4JSON <?> daoInstance = typeFound .getDeclaredConstructor ().newInstance ();
109+ registerDAO (daoInstance );
110+ } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e ) {
111+ throw new GraphException ("Failed to register DAO: " + typeFound .getName (), e );
112+ }
113+ }
114+ }
91115}
0 commit comments