1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package net.sourceforge.addam.ddlrun.grammars;
20
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.net.URL;
24 import java.sql.Connection;
25 import java.sql.SQLException;
26 import java.util.Enumeration;
27 import java.util.Properties;
28
29 /**
30 * Used to get the correct grammar for a JDBC connection
31 *
32 * @author TIM3
33 * @since Mar 28, 2005
34 */
35 public class ScriptGrammarManager {
36
37 /**
38 * Constructor.
39 *
40 * @todo externalize the property filename in this method.
41 */
42 public ScriptGrammarManager() {
43
44 this("net/sourceforge/addam/ddlrun/grammars/ScriptGrammars.properties");
45 }
46
47 public ScriptGrammarManager(String resourceName) {
48 Enumeration resources;
49 try {
50 resources = ScriptGrammarManager.class.getClassLoader().getResources(resourceName);
51 } catch (IOException e) {
52 throw new RuntimeException("unable to load resource named " + resourceName, e);
53 }
54
55 if (!resources.hasMoreElements()) {
56 throw new RuntimeException("no such resource " + resourceName);
57 }
58
59 while (resources.hasMoreElements()) {
60 URL resource = (URL) resources.nextElement();
61 InputStream in = null;
62 try {
63 in = resource.openStream();
64 registry.load(in);
65 } catch (IOException e) {
66 throw new RuntimeException("unable to load resource " + resource, e);
67 } finally {
68 try {
69 if (in != null) {
70 in.close();
71 }
72 } catch (IOException e) {
73
74 throw new RuntimeException("unable to load resource " + resource, e);
75 }
76 }
77 }
78 }
79
80 public ScriptGrammarManager(Properties registry) {
81 this.registry.putAll(registry);
82 }
83
84 public ScriptGrammar getGrammar(Connection connection) {
85 String productName = null;
86 if (connection != null) {
87 try {
88 productName = connection.getMetaData().getDatabaseProductName();
89 } catch (SQLException e) {
90 throw new RuntimeException("unable to determine database product name", e);
91 }
92 }
93
94 ScriptGrammar grammar = null;
95 if (productName != null) {
96 String grammarClassName = registry.getProperty(productName);
97 if (grammarClassName != null) {
98 try {
99 grammar = (ScriptGrammar) Class.forName(grammarClassName).newInstance();
100 } catch (InstantiationException e) {
101 throw new RuntimeException("unable to instantiate: " + grammarClassName, e);
102 } catch (IllegalAccessException e) {
103 throw new RuntimeException("illegal access when instantiating: " + grammarClassName, e);
104 } catch (ClassNotFoundException e) {
105 throw new RuntimeException("class not found: " + grammarClassName, e);
106 }
107 }
108
109 }
110 return grammar;
111 }
112
113
114 Properties getGrammarRegistry() {
115
116 return new Properties(registry);
117 }
118
119 private final Properties registry = new Properties();
120 }