1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 package org.sovt.xml;
29
30 import org.apache.commons.digester.Digester;
31 import org.sovt.impl.GroupInspector;
32 import org.sovt.impl.PropertySelector;
33
34 import java.io.IOException;
35 import java.io.InputStream;
36 import java.net.URL;
37
38 /***
39 * This is class for loading SOVT XML libraries.
40 *
41 * @author Vilmantas Baranauskas (vilmantas_baranauskas@yahoo.com)
42 */
43 public final class Loader {
44
45
46
47 /***
48 * Hide constructor in utility class. It should be never used.
49 */
50 private Loader() {
51 }
52
53
54 /***
55 * Loads SOVT library from given URL.
56 *
57 * @param url URL of the library to load.
58 * @throws InstantiationException if Cannot load given library.
59 */
60 public static synchronized void loadLibrary(
61 URL url
62 ) throws InstantiationException {
63 Digester digester = new Digester();
64 InputStream in = null;
65 try {
66 in = url.openStream();
67 digester.addObjectCreate("sovt", GroupInspector.class);
68 digester.addFactoryCreate("*/validator", new ValidatorFactory());
69 digester.addSetProperties("*/validator");
70 digester.addSetNext("*/validator", "addValidator");
71
72 digester.addFactoryCreate("*/transformer", new TransformerFactory());
73 digester.addSetProperties("*/transformer");
74 digester.addSetNext("*/transformer", "addTransformer");
75
76 digester.addFactoryCreate("*/inspector", new InspectorFactory());
77 digester.addSetProperties("*/inspector");
78 digester.addSetNext("*/inspector", "addInspector");
79
80 addPropertyRules(digester, "*/inspector", "addInspector");
81 addPropertyRules(digester, "*/property", "addInspector");
82 addPropertyRules(digester, "*/transformer", "addTransformer");
83 addPropertyRules(digester, "*/validator", "addValidator");
84
85 digester.parse(in);
86
87 } catch (Exception ex) {
88 ex.printStackTrace();
89 throw new InstantiationException(
90 "Cannot load file [" + url.toString() + "]"
91 );
92 } finally {
93 try {
94 if (in != null) {
95 in.close();
96 }
97 } catch (IOException e) {
98
99 }
100 }
101 }
102
103
104 private static void addPropertyRules(Digester digester, String prefix,
105 String setNext) {
106 digester.addObjectCreate(prefix + "/property", PropertySelector.class);
107 digester.addSetProperties(prefix + "/property");
108 if (setNext != null) {
109 digester.addSetNext(prefix + "/property", setNext);
110 }
111 }
112
113 /***
114 * Loads SOVT library from given file.
115 *
116 * @param libraryFileName Name of the library file.
117 * @throws InstantiationException if Cannot load given library.
118 */
119 public static void loadLibrary(
120 String libraryFileName
121 ) throws InstantiationException {
122 URL url = Loader.class.getClassLoader().getResource(
123 libraryFileName
124 );
125 if (url == null) {
126 throw new InstantiationException(
127 "No such file [" + libraryFileName + "]"
128 );
129 }
130 loadLibrary(url);
131 }
132 }