KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > pentaho > data > connection > sql > SQLConnection


1 /*
2  * Copyright 2006 Pentaho Corporation. All rights reserved.
3  * This software was developed by Pentaho Corporation and is provided under the terms
4  * of the Mozilla Public License, Version 1.1, or any later version. You may not use
5  * this file except in compliance with the license. If you need a copy of the license,
6  * please go to http://www.mozilla.org/MPL/MPL-1.1.txt. The Original Code is the Pentaho
7  * BI Platform. The Initial Developer is Pentaho Corporation.
8  *
9  * Software distributed under the Mozilla Public License is distributed on an "AS IS"
10  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
11  * the license for the specific language governing your rights and limitations.
12  *
13  * Created Aug 30, 2005
14  * @author wseyler
15  */

16 package org.pentaho.data.connection.sql;
17
18 import java.sql.Connection JavaDoc;
19 import java.sql.Driver JavaDoc;
20 import java.sql.DriverManager JavaDoc;
21 import java.sql.PreparedStatement JavaDoc;
22 import java.sql.ResultSet JavaDoc;
23 import java.sql.SQLException JavaDoc;
24 import java.sql.Statement JavaDoc;
25 import java.util.List JavaDoc;
26 import java.util.Properties JavaDoc;
27 import javax.sql.DataSource JavaDoc;
28 import org.pentaho.core.connection.IPentahoConnection;
29 import org.pentaho.core.connection.IPentahoResultSet;
30 import org.pentaho.core.util.DatasourceHelper;
31 import org.pentaho.messages.Messages;
32 import org.pentaho.util.logging.ILogger;
33
34 /**
35  * @author wseyler
36  *
37  * TODO To change the template for this generated type comment go to Window - Preferences - Java - Code Style - Code Templates
38  */

