KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > servicemix > components > jdbc > JdbcComponent


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

17 package org.apache.servicemix.components.jdbc;
18
19 import org.apache.servicemix.MessageExchangeListener;
20 import org.apache.servicemix.components.util.TransformComponentSupport;
21 import org.apache.servicemix.jbi.jaxp.SourceTransformer;
22 import org.apache.servicemix.jbi.jaxp.StringSource;
23 import org.apache.commons.logging.LogFactory;
24 import org.apache.commons.logging.Log;
25 import org.apache.xpath.CachedXPathAPI;
26 import org.w3c.dom.Node JavaDoc;
27
28 import javax.jbi.messaging.MessageExchange;
29 import javax.jbi.messaging.MessagingException;
30 import javax.jbi.messaging.NormalizedMessage;
31 import javax.sql.DataSource JavaDoc;
32 import javax.xml.transform.Source JavaDoc;
33 import java.sql.Connection JavaDoc;
34 import java.sql.Statement JavaDoc;
35 import java.sql.ResultSet JavaDoc;
36 import java.sql.SQLException JavaDoc;
37 import java.sql.ResultSetMetaData JavaDoc;
38
39 public class JdbcComponent extends TransformComponentSupport implements MessageExchangeListener {
40     private static final Log log = LogFactory.getLog(JdbcComponent.class);
41
42     private DataSource JavaDoc dataSource;
43     private boolean responseRequired = false;
44
45     public boolean transform(MessageExchange exchange, NormalizedMessage in, NormalizedMessage out) throws MessagingException {
46         log.debug("Received a JDBC request. Datasource=" + dataSource + ", ResponseRequired=" + responseRequired);
47         Connection JavaDoc conn = null;
48         Statement JavaDoc stmt = null;
49         ResultSet JavaDoc rs = null;
50
51         try {
52
53             SourceTransformer domTransform = new SourceTransformer();
54             Node JavaDoc domNode = domTransform.toDOMNode(in);
55
56             // Return the exception message
57
// if (isExceptionXml(domNode)) {
58
// log.debug("Found an exception message: " + domNode);
59
// out.setContent(in.getContent());
60
// return true;
61
// }
62

63             String JavaDoc query = getQuery(domNode);
64             log.debug("Retrieved query: " + query);
65
66             conn = dataSource.getConnection();
67
68             stmt = conn.createStatement();
69
70             Source outMsg = null;
71             if (query != null && query.length() > 0) {
72                 if (stmt.execute(query)) {
73                     // Result is a ResultSet object
74
rs = stmt.getResultSet();
75
76                     log.debug("Formatting ResultSet: " + rs);
77                     outMsg = toXmlSource(rs);
78                 } else {
79                     int updateCount = stmt.getUpdateCount();
80                     if (updateCount > -1) {
81                         log.debug("Formatting UpdateCount: " + updateCount);
82                         // Result is an update count
83
outMsg = toXmlSource(updateCount);
84                     } else {
85                         log.debug("Formatting NoResult.");
86                         // Result is neither a result set nor an update count
87
outMsg = null;
88                     }
89                 }
90             }
91
92             if (outMsg != null) {
93                 // There is a valid response
94
log.debug("Response: " + domTransform.toString(outMsg));
95                 out.setContent(outMsg);
96                 return true;
97
98             } else if (responseRequired) {
99                 // Create an empty <sqlResult> element
100
log.debug("Response: Empty Response");
101                 out.setContent(toXmlSource());
102                 return true;
103
104             } else {
105                 log.debug("Response: No Response");
106                 // There is no valid response
107
return false;
108             }
109         } catch (Exception JavaDoc e) {
110             log.error("JDBC Component Exception: ", e);
111 // out.setContent(createExceptionXml(e));
112
// return true;
113
throw new MessagingException(e);
114         } finally {
115             if (rs != null) {
116                 try {
117                     rs.close();
118                 } catch (SQLException JavaDoc e) {
119                     // Ignore
120
}
121             }
122
123             if (stmt != null) {
124                 try {
125                     stmt.close();
126                 } catch (SQLException JavaDoc e) {
127                     // Ignore
128
}
129             }
130
131             if (conn != null) {
132                 try {
133                     conn.close();
134                 } catch (SQLException JavaDoc e) {
135                     // Ignore
136
}
137             }
138         }
139     }
140
141     public String JavaDoc getQuery(Node JavaDoc node) throws Exception JavaDoc {
142         CachedXPathAPI xpath = new CachedXPathAPI();
143
144         node = xpath.selectSingleNode(node, "sql/child::text()");
145
146         // First child should be <sql></sql> element
147
if (node == null) {
148             throw new IllegalStateException JavaDoc("Expecting <sql></sql> node. Found: " + node);
149         }
150
151         return node.getNodeValue();
152     }
153
154     public void setDataSource(DataSource JavaDoc ds) {
155         dataSource = ds;
156     }
157
158     public DataSource JavaDoc getDataSource() {
159         return dataSource;
160     }
161
162     /**
163      * If true, an empty <sqlResult> element is created and send as a response if there is no result
164      * @param val
165      */

166     public void setResponseRequired(boolean val) {
167         responseRequired = val;
168     }
169
170     public boolean getResponseRequired() {
171         return responseRequired;
172     }
173
174     protected Source toXmlSource(ResultSet JavaDoc rs) throws Exception JavaDoc {
175
176         ResultSetMetaData JavaDoc meta = rs.getMetaData();
177         int colCount = meta.getColumnCount();
178
179         StringBuffer JavaDoc buff = new StringBuffer JavaDoc("");
180
181         while (rs.next()) {
182             buff.append("<row ");
183             for (int i=1; i<=colCount; i++) {
184                 String JavaDoc colName = meta.getColumnName(i);
185                 if (colName.equals("")) {
186                     colName = "__unknown_column__";
187                 }
188                 buff.append(colName.toLowerCase() + "='" + rs.getString(i) + "' ");
189             }
190             buff.append("/>");
191         }
192
193         if (buff.length() > 0) {
194             // If non-empty result, insert parent tags
195
buff.insert(0, "<sqlResult><resultSet>");
196             buff.append("</resultSet></sqlResult>");
197         } else {
198             // If empty result, return null source
199
return null;
200         }
201
202         return new StringSource(buff.toString());
203     }
204
205     protected Source toXmlSource(int updateCount) throws Exception JavaDoc {
206         return new StringSource("<sqlResult><updateCount value='" + updateCount + "'/></sqlResult>");
207     }
208
209     protected Source toXmlSource() throws Exception JavaDoc {
210         return new StringSource("<sqlResult></sqlResult>");
211     }
212
213
214     // Custom method to create and handle exception
215
/*
216     public boolean isExceptionXml(Node document) {
217         return document.getFirstChild().getNodeName().equalsIgnoreCase("exception");
218     }
219
220     public Source createExceptionXml(Throwable e) {
221         return new StringSource("<exception class='" + e.getClass() + "'>'" + e.getMessage() + "'</exception>");
222     } */

223 }
224
Popular Tags