KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opensubsystems > core > persist > db > oracle > OracleDatabaseImpl


1 /*
2  * Copyright (c) 2003 - 2007 OpenSubsystems s.r.o. Slovak Republic. All rights reserved.
3  *
4  * Project: OpenSubsystems
5  *
6  * $Id: OracleDatabaseImpl.java,v 1.7 2007/01/07 06:14:20 bastafidli Exp $
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; version 2 of the License.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20  */

21
22 package org.opensubsystems.core.persist.db.oracle;
23
24 import java.sql.CallableStatement JavaDoc;
25 import java.sql.Connection JavaDoc;
26 import java.sql.PreparedStatement JavaDoc;
27 import java.sql.SQLException JavaDoc;
28 import java.sql.Statement JavaDoc;
29 import java.util.Iterator JavaDoc;
30 import java.util.Map JavaDoc;
31 import java.util.logging.Level JavaDoc;
32 import java.util.logging.Logger JavaDoc;
33
34 import org.opensubsystems.core.data.BasicDataObject;
35 import org.opensubsystems.core.data.ModifiableDataObject;
36 import org.opensubsystems.core.error.OSSDatabaseAccessException;
37 import org.opensubsystems.core.error.OSSException;
38 import org.opensubsystems.core.persist.db.DatabaseConnectionFactoryImpl;
39 import org.opensubsystems.core.persist.db.DatabaseImpl;
40 import org.opensubsystems.core.persist.db.DatabaseTransactionFactoryImpl;
41 import org.opensubsystems.core.util.DatabaseUtils;
42 import org.opensubsystems.core.util.Log;
43
44 /**
45  * Management layer for Oracle database (www.oracle.com)
46  *
47  * @version $Id: OracleDatabaseImpl.java,v 1.7 2007/01/07 06:14:20 bastafidli Exp $
48  * @author Julo Legeny
49  * @code.reviewer Miro Halas
50  * @code.reviewed 1.2 2006/04/05 05:03:09 bastafidli
51  */