39 public class SQLConnection implements IPentahoConnection {
40   Connection JavaDoc nativeConnection;
41   /*
42    * private static int connectionCtr = 0;
43    */

44   // private int myCtr;
45
Statement JavaDoc stmt;
46   IPentahoResultSet sqlResultSet = null;
47   ILogger logger = null;
48   int maxRows = -1;
49   int fetchSize = -1;
50   /*
51    * private synchronized void bump() { connectionCtr++; }
52    */

53   String JavaDoc lastQuery = null;
54
55   /**
56    * @throws SQLException
57    *
58    */

59   public SQLConnection(Properties JavaDoc props, ILogger logger) {
60     super();
61     this.logger = logger;
62     connect(props);
63   }
64
65   public SQLConnection(String JavaDoc jndiName, ILogger logger) {
66     super();
67     this.logger = logger;
68     initWithJNDI(jndiName);
69   }
70
71   public SQLConnection(String JavaDoc driverName, String JavaDoc location, String JavaDoc userName, String JavaDoc password, ILogger logger) {
72     super();
73     this.logger = logger;
74     init(driverName, location, userName, password);
75   }
76
77   private void init(String JavaDoc driverName, String JavaDoc location, String JavaDoc userName, String JavaDoc password) {
78     // bump();
79
try {
80       /*
81        * TODO This is where we use the java.sql package to provide a SQL connection object back to the caller
82        */

83       Driver JavaDoc driver = null;
84       try {
85         driver = DriverManager.getDriver(location);
86       } catch (Exception JavaDoc e) {
87         // if we don't find this connection, it isn't registered, so we'll try to find it on the classpath
88
}
89       if (driver == null) {
90         Class JavaDoc driverClass = Class.forName(driverName);
91         driver = (Driver JavaDoc) driverClass.newInstance();
92         DriverManager.registerDriver(driver);
93       }
94       Properties JavaDoc info = new Properties JavaDoc();
95       info.put("user", userName); //$NON-NLS-1$
96
info.put("password", password); //$NON-NLS-1$
97
nativeConnection = driver.connect(location, info);
98       if (nativeConnection == null) {
99         logger.error(Messages.getErrorString("ConnectFactory.ERROR_0001_INVALID_CONNECTION2", driverName, location)); //$NON-NLS-1$
100
}
101     } catch (Throwable JavaDoc t) {
102       logger.error(Messages.getErrorString("ConnectFactory.ERROR_0001_INVALID_CONNECTION2", driverName, location), t); //$NON-NLS-1$
103
}
104   }
105
106   public boolean initialized() {
107     return nativeConnection != null;
108   }
109
110   private void initWithJNDI(String JavaDoc jndiName) {
111     // bump();
112
// myCtr = connectionCtr;
113
try {
114       DataSource JavaDoc dataSource = DatasourceHelper.getDataSourceFromJndi(jndiName);
115       if (dataSource != null) {
116         nativeConnection = dataSource.getConnection();
117         if (nativeConnection == null) {
118             logger.error(Messages.getErrorString("ConnectFactory.ERROR_0001_INVALID_CONNECTION", jndiName)); //$NON-NLS-1$
119
}
120       } else {
121         logger.error(Messages.getErrorString("ConnectFactory.ERROR_0001_INVALID_CONNECTION", jndiName)); //$NON-NLS-1$
122
}
123     } catch (Exception JavaDoc e) {
124       logger.error(Messages.getErrorString("ConnectFactory.ERROR_0001_INVALID_CONNECTION", jndiName), e); //$NON-NLS-1$
125
}
126   }
127
128   /*
129    * (non-Javadoc)
130    *
131    * @see org.pentaho.connection.IPentahoConnection#close()
132    */

133   public void close() {
134     closeStatement();
135     if (nativeConnection != null) {
136       try {
137         nativeConnection.close();
138       } catch (SQLException JavaDoc e) {
139         // TODO Auto-generated catch block
140
e.printStackTrace();
141       }
142     }
143     nativeConnection = null;
144   }
145
146   /*
147    * (non-Javadoc)
148    *
149    * @see org.pentaho.connection.IPentahoConnection#getLastQuery()
150    */

151   public String JavaDoc getLastQuery() {
152     return lastQuery;
153   }
154
155   /*
156    * (non-Javadoc)
157    *
158    * @see org.pentaho.connection.IPentahoConnection#executeQuery(java.lang.String)
159    */

160   public IPentahoResultSet executeQuery(String JavaDoc query) throws SQLException JavaDoc {
161     closeStatement();
162     // Create a statement for a scrollable resultset.
163
stmt = nativeConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
164     if (fetchSize > 0) {
165       stmt.setFetchSize(fetchSize);
166     }
167     if (maxRows != -1) {
168       stmt.setMaxRows(maxRows);
169     }
170     ResultSet JavaDoc resultSet = stmt.executeQuery(query);
171     sqlResultSet = new SQLResultSet(resultSet, this);
172     lastQuery = query;
173     return sqlResultSet;
174   }
175
176   public IPentahoResultSet prepareAndExecuteQuery(String JavaDoc query, List JavaDoc parameters) throws SQLException JavaDoc {
177     closeStatement();
178     // Create a prepared statement
179
PreparedStatement JavaDoc pStmt = nativeConnection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
180     stmt = pStmt;
181     if (fetchSize > 0) {
182       stmt.setFetchSize(fetchSize);
183     }
184     if (maxRows != -1) {
185       stmt.setMaxRows(maxRows);
186     }
187     
188     for (int i=0; i<parameters.size(); i++) {
189       pStmt.setObject(i+1, parameters.get(i));
190     }
191     ResultSet JavaDoc resultSet = pStmt.executeQuery();
192     sqlResultSet = new SQLResultSet(resultSet, this);
193     lastQuery = query;
194     return sqlResultSet;
195   }
196
197   public boolean preparedQueriesSupported() {
198     return true;
199   }
200   
201   /*
202    * (non-Javadoc)
203    *
204    * @see org.pentaho.connection.IPentahoConnection#isClosed()
205    */

206   public boolean isClosed() {
207     try {
208       return nativeConnection.isClosed();
209     } catch (SQLException JavaDoc e) {
210       // TODO Auto-generated catch block
211
e.printStackTrace();
212     }
213     return true; // assume since we couldn't get here if it
214
// was open then we must be closed.
215
}
216
217   /*
218    * (non-Javadoc)
219    *
220    * @see org.pentaho.connection.IPentahoConnection#isReadOnly()
221    *
222    * Right now this archetecture only support selects (read only)
223    */

224   public boolean isReadOnly() {
225     return true;
226   }
227
228   public void clearWarnings() {
229     try {
230       nativeConnection.clearWarnings();
231     } catch (SQLException JavaDoc e) {
232       // TODO Auto-generated catch block
233
e.printStackTrace();
234     }
235   }
236
237   private void closeStatement() {
238     if (stmt != null) {
239       try {
240         stmt.close();
241       } catch (Exception JavaDoc ignored) {
242       }
243     }
244     stmt = null;
245   }
246
247   public IPentahoResultSet getResultSet() {
248     return sqlResultSet;
249   }
250
251   public boolean connect(Properties JavaDoc props) {
252     close();
253     String JavaDoc jndiName = props.getProperty(IPentahoConnection.JNDI_NAME_KEY);
254     if (jndiName != null && jndiName.length() > 0) {
255       initWithJNDI(jndiName);
256     } else {
257       String JavaDoc driver = props.getProperty(IPentahoConnection.DRIVER_KEY);
258       String JavaDoc provider = props.getProperty(IPentahoConnection.LOCATION_KEY);
259       String JavaDoc userName = props.getProperty(IPentahoConnection.USERNAME_KEY);
260       String JavaDoc password = props.getProperty(IPentahoConnection.PASSWORD_KEY);
261       init(driver, provider, userName, password);
262       String JavaDoc query = props.getProperty(IPentahoConnection.QUERY_KEY);
263       if (query != null && query.length() > 0) {
264         try {
265           executeQuery(query);
266         } catch (SQLException JavaDoc e) {
267           // TODO Auto-generated catch block
268
e.printStackTrace();
269         }
270       }
271     }
272     return (nativeConnection != null && !isClosed());
273   }
274
275   public int execute(String JavaDoc query) throws SQLException JavaDoc {
276     closeStatement();
277     // Create a statement for a scrollable resultset.
278
stmt = nativeConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
279     int result = stmt.executeUpdate(query);
280     lastQuery = query;
281     return result;
282   }
283
284   /**
285    * @return Returns the nativeConnection.
286    */

287   public Connection JavaDoc getNativeConnection() {
288     return nativeConnection;
289   }
290
291   /**
292    * @return Returns the fetchSize.
293    */

294   public int getFetchSize() {
295     return fetchSize;
296   }
297
298   /**
299    * @param fetchSize
300    * The fetchSize to set.
301    */

302   public void setFetchSize(int fetchSize) {
303     this.fetchSize = fetchSize;
304   }
305
306   /**
307    * @return Returns the maxRows.
308    */

309   public int getMaxRows() {
310     return maxRows;
311   }
312
313   /**
314    * @param maxRows
315    * The maxRows to set.
316    */

317   public void setMaxRows(int maxRows) {
318     this.maxRows = maxRows;
319   }
320 }
321
Popular Tags