1 package nl.tudelft.jpacman.points;
2
3 import java.io.IOException;
4 import java.net.URL;
5 import java.net.URLClassLoader;
6 import java.util.Properties;
7
8 /**
9 * The responsibility of this loader is to obtain the appropriate points calculator.
10 * By default the {@link DefaultPointCalculator} is returned.
11 */
12 public class PointCalculatorLoader {
13
14 private static Class clazz = null;
15
16 /**
17 * Load a points calculator and return it.
18 *
19 * @return The (dynamically loaded) points calculator.
20 */
21 public PointCalculator load() {
22 try {
23 if (clazz == null) {
24 clazz = loadClassFromFile();
25 }
26
27 return (PointCalculator) clazz.newInstance();
28 } catch (Exception e) {
29 throw new RuntimeException("Could not dynamically load the points calculator.", e);
30 }
31 }
32
33 private Class loadClassFromFile() throws IOException, ClassNotFoundException {
34 String strategyToLoad = getCalculatorClassName();
35
36 if ("DefaultPointCalculator".equals(strategyToLoad)) {
37 return DefaultPointCalculator.class;
38 }
39
40 URL[] urls = new URL[]{getClass().getClassLoader().getResource("scoreplugins/")};
41
42 try (URLClassLoader classLoader = new URLClassLoader(urls, getClass().getClassLoader())) {
43 return classLoader.loadClass(strategyToLoad);
44 }
45 }
46
47 private String getCalculatorClassName() throws IOException {
48 Properties properties = new Properties();
49
50 properties.load(getClass().getClassLoader().getResourceAsStream("scorecalc.properties"));
51
52 return properties.getProperty("scorecalculator.name");
53 }
54 }