52 public class OracleDatabaseImpl extends DatabaseImpl
53 {
54    // Cached values ////////////////////////////////////////////////////////////
55

56    /**
57     * Logger for this class
58     */

59    private static Logger JavaDoc s_logger = Log.getInstance(OracleDatabaseImpl.class);
60
61    // Constructors /////////////////////////////////////////////////////////////
62

63    /**
64     * Default constructor for empty database.
65     *
66     * @throws OSSException - problem connecting to database
67     */

68    public OracleDatabaseImpl(
69    ) throws OSSException
70    {
71       super();
72    }
73    
74    // Database administration //////////////////////////////////////////////////
75

76    /**
77     * {@inheritDoc}
78     */

79    protected void createUser(
80       Connection JavaDoc cntAdminDBConnection
81    ) throws OSSException
82    {
83       // Now create the user
84
PreparedStatement JavaDoc pstmQuery = null;
85       try
86       {
87          // Oracle doesn't support creation of users using ?, we must immidiately
88
// specify name and password
89
/*
90          pstmQuery = cntAdminDBConnection.prepareStatement("create user ? password ?");
91          pstmQuery.setString(1, m_dcfConnectionFactory.getDatabaseUser());
92          pstmQuery.setString(2, m_dcfConnectionFactory.getDatabasePassword());
93          */

94          StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
95          
96          // create user and set him particular tablespace
97
buffer.append("CREATE USER ");
98          buffer.append(DatabaseConnectionFactoryImpl.getInstance().getDatabaseUser());
99          buffer.append(" PROFILE DEFAULT IDENTIFIED BY ");
100          buffer.append(DatabaseConnectionFactoryImpl.getInstance().getDatabasePassword());
101          buffer.append(" DEFAULT TABLESPACE USERS TEMPORARY TABLESPACE TEMP ACCOUNT UNLOCK ");
102
103          pstmQuery = cntAdminDBConnection.prepareStatement(buffer.toString());
104          if (pstmQuery.execute())
105          {
106             // Close any results
107
pstmQuery.getMoreResults(Statement.CLOSE_ALL_RESULTS);
108          }
109
110          // add grant for particular tablespaces to the current created user
111
buffer.delete(0, buffer.length());
112          buffer.append("ALTER USER ");
113          buffer.append(DatabaseConnectionFactoryImpl.getInstance().getDatabaseUser());
114          buffer.append(" QUOTA UNLIMITED ON USERS");
115
116          pstmQuery = cntAdminDBConnection.prepareStatement(buffer.toString());
117          if (pstmQuery.execute())
118          {
119             // Close any results
120
pstmQuery.getMoreResults(Statement.CLOSE_ALL_RESULTS);
121          }
122
123          // add grant for connecting user to the DB and creating procedures
124
buffer.delete(0, buffer.length());
125          buffer.append("GRANT CONNECT, CREATE PROCEDURE TO ");
126          buffer.append(DatabaseConnectionFactoryImpl.getInstance().getDatabaseUser());
127
128          pstmQuery = cntAdminDBConnection.prepareStatement(buffer.toString());
129          if (pstmQuery.execute())
130          {
131             // Close any results
132
pstmQuery.getMoreResults(Statement.CLOSE_ALL_RESULTS);
133          }
134
135          // At this point we don't know if this is just a single operation
136
// and we need to commit or if it is a part of bigger transaction
137
// and the commit is not desired until all operations proceed.
138
// Therefore let the DatabaseTransactionFactory resolve it
139
DatabaseTransactionFactoryImpl.getInstance().commitTransaction(
140                                                  cntAdminDBConnection);
141          
142          s_logger.log(Level.FINER, "Database user "
143                              + DatabaseConnectionFactoryImpl.getInstance().getDatabaseUser()
144                              + " with password "
145                              + DatabaseConnectionFactoryImpl.getInstance().getDatabasePassword()
146                              + " created.");
147       }
148       catch (SQLException JavaDoc sqleExc)
149       {
150          try
151          {
152             // At this point we don't know if this is just a single operation
153
// and we need to commit or if it is a part of bigger transaction
154
// and the commit is not desired until all operations proceed.
155
// Therefore let the DatabaseTransactionFactory resolve it
156
DatabaseTransactionFactoryImpl.getInstance().rollbackTransaction(
157                cntAdminDBConnection);
158          }
159          catch (SQLException JavaDoc sqleExc2)
160          {
161             // Ignore this
162
s_logger.log(Level.WARNING,
163                                 "Failed to rollback changes for creation of user.",
164                                 sqleExc2);
165          }
166          s_logger.log(Level.SEVERE,
167                              "Unable to create default database user.",
168                              sqleExc);
169          throw new OSSDatabaseAccessException("Unable to create default database user.",
170                                               sqleExc);
171       }
172       finally
173       {
174          DatabaseUtils.closeStatement(pstmQuery);
175       }
176    }
177     
178    /**
179     * {@inheritDoc}
180     */

181    public void startDatabaseServer(
182    ) throws OSSException
183    {
184       // TODO: Feature: Implement starting database server
185
}
186
187    /**
188     * {@inheritDoc}
189     */

190    public void createDatabaseInstance(
191    ) throws OSSException
192    {
193       // TODO: Feature: Implement creating database instance
194
}
195
196    /**
197     * {@inheritDoc}
198     */

199    public int getDatabaseType()
200    {
201       return DatabaseImpl.ORACLE_DATABASE_TYPE;
202    }
203
204    /**
205     * {@inheritDoc}
206     */

207    public String JavaDoc getDatabaseTypeIdentifier()
208    {
209       return DatabaseImpl.ORACLE_DATABASE_TYPE_IDENTIFIER;
210    }
211
212    /**
213     * {@inheritDoc}
214     */

215    public void stop(
216    ) throws OSSException
217    {
218       s_logger.entering(this.getClass().getName(), "stop");
219
220       // TODO: Feature: Implement this so we can safely stop the database when
221
// the application is finished.
222
super.stop();
223
224       s_logger.entering(this.getClass().getName(), "stop");
225    }
226
227    /**
228     * {@inheritDoc}
229     */

230    public String JavaDoc getCurrentTimestampFunctionCall()
231    {
232       // Oracle uses SYSTIMESTAMP retrieving current timestamp.
233
// SYSTIMESTAMP returns the system date, including fractional
234
// seconds and time zone, of the system on which the database
235
// resides. The return type is TIMESTAMP WITH TIME ZONE.
236
return "SYSTIMESTAMP";
237    }
238
239    /**
240     * {@inheritDoc}
241     */

242    public String JavaDoc getSQLCountFunctionCall()
243    {
244       // For Oracle 9i is best for performance use COUNT(1)
245
return "count(1)";
246    }
247
248    /**
249     * {@inheritDoc}
250     */

251    public boolean preferCountToLast(
252    )
253    {
254       // For Oracle 9i it is generally faster to execute count(1) than to do last().
255
// We can speed up performance by using select ... ROWNUM ... that allows us
256
// to retrieve just specified range of items. But when we use ROWNUM
257
// we cannot use last()
258
return true;
259    }
260
261    /**
262     * {@inheritDoc}
263     */

264    public boolean hasSelectListRangeSupport(
265    )
266    {
267       // Oracle 9i supports rows limitation by using clause ROWNUM
268
return true;
269    }
270
271    /**
272     * {@inheritDoc}
273     */

274    public Object JavaDoc[] getSQLAnalyzeFunctionCall(
275       Map JavaDoc mapTableNames
276    )
277    {
278       // Oracle 91 uses ANALYZE TABLE <table_name> COMPUTE STATISTICS to update
279
// indexes and increase performance.
280

281       String JavaDoc[] arrReturn = new String JavaDoc[mapTableNames.size()];
282       StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
283       Iterator JavaDoc itItem;
284       int iIndex = 0;
285
286       itItem = mapTableNames.values().iterator();
287       while (itItem.hasNext())
288       {
289          // construct analyze query for each table from the array
290
buffer.append("analyze table ");
291          buffer.append((String JavaDoc)itItem.next());
292          buffer.append(" compute statistics");
293          // add constructed query to the output array
294
arrReturn[iIndex++] = buffer.toString();
295          // delete buffer for next usage
296
buffer.delete(0, buffer.length());
297       }
298
299       return new Object JavaDoc[] {arrReturn, Boolean.TRUE};
300    }
301
302    /**
303     * {@inheritDoc}
304     */

305    public boolean isCallableStatement(
306       String JavaDoc strQuery
307    )
308    {
309       return strQuery.indexOf("{call ") != -1;
310    }
311
312    /**
313     * {@inheritDoc}
314     */

315    public void insertAndFetchGeneratedValues(
316       Connection JavaDoc dbConnection,
317       PreparedStatement JavaDoc insertStatement,
318       boolean bIsInDomain,
319       String JavaDoc strTableName,
320       int iIndex,
321       BasicDataObject data
322    ) throws SQLException JavaDoc,
323             OSSException
324    {
325       OracleDataUtils.insertAndFetchGeneratedValues((CallableStatement JavaDoc)insertStatement,
326                                                  iIndex, data);
327    }
328
329    /**
330     * {@inheritDoc}
331     */

332    public void updatedAndFetchGeneratedValues(
333       String JavaDoc strDataName,
334       Connection JavaDoc dbConnection,
335       PreparedStatement JavaDoc updateStatement,
336       boolean bIsInDomain,
337       String JavaDoc strTableName,
338       int iIndex,
339       ModifiableDataObject data
340    ) throws SQLException JavaDoc,
341             OSSException
342    {
343       OracleDataUtils.updateAndFetchGeneratedValues((CallableStatement JavaDoc)updateStatement,
344                                                     iIndex, data);
345    }
346 }
347
Popular Tags