KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > opencms > defaults > master > genericsql > CmsSqlManager


1 /*
2  * File : $Source: /usr/local/cvs/opencms/src-modules/com/opencms/defaults/master/genericsql/CmsSqlManager.java,v $
3  * Date : $Date: 2005/06/27 23:22:23 $
4  * Version: $Revision: 1.4 $
5  *
6  * This library is part of OpenCms -
7  * the Open Source Content Mananagement System
8  *
9  * Copyright (C) 2002 Alkacon Software (http://www.alkacon.com)
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19  * Lesser General Public License for more details.
20  *
21  * For further information about Alkacon Software, please see the
22  * company website: http://www.alkacon.com
23  *
24  * For further information about OpenCms, please see the
25  * project website: http://www.opencms.org
26  *
27  * You should have received a copy of the GNU Lesser General Public
28  * License along with this library; if not, write to the Free Software
29  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
30  */

31 package com.opencms.defaults.master.genericsql;
32
33 import org.opencms.db.CmsDbContext;
34 import org.opencms.db.CmsDbPool;
35 import org.opencms.file.CmsObject;
36 import org.opencms.file.CmsProject;
37 import org.opencms.main.CmsLog;
38 import org.opencms.util.CmsStringUtil;
39
40 import java.sql.Connection JavaDoc;
41 import java.sql.PreparedStatement JavaDoc;
42 import java.sql.ResultSet JavaDoc;
43 import java.sql.SQLException JavaDoc;
44 import java.sql.Statement JavaDoc;
45 import java.util.HashMap JavaDoc;
46 import java.util.Iterator JavaDoc;
47 import java.util.Properties JavaDoc;
48
49 /**
50  * A helper object to manage SQL queries. First, it loads key/value encoded SQL queries from a Java
51  * properties hash. Second, it has a set of methods to return JDBC connections and statements
52  * from different connection pools in the Cms dependent on the CmsProject/project-ID.
53  *
54  * <p>
55  *
56  * Things to know:
57  * <ul>
58  * <li>"name" parameters (e.g. "attributeName") identify an attribute in a table</li>
59  * <li>"key" parameters (e.g. "queryKey") identify a key in query.properties to receive a SQL or attribute name</li>
60  * </ul>
61  *
62  * @author Andreas Zahner
63  * @version $Revision: 1.4 $ $Date: 2005/06/27 23:22:23 $
64  *
65  * @deprecated Will not be supported past the OpenCms 6 release.
66  */

67 public class CmsSqlManager extends org.opencms.db.generic.CmsSqlManager {
68     
69     /** the query properties for the cos */
70     //private static Properties m_queries;
71

72     /**
73      * CmsSqlManager constructor
74      */

75     public CmsSqlManager(String JavaDoc dbPoolUrl, Class JavaDoc currentClass) {
76         
77         if (!dbPoolUrl.startsWith(CmsDbPool.DBCP_JDBC_URL_PREFIX)) {
78             dbPoolUrl = CmsDbPool.DBCP_JDBC_URL_PREFIX + dbPoolUrl;
79         }
80         m_poolUrl = dbPoolUrl;
81         
82         m_queries = new HashMap JavaDoc();
83         m_cachedQueries = new HashMap JavaDoc();
84         
85         loadQueries(currentClass);
86         combineQueries();
87         
88     }
89     
90     /**
91      * Loads recursively all query.properties from all packages of the
92      * superclasses. This method calls recursively itself with the superclass
93      * (if exists) as parameter.<p>
94      *
95      * @param the current Class of the dbaccess module.
96      */

97     protected void loadQueries(Class JavaDoc currentClass) {
98         
99         Properties JavaDoc properties = new Properties JavaDoc();
100         
101         // creates the queryFilenam from the packagename and
102
// filename query.properties
103
String JavaDoc className = currentClass.getName();
104         String JavaDoc queryFilename = className.substring(0, className.lastIndexOf('.'));
105         queryFilename = queryFilename.replace('.','/') + "/query.properties";
106         // gets the superclass and calls this method recursively
107
Class JavaDoc superClass = currentClass.getSuperclass();
108         if(superClass != java.lang.Object JavaDoc.class) {
109             loadQueries(superClass);
110         }
111         try {
112             // load the queries. Entries of the most recent class will overwrite
113
// entries of superclasses.
114
properties.load(getClass().getClassLoader().getResourceAsStream(queryFilename));
115             m_queries.putAll(properties);
116         } catch(Exception JavaDoc exc) {
117             // no query.properties found - write to logstream.
118
if(CmsLog.getLog(this).isErrorEnabled()) {
119                 CmsLog.getLog(this).error("Couldn't load " + queryFilename, exc);
120             }
121         }
122     }
123
124     /**
125      * Combines the queries in the properties to complete queries. Therefore a
126      * replacement is needed: The following Strings will be replaced
127      * automatically by the corresponding property-entrys:
128      * ${property_key}<p>
129      */

130     protected void combineQueries() {
131         Iterator JavaDoc keys = m_queries.keySet().iterator();
132         while(keys.hasNext()) {
133             String JavaDoc key = (String JavaDoc)keys.next();
134             // replace while there has been replacements performed
135
while(replace(key));
136         }
137     }
138     
139     /**
140      * Returns a JDBC connection from the connection pool.<p>
141      *
142      * @return a JDBC connection
143      * @throws SQLException if a database access error occurs
144      */

145     public Connection JavaDoc getConnection() throws SQLException JavaDoc {
146
147         return getConnection(0);
148     }
149     
150     /**
151      * @see org.opencms.db.generic.CmsSqlManager#getConnection(int)
152      */

153     public Connection JavaDoc getConnection(int projectId) throws SQLException JavaDoc {
154
155         return super.getConnection(projectId);
156     }
157     
158     /**
159      * Returns a JDBC connection from the connection pool.<p>
160      *
161      * @param project the project to get the connection for
162      *
163      * @return a JDBC connection
164      * @throws SQLException if a database access error occurs
165      */

166     public Connection JavaDoc getConnection(CmsProject project) throws SQLException JavaDoc {
167
168         return super.getConnection(project.getId());
169     }
170     
171     /**
172      * Computes one run of the replacement for one query.
173      * Stores the new value into m_queries.<p>
174      * @param key the key for the query to compute.
175      * @return true if in this run replacements are done.
176      */

177     protected boolean replace(String JavaDoc key) {
178         boolean retValue = false;
179         String JavaDoc value = (String JavaDoc)m_queries.get(key);
180         String JavaDoc newValue = new String JavaDoc();
181         int index = 0;
182         int lastIndex = 0;
183         // run as long as there are "${" strings found
184
while(index != -1) {
185             index = value.indexOf("${", lastIndex);
186             if(index != -1) {
187                 retValue = true;
188                 int nextIndex = value.indexOf('}', index);
189                 if(nextIndex != -1) {
190                     // get the replacer key
191
String JavaDoc replacer = value.substring(index+2, nextIndex);
192                     // copy the first part of the query
193
newValue += value.substring(lastIndex, index);
194                     // copy the replcement-value
195
String JavaDoc replacerStr = (String JavaDoc)m_queries.get(replacer);
196                     if (replacerStr == null) {
197                         replacerStr = "";
198                     }
199                     newValue += replacerStr;
200                     // set up lastindex
201
lastIndex = nextIndex+1;
202                 } else {
203                     // no key found, just copy the query-part
204
newValue += value.substring(lastIndex, index+2);
205                     // set up lastindex
206
lastIndex = index+2;
207                 }
208             } else {
209                 // end of the string, copy the tail into new value
210
newValue += value.substring(lastIndex);
211             }
212         }
213         // put back the new query to the queries
214
m_queries.put(key, newValue);
215         // returns true, if replacements were made in this run
216
return retValue;
217     }
218     
219     /**
220      * Creates a new connection and prepares a statement.<p>
221      *
222      * @param cms the CmsObject to get access to cms resources.
223      * @param conn the Connection to use.
224      * @param queryKey the key for the query to use.
225      */

226     public PreparedStatement JavaDoc sqlPrepare(CmsObject cms, Connection JavaDoc conn, String JavaDoc queryKey) throws SQLException JavaDoc {
227         return sqlPrepare(cms, conn, queryKey, null);
228     }
229
230     /**
231      * Replaces in a SQL statement $XXX tokens by strings and returns a prepared statement.<p>
232      *
233      * @param cms the current user's CmsObject instance
234      * @param conn the JDBC connection
235      * @param queryKey the name of the SQL statement (in query.properties)
236      * @param optionalSqlTokens a HashMap with optional SQL tokens to be replaced in the SQL statement
237      * @return a new PreparedStatement
238      * @throws SQLException
239      */

240     public PreparedStatement JavaDoc sqlPrepare(CmsObject cms, Connection JavaDoc conn, String JavaDoc queryKey, HashMap JavaDoc optionalSqlTokens) throws SQLException JavaDoc {
241         String JavaDoc statement = null;
242         String JavaDoc moduleMaster = "CMS_MODULE_MASTER";
243         String JavaDoc channelRel = "CMS_MODULE_CHANNEL_REL";
244         String JavaDoc media = "CMS_MODULE_MEDIA";
245
246         // get the string of the SQL statement
247
String JavaDoc statementStr = (String JavaDoc)m_queries.get(queryKey);
248         if(statementStr == null) {
249             statementStr = "";
250         }
251         statement = statementStr;
252
253         // choose the right tables depending on the online/offline project
254
if (cms.getRequestContext().currentProject().isOnlineProject()) {
255             moduleMaster = "CMS_MODULE_ONLINE_MASTER";
256             channelRel = "CMS_MODULE_ONLINE_CHANNEL_REL";
257             media = "CMS_MODULE_ONLINE_MEDIA";
258         }
259
260         // replace in the SQL statement the table names
261
statement = CmsStringUtil.substitute(statement, "$CMS_MODULE_MASTER", moduleMaster);
262         statement = CmsStringUtil.substitute(statement, "$CMS_MODULE_CHANNEL_REL", channelRel);
263         statement = CmsStringUtil.substitute(statement, "$CMS_MODULE_MEDIA", media);
264
265         // replace in the SQL statement further optional SQL tokens
266
if (optionalSqlTokens != null) {
267             Iterator JavaDoc optionalSqlKeys = optionalSqlTokens.keySet().iterator();
268             while (optionalSqlKeys.hasNext()) {
269                 String JavaDoc currentKey = (String JavaDoc) optionalSqlKeys.next();
270                 String JavaDoc currentValue = (String JavaDoc) optionalSqlTokens.get(currentKey);
271                 statement = CmsStringUtil.substitute(statement, currentKey, currentValue);
272             }
273         }
274         
275         return conn.prepareStatement(statement);
276     }
277     
278     /**
279      * Searches for the SQL query with the specified key.
280      *
281      * @param queryKey the SQL query key
282      * @return String the SQL query in this property list with the specified key
283      */

284     public String JavaDoc readQuery(String JavaDoc queryKey) {
285         String JavaDoc value = null;
286         if ((value = (String JavaDoc)m_queries.get(queryKey)) == null) {
287             if (CmsLog.getLog(this).isErrorEnabled()) {
288                 CmsLog.getLog(this).error("Query '" + queryKey + "' not found");
289             }
290         }
291         return value;
292     }
293     
294     /**
295      * @see org.opencms.db.generic.CmsSqlManager#closeAll(org.opencms.db.CmsDbContext, java.sql.Connection, java.sql.Statement, java.sql.ResultSet)
296      */

297     public void closeAll(CmsDbContext dbc, Connection JavaDoc con, Statement JavaDoc stmnt, ResultSet JavaDoc res) {
298
299         if (dbc == null) {
300             dbc = new CmsDbContext();
301         }
302         super.closeAll(dbc, con, stmnt, res);
303     }
304     
305 }
306
Popular Tags