KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > portal > setup > impl > dl > dbloader > hibernate > HibernateDataLoader


1 /*****************************************
2  * *
3  * JBoss Portal: The OpenSource Portal *
4  * *
5  * Distributable under LGPL license. *
6  * See terms of license at gnu.org. *
7  * *
8  *****************************************/

9 package org.jboss.portal.setup.impl.dl.dbloader.hibernate;
10
11 import org.jboss.portal.setup.dl.DataLoader;
12 import org.jboss.portal.setup.dl.DataLoaderConfig;
13 import org.jboss.portal.setup.dl.HibernateDataLoaderConfig;
14 import org.jboss.portal.setup.PortalSetupException;
15 import org.jboss.portal.setup.pm.PersistenceSession;
16 import org.jboss.portal.setup.config.HibernateConfig;
17 import org.jboss.portal.setup.impl.dl.StatementMetaData;
18 import org.jboss.portal.setup.impl.dl.DataLoaderBase;
19 import org.jboss.portal.setup.impl.dl.StatementType;
20 import org.jboss.portal.setup.impl.dl.dbloader.ValueRowMetaData;
21 import org.jboss.portal.setup.impl.dl.dbloader.SqlFunctionMetaData;
22
23 import org.jboss.portal.setup.impl.pm.HibernatePersistenceManager;
24
25 import org.w3c.dom.Element JavaDoc;
26
27 import org.apache.log4j.Logger;
28 import org.hibernate.tool.hbm2ddl.DatabaseMetadata;
29 import org.hibernate.tool.hbm2ddl.TableMetadata;
30 import org.hibernate.tool.hbm2ddl.ColumnMetadata;
31 import org.hibernate.cfg.Configuration;
32 import org.hibernate.cfg.Mappings;
33 import org.hibernate.mapping.Table;
34 import org.hibernate.mapping.Column;
35 import org.hibernate.HibernateException;
36 import org.hibernate.sql.Insert;
37
38 import java.util.List JavaDoc;
39 import java.util.Iterator JavaDoc;
40 import java.util.ArrayList JavaDoc;
41 import java.util.Map JavaDoc;
42
43
44
45
46 /**
47  * @author <a HREF="mailto:palber@novell.com">Polina Alber</a>
48  * Date: Apr 13, 2005; Time: 12:57:09 PM
49  * @since JBoss portal 2.0
50  * Class org.jboss.portal.setup.impl.dl.dbloader.hibernate.HibernateDataLoader
51  */

52 public class HibernateDataLoader extends DataLoaderBase implements DataLoader
53 {
54
55    private final Logger m_log = Logger.getLogger(getClass());
56    private HibernatePersistenceManager m_pm = new HibernatePersistenceManager();
57
58
59    /**
60     * @param config a DataLoaderConfig
61     */

62    public void setDataLoaderConfiguration(DataLoaderConfig config) throws PortalSetupException
63    {
64
65       if (null != config && config.getConfiguration() instanceof HibernateDataLoaderConfig)
66       {
67          super.setDataLoaderConfiguration(config);
68          setupHibernate();
69       }
70       else
71       {
72          throw new PortalSetupException("Data loader configuration obect of a wrong class;" +
73             "Expected instance of org.jboss.portal.setup.dl.HibernateDataLoaderConfig class ");
74       }
75    }
76
77    public void destroy() throws PortalSetupException
78    {
79       m_pm.destroy();
80    }
81
82    /**
83     * @return boolean flag; when true means that database data have been initialized
84     * @throws PortalSetupException in case of an error: database schema have not been loaded,
85     * cannot connect to database instance, etc.
86     */

87    public boolean checkDataInitialized() throws PortalSetupException
88    {
89       boolean result = false;
90       String JavaDoc checkSchemaSql = getDataLoaderConfiguration().getDataQueryString();
91       PersistenceSession session = null;
92       try
93       {
94          session = m_pm.getSession();
95          result = session.validate(checkSchemaSql, true);
96       }
97       finally
98       {
99          session.close();
100       }
101       return result;
102
103    }
104
105
106    protected StatementMetaData parseStatement(Element JavaDoc statementElmt) throws PortalSetupException
107    {
108       HibernateStatementMetaData md = null;
109       try
110       {
111
112
113          md = new HibernateStatementMetaData(statementElmt);
114          DatabaseMetadata dbMetaData = m_pm.getDatabaseMetadata();
115          TableMetadata tbMetaData = null;//dbMetaData.getTableMetadata(md.getTableName());
116
if (null == tbMetaData)
117          {
118             //HSQL data base cannot find table metadata
119
// throw new PortalSetupException("Table '" + md.getTableName() +
120
// "' does not exists, check that data base schema have been loaded");
121
}
122
123          List JavaDoc columns = md.getColumns();
124          Configuration config = m_pm.getHibernateConfiguration();
125          Mappings maps = config.createMappings();
126
127          Table hbTable = config.createMappings().getTable(maps.getSchemaName(), md.getTableName(), null); //XXXX check argument
128

129          for (int i = 0; i < columns.size(); i++)
130          {
131             HibernateColumnMetaData column = (HibernateColumnMetaData)columns.get(i);
132             ColumnMetadata hbColMd = tbMetaData == null ? null : tbMetaData.getColumnMetadata(column.getColumnName());
133             //resolve column metadata and literal types
134
Column hbColumn = findHibernateColumn(hbTable, column.getColumnName());
135
136             column.setColumnTypeValues(hbColMd, m_pm.getDialect(), hbColumn, m_pm.getHibernateConfiguration());
137          }
138       }
139       catch (HibernateException he)
140       {
141          throw new PortalSetupException(he);
142       }
143       return md;
144    }
145
146    protected boolean executeStatements(List JavaDoc stmtList) throws PortalSetupException
147    {
148       boolean result = false;
149       PersistenceSession session = m_pm.getSession();
150       List JavaDoc sqlList = null;
151       String JavaDoc sql = null;
152       try
153       {
154          if (stmtList != null)
155          {
156             Iterator JavaDoc iter = stmtList.iterator();
157             while (iter.hasNext())
158             {
159                HibernateStatementMetaData hbStmt = (HibernateStatementMetaData)iter.next();
160                sqlList = generateSQLSatement(hbStmt);
161             }
162             result = session.execute(sqlList);
163          }
164          result = true;
165       }
166       catch (PortalSetupException pse)
167       {
168          m_log.error(pse.getMessage(), pse);
169          throw pse;
170       }
171       finally
172       {
173          if (session != null)
174          {
175             session.close();
176          }
177       }
178       return result;
179
180
181    }
182
183    private void setupHibernate() throws PortalSetupException
184    {
185
186       HibernateConfig hbc = ((HibernateDataLoaderConfig)getDataLoaderConfiguration()).getHibernateConfig();
187       m_pm.initialize(hbc, null);
188    }
189
190
191    private List JavaDoc generateSQLSatement(HibernateStatementMetaData stmtMd) throws PortalSetupException
192    {
193       List JavaDoc sqlList = new ArrayList JavaDoc();
194       StatementType type = stmtMd.getType();
195       if (StatementType.INSERT == type)
196       {
197          sqlList = generateInsertStatement(stmtMd);
198       }
199       else
200       {
201          throw new PortalSetupException("Statement type '" + type.toString() + "' is not supported");
202       }
203       return sqlList;
204    }
205
206    private List JavaDoc generateInsertStatement(HibernateStatementMetaData stmtMd) throws PortalSetupException
207    {
208       List JavaDoc sqlList = new ArrayList JavaDoc();
209       Insert insertStatement = new Insert(m_pm.getDialect());
210       insertStatement.setTableName(stmtMd.getTableName());
211       List JavaDoc columns = stmtMd.getColumns();
212       List JavaDoc rows = stmtMd.getValues();
213       Map JavaDoc funcMap = m_pm.getDialect().getFunctions();
214       for (int i = 0, rnumber = rows.size(); i < rnumber; i++)
215       {
216          ValueRowMetaData row = (ValueRowMetaData)rows.get(i);
217          List JavaDoc values = row.getValues();
218          int rowSize = values.size();
219          if (columns.size() != rowSize)
220          {
221             throw new PortalSetupException("Number of column definition does not much row value size");
222          }
223          for (int j = 0; j < rowSize; j++)
224          {
225
226             HibernateColumnMetaData column = (HibernateColumnMetaData)columns.get(j);
227             try
228             {
229                Object JavaDoc value = values.get(j);
230                if (value instanceof SqlFunctionMetaData)
231                {
232                   //check if supported
233
String JavaDoc funcNameLowCase = ((SqlFunctionMetaData)value).getFuncName().toLowerCase();
234                   Object JavaDoc func = funcMap.get(funcNameLowCase);
235                   if (func == null)
236                   {
237                      value = resolveSQLFunction((SqlFunctionMetaData)value);
238                      String JavaDoc strVal = TypeResolver.resolveValueByType(column.getDbTypeName(), value, column.getLiteralType());
239                      insertStatement.addColumn(column.getColumnName(), strVal);
240                      //values.set(j, value);
241
// insertStatement.addColumn(column.getColumnName(), value, column.getLiteralType());
242
}
243                   else
244                   {
245                      insertStatement.addColumn(column.getColumnName(), value.toString());
246                   }
247                }
248                else
249                {
250                   insertStatement.addColumn(column.getColumnName(), value, column.getLiteralType());
251                }
252             }
253             catch (Exception JavaDoc ex)
254             {
255                throw new PortalSetupException("Failed to add column '" + column.getColumnName() + "' to sql insert statement.", ex);
256             }
257
258          }
259
260          String JavaDoc sql = insertStatement.toStatementString();
261          sqlList.add(sql);
262       }
263       //LiteralType type;
264

265       return sqlList;
266    }
267
268 //heleper methods to be moved to utility classes
269
private Column findHibernateColumn(Table hbTable, String JavaDoc columnName) throws PortalSetupException
270    {
271       Iterator JavaDoc colIter = hbTable.getColumnIterator();
272       while (colIter.hasNext())
273       {
274          Column col = (Column)colIter.next();
275          if (col.getName().equals(columnName))
276          {
277             return col;
278          }
279       }
280       throw new PortalSetupException("Failed to resolve a column '" + columnName + "' within hibernate configuration");
281    }
282
283    private Object JavaDoc resolveSQLFunction(SqlFunctionMetaData md) throws PortalSetupException
284    {
285       return md.resolveSQLFunction(m_pm.getDialect().getClass().getName());
286    }
287 }
288
Popular Tags