ReceiptNumberGeneratorFactory { public static IReceiptNumberGenerator[] locateGenerators() { Reflections reflections = new Reflections("org.openmrs.module"); List<Class<? extends IReceiptNumberGenerator>> classes = new ArrayList<Class<? extends IReceiptNumberGenerator>>(); for (Class<? extends IReceiptNumberGenerator> cls : reflections.getSubTypesOf(IReceiptNumberGenerator.class)) { if (!cls.isInterface() && !Modifier.isAbstract(cls.getModifiers()) && Modifier.isPublic(cls.getModifiers())) { classes.add(cls); } } List<IReceiptNumberGenerator> instances = new ArrayList<IReceiptNumberGenerator>(); for (Class<? extends IReceiptNumberGenerator> cls : classes) { if (generator != null && cls.equals(generator.getClass())) { instances.add(generator); } else { try { instances.add(cls.newInstance()); } catch (Exception ex) { LOG.warn("Could not instantiate the '" + cls.getName() + "' class. It will be ignored."); } } } IReceiptNumberGenerator[] results = new IReceiptNumberGenerator[instances.size()]; instances.toArray(results); return results; } protected  ReceiptNumberGeneratorFactory(); static IReceiptNumberGenerator getGenerator(); static void setGenerator(IReceiptNumberGenerator generator); static IReceiptNumberGenerator[] locateGenerators();  }
@Test public void locateGenerators_shouldLocateAllClassesThatImplementIReceiptNumberGenerator() throws Exception { IReceiptNumberGenerator[] generators = ReceiptNumberGeneratorFactory.locateGenerators(); Assert.assertNotNull(generators); Assert.assertTrue(generators.length >= 2); boolean foundTest1 = false, foundTest2 = false; for (IReceiptNumberGenerator generator : generators) { if (generator.getClass().equals(TestReceiptNumberGenerator.class)) { foundTest1 = true; } else if (generator.getClass().equals(AnotherTestReceiptNumberGenerator.class)) { foundTest2 = true; } if (foundTest1 && foundTest2) { break; } } Assert.assertTrue("Both of the two test receipt number generators were not located.", foundTest1 && foundTest2); }
@Test public void locateGenerators_shouldNotThrowAnExceptionIfTheClassInstantiationFails() throws Exception { IReceiptNumberGenerator[] generators = ReceiptNumberGeneratorFactory.locateGenerators(); Assert.assertNotNull(generators); Assert.assertTrue(generators.length >= 2); boolean foundInvalidGenerator = false; for (IReceiptNumberGenerator generator : generators) { if (generator.getClass().equals(InvalidReceiptNumberGenerator.class)) { foundInvalidGenerator = true; break; } } Assert.assertFalse("The invalid generator was unexpectedly located.", foundInvalidGenerator); }