KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > freecs > auth > sqlConnectionPool > DbProperties


1 /**
2  * Copyright (C) 2003 Manfred Andres
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17  *
18  * Created on 04.05.2004
19  */

20
21 package freecs.auth.sqlConnectionPool;
22
23 import java.sql.ResultSet JavaDoc;
24 import java.sql.ResultSetMetaData JavaDoc;
25 import java.sql.SQLException JavaDoc;
26 import java.util.Enumeration JavaDoc;
27 import java.util.Properties JavaDoc;
28 import java.util.Vector JavaDoc;
29
30 import freecs.Server;
31
32 /**
33  * @author Manfred Andres
34  *
35  * freecs.auth.sqlConnectionPool
36  */

37 /**
38  * An instance of DbProperties represents a parsed and validated db-properties file
39  * @author Manfred Andres
40  *
41  * freecs.auth.sqlConnectionPool
42  */

43 public class DbProperties {
44     public boolean readOnly = false;
45     public String JavaDoc url, table, idField, fc_username, fc_password;
46     public String JavaDoc[] columns, names, updCols, updNames;
47     public Vector JavaDoc colV, nameV;
48     private boolean cachedMetaData=false;
49     public int[] types;
50     public Properties JavaDoc conProps = new Properties JavaDoc();
51     public int poolsize = 10, maxStmtPerCon = 1000, queryTimeout=0;
52     public long conTTL = 3600000;
53
54     /**
55      * Creates a new DbProperties-instance. All values are checked for
56      * validity. If properties are missing or invalid, an exception will
57      * be thrown.
58      * @param p db-properties
59      * @throws Exception if properties are missing or invalid
60      */

61     public DbProperties (Properties JavaDoc props, Properties JavaDoc mapping) throws Exception JavaDoc {
62
63         int err=0, warn=0;
64
65         colV = new Vector JavaDoc();
66         nameV = new Vector JavaDoc();
67
68         Vector JavaDoc updColV = new Vector JavaDoc();
69         Vector JavaDoc updNamV = new Vector JavaDoc();
70         
71         // try to load jdbc driver
72
try {
73             Class.forName (props.getProperty("driver"));
74         } catch (Exception JavaDoc ex) {
75             StringBuffer JavaDoc tsb = new StringBuffer JavaDoc ("Unable to load jdbc-driver '").append (props.getProperty("driver")).append ("'");
76             throw new Exception JavaDoc (tsb.toString (), ex);
77         }
78
79         StringBuffer JavaDoc warnMsg = new StringBuffer JavaDoc();
80
81         // copy/parse values from properties
82
table = props.getProperty("table");
83         url = props.getProperty("url");
84         queryTimeout = parseInt("queryTimeout", props.getProperty("queryTimeout"), 0, warnMsg);
85         poolsize = parseInt("poolsize", props.getProperty("poolsize"), 10, warnMsg);
86         maxStmtPerCon = parseInt("conStatements", props.getProperty("conStatements"), 1000, warnMsg);
87         conTTL = parseInt("conValidityTime", props.getProperty("conValidityTime"), 60, warnMsg);
88         conTTL = conTTL * 60000;
89         if ("true".equalsIgnoreCase(props.getProperty("readOnly")) ||
90             "1".equalsIgnoreCase(props.getProperty("readOnly"))) {
91             readOnly = true;
92         } else if ("false".equalsIgnoreCase(props.getProperty("readOnly")) ||
93             "0".equalsIgnoreCase(props.getProperty("readOnly"))) {
94             readOnly = false;
95         } else {
96             warnMsg.append (".) Readonly-Flag has unknown value (");
97             warnMsg.append (props.getProperty("readOnly"));
98             warnMsg.append ("). Defaulting to false.");
99         }
100         conProps.setProperty("user", props.getProperty("username"));
101         conProps.setProperty("password", props.getProperty("password"));
102
103         // then we copy the column-2-property-mappings
104
for (Enumeration JavaDoc e = mapping.keys(); e.hasMoreElements(); ) {
105             String JavaDoc key = (String JavaDoc) e.nextElement();
106             String JavaDoc val = mapping.getProperty(key);
107             if ("id".equalsIgnoreCase(key)) {
108                 idField = val;
109                 nameV.add(key);
110                 colV.add(val);
111             } else if ("username".equals(key)) {
112                 fc_username = val;
113             } else if ("password".equals(key)) {
114                 fc_password = val;
115             } else if (key.startsWith("db.")) {
116                 // further jdbc properties possible
117
conProps.setProperty(key.substring(3), val);
118             } else if (key.equalsIgnoreCase("userrights") && val.equalsIgnoreCase("serverconfig")) {
119                 continue;
120             } else {
121                 if ("chattime".equalsIgnoreCase(key)
122                     || "userrights".equalsIgnoreCase(key)
123                     || "color".equalsIgnoreCase(key)
124                     || "cookie".equalsIgnoreCase(key)
125                     // FIXME: why not load the friendslist etc?
126
/* || "friends".equalsIgnoreCase(key)
127                     || "notifyfriends".equalsIgnoreCase(key)
128                     || "extratitle".equalsIgnoreCase(key)
129                     || "blocked".equalsIgnoreCase(key) */
) {
130                     updNamV.add(key.toLowerCase());
131                     updColV.add(val);
132                 }
133                 nameV.add(key.toLowerCase());
134                 colV.add(val);
135             }
136         }
137
138         // and now we check the crucial values
139
StringBuffer JavaDoc errMsg = new StringBuffer JavaDoc();
140         if (table == null) {
141             err++;
142             errMsg.append (".) No tablename defined (SQLAuthenticator.table)\r\n");
143         }
144         if (url == null) {
145             errMsg.append (".) No URL to locate the database (SQLAuthenticator.url)\r\n");
146             err++;
147         }
148         if (fc_username==null || fc_password==null) {
149             errMsg.append (".) No columns given to check user-credentials for users logging in (username, password)\r\n");
150             err++;
151         }
152         if (!conProps.containsKey("user") || !conProps.containsKey("password")) {
153             errMsg.append (".) No connection-credentials given (SQLAuthenticator.mapping.username and SQLAuthenticator.mapping.password)\r\n");
154             err++;
155         }
156         if (warn>0) {
157             warnMsg.insert(0, "Encountered warnings:\r\n");
158             Server.log (this, warnMsg.toString (), Server.MSG_CONFIG, Server.LVL_MAJOR);
159         }
160         if (err>0) {
161             errMsg.insert(0, " errors:\r\n");
162             errMsg.insert(0, err);
163             errMsg.insert(0, "Encountered ");
164             throw new Exception JavaDoc (errMsg.toString ());
165         }
166         columns = (String JavaDoc[]) colV.toArray(new String JavaDoc[0]);
167         names = (String JavaDoc[]) nameV.toArray(new String JavaDoc[0]);
168         updCols = (String JavaDoc[]) updColV.toArray(new String JavaDoc[0]);
169         updNames = (String JavaDoc[]) updNamV.toArray(new String JavaDoc[0]);
170         if (Server.TRACE_CREATE_AND_FINALIZE)
171             Server.log (this, "++++++++++++++++++++++++++++++++++++++++CREATE", Server.MSG_STATE, Server.LVL_VERY_VERBOSE);
172     }
173
174     public String JavaDoc column4property (String JavaDoc prop) {
175         int idx = nameV.indexOf(prop);
176         if (idx == -1)
177             return null;
178         return columns[idx];
179     }
180     
181     public synchronized void cacheMetaData (ResultSet JavaDoc rs) throws SQLException JavaDoc {
182         if (cachedMetaData)
183             return;
184         Server.log(Thread.currentThread(), this.toString() + " cacheMetaData", Server.MSG_AUTH, Server.LVL_VERBOSE);
185         ResultSetMetaData JavaDoc rsm = rs.getMetaData();
186         Vector JavaDoc v = new Vector JavaDoc();
187         types = new int[rsm.getColumnCount()];
188         for (int i = 1; i < rsm.getColumnCount(); i++) {
189             types[i-1] = rsm.getColumnType(i);
190         }
191         cachedMetaData=true;
192     }
193     
194     public String JavaDoc toString() {
195         return "[DbProperties]";
196     }
197
198     public void finalize() {
199         if (Server.TRACE_CREATE_AND_FINALIZE)
200             Server.log(this, "----------------------------------------FINALIZED", Server.MSG_STATE, Server.LVL_VERY_VERBOSE);
201     }
202
203     /**
204      * helper method to parse and check string values from config into integers
205      * @param name name of property (used for logging)
206      * @param value value of property
207      * @param def default value
208      * @param logger stringbuffer for error messages
209      */

210     private int parseInt(String JavaDoc name, String JavaDoc value, int def, StringBuffer JavaDoc logger) {
211         try {
212             int i = Integer.parseInt(value);
213             if (i < 0) {
214                 logger.append (".) SQLAuthenticator." + name + " was set to a value below zero. Corrected to default of " + def + ".\r\n");
215                 return def;
216             } else {
217                 return i;
218             }
219         } catch (NumberFormatException JavaDoc nfe) {
220             logger.append (".) SQLAuthenticator." + name + " wasn't a number. Corrected to default of " + def + ".\r\n");
221             return def;
222         }
223     }
224
225 }
Popular Tags