KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > acting > DatabaseSelectAction


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.apache.cocoon.acting;
17
18 import org.apache.avalon.excalibur.datasource.DataSourceComponent;
19 import org.apache.avalon.framework.configuration.Configuration;
20 import org.apache.avalon.framework.configuration.ConfigurationException;
21 import org.apache.avalon.framework.parameters.Parameters;
22 import org.apache.avalon.framework.thread.ThreadSafe;
23 import org.apache.cocoon.Constants;
24 import org.apache.cocoon.ProcessingException;
25 import org.apache.cocoon.environment.ObjectModelHelper;
26 import org.apache.cocoon.environment.Redirector;
27 import org.apache.cocoon.environment.Request;
28 import org.apache.cocoon.environment.SourceResolver;
29 import org.apache.commons.lang.StringUtils;
30
31 import java.sql.Connection JavaDoc;
32 import java.sql.PreparedStatement JavaDoc;
33 import java.sql.ResultSet JavaDoc;
34 import java.sql.SQLException JavaDoc;
35 import java.util.HashMap JavaDoc;
36 import java.util.Map JavaDoc;
37
38 /**
39  * Select a record from a database. If request parameters are present,
40  * their values are used to populate request attributes. Otherwise,
41  * values from database are used.
42  *
43  * @author <a HREF="mailto:bloritsch@apache.org">Berin Loritsch</a>
44  * @author <a HREF="mailto:vgritsenko@apache.org">Vadim Gritsenko</a>
45  * @version CVS $Id: DatabaseSelectAction.java 30932 2004-07-29 17:35:38Z vgritsenko $
46  */

47 public class DatabaseSelectAction extends AbstractDatabaseAction implements ThreadSafe {
48
49     private static final Map JavaDoc selectStatements = new HashMap JavaDoc();
50
51     /**
52      * Select a record from the database. This action assumes that
53      * the file referenced by the "descriptor" parameter conforms
54      * to the AbstractDatabaseAction specifications.
55      */

56     public Map JavaDoc act(Redirector redirector, SourceResolver resolver, Map JavaDoc objectModel, String JavaDoc source, Parameters param) throws Exception JavaDoc {
57         DataSourceComponent datasource = null;
58         Connection JavaDoc conn = null;
59         int currentIndex = 0;
60
61         // read global parameter settings
62
boolean reloadable = Constants.DESCRIPTOR_RELOADABLE_DEFAULT;
63         if (this.settings.containsKey("reloadable"))
64             reloadable = Boolean.valueOf((String JavaDoc) this.settings.get("reloadable")).booleanValue();
65         // read local parameter settings
66
try {
67             Configuration conf =
68                 this.getConfiguration(param.getParameter("descriptor", (String JavaDoc) this.settings.get("descriptor")),
69                                       resolver,
70                                       param.getParameterAsBoolean("reloadable",reloadable));
71
72             Request request = ObjectModelHelper.getRequest(objectModel);
73
74             Configuration[] keys = conf.getChild("table").getChild("keys").getChildren("key");
75             Configuration[] values = conf.getChild("table").getChild("values").getChildren("value");
76
77             PreparedStatement JavaDoc statement = null;
78             ResultSet JavaDoc rset = null;
79             boolean result = false;
80
81             for (int i = 0; i < keys.length; i++) {
82                 final String JavaDoc parameter = keys[i].getAttribute("param");
83                 Object JavaDoc value = request.getParameter(parameter);
84                 if (StringUtils.isEmpty((String JavaDoc)value)) {
85                     if (statement == null) {
86                         final String JavaDoc query = this.getSelectQuery(conf);
87                         datasource = this.getDataSource(conf);
88                         conn = datasource.getConnection();
89                         statement = conn.prepareStatement(query);
90                         currentIndex = 1;
91                         for (int j = 0; j < keys.length; j++, currentIndex++) {
92                             this.setColumn(statement, currentIndex, request, keys[j]);
93                         }
94                         rset = statement.executeQuery();
95                         result = rset.next();
96                     }
97                     if (result) {
98                         value = this.getColumn(rset, request, keys[i]);
99                     }
100                 }
101                 if (value != null) {
102                     request.setAttribute(parameter, value.toString());
103                 }
104             }
105
106             for (int i = 0; i < values.length; i++) {
107                 final String JavaDoc parameter = values[i].getAttribute("param");
108                 Object JavaDoc value = request.getParameter(parameter);
109                 if (StringUtils.isEmpty((String JavaDoc)value)) {
110                     if (statement == null) {
111                         final String JavaDoc query = this.getSelectQuery(conf);
112                         datasource = this.getDataSource(conf);
113                         conn = datasource.getConnection();
114                         statement = conn.prepareStatement(query);
115                         currentIndex = 1;
116                         for (int j = 0; j < keys.length; j++, currentIndex++) {
117                             this.setColumn(statement, currentIndex, request, keys[j]);
118                         }
119                         rset = statement.executeQuery();
120                         result = rset.next();
121                     }
122                     if (result) {
123                         value = this.getColumn(rset, request, values[i]);
124                     }
125                 }
126                 if (value != null) {
127                     request.setAttribute(parameter, value.toString());
128                 }
129             }
130             if(statement != null) {
131                 statement.close();
132             }
133             return EMPTY_MAP;
134         } catch (Exception JavaDoc e) {
135             throw new ProcessingException("Could not prepare statement :position = " + currentIndex, e);
136         } finally {
137             if (conn != null) {
138                 try {
139                     conn.close();
140                 } catch (SQLException JavaDoc sqe) {
141                     getLogger().warn("There was an error closing the datasource", sqe);
142                 }
143             }
144             if (datasource != null) {
145                 this.dbselector.release(datasource);
146             }
147         }
148
149         // Result is empty map or exception. No null.
150
}
151
152     /**
153      * Get the String representation of the PreparedStatement. This is
154      * mapped to the Configuration object itself, so if it doesn't exist,
155      * it will be created.
156      */

157     protected String JavaDoc getSelectQuery(Configuration conf) throws ConfigurationException {
158         String JavaDoc query = null;
159
160         synchronized (DatabaseSelectAction.selectStatements) {
161             query = (String JavaDoc)DatabaseSelectAction.selectStatements.get(conf);
162
163             if (query == null) {
164                 Configuration table = conf.getChild("table");
165                 Configuration[] keys = table.getChild("keys").getChildren("key");
166                 Configuration[] values = table.getChild("values").getChildren("value");
167
168                 StringBuffer JavaDoc queryBuffer = new StringBuffer JavaDoc("SELECT ");
169                 queryBuffer.append(buildList(keys, 0));
170                 queryBuffer.append(buildList(values, keys.length));
171                 queryBuffer.append(" FROM ");
172                 queryBuffer.append(table.getAttribute("name"));
173
174                 queryBuffer.append(" WHERE ");
175                 queryBuffer.append(buildList(keys, " AND "));
176                 query = queryBuffer.toString();
177
178                 DatabaseSelectAction.selectStatements.put(conf, query);
179             }
180         }
181         return query;
182     }
183 }
Popular Tags