KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opensubsystems > patterns > mappeddata > persist > db > MappingDatabaseFactory


1 /*
2  * Copyright (c) 2006 - 2007 OpenSubsystems s.r.o. Slovak Republic. All rights reserved.
3  *
4  * Project: OpenSubsystems
5  *
6  * $Id: MappingDatabaseFactory.java,v 1.18 2007/01/28 06:54:53 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.patterns.mappeddata.persist.db;
23
24 import java.sql.Connection JavaDoc;
25 import java.sql.PreparedStatement JavaDoc;
26 import java.sql.ResultSet JavaDoc;
27 import java.sql.SQLException JavaDoc;
28 import java.sql.Types JavaDoc;
29 import java.util.Collection JavaDoc;
30
31 import org.opensubsystems.core.data.DataConstant;
32 import org.opensubsystems.core.data.DataObject;
33 import org.opensubsystems.core.data.ModifiableDataObject;
34 import org.opensubsystems.core.error.OSSDataNotFoundException;
35 import org.opensubsystems.core.error.OSSDatabaseAccessException;
36 import org.opensubsystems.core.error.OSSException;
37 import org.opensubsystems.core.error.OSSInconsistentDataException;
38 import org.opensubsystems.core.persist.db.DatabaseCreateMultipleDataObjectsOperation;
39 import org.opensubsystems.core.persist.db.DatabaseDeleteSingleDataObjectOperation;
40 import org.opensubsystems.core.persist.db.DatabaseFactoryImpl;
41 import org.opensubsystems.core.persist.db.DatabaseReadMultipleOperation;
42 import org.opensubsystems.core.persist.db.DatabaseReadOperation;
43 import org.opensubsystems.core.persist.db.DatabaseReadSingleDataObjectOperation;
44 import org.opensubsystems.core.persist.db.DatabaseUpdateOperation;
45 import org.opensubsystems.core.util.DatabaseUtils;
46 import org.opensubsystems.core.util.GlobalConstants;
47 import org.opensubsystems.core.util.ThreeIntStruct;
48 import org.opensubsystems.patterns.mappeddata.data.MappedData;
49 import org.opensubsystems.patterns.mappeddata.persist.MappingFactory;
50
51 /**
52  * Data factory to retrieve and manipulate mapping records in persistence store.
53  *
54  * Subsystems that want to create mappings should derive database factory class
55  * from this class. The only thing which is required is to implement constructor
56  * that provides database schema, that is able to provide database queries to
57  * this factory.
58  *
59  * @version $Id: MappingDatabaseFactory.java,v 1.18 2007/01/28 06:54:53 bastafidli Exp $
60  * @author Julian Legeny
61  * @code.reviewer Miro Halas
62  * @code.reviewed 1.13 2006/08/11 00:33:16 jlegeny
63  */

64 public class MappingDatabaseFactory extends DatabaseFactoryImpl
65                                     implements MappingFactory
66 {
67    // Cached values ////////////////////////////////////////////////////////////
68

69    /**
70     * Schema to use to execute database dependent operations.
71     */

72    protected MappingDatabaseSchema m_schema;
73
74    // Constructors /////////////////////////////////////////////////////////////
75

76    /**
77     * Default constructor.
78     *
79     * @param schema - schema to use by this factory to execute database dependent
80     * operations
81     * @throws OSSException - an error has occured
82     */

83    public MappingDatabaseFactory(
84       MappingDatabaseSchema schema
85    ) throws OSSException
86    {
87       super(DataConstant.MAPPEDDATA_DATA_TYPE);
88       
89       m_schema = schema;
90    }
91
92    // Basic operations /////////////////////////////////////////////////////////
93

94    /**
95     * {@inheritDoc}
96     */

97    public void create(
98       final ThreeIntStruct tisIDs
99    ) throws OSSException
100    {
101       if (GlobalConstants.ERROR_CHECKING)
102       {
103          assert tisIDs != null : "Cannot create unspecified mapping values.";
104       }
105
106       DatabaseUpdateOperation dbop = new DatabaseUpdateOperation(
107                this, m_schema.getInsertMappingRecord(), m_schema,
108                DatabaseUpdateOperation.DBOP_INSERT, null)
109       {
110          protected void performOperation(
111             DatabaseFactoryImpl dbfactory,
112             Connection JavaDoc cntConnection,
113             PreparedStatement JavaDoc pstmQuery
114          ) throws OSSException,
115                   SQLException JavaDoc
116          {
117             pstmQuery.setInt(1, tisIDs.getFirst());
118             pstmQuery.setInt(2, tisIDs.getSecond());
119             pstmQuery.setInt(3, tisIDs.getThird());
120             pstmQuery.setNull(4, Types.INTEGER);
121             pstmQuery.executeUpdate();
122          }
123       };
124       dbop.executeUpdate();
125    }
126
127    /**
128     * {@inheritDoc}
129     */

130    public void delete(
131       final ThreeIntStruct tisIDs
132    ) throws OSSException
133    {
134       if (GlobalConstants.ERROR_CHECKING)
135       {
136          assert tisIDs != null : "Cannot delete unspecified mapping values.";
137       }
138
139       DatabaseUpdateOperation dbop = new DatabaseUpdateOperation(
140                this, m_schema.getDeleteMappingRecord(), m_schema,
141                DatabaseUpdateOperation.DBOP_DELETE, null)
142       {
143          protected void performOperation(
144             DatabaseFactoryImpl dbfactory,
145             Connection JavaDoc cntConnection,
146             PreparedStatement JavaDoc pstmQuery
147          ) throws OSSException,
148                   SQLException JavaDoc
149          {
150             int iDeleted;
151             
152             pstmQuery.setInt(1, tisIDs.getFirst());
153             pstmQuery.setInt(2, tisIDs.getSecond());
154             pstmQuery.setInt(3, tisIDs.getThird());
155             iDeleted = pstmQuery.executeUpdate();
156             
157             if (iDeleted == 0)
158             {
159                throw new OSSDataNotFoundException(
160                             "Data to delete cannot be found in the database");
161             }
162             else if (iDeleted != 1)
163             {
164                throw new OSSInconsistentDataException("Inconsistent database contains multiple ("
165                             + iDeleted + ") data object with the same ID");
166             }
167          }
168       };
169       dbop.executeUpdate();
170    }
171
172    /**
173     * {@inheritDoc}
174     */

175    public int[] getMappedData(
176       final int iId,
177       final int iMappingType
178    ) throws OSSException
179    {
180       int[] arrMappedData = null;
181
182       if (iId > DataObject.NEW_ID)
183       {
184          DatabaseReadOperation dbop = new DatabaseReadMultipleOperation(
185             this, m_schema.geSelectMappingRecords(), m_schema)
186          {
187             protected Object JavaDoc performOperation(
188                DatabaseFactoryImpl dbfactory,
189                Connection JavaDoc cntConnection,
190                PreparedStatement JavaDoc pstmQuery
191             ) throws OSSException,
192                      SQLException JavaDoc
193             {
194                pstmQuery.setInt(1, iId);
195                pstmQuery.setInt(2, iMappingType);
196                return DatabaseUtils.loadMultipleIntsAsArray(pstmQuery);
197             }
198          };
199          arrMappedData = (int[])dbop.executeRead();
200       }
201       
202       return arrMappedData;
203    }
204
205    /**
206     * {@inheritDoc}
207     */

208    public int[] getMappedData(
209       final String JavaDoc strColumnIDs,
210       final int iMappingType
211    ) throws OSSException
212    {
213       // TODO: For Julo: Make test for this method
214

215       int[] arrMappedData = null;
216
217       if ((strColumnIDs != null) && (strColumnIDs.length() > 0)
218            && !(strColumnIDs.equals("-1")))
219       {
220          DatabaseReadOperation dbop = new DatabaseReadMultipleOperation(
221             this, m_schema.geSelectMappingMultipleRecords(strColumnIDs), m_schema)
222          {
223             protected Object JavaDoc performOperation(
224                DatabaseFactoryImpl dbfactory,
225                Connection JavaDoc cntConnection,
226                PreparedStatement JavaDoc pstmQuery
227             ) throws OSSException,
228                      SQLException JavaDoc
229             {
230                pstmQuery.setInt(1, iMappingType);
231                return DatabaseUtils.loadMultipleIntsAsArray(pstmQuery);
232             }
233          };
234          arrMappedData = (int[])dbop.executeRead();
235       }
236       
237       return arrMappedData;
238    }
239
240    /**
241     * {@inheritDoc}
242     */

243    public DataObject load(
244       ResultSet JavaDoc rsQueryResults,
245       int initialIndex
246    ) throws OSSDatabaseAccessException
247    {
248       MappedData data;
249
250       try
251       {
252          // The order must exactly match the order in COLUMNS constant
253
data = new MappedData(rsQueryResults.getInt(initialIndex),
254                                rsQueryResults.getInt(initialIndex + 1),
255                                rsQueryResults.getInt(initialIndex + 2),
256                                rsQueryResults.getInt(initialIndex + 3),
257                                rsQueryResults.getString(initialIndex + 4),
258                                rsQueryResults.getTimestamp(initialIndex + 5),
259                                rsQueryResults.getTimestamp(initialIndex + 6));
260          data.setFromPersistenceStore();
261       }
262       catch (SQLException JavaDoc sqleExc)
263       {
264          throw new OSSDatabaseAccessException("Failed to load data from the database.",
265                                               sqleExc);
266       }
267
268       return data;
269    }
270
271    /**
272     * {@inheritDoc}
273     */

274    public DataObject get(
275       final int iId,
276       final int iDomainId
277    ) throws OSSException
278    {
279       DataObject data = null;
280
281       // If the ID is supplied try to read the data from the database,
282
// if it is not, it is new data which doesn't have ID yet
283
if (iId == DataObject.NEW_ID)
284       {
285          // This mapped data doesn't exist yet so just create a new one
286
data = new MappedData();
287       }
288       else
289       {
290          DatabaseReadOperation dbop = new DatabaseReadSingleDataObjectOperation(
291             this,
292             m_schema.getSelectMappedDataById(MappedData.ALL_MAPPEDDATA_COLUMNS),
293             m_schema, iId, iDomainId);
294          data = (DataObject)dbop.executeRead();
295       }
296
297       return data;
298    }
299
300    /**
301     * {@inheritDoc}
302     */

303    public DataObject create(
304       final DataObject data
305    ) throws OSSException
306    {
307       if (GlobalConstants.ERROR_CHECKING)
308       {
309          assert data.getId() == DataObject.NEW_ID
310                 : "Cannot create already created data.";
311       }
312       
313       DatabaseUpdateOperation dbop = new DatabaseUpdateOperation(
314          this, DatabaseUpdateOperation.DBOP_INSERT)
315       {
316          protected void performOperation(
317             DatabaseFactoryImpl dbfactory,
318             Connection JavaDoc cntConnection,
319             PreparedStatement JavaDoc pstmQuery
320          ) throws OSSException,
321                   SQLException JavaDoc
322          {
323             setReturnData(m_schema.insertMappedData(cntConnection, (MappedData)data));
324          }
325       };
326       dbop.executeUpdate();
327      
328       return (DataObject)dbop.getReturnData();
329    }
330    
331    /**
332     * {@inheritDoc}
333     */

334    public int create(
335       Collection JavaDoc colDataObject
336    ) throws OSSException
337    {
338       if (GlobalConstants.ERROR_CHECKING)
339       {
340          assert colDataObject != null && !colDataObject.isEmpty()
341                 : "Cannot create empty data list.";
342       }
343
344       DatabaseUpdateOperation dbop = new DatabaseCreateMultipleDataObjectsOperation(
345          this, m_schema.getInsertMappingRecord(), m_schema, colDataObject, false);
346       dbop.executeUpdate();
347       
348       return ((Integer JavaDoc)dbop.getReturnData()).intValue();
349    }
350    
351    /**
352     * {@inheritDoc}
353     */

354    public void delete(
355       final int iId,
356       final int iDomainId
357    ) throws OSSException
358    {
359       if (GlobalConstants.ERROR_CHECKING)
360       {
361          assert iId != DataObject.NEW_ID
362                 : "Cannot delete data, which wasn't created yet.";
363       }
364
365       DatabaseUpdateOperation dbop = new DatabaseDeleteSingleDataObjectOperation(
366          this, m_schema.getDeleteMappedDataById(), m_schema, iId, iDomainId);
367       dbop.executeUpdate();
368    }
369
370    // Extended operations //////////////////////////////////////////////////////
371

372    /**
373     * {@inheritDoc}
374     */

375    public ModifiableDataObject save(
376       final ModifiableDataObject data
377    ) throws OSSException
378    {
379       if (GlobalConstants.ERROR_CHECKING)
380       {
381          assert data != null
382                   : "Data can not be null";
383          assert data.getId() != DataObject.NEW_ID
384                   : "Cannot save data which wasn't created yet.";
385       }
386
387       DatabaseUpdateOperation dbop = new DatabaseUpdateOperation(
388          this, DatabaseUpdateOperation.DBOP_UPDATE)
389       {
390          protected void performOperation(
391             DatabaseFactoryImpl dbfactory,
392             Connection JavaDoc cntConnection,
393             PreparedStatement JavaDoc pstmQuery
394          ) throws OSSException,
395                   SQLException JavaDoc
396          {
397             setReturnData(m_schema.updateMappedData(cntConnection, (MappedData)data));
398          }
399       };
400       dbop.executeUpdate();
401      
402       return (ModifiableDataObject)dbop.getReturnData();
403    }
404 }
405
Popular Tags