Source Code Cross Referenced for HibernateUtil.java in  » Report » pentaho-report » org » pentaho » repository » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Report » pentaho report » org.pentaho.repository 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:         * Copyright 2006 Pentaho Corporation.  All rights reserved. 
003:         * This software was developed by Pentaho Corporation and is provided under the terms 
004:         * of the Mozilla Public License, Version 1.1, or any later version. You may not use 
005:         * this file except in compliance with the license. If you need a copy of the license, 
006:         * please go to http://www.mozilla.org/MPL/MPL-1.1.txt. The Original Code is the Pentaho 
007:         * BI Platform.  The Initial Developer is Pentaho Corporation.
008:         *
009:         * Software distributed under the Mozilla Public License is distributed on an "AS IS" 
010:         * basis, WITHOUT WARRANTY OF ANY KIND, either express or  implied. Please refer to 
011:         * the license for the specific language governing your rights and limitations.
012:         *
013:         * @created Apr 20, 2005 
014:         * @author Marc Batchelor
015:         * 
016:         */
017:
018:        package org.pentaho.repository;
019:
020:        import java.io.File;
021:        import java.util.ArrayList;
022:        import java.util.List;
023:        import java.util.StringTokenizer;
024:
025:        import javax.naming.Context;
026:        import javax.naming.InitialContext;
027:        import javax.naming.NamingException;
028:
029:        import org.apache.commons.logging.Log;
030:        import org.apache.commons.logging.LogFactory;
031:        import org.dom4j.Node;
032:        import org.hibernate.HibernateException;
033:        import org.hibernate.Interceptor;
034:        import org.hibernate.Query;
035:        import org.hibernate.Session;
036:        import org.hibernate.SessionFactory;
037:        import org.hibernate.Transaction;
038:        import org.hibernate.cfg.Configuration;
039:        import org.hibernate.cfg.Environment;
040:        import org.hibernate.dialect.Dialect;
041:        import org.pentaho.core.repository.RepositoryException;
042:        import org.pentaho.core.repository.content.ContentException;
043:        import org.pentaho.core.system.IApplicationContext;
044:        import org.pentaho.core.system.IPentahoSystemEntryPoint;
045:        import org.pentaho.core.system.IPentahoSystemExitPoint;
046:        import org.pentaho.core.system.ISystemSettings;
047:        import org.pentaho.core.system.PentahoSystem;
048:        import org.pentaho.core.util.DatasourceHelper;
049:        import org.pentaho.messages.MessageUtil;
050:        import org.pentaho.messages.Messages;
051:
052:        public class HibernateUtil implements  IPentahoSystemEntryPoint,
053:                IPentahoSystemExitPoint {
054:
055:            private static Log log = LogFactory.getLog(HibernateUtil.class);
056:
057:            private final static boolean debug = PentahoSystem.debug;
058:
059:            private static Configuration configuration;
060:
061:            private static SessionFactory sessionFactory;
062:
063:            private static final byte[] lock = new byte[0];
064:
065:            private static final ThreadLocal threadSession = new ThreadLocal();
066:
067:            private static final ThreadLocal threadTransaction = new ThreadLocal();
068:
069:            private static final ThreadLocal threadInterceptor = new ThreadLocal();
070:
071:            // private static final ThreadLocal commitNeeded = new ThreadLocal();
072:            private static boolean hibernateManaged;
073:
074:            private static String factoryJndiName;
075:
076:            private static String dialect;
077:
078:            private static Context iniCtx;
079:
080:            private static List objectHandlers = new ArrayList();
081:
082:            private static final String QUERYWILDCARD = "%{0}%"; //$NON-NLS-1$
083:
084:            static {
085:                // JIRA case #PLATFORM 150: removed listener and changed to lazy init
086:                initialize();
087:            }
088:
089:            //
090:            private HibernateUtil() {
091:            }
092:
093:            protected static boolean initialize() {
094:                IApplicationContext applicationContext = PentahoSystem
095:                        .getApplicationContext();
096:                // Add to entry/exit points list
097:                HibernateUtil hUtil = new HibernateUtil();
098:                applicationContext.addEntryPointHandler(hUtil);
099:                applicationContext.addExitPointHandler(hUtil);
100:
101:                // Look for some hibernate-specific properties...
102:                String hibernateConfigurationFile = applicationContext
103:                        .getProperty("hibernateConfigPath", null); //$NON-NLS-1$
104:                if ((hibernateConfigurationFile != null)) {
105:                    if (hibernateConfigurationFile.trim().length() == 0) {
106:                        hibernateConfigurationFile = null;
107:                    }
108:                }
109:                String tmp = applicationContext.getProperty(
110:                        "hibernateManaged", "false").trim().toLowerCase(); //$NON-NLS-1$ //$NON-NLS-2$
111:                hibernateManaged = tmp.equals("true"); //$NON-NLS-1$
112:                try {
113:                    configuration = new Configuration();
114:                    configuration
115:                            .setEntityResolver(new PentahoEntityResolver());
116:                    configuration.setListener(
117:                            "load", new HibernateLoadEventListener()); //$NON-NLS-1$
118:
119:                    if (hibernateConfigurationFile != null) {
120:                        String configPath = applicationContext
121:                                .getSolutionPath(hibernateConfigurationFile);
122:                        File cfgFile = new File(configPath);
123:                        if (cfgFile.exists()) {
124:                            configuration.configure(cfgFile);
125:                        } else {
126:                            log
127:                                    .error(Messages
128:                                            .getErrorString(
129:                                                    "HIBUTIL.ERROR_0012_CONFIG_NOT_FOUND", configPath)); //$NON-NLS-1$
130:                            return false;
131:                        }
132:                    } else {
133:                        configuration.configure(); // Read in the .xml document
134:                    }
135:                    String dsName = configuration
136:                            .getProperty("connection.datasource"); //$NON-NLS-1$
137:                    if ((dsName != null)
138:                            && dsName.toUpperCase().endsWith("HIBERNATE")) { //$NON-NLS-1$
139:                        String actualDSName = DatasourceHelper
140:                                .getDSBoundName("Hibernate"); //$NON-NLS-1$
141:                        configuration
142:                                .setProperty(
143:                                        "hibernate.connection.datasource", actualDSName); //$NON-NLS-1$
144:                    }
145:
146:                    dialect = configuration.getProperty("dialect"); //$NON-NLS-1$
147:
148:                    setupConfigurationHandlers();
149:                    // Add in the classes we know about.
150:                    addConfigurations(configuration);
151:
152:                    /*
153:                     * configuration.addResource("org/pentaho/repository/runtime/RuntimeElement.hbm.xml");
154:                     * //$NON-NLS-1$
155:                     * configuration.addResource("org/pentaho/repository/content/ContentLocation.hbm.xml");//$NON-NLS-1$
156:                     * configuration.addResource("org/pentaho/repository/content/ContentItem.hbm.xml");//$NON-NLS-1$
157:                     * configuration.addResource("org/pentaho/repository/content/ContentItemFile.hbm.xml");//$NON-NLS-1$
158:                     * configuration.addResource("org/pentaho/repository/DefinitionVersionManager.hbm.xml");//$NON-NLS-1$
159:                     */
160:                    if (!hibernateManaged) {
161:                        log.info(Messages
162:                                .getString("HIBUTIL.USER_HIBERNATEUNMANAGED")); //$NON-NLS-1$
163:                        sessionFactory = configuration.buildSessionFactory();
164:                    } else {
165:                        factoryJndiName = configuration
166:                                .getProperty(Environment.SESSION_FACTORY_NAME);
167:                        if (factoryJndiName == null) {
168:                            log
169:                                    .error(Messages
170:                                            .getErrorString("HIBUTIL.ERROR_0013_NO_SESSION_FACTORY"));//$NON-NLS-1$
171:                            return false;
172:                        }
173:                        log.info(Messages
174:                                .getString("HIBUTIL.USER_HIBERNATEMANAGED")); //$NON-NLS-1$
175:                        configuration.buildSessionFactory(); // Let hibernate Bind it
176:                        // to JNDI...
177:                    }
178:                    Dialect.getDialect(configuration.getProperties());
179:                    DefinitionVersionManager.performAutoUpdateIfRequired();
180:                    return true;
181:                } catch (Throwable ex) {
182:                    log
183:                            .error(
184:                                    Messages
185:                                            .getErrorString("HIBUTIL.ERROR_0006_BUILD_SESSION_FACTORY"), ex); //$NON-NLS-1$
186:                    throw new ExceptionInInitializerError(ex);
187:                }
188:            }
189:
190:            private static void setupConfigurationHandlers() {
191:                ISystemSettings systemSettings = PentahoSystem
192:                        .getSystemSettings();
193:                List objectHandlerDefs = systemSettings
194:                        .getSystemSettings("HibernatedObjectHandlers/*"); //$NON-NLS-1$
195:                if ((objectHandlerDefs != null)
196:                        && (objectHandlerDefs.size() > 0)) {
197:                    String handlerClass;
198:                    for (int i = 0; i < objectHandlerDefs.size(); i++) {
199:                        handlerClass = ((Node) objectHandlerDefs.get(i))
200:                                .getText();
201:                        IHibernatedObjectExtensionList extension = (IHibernatedObjectExtensionList) PentahoSystem
202:                                .createObject(handlerClass);
203:                        if (extension != null) {
204:                            objectHandlers.add(extension);
205:                        }
206:                    }
207:                } else {
208:                    // Handle old condition where it didn't exist in pentaho.xml
209:                    objectHandlers.add(new StdHibernateClassHandler());
210:                }
211:            }
212:
213:            private static void addConfigurations(Configuration theConfiguration) {
214:                IHibernatedObjectExtensionList extension;
215:                for (int i = 0; i < objectHandlers.size(); i++) {
216:                    extension = (IHibernatedObjectExtensionList) objectHandlers
217:                            .get(i);
218:                    List resourceList = extension
219:                            .getHibernatedObjectResourceList();
220:                    for (int j = 0; j < resourceList.size(); j++) {
221:                        theConfiguration.addResource((String) resourceList
222:                                .get(j));
223:                    }
224:                }
225:            }
226:
227:            /**
228:             * Returns the SessionFactory used for this static class.
229:             * 
230:             * @return SessionFactory
231:             */
232:            public static SessionFactory getSessionFactory() {
233:                if (!hibernateManaged) {
234:                    return sessionFactory;
235:                }
236:                SessionFactory sf = null;
237:                try {
238:                    if (iniCtx == null) {
239:                        iniCtx = new InitialContext();
240:                    }
241:                    String jndiName = factoryJndiName;
242:                    try {
243:                        sf = (SessionFactory) iniCtx.lookup(jndiName);
244:                    } catch (Exception ignored) {
245:                    }
246:                    if (sf == null) {
247:                        try {
248:                            sf = (SessionFactory) iniCtx
249:                                    .lookup("java:" + jndiName); //$NON-NLS-1$
250:                        } catch (Exception ignored) {
251:                            ignored.printStackTrace();
252:                        }
253:                    }
254:                } catch (NamingException ignored) {
255:                }
256:                return sf;
257:            }
258:
259:            /**
260:             * Returns the original Hibernate configuration.
261:             * 
262:             * @return Configuration
263:             */
264:            public static Configuration getConfiguration() {
265:                return configuration;
266:            }
267:
268:            public static void updateSchema() throws RepositoryException {
269:                PentahoSchemaUpdate upd = new PentahoSchemaUpdate(
270:                        getConfiguration());
271:                upd.execute(true, true);
272:            }
273:
274:            /**
275:             * Rebuild the SessionFactory with the static Configuration.
276:             * 
277:             */
278:            public static void rebuildSessionFactory()
279:                    throws RepositoryException {
280:                if (!hibernateManaged) {
281:                    synchronized (lock) {
282:                        try {
283:                            sessionFactory = getConfiguration()
284:                                    .buildSessionFactory();
285:                        } catch (Exception ex) {
286:                            log
287:                                    .error(
288:                                            Messages
289:                                                    .getErrorString("HIBUTIL.ERROR_0007_REBUILD_SESSION_FACTORY"), ex); //$NON-NLS-1$
290:                            throw new RepositoryException(
291:                                    Messages
292:                                            .getErrorString("HIBUTIL.ERROR_0007_REBUILD_SESSION_FACTORY"), ex); //$NON-NLS-1$
293:                        }
294:                    }
295:                } else {
296:                    try {
297:                        getConfiguration().buildSessionFactory();
298:                    } catch (Exception ex) {
299:                        log
300:                                .error(
301:                                        Messages
302:                                                .getErrorString("HIBUTIL.ERROR_0007_REBUILD_SESSION_FACTORY"), ex); //$NON-NLS-1$
303:                        throw new RepositoryException(
304:                                Messages
305:                                        .getErrorString("HIBUTIL.ERROR_0007_REBUILD_SESSION_FACTORY"), ex); //$NON-NLS-1$
306:                    }
307:                }
308:            }
309:
310:            /**
311:             * Rebuild the SessionFactory with the given Hibernate Configuration.
312:             * 
313:             * @param cfg
314:             */
315:            public static void rebuildSessionFactory(Configuration cfg)
316:                    throws RepositoryException {
317:                if (!hibernateManaged) {
318:                    synchronized (lock) {
319:                        try {
320:                            sessionFactory = cfg.buildSessionFactory();
321:                            configuration = cfg;
322:                        } catch (Exception ex) {
323:                            log
324:                                    .error(
325:                                            Messages
326:                                                    .getErrorString("HIBUTIL.ERROR_0007_REBUILD_SESSION_FACTORY"), ex); //$NON-NLS-1$
327:                            throw new RepositoryException(
328:                                    Messages
329:                                            .getErrorString("HIBUTIL.ERROR_0007_REBUILD_SESSION_FACTORY"), ex); //$NON-NLS-1$
330:                        }
331:                    }
332:                } else {
333:                    try {
334:                        cfg.buildSessionFactory();
335:                        configuration = cfg;
336:                    } catch (Exception ex) {
337:                        log
338:                                .error(
339:                                        Messages
340:                                                .getErrorString("HIBUTIL.ERROR_0007_REBUILD_SESSION_FACTORY"), ex); //$NON-NLS-1$
341:                        throw new RepositoryException(
342:                                Messages
343:                                        .getErrorString("HIBUTIL.ERROR_0007_REBUILD_SESSION_FACTORY"), ex); //$NON-NLS-1$
344:                    }
345:                }
346:            }
347:
348:            /**
349:             * Retrieves the current Session local to the thread. <p/> If no Session is
350:             * open, opens a new Session for the running thread.
351:             * 
352:             * @return Session
353:             */
354:            public static Session getSession() throws RepositoryException {
355:                Session s = (Session) threadSession.get();
356:                try {
357:                    if (s == null) {
358:                        if (debug)
359:                            log
360:                                    .debug(Messages
361:                                            .getString("HIBUTIL.DEBUG_OPEN_NEW_SESSION")); //$NON-NLS-1$
362:                        if (getInterceptor() != null) {
363:                            if (debug)
364:                                log
365:                                        .debug(Messages
366:                                                .getString("HIBUTIL.DEBUG_USING_INTERCEPTOR") + getInterceptor().getClass()); //$NON-NLS-1$
367:                            s = getSessionFactory().openSession(
368:                                    getInterceptor());
369:                        } else {
370:                            s = getSessionFactory().openSession();
371:                        }
372:                        threadSession.set(s);
373:                    }
374:                } catch (HibernateException ex) {
375:                    log
376:                            .error(
377:                                    Messages
378:                                            .getErrorString("HIBUTIL.ERROR_0005_GET_SESSION"), ex); //$NON-NLS-1$
379:                    throw new RepositoryException(
380:                            Messages
381:                                    .getErrorString("HIBUTIL.ERROR_0005_GET_SESSION"), ex); //$NON-NLS-1$
382:                }
383:                return s;
384:            }
385:
386:            public static void flushSession() throws RepositoryException {
387:                try {
388:                    Session s = getSession();
389:                    s.flush();
390:                } catch (HibernateException ex) {
391:                    throw new RepositoryException(ex);
392:                }
393:            }
394:
395:            /**
396:             * Closes the Session local to the thread.
397:             */
398:            public static void closeSession() throws RepositoryException {
399:                try {
400:                    Session s = (Session) threadSession.get();
401:                    threadSession.set(null);
402:                    if (s != null && s.isOpen()) {
403:                        if (debug)
404:                            log
405:                                    .debug(Messages
406:                                            .getString("HIBUTIL.DEBUG_CLOSING_SESSION")); //$NON-NLS-1$
407:                        s.close();
408:                    }
409:                    threadTransaction.set(null);
410:                } catch (HibernateException ex) {
411:                    log
412:                            .error(
413:                                    Messages
414:                                            .getErrorString("HIBUTIL.ERROR_0009_CLOSE_SESSION"), ex); //$NON-NLS-1$
415:                    threadTransaction.set(null);
416:                    throw new RepositoryException(
417:                            Messages
418:                                    .getErrorString("HIBUTIL.ERROR_0009_CLOSE_SESSION"), ex); //$NON-NLS-1$
419:                }
420:
421:            }
422:
423:            /**
424:             * Start a new database transaction.
425:             */
426:            public static void beginTransaction() throws RepositoryException {
427:                // commitNeeded.set(Boolean.TRUE);
428:                Transaction tx = (Transaction) threadTransaction.get();
429:                try {
430:                    if (tx == null) {
431:                        if (debug)
432:                            log.debug(Messages
433:                                    .getString("HIBUTIL.DEBUG_START_TRANS")); //$NON-NLS-1$
434:                        tx = getSession().beginTransaction();
435:                        threadTransaction.set(tx);
436:                    }
437:                } catch (HibernateException ex) {
438:                    log
439:                            .error(
440:                                    Messages
441:                                            .getErrorString("HIBUTIL.ERROR_0004_START_TRANS"), ex); //$NON-NLS-1$
442:                    throw new RepositoryException(
443:                            Messages
444:                                    .getErrorString("HIBUTIL.ERROR_0004_START_TRANS"), ex); //$NON-NLS-1$
445:                }
446:            }
447:
448:            /**
449:             * Commit the database transaction.
450:             */
451:            public static void commitTransaction() throws RepositoryException {
452:                // Boolean needed = (Boolean)commitNeeded.get();
453:                // if (needed.booleanValue()){
454:                Transaction tx = (Transaction) threadTransaction.get();
455:                try {
456:                    if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
457:                        if (debug)
458:                            log.debug(Messages
459:                                    .getString("HIBUTIL.DEBUG_COMMIT_TRANS")); //$NON-NLS-1$
460:                        tx.commit();
461:                    }
462:                } catch (HibernateException ex) {
463:                    log
464:                            .error(
465:                                    Messages
466:                                            .getErrorString("HIBUTIL.ERROR_0008_COMMIT_TRANS"), ex); //$NON-NLS-1$
467:                    try {
468:                        rollbackTransaction();
469:                    } catch (Exception e2) {
470:                    }
471:                    // throw new
472:                    // RepositoryException(Messages.getErrorString("HIBUTIL.ERROR_0008_COMMIT_TRANS"),
473:                    // ex); //$NON-NLS-1$
474:                } finally {
475:                    threadTransaction.set(null);
476:                }
477:                // }
478:                // commitNeeded.set(Boolean.FALSE);
479:            }
480:
481:            /**
482:             * Commit the database transaction.
483:             */
484:            public static void rollbackTransaction() throws RepositoryException {
485:                Transaction tx = (Transaction) threadTransaction.get();
486:                try {
487:                    threadTransaction.set(null);
488:                    if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
489:                        if (debug)
490:                            log.debug(Messages
491:                                    .getString("HIBUTIL.DEBUG_ROLLBACK")); //$NON-NLS-1$
492:                        tx.rollback();
493:                    }
494:                } catch (HibernateException ex) {
495:                    log.error(Messages
496:                            .getErrorString("HIBUTIL.ERROR_0003_ROLLBACK"), ex); //$NON-NLS-1$
497:                    throw new RepositoryException(Messages
498:                            .getErrorString("HIBUTIL.ERROR_0003_ROLLBACK"), ex); //$NON-NLS-1$
499:                } finally {
500:                    closeSession();
501:                }
502:            }
503:
504:            /**
505:             * Reconnects a Hibernate Session to the current Thread.
506:             * 
507:             * @param session
508:             *            The Hibernate Session to be reconnected.
509:             */
510:            /*
511:             * public static void reconnect(Session session) throws RepositoryException {
512:             * try { session.reconnect(); threadSession.set(session); } catch
513:             * (HibernateException ex) {
514:             * log.error(Messages.getErrorString("HIBUTIL.ERROR_0001_RECONNECT"), ex);
515:             * //$NON-NLS-1$ throw new RepositoryException(ex); } }
516:             */
517:            /**
518:             * Disconnect and return Session from current Thread.
519:             * 
520:             * @return Session the disconnected Session
521:             */
522:            public static Session disconnectSession()
523:                    throws RepositoryException {
524:
525:                Session session = getSession();
526:                try {
527:                    threadSession.set(null);
528:                    if (session.isConnected() && session.isOpen())
529:                        session.disconnect();
530:                } catch (HibernateException ex) {
531:                    log
532:                            .error(
533:                                    Messages
534:                                            .getErrorString("HIBUTIL.ERROR_0002_DISCONNECT"), ex); //$NON-NLS-1$
535:                    throw new RepositoryException(
536:                            Messages
537:                                    .getErrorString("HIBUTIL.ERROR_0002_DISCONNECT"), ex); //$NON-NLS-1$
538:                }
539:                return session;
540:            }
541:
542:            /**
543:             * Register a Hibernate interceptor with the current thread.
544:             * <p>
545:             * Every Session opened is opened with this interceptor after registration.
546:             * Has no effect if the current Session of the thread is already open,
547:             * effective on next close()/getSession().
548:             */
549:            public static void registerInterceptor(Interceptor interceptor) {
550:                threadInterceptor.set(interceptor);
551:            }
552:
553:            private static Interceptor getInterceptor() {
554:                Interceptor interceptor = (Interceptor) threadInterceptor.get();
555:                return interceptor;
556:            }
557:
558:            /**
559:             * Searches an ISearchable object for a search term. The search rules are as
560:             * follows:
561:             * 
562:             * If the searchType is ISearchable.SEARCH_TYPE_PHRASE, then the fields in
563:             * the table are searched for the exact phrase given.
564:             * 
565:             * If the searchType is ISearchable.SEARCH_TYPE_WORDS_AND or ..._OR, then
566:             * the following happens: a- Each word in the searchTerm is extracted and
567:             * put into a list of search terms. b- Each search term is surrounded by the
568:             * SQL wildcard '%'. So each search term becomes %term%. c- A dynamic query
569:             * is generated searching each of the columns for each search term d- The
570:             * searchType is used to determine the connector between each search term.
571:             * e- The AND will match only if all of the terms appear in a specific
572:             * column - cross-column searching using ..._AND will NOT work. In other
573:             * words, if your search term is "East Sales", and your search type is
574:             * ..._AND, a row will be returned if one of the columns contains East and
575:             * the same column contains Sales. A row will NOT be returned if one column
576:             * only contains East, and another column only contains Sales. This type of
577:             * functionality could be obtained using a view that concatenates all of the
578:             * searchable columns together into one large column, but this would be
579:             * costly and database-specific.
580:             * 
581:             * @param searchable
582:             *            ISearchable to search
583:             * @param searchTerm
584:             *            Search Term - see above for rules
585:             * @param searchType
586:             *            One of:
587:             *            ISearchable.SEARCH_TYPE_PHRASE,ISearchable.SEARCH_TYPE_WORDS_AND,
588:             *            ISearchable.SEARCH_TYPE_WORDS_OR
589:             * @return A list of objects from Hibernate that met the conditions
590:             *         specified.
591:             */
592:            public static List searchForTerm(ISearchable searchable,
593:                    String searchTerm, int searchType) {
594:                Session session = getSession();
595:                if (searchType == ISearchable.SEARCH_TYPE_PHRASE) {
596:                    Query qry = session.getNamedQuery(searchable
597:                            .getPhraseSearchQueryName());
598:                    String searchWildcard = MessageUtil.formatErrorMessage(
599:                            QUERYWILDCARD, searchTerm);
600:                    qry.setString("searchTerm", searchWildcard); //$NON-NLS-1$
601:                    List rtn = qry.list();
602:                    return rtn;
603:                }
604:                String connector;
605:                if (searchType == ISearchable.SEARCH_TYPE_WORDS_AND) {
606:                    connector = " and "; //$NON-NLS-1$
607:                } else {
608:                    connector = " or "; //$NON-NLS-1$
609:                }
610:                StringTokenizer st = new StringTokenizer(searchTerm, " "); //$NON-NLS-1$
611:                List searchWords = new ArrayList();
612:                while (st.hasMoreTokens()) {
613:                    searchWords.add(MessageUtil.formatErrorMessage(
614:                            QUERYWILDCARD, st.nextToken()));
615:                }
616:                // Ok, we now have a list of search words.
617:                StringBuffer assembly = assembleQuery(searchable
618:                        .getSearchableTable(), connector, searchWords,
619:                        searchable.getSearchableColumns());
620:                Query qry = session.createQuery(assembly.toString());
621:                for (int j = 0; j < searchWords.size(); j++) {
622:                    qry.setParameter("searchTerm" + j, searchWords.get(j)); //$NON-NLS-1$
623:                }
624:                List rtn = qry.list();
625:                return rtn;
626:            }
627:
628:            private static StringBuffer assembleQuery(String tableName,
629:                    String connector, List terms, String[] columns) {
630:                StringBuffer qry = new StringBuffer();
631:                qry.append("from ").append(tableName).append(" tbl where "); //$NON-NLS-1$ //$NON-NLS-2$
632:                String currCol, term;
633:                for (int colno = 0; colno < columns.length; colno++) {
634:                    currCol = columns[colno];
635:                    qry.append("("); //$NON-NLS-1$
636:                    for (int termNo = 0; termNo < terms.size(); termNo++) {
637:                        term = (String) terms.get(termNo);
638:                        qry
639:                                .append("tbl.").append(currCol).append(" like :searchTerm").append(term).append(" "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
640:                        if (termNo < terms.size() - 1) {
641:                            qry.append(connector);
642:                        }
643:                    }
644:                    qry.append(")"); //$NON-NLS-1$
645:                    if (colno < columns.length - 1) {
646:                        qry.append(" or "); // Columns are always or'd //$NON-NLS-1$
647:                    }
648:                }
649:                return qry;
650:            }
651:
652:            public static void clear() {
653:                getSession().clear();
654:            }
655:
656:            /**
657:             * Persists changes to the object. Object must be defined to hibernate.
658:             * 
659:             * @param obj
660:             *            The object to make persistent
661:             * @throws RepositoryException
662:             */
663:            public static void makePersistent(Object obj)
664:                    throws RepositoryException {
665:                if (debug)
666:                    log.debug(Messages.getString(
667:                            "HIBUTIL.DEBUG_MAKE_PERSISTENT", obj.toString())); //$NON-NLS-1$
668:                try {
669:                    getSession().saveOrUpdate(obj);
670:                } catch (HibernateException ex) {
671:                    log
672:                            .error(
673:                                    Messages
674:                                            .getErrorString("HIBUTIL.ERROR_0010_SAVING_UPDATING"), ex); //$NON-NLS-1$
675:                    throw new ContentException(
676:                            Messages
677:                                    .getErrorString("HIBUTIL.ERROR_0010_SAVING_UPDATING"), ex); //$NON-NLS-1$
678:                }
679:            }
680:
681:            /**
682:             * Deletes the object from Hibernate
683:             * 
684:             * @param obj
685:             *            The object to make transient
686:             * @throws RepositoryException
687:             */
688:            public static void makeTransient(Object obj)
689:                    throws RepositoryException {
690:                if (debug)
691:                    log.debug(Messages.getString(
692:                            "HIBUTIL.DEBUG_MAKE_TRANSIENT", obj.toString())); //$NON-NLS-1$
693:                try {
694:                    getSession().delete(obj);
695:                } catch (HibernateException ex) {
696:                    log
697:                            .error(
698:                                    Messages
699:                                            .getErrorString("HIBUTIL.ERROR_0011_DELETING_OBJ"), ex); //$NON-NLS-1$
700:                    throw new ContentException(
701:                            Messages
702:                                    .getErrorString("HIBUTIL.ERROR_0011_DELETING_OBJ"), ex); //$NON-NLS-1$
703:                }
704:            }
705:
706:            /**
707:             * HACK This method is necessary to determine whether code should execute based on Oracle
708:             * in use as the RDBMS repository for the platform. Helps us work around Oracle 
709:             * JDBC driver bugs. 
710:             * 
711:             * @return true if Hibernate dialect for oracle is in use. 
712:             */
713:            public static boolean isOracleDialect() {
714:                return dialect.indexOf("oracle") >= 0 || //$NON-NLS-1$
715:                        dialect.indexOf("Oracle") >= 0 || //$NON-NLS-1$
716:                        dialect.indexOf("ORACLE") >= 0; //$NON-NLS-1$
717:            }
718:
719:            /**
720:             * Evicts the object from the Hibernate cache. Call this if you don't
721:             * believe you'll need this object in the cache. This is also good to call
722:             * if you're doing semi-mass updates.
723:             * 
724:             * @param obj
725:             */
726:            public static void evict(Object obj) {
727:                // if (debug)
728:                // log.debug(Messages.getString("HIBUTIL.DEBUG_EVICT", obj.toString())); //$NON-NLS-1$
729:                try {
730:                    getSession().evict(obj);
731:                } catch (HibernateException ex) {
732:                    log
733:                            .error(
734:                                    Messages
735:                                            .getErrorString("HIBUTIL.ERROR_0014_EVICTING_OBJECT"), ex); //$NON-NLS-1$
736:                }
737:
738:            }
739:
740:            public static List getHibernatedObjectHandlerList() {
741:                return objectHandlers;
742:            }
743:
744:            public void systemEntryPoint() {
745:                // No need to do anything for Hibernate here.
746:            }
747:
748:            public void systemExitPoint() {
749:                try {
750:                    HibernateUtil.commitTransaction();
751:                } catch (Throwable t) {
752:                    // get some real logging code in here
753:                    t.printStackTrace();
754:                }
755:
756:                try {
757:                    HibernateUtil.closeSession();
758:                } catch (Throwable t) {
759:                    // get some real logging code in here
760:                    t.printStackTrace();
761:                }
762:            }
763:
764:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.