1 17 18 package org.pentaho.repository; 19 20 import java.io.File ; 21 import java.util.ArrayList ; 22 import java.util.List ; 23 import java.util.StringTokenizer ; 24 import javax.naming.Context ; 25 import javax.naming.InitialContext ; 26 import javax.naming.NamingException ; 27 import org.apache.commons.logging.Log; 28 import org.apache.commons.logging.LogFactory; 29 import org.dom4j.Node; 30 import org.hibernate.HibernateException; 31 import org.hibernate.Interceptor; 32 import org.hibernate.Query; 33 import org.hibernate.Session; 34 import org.hibernate.SessionFactory; 35 import org.hibernate.Transaction; 36 import org.hibernate.cfg.Configuration; 37 import org.hibernate.cfg.Environment; 38 import org.hibernate.dialect.Dialect; 39 import org.pentaho.core.repository.RepositoryException; 40 import org.pentaho.core.system.IApplicationContext; 41 import org.pentaho.core.system.IPentahoSystemEntryPoint; 42 import org.pentaho.core.system.IPentahoSystemExitPoint; 43 import org.pentaho.core.system.ISystemSettings; 44 import org.pentaho.core.system.PentahoSystem; 45 import org.pentaho.core.util.DatasourceHelper; 46 import org.pentaho.messages.MessageUtil; 47 import org.pentaho.messages.Messages; 48 import org.pentaho.core.repository.content.ContentException; 49 50 public class HibernateUtil implements IPentahoSystemEntryPoint, IPentahoSystemExitPoint{ 51 52 private static Log log = LogFactory.getLog(HibernateUtil.class); 53 54 private final static boolean debug = PentahoSystem.debug; 55 56 private static Configuration configuration; 57 58 private static SessionFactory sessionFactory; 59 60 private static final byte[] lock = new byte[0]; 61 62 private static final ThreadLocal threadSession = new ThreadLocal (); 63 64 private static final ThreadLocal threadTransaction = new ThreadLocal (); 65 66 private static final ThreadLocal threadInterceptor = new ThreadLocal (); 67 68 private static boolean hibernateManaged; 70 71 private static String factoryJndiName; 72 73 private static Context iniCtx; 74 75 private static List objectHandlers = new ArrayList (); 76 77 private static final String QUERYWILDCARD = "%{0}%"; 79 static { 80 initialize(); 82 } 83 84 protected static boolean initialize() { 85 IApplicationContext applicationContext = PentahoSystem.getApplicationContext(); 86 HibernateUtil hUtil = new HibernateUtil(); 88 applicationContext.addEntryPointHandler(hUtil); 89 applicationContext.addExitPointHandler(hUtil); 90 91 String hibernateConfigurationFile = applicationContext.getProperty("hibernateConfigPath", null); if ((hibernateConfigurationFile != null)) { 94 if (hibernateConfigurationFile.trim().length() == 0) { 95 hibernateConfigurationFile = null; 96 } 97 } 98 String tmp = applicationContext.getProperty("hibernateManaged", "false").trim().toLowerCase(); hibernateManaged = tmp.equals("true"); try { 101 configuration = new Configuration(); 102 configuration.setEntityResolver(new PentahoEntityResolver()); 103 configuration.setListener("load", new HibernateLoadEventListener()); 105 if (hibernateConfigurationFile != null) { 106 String configPath = applicationContext.getSolutionPath(hibernateConfigurationFile); 107 File cfgFile = new File (configPath); 108 if (cfgFile.exists()) { 109 configuration.configure(cfgFile); 110 } else { 111 log.error(Messages.getErrorString("HIBUTIL.ERROR_0012_CONFIG_NOT_FOUND", configPath)); return false; 113 } 114 } else { 115 configuration.configure(); } 117 String dsName = configuration.getProperty("connection.datasource"); if ((dsName != null) && dsName.toUpperCase().endsWith("HIBERNATE")) { String actualDSName = DatasourceHelper.getDSBoundName("Hibernate"); configuration.setProperty("hibernate.connection.datasource", actualDSName); } 122 123 setupConfigurationHandlers(); 124 addConfigurations(configuration); 126 127 135 if (!hibernateManaged) { 136 log.info(Messages.getString("HIBUTIL.USER_HIBERNATEUNMANAGED")); sessionFactory = configuration.buildSessionFactory(); 138 } else { 139 factoryJndiName = configuration.getProperty(Environment.SESSION_FACTORY_NAME); 140 if (factoryJndiName == null) { 141 log.error(Messages.getErrorString("HIBUTIL.ERROR_0013_NO_SESSION_FACTORY")); return false; 143 } 144 log.info(Messages.getString("HIBUTIL.USER_HIBERNATEMANAGED")); configuration.buildSessionFactory(); } 148 Dialect.getDialect(configuration.getProperties()); 149 DefinitionVersionManager.performAutoUpdateIfRequired(); 150 return true; 151 } catch (Throwable ex) { 152 log.error(Messages.getErrorString("HIBUTIL.ERROR_0006_BUILD_SESSION_FACTORY"), ex); throw new ExceptionInInitializerError (ex); 154 } 155 } 156 157 private static void setupConfigurationHandlers() { 158 ISystemSettings systemSettings = PentahoSystem.getSystemSettings(); 159 List objectHandlerDefs = systemSettings.getSystemSettings("HibernatedObjectHandlers/*"); if ((objectHandlerDefs != null) && (objectHandlerDefs.size() > 0)) { 161 String handlerClass; 162 for (int i = 0; i < objectHandlerDefs.size(); i++) { 163 handlerClass = ((Node) objectHandlerDefs.get(i)).getText(); 164 IHibernatedObjectExtensionList extension = (IHibernatedObjectExtensionList) PentahoSystem.createObject(handlerClass); 165 if (extension != null) { 166 objectHandlers.add(extension); 167 } 168 } 169 } else { 170 objectHandlers.add(new StdHibernateClassHandler()); 172 } 173 } 174 175 private static void addConfigurations(Configuration theConfiguration) { 176 IHibernatedObjectExtensionList extension; 177 for (int i = 0; i < objectHandlers.size(); i++) { 178 extension = (IHibernatedObjectExtensionList) objectHandlers.get(i); 179 List resourceList = extension.getHibernatedObjectResourceList(); 180 for (int j = 0; j < resourceList.size(); j++) { 181 theConfiguration.addResource((String ) resourceList.get(j)); 182 } 183 } 184 } 185 186 191 public static SessionFactory getSessionFactory() { 192 if (!hibernateManaged) { 193 return sessionFactory; 194 } 195 SessionFactory sf = null; 196 try { 197 if (iniCtx == null) { 198 iniCtx = new InitialContext (); 199 } 200 String jndiName = factoryJndiName; 201 try { 202 sf = (SessionFactory) iniCtx.lookup(jndiName); 203 } catch (Exception ignored) { 204 } 205 if (sf == null) { 206 try { 207 sf = (SessionFactory) iniCtx.lookup("java:" + jndiName); } catch (Exception ignored) { 209 ignored.printStackTrace(); 210 } 211 } 212 } catch (NamingException ignored) { 213 } 214 return sf; 215 } 216 217 222 public static Configuration getConfiguration() { 223 return configuration; 224 } 225 226 public static void updateSchema() throws RepositoryException { 227 PentahoSchemaUpdate upd = new PentahoSchemaUpdate(getConfiguration()); 228 upd.execute(true, true); 229 } 230 231 235 public static void rebuildSessionFactory() throws RepositoryException { 236 if (!hibernateManaged) { 237 synchronized (lock) { 238 try { 239 sessionFactory = getConfiguration().buildSessionFactory(); 240 } catch (Exception ex) { 241 log.error(Messages.getErrorString("HIBUTIL.ERROR_0007_REBUILD_SESSION_FACTORY"), ex); throw new RepositoryException(Messages.getErrorString("HIBUTIL.ERROR_0007_REBUILD_SESSION_FACTORY"), ex); } 244 } 245 } else { 246 try { 247 getConfiguration().buildSessionFactory(); 248 } catch (Exception ex) { 249 log.error(Messages.getErrorString("HIBUTIL.ERROR_0007_REBUILD_SESSION_FACTORY"), ex); throw new RepositoryException(Messages.getErrorString("HIBUTIL.ERROR_0007_REBUILD_SESSION_FACTORY"), ex); } 252 } 253 } 254 255 260 public static void rebuildSessionFactory(Configuration cfg) throws RepositoryException { 261 if (!hibernateManaged) { 262 synchronized (lock) { 263 try { 264 sessionFactory = cfg.buildSessionFactory(); 265 configuration = cfg; 266 } catch (Exception ex) { 267 log.error(Messages.getErrorString("HIBUTIL.ERROR_0007_REBUILD_SESSION_FACTORY"), ex); throw new RepositoryException(Messages.getErrorString("HIBUTIL.ERROR_0007_REBUILD_SESSION_FACTORY"), ex); } 270 } 271 } else { 272 try { 273 cfg.buildSessionFactory(); 274 configuration = cfg; 275 } catch (Exception ex) { 276 log.error(Messages.getErrorString("HIBUTIL.ERROR_0007_REBUILD_SESSION_FACTORY"), ex); throw new RepositoryException(Messages.getErrorString("HIBUTIL.ERROR_0007_REBUILD_SESSION_FACTORY"), ex); } 279 } 280 } 281 282 288 public static Session getSession() throws RepositoryException { 289 Session s = (Session) threadSession.get(); 290 try { 291 if (s == null) { 292 if (debug) 293 log.debug(Messages.getString("HIBUTIL.DEBUG_OPEN_NEW_SESSION")); if (getInterceptor() != null) { 295 if (debug) 296 log.debug(Messages.getString("HIBUTIL.DEBUG_USING_INTERCEPTOR") + getInterceptor().getClass()); s = getSessionFactory().openSession(getInterceptor()); 298 } else { 299 s = getSessionFactory().openSession(); 300 } 301 threadSession.set(s); 302 } 303 } catch (HibernateException ex) { 304 log.error(Messages.getErrorString("HIBUTIL.ERROR_0005_GET_SESSION"), ex); throw new RepositoryException(Messages.getErrorString("HIBUTIL.ERROR_0005_GET_SESSION"), ex); } 307 return s; 308 } 309 310 public static void flushSession() throws RepositoryException { 311 try { 312 Session s = getSession(); 313 s.flush(); 314 } catch (HibernateException ex) { 315 throw new RepositoryException(ex); 316 } 317 } 318 319 322 public static void closeSession() throws RepositoryException { 323 try { 324 Session s = (Session) threadSession.get(); 325 threadSession.set(null); 326 if (s != null && s.isOpen()) { 327 if (debug) 328 log.debug(Messages.getString("HIBUTIL.DEBUG_CLOSING_SESSION")); s.close(); 330 } 331 threadTransaction.set(null); 332 } catch (HibernateException ex) { 333 log.error(Messages.getErrorString("HIBUTIL.ERROR_0009_CLOSE_SESSION"), ex); threadTransaction.set(null); 335 throw new RepositoryException(Messages.getErrorString("HIBUTIL.ERROR_0009_CLOSE_SESSION"), ex); } 337 338 } 339 340 343 public static void beginTransaction() throws RepositoryException { 344 Transaction tx = (Transaction) threadTransaction.get(); 346 try { 347 if (tx == null) { 348 if (debug) 349 log.debug(Messages.getString("HIBUTIL.DEBUG_START_TRANS")); tx = getSession().beginTransaction(); 351 threadTransaction.set(tx); 352 } 353 } catch (HibernateException ex) { 354 log.error(Messages.getErrorString("HIBUTIL.ERROR_0004_START_TRANS"), ex); throw new RepositoryException(Messages.getErrorString("HIBUTIL.ERROR_0004_START_TRANS"), ex); } 357 } 358 359 362 public static void commitTransaction() throws RepositoryException { 363 Transaction tx = (Transaction) threadTransaction.get(); 366 try { 367 if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) { 368 if (debug) 369 log.debug(Messages.getString("HIBUTIL.DEBUG_COMMIT_TRANS")); tx.commit(); 371 } 372 } catch (HibernateException ex) { 373 log.error(Messages.getErrorString("HIBUTIL.ERROR_0008_COMMIT_TRANS"), ex); try { 375 rollbackTransaction(); 376 } catch (Exception e2) { 377 } 378 } finally { 382 threadTransaction.set(null); 383 } 384 } 387 388 391 public static void rollbackTransaction() throws RepositoryException { 392 Transaction tx = (Transaction) threadTransaction.get(); 393 try { 394 threadTransaction.set(null); 395 if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) { 396 if (debug) 397 log.debug(Messages.getString("HIBUTIL.DEBUG_ROLLBACK")); tx.rollback(); 399 } 400 } catch (HibernateException ex) { 401 log.error(Messages.getErrorString("HIBUTIL.ERROR_0003_ROLLBACK"), ex); throw new RepositoryException(Messages.getErrorString("HIBUTIL.ERROR_0003_ROLLBACK"), ex); } finally { 404 closeSession(); 405 } 406 } 407 408 414 421 426 public static Session disconnectSession() throws RepositoryException { 427 428 Session session = getSession(); 429 try { 430 threadSession.set(null); 431 if (session.isConnected() && session.isOpen()) 432 session.disconnect(); 433 } catch (HibernateException ex) { 434 log.error(Messages.getErrorString("HIBUTIL.ERROR_0002_DISCONNECT"), ex); throw new RepositoryException(Messages.getErrorString("HIBUTIL.ERROR_0002_DISCONNECT"), ex); } 437 return session; 438 } 439 440 447 public static void registerInterceptor(Interceptor interceptor) { 448 threadInterceptor.set(interceptor); 449 } 450 451 private static Interceptor getInterceptor() { 452 Interceptor interceptor = (Interceptor) threadInterceptor.get(); 453 return interceptor; 454 } 455 456 490 public static List searchForTerm(ISearchable searchable, String searchTerm, int searchType) { 491 Session session = getSession(); 492 if (searchType == ISearchable.SEARCH_TYPE_PHRASE) { 493 Query qry = session.getNamedQuery(searchable.getPhraseSearchQueryName()); 494 String searchWildcard = MessageUtil.formatErrorMessage(QUERYWILDCARD, searchTerm); 495 qry.setString("searchTerm", searchWildcard); List rtn = qry.list(); 497 return rtn; 498 } 499 String connector; 500 if (searchType == ISearchable.SEARCH_TYPE_WORDS_AND) { 501 connector = " and "; } else { 503 connector = " or "; } 505 StringTokenizer st = new StringTokenizer (searchTerm, " "); List searchWords = new ArrayList (); 507 while (st.hasMoreTokens()) { 508 searchWords.add(MessageUtil.formatErrorMessage(QUERYWILDCARD, st.nextToken())); 509 } 510 StringBuffer assembly = assembleQuery(searchable.getSearchableTable(), connector, searchWords, searchable.getSearchableColumns()); 512 Query qry = session.createQuery(assembly.toString()); 513 for (int j = 0; j < searchWords.size(); j++) { 514 qry.setParameter("searchTerm" + j, searchWords.get(j)); } 516 List rtn = qry.list(); 517 return rtn; 518 } 519 520 private static StringBuffer assembleQuery(String tableName, String connector, List terms, String [] columns) { 521 StringBuffer qry = new StringBuffer (); 522 qry.append("from ").append(tableName).append(" tbl where "); String currCol, term; 524 for (int colno = 0; colno < columns.length; colno++) { 525 currCol = columns[colno]; 526 qry.append("("); for (int termNo = 0; termNo < terms.size(); termNo++) { 528 term = (String ) terms.get(termNo); 529 qry.append("tbl.").append(currCol).append(" like :searchTerm").append(term).append(" "); if (termNo < terms.size() - 1) { 531 qry.append(connector); 532 } 533 } 534 qry.append(")"); if (colno < columns.length - 1) { 536 qry.append(" or "); } 538 } 539 return qry; 540 } 541 542 public static void clear() { 543 getSession().clear(); 544 } 545 546 553 public static void makePersistent(Object obj) throws RepositoryException { 554 if (debug) 555 log.debug(Messages.getString("HIBUTIL.DEBUG_MAKE_PERSISTENT", obj.toString())); try { 557 getSession().saveOrUpdate(obj); 558 } catch (HibernateException ex) { 559 log.error(Messages.getErrorString("HIBUTIL.ERROR_0010_SAVING_UPDATING"), ex); throw new ContentException(Messages.getErrorString("HIBUTIL.ERROR_0010_SAVING_UPDATING"), ex); } 562 } 563 564 571 public static void makeTransient(Object obj) throws RepositoryException { 572 if (debug) 573 log.debug(Messages.getString("HIBUTIL.DEBUG_MAKE_TRANSIENT", obj.toString())); try { 575 getSession().delete(obj); 576 } catch (HibernateException ex) { 577 log.error(Messages.getErrorString("HIBUTIL.ERROR_0011_DELETING_OBJ"), ex); throw new ContentException(Messages.getErrorString("HIBUTIL.ERROR_0011_DELETING_OBJ"), ex); } 580 } 581 582 589 public static void evict(Object obj) { 590 try { 593 getSession().evict(obj); 594 } catch (HibernateException ex) { 595 log.error(Messages.getErrorString("HIBUTIL.ERROR_0014_EVICTING_OBJECT"), ex); } 597 598 } 599 600 public static List getHibernatedObjectHandlerList() { 601 return objectHandlers; 602 } 603 604 public void systemEntryPoint() { 605 } 607 608 public void systemExitPoint() { 609 try { 610 HibernateUtil.commitTransaction(); 611 } catch (Throwable t) { 612 t.printStackTrace(); 613 } 614 615 try { 616 HibernateUtil.closeSession(); 617 } catch (Throwable t) { 618 t.printStackTrace(); 619 } 620 } 621 622 } 623 | Popular Tags |