===================================================================== Found a 185 line (553 tokens) duplication in the following files: Starting at line 363 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/SessionFactoryUtils.java Starting at line 331 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/SessionFactoryUtils.java } /** * Retrieve a Session from the given SessionHolder, potentially from a * JTA transaction synchronization. * @param sessionHolder the SessionHolder to check * @param sessionFactory the SessionFactory to get the JTA TransactionManager from * @param jdbcExceptionTranslator SQLExceptionTranslator to use for flushing the * Session on transaction synchronization (can be null) * @return the associated Session, if any * @throws DataAccessResourceFailureException if the Session couldn't be created */ private static Session getJtaSynchronizedSession( SessionHolder sessionHolder, SessionFactory sessionFactory, SQLExceptionTranslator jdbcExceptionTranslator) throws DataAccessResourceFailureException { // JTA synchronization is only possible with a javax.transaction.TransactionManager. // We'll check the Hibernate SessionFactory: If a TransactionManagerLookup is specified // in Hibernate configuration, it will contain a TransactionManager reference. TransactionManager jtaTm = getJtaTransactionManager(sessionFactory, sessionHolder.getAnySession()); if (jtaTm != null) { // Check whether JTA transaction management is active -> // fetch pre-bound Session for the current JTA transaction, if any. // (just necessary for JTA transaction suspension, with an individual // Hibernate Session per currently active/suspended transaction) try { int jtaStatus = jtaTm.getStatus(); if (jtaStatus == Status.STATUS_ACTIVE || jtaStatus == Status.STATUS_MARKED_ROLLBACK) { // look for transaction-specific Session Transaction jtaTx = jtaTm.getTransaction(); Session session = sessionHolder.getValidatedSession(jtaTx); if (session == null && !sessionHolder.isSynchronizedWithTransaction()) { // No transaction-specific Session found: If not already marked as // synchronized with transaction, register the default thread-bound // Session as JTA-transactional. If there is no default Session, // we're a new inner JTA transaction with an outer one being suspended: // In that case, we'll return null to trigger opening of a new Session. session = sessionHolder.getValidatedSession(); if (session != null) { logger.debug("Registering JTA transaction synchronization for existing Hibernate Session"); sessionHolder.addSession(jtaTx, session); jtaTx.registerSynchronization( new JtaSessionSynchronization( new SpringSessionSynchronization( sessionHolder, sessionFactory, jdbcExceptionTranslator, false), jtaTm)); sessionHolder.setSynchronizedWithTransaction(true); // Switch to FlushMode.AUTO if we're not within a read-only transaction. FlushMode flushMode = session.getFlushMode(); if (FlushMode.NEVER.equals(flushMode)) { session.setFlushMode(FlushMode.AUTO); sessionHolder.setPreviousFlushMode(flushMode); } } } return session; } else { // No transaction active -> simply return default thread-bound Session, if any // (possibly from OpenSessionInViewFilter/Interceptor). return sessionHolder.getValidatedSession(); } } catch (Exception ex) { throw new DataAccessResourceFailureException("Could not check JTA transaction", ex); } } else { // No JTA TransactionManager -> simply return default thread-bound Session, if any // (possibly from OpenSessionInViewFilter/Interceptor). return sessionHolder.getValidatedSession(); } } /** * Register a JTA synchronization for the given Session, if any. * @param sessionHolder the existing thread-bound SessionHolder, if any * @param session the Session to register * @param sessionFactory the SessionFactory that the Session was created with * @param jdbcExceptionTranslator SQLExcepionTranslator to use for flushing the * Session on transaction synchronization (can be null) */ private static void registerJtaSynchronization(Session session, SessionFactory sessionFactory, SQLExceptionTranslator jdbcExceptionTranslator, SessionHolder sessionHolder) { // JTA synchronization is only possible with a javax.transaction.TransactionManager. // We'll check the Hibernate SessionFactory: If a TransactionManagerLookup is specified // in Hibernate configuration, it will contain a TransactionManager reference. TransactionManager jtaTm = getJtaTransactionManager(sessionFactory, session); if (jtaTm != null) { try { int jtaStatus = jtaTm.getStatus(); if (jtaStatus == Status.STATUS_ACTIVE || jtaStatus == Status.STATUS_MARKED_ROLLBACK) { logger.debug("Registering JTA transaction synchronization for new Hibernate Session"); javax.transaction.Transaction jtaTx = jtaTm.getTransaction(); SessionHolder holderToUse = sessionHolder; // Register JTA Transaction with existing SessionHolder. // Create a new SessionHolder if none existed before. if (holderToUse == null) { holderToUse = new SessionHolder(jtaTx, session); } else { holderToUse.addSession(jtaTx, session); } jtaTx.registerSynchronization( new JtaSessionSynchronization( new SpringSessionSynchronization( holderToUse, sessionFactory, jdbcExceptionTranslator, true), jtaTm)); holderToUse.setSynchronizedWithTransaction(true); if (holderToUse != sessionHolder) { TransactionSynchronizationManager.bindResource(sessionFactory, holderToUse); } } } catch (Exception ex) { throw new DataAccessResourceFailureException( "Could not register synchronization with JTA TransactionManager", ex); } } } /** * Get a new Hibernate Session from the given SessionFactory. * Will return a new Session even if there already is a pre-bound * Session for the given SessionFactory. *

Within a transaction, this method will create a new Session * that shares the transaction's JDBC Connection. More specifically, * it will use the same JDBC Connection as the pre-bound Hibernate Session. * @param sessionFactory Hibernate SessionFactory to create the session with * @return the new Session */ public static Session getNewSession(SessionFactory sessionFactory) { return getNewSession(sessionFactory, null); } /** * Get a new Hibernate Session from the given SessionFactory. * Will return a new Session even if there already is a pre-bound * Session for the given SessionFactory. *

Within a transaction, this method will create a new Session * that shares the transaction's JDBC Connection. More specifically, * it will use the same JDBC Connection as the pre-bound Hibernate Session. * @param sessionFactory Hibernate SessionFactory to create the session with * @param entityInterceptor Hibernate entity interceptor, or null if none * @return the new Session */ public static Session getNewSession(SessionFactory sessionFactory, Interceptor entityInterceptor) { Assert.notNull(sessionFactory, "No SessionFactory specified"); try { SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory); if (sessionHolder != null && !sessionHolder.isEmpty()) { if (entityInterceptor != null) { return sessionFactory.openSession(sessionHolder.getAnySession().connection(), entityInterceptor); } else { return sessionFactory.openSession(sessionHolder.getAnySession().connection()); } } else { if (entityInterceptor != null) { return sessionFactory.openSession(entityInterceptor); } else { return sessionFactory.openSession(); } } } catch (HibernateException ex) { throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex); } } /** * Return whether the given Hibernate Session is transactional, that is, * bound to the current thread by Spring's transaction facilities. * @param session the Hibernate Session to check * @param sessionFactory Hibernate SessionFactory that the Session was created with * (can be null) * @return whether the Session is transactional */ public static boolean isSessionTransactional(Session session, SessionFactory sessionFactory) { ===================================================================== Found a 166 line (518 tokens) duplication in the following files: Starting at line 829 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/LocalSessionFactoryBean.java Starting at line 554 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/LocalSessionFactoryBean.java return config.buildSessionFactory(); } /** * Execute schema drop script, determined by the Configuration object * used for creating the SessionFactory. A replacement for Hibernate's * SchemaExport class, to be invoked on application setup. *

Fetch the LocalSessionFactoryBean itself rather than the exposed * SessionFactory to be able to invoke this method, e.g. via * LocalSessionFactoryBean lsfb = (LocalSessionFactoryBean) ctx.getBean("&mySessionFactory");. *

Uses the SessionFactory that this bean generates for accessing a JDBC * connection to perform the script. * @throws DataAccessException in case of script execution errors * @see net.sf.hibernate.cfg.Configuration#generateDropSchemaScript * @see net.sf.hibernate.tool.hbm2ddl.SchemaExport#drop */ public void dropDatabaseSchema() throws DataAccessException { logger.info("Dropping database schema for Hibernate SessionFactory"); HibernateTemplate hibernateTemplate = new HibernateTemplate(this.sessionFactory); hibernateTemplate.execute( new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Connection con = session.connection(); Dialect dialect = Dialect.getDialect(configuration.getProperties()); String[] sql = configuration.generateDropSchemaScript(dialect); executeSchemaScript(con, sql); return null; } } ); } /** * Execute schema creation script, determined by the Configuration object * used for creating the SessionFactory. A replacement for Hibernate's * SchemaExport class, to be invoked on application setup. *

Fetch the LocalSessionFactoryBean itself rather than the exposed * SessionFactory to be able to invoke this method, e.g. via * LocalSessionFactoryBean lsfb = (LocalSessionFactoryBean) ctx.getBean("&mySessionFactory");. *

Uses the SessionFactory that this bean generates for accessing a JDBC * connection to perform the script. * @throws DataAccessException in case of script execution errors * @see net.sf.hibernate.cfg.Configuration#generateSchemaCreationScript * @see net.sf.hibernate.tool.hbm2ddl.SchemaExport#create */ public void createDatabaseSchema() throws DataAccessException { logger.info("Creating database schema for Hibernate SessionFactory"); HibernateTemplate hibernateTemplate = new HibernateTemplate(this.sessionFactory); hibernateTemplate.execute( new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Connection con = session.connection(); final Dialect dialect = Dialect.getDialect(configuration.getProperties()); String[] sql = configuration.generateSchemaCreationScript(dialect); executeSchemaScript(con, sql); return null; } } ); } /** * Execute schema update script, determined by the Configuration object * used for creating the SessionFactory. A replacement for Hibernate's * SchemaUpdate class, for automatically executing schema update scripts * on application startup. Can also be invoked manually. *

Fetch the LocalSessionFactoryBean itself rather than the exposed * SessionFactory to be able to invoke this method, e.g. via * LocalSessionFactoryBean lsfb = (LocalSessionFactoryBean) ctx.getBean("&mySessionFactory");. *

Uses the SessionFactory that this bean generates for accessing a JDBC * connection to perform the script. * @throws HibernateException in case of Hibernate initialization errors * @see #setSchemaUpdate * @see net.sf.hibernate.cfg.Configuration#generateSchemaUpdateScript * @see net.sf.hibernate.tool.hbm2ddl.SchemaUpdate */ public void updateDatabaseSchema() throws HibernateException { logger.info("Updating database schema for Hibernate SessionFactory"); HibernateTemplate hibernateTemplate = new HibernateTemplate(this.sessionFactory); hibernateTemplate.setFlushMode(HibernateTemplate.FLUSH_NEVER); hibernateTemplate.execute( new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Connection con = session.connection(); final Dialect dialect = Dialect.getDialect(configuration.getProperties()); DatabaseMetadata metadata = new DatabaseMetadata(con, dialect); String[] sql = configuration.generateSchemaUpdateScript(dialect, metadata); executeSchemaScript(con, sql); return null; } } ); } /** * Execute the given schema script on the given JDBC Connection. * Will log unsuccessful statements and continue to execute. * @param con the JDBC Connection to execute the script on * @param sql the SQL statements to execute * @throws SQLException if thrown by JDBC methods */ protected void executeSchemaScript(Connection con, String[] sql) throws SQLException { if (sql != null && sql.length > 0) { boolean oldAutoCommit = con.getAutoCommit(); if (!oldAutoCommit) { con.setAutoCommit(true); } try { Statement stmt = con.createStatement(); try { for (int i = 0; i < sql.length; i++) { logger.debug("Executing schema statement: " + sql[i]); try { stmt.executeUpdate(sql[i]); } catch (SQLException ex) { logger.warn("Unsuccessful schema statement: " + sql[i], ex); } } } finally { JdbcUtils.closeStatement(stmt); } } finally { if (!oldAutoCommit) { con.setAutoCommit(false); } } } } /** * Return the Configuration object used to build the SessionFactory. * Allows access to configuration metadata stored there (rarely needed). */ public Configuration getConfiguration() { return configuration; } /** * Return the singleton SessionFactory. */ public Object getObject() { return this.sessionFactory; } public Class getObjectType() { return (this.sessionFactory != null) ? this.sessionFactory.getClass() : SessionFactory.class; } public boolean isSingleton() { return true; } /** * Close the SessionFactory on bean factory shutdown. */ public void destroy() throws HibernateException { logger.info("Closing Hibernate SessionFactory"); this.sessionFactory.close(); } ===================================================================== Found a 153 line (449 tokens) duplication in the following files: Starting at line 86 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/support/PortletOpenSessionInViewInterceptor.java Starting at line 86 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/support/PortletOpenSessionInViewInterceptor.java public class PortletOpenSessionInViewInterceptor extends HibernateAccessor implements HandlerInterceptor { /** * Suffix that gets appended to the SessionFactory toString representation * for the "participate in existing session handling" request attribute. * @see #getParticipateAttributeName */ public static final String PARTICIPATE_SUFFIX = ".PARTICIPATE"; private boolean singleSession = true; /** * Create a new PortletOpenSessionInViewInterceptor, * turning the default flushMode to FLUSH_NEVER. * @see #setFlushMode */ public PortletOpenSessionInViewInterceptor() { setFlushMode(FLUSH_NEVER); } /** * Set whether to use a single session for each request. Default is true. *

If set to false, each data access operation or transaction will use * its own session (like without Open Session in View). Each of those * sessions will be registered for deferred close, though, actually * processed at request completion. * @see SessionFactoryUtils#initDeferredClose * @see SessionFactoryUtils#processDeferredClose */ public void setSingleSession(boolean singleSession) { this.singleSession = singleSession; } /** * Return whether to use a single session for each request. */ protected boolean isSingleSession() { return singleSession; } /** * Open a new Hibernate Session according to the settings of this HibernateAccessor * and binds in to the thread via TransactionSynchronizationManager. * @see org.springframework.orm.hibernate.SessionFactoryUtils#getSession * @see org.springframework.transaction.support.TransactionSynchronizationManager */ public boolean preHandle(PortletRequest request, PortletResponse response, Object handler) throws DataAccessException { if ((isSingleSession() && TransactionSynchronizationManager.hasResource(getSessionFactory())) || SessionFactoryUtils.isDeferredCloseActive(getSessionFactory())) { // Do not modify the Session: just mark the request accordingly. String participateAttributeName = getParticipateAttributeName(); Integer count = (Integer) request.getAttribute(participateAttributeName); int newCount = (count != null) ? count.intValue() + 1 : 1; request.setAttribute(getParticipateAttributeName(), new Integer(newCount)); } else { if (isSingleSession()) { // single session mode logger.debug("Opening single Hibernate Session in PortletOpenSessionInViewInterceptor"); Session session = SessionFactoryUtils.getSession( getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator()); applyFlushMode(session, false); TransactionSynchronizationManager.bindResource(getSessionFactory(), new SessionHolder(session)); } else { // deferred close mode SessionFactoryUtils.initDeferredClose(getSessionFactory()); } } return true; } /** * Flush the Hibernate Session before view rendering, if necessary. * Note that this just applies in single session mode! *

The default is FLUSH_NEVER to avoid this extra flushing, assuming that * middle tier transactions have flushed their changes on commit. * @see #setFlushMode */ public void postHandle( RenderRequest request, RenderResponse response, Object handler, ModelAndView modelAndView) throws DataAccessException { if (isSingleSession()) { // only potentially flush in single session mode SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory()); logger.debug("Flushing single Hibernate Session in PortletOpenSessionInViewInterceptor"); try { flushIfNecessary(sessionHolder.getSession(), false); } catch (HibernateException ex) { throw convertHibernateAccessException(ex); } } } /** * Unbind the Hibernate Session from the thread and closes it (in single session * mode), or process deferred close for all sessions that have been opened * during the current request (in deferred close mode). * @see org.springframework.orm.hibernate.SessionFactoryUtils#releaseSession * @see org.springframework.transaction.support.TransactionSynchronizationManager */ public void afterCompletion( PortletRequest request, PortletResponse response, Object handler, Exception ex) throws DataAccessException { String participateAttributeName = getParticipateAttributeName(); Integer count = (Integer) request.getAttribute(participateAttributeName); if (count != null) { // Do not modify the Session: just clear the marker. if (count.intValue() > 1) { request.setAttribute(participateAttributeName, new Integer(count.intValue() - 1)); } else { request.removeAttribute(participateAttributeName); } } else { if (isSingleSession()) { // single session mode SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(getSessionFactory()); logger.debug("Closing single Hibernate Session in PortletOpenSessionInViewInterceptor"); SessionFactoryUtils.releaseSession(sessionHolder.getSession(), getSessionFactory()); } else { // deferred close mode SessionFactoryUtils.processDeferredClose(getSessionFactory()); } } } /** * Return the name of the request attribute that identifies that a request is * already filtered. Default implementation takes the toString representation * of the SessionFactory instance and appends ".PARTICIPATE". * @see #PARTICIPATE_SUFFIX */ protected String getParticipateAttributeName() { return getSessionFactory().toString() + PARTICIPATE_SUFFIX; } } ===================================================================== Found a 153 line (449 tokens) duplication in the following files: Starting at line 84 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/support/OpenSessionInViewInterceptor.java Starting at line 84 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/support/OpenSessionInViewInterceptor.java public class OpenSessionInViewInterceptor extends HibernateAccessor implements HandlerInterceptor { /** * Suffix that gets appended to the SessionFactory toString representation * for the "participate in existing session handling" request attribute. * @see #getParticipateAttributeName */ public static final String PARTICIPATE_SUFFIX = ".PARTICIPATE"; private boolean singleSession = true; /** * Create a new OpenSessionInViewInterceptor, * turning the default flushMode to FLUSH_NEVER. * @see #setFlushMode */ public OpenSessionInViewInterceptor() { setFlushMode(FLUSH_NEVER); } /** * Set whether to use a single session for each request. Default is "true". *

If set to false, each data access operation or transaction will use * its own session (like without Open Session in View). Each of those * sessions will be registered for deferred close, though, actually * processed at request completion. * @see SessionFactoryUtils#initDeferredClose * @see SessionFactoryUtils#processDeferredClose */ public void setSingleSession(boolean singleSession) { this.singleSession = singleSession; } /** * Return whether to use a single session for each request. */ protected boolean isSingleSession() { return singleSession; } /** * Open a new Hibernate Session according to the settings of this HibernateAccessor * and binds in to the thread via TransactionSynchronizationManager. * @see org.springframework.orm.hibernate.SessionFactoryUtils#getSession * @see org.springframework.transaction.support.TransactionSynchronizationManager */ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws DataAccessException { if ((isSingleSession() && TransactionSynchronizationManager.hasResource(getSessionFactory())) || SessionFactoryUtils.isDeferredCloseActive(getSessionFactory())) { // Do not modify the Session: just mark the request accordingly. String participateAttributeName = getParticipateAttributeName(); Integer count = (Integer) request.getAttribute(participateAttributeName); int newCount = (count != null) ? count.intValue() + 1 : 1; request.setAttribute(getParticipateAttributeName(), new Integer(newCount)); } else { if (isSingleSession()) { // single session mode logger.debug("Opening single Hibernate Session in OpenSessionInViewInterceptor"); Session session = SessionFactoryUtils.getSession( getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator()); applyFlushMode(session, false); TransactionSynchronizationManager.bindResource(getSessionFactory(), new SessionHolder(session)); } else { // deferred close mode SessionFactoryUtils.initDeferredClose(getSessionFactory()); } } return true; } /** * Flush the Hibernate Session before view rendering, if necessary. * Note that this just applies in single session mode! *

The default is FLUSH_NEVER to avoid this extra flushing, assuming that * middle tier transactions have flushed their changes on commit. * @see #setFlushMode */ public void postHandle( HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws DataAccessException { if (isSingleSession()) { // only potentially flush in single session mode SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory()); logger.debug("Flushing single Hibernate Session in OpenSessionInViewInterceptor"); try { flushIfNecessary(sessionHolder.getSession(), false); } catch (HibernateException ex) { throw convertHibernateAccessException(ex); } } } /** * Unbind the Hibernate Session from the thread and closes it (in single session * mode), or process deferred close for all sessions that have been opened * during the current request (in deferred close mode). * @see org.springframework.orm.hibernate.SessionFactoryUtils#releaseSession * @see org.springframework.transaction.support.TransactionSynchronizationManager */ public void afterCompletion( HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws DataAccessException { String participateAttributeName = getParticipateAttributeName(); Integer count = (Integer) request.getAttribute(participateAttributeName); if (count != null) { // Do not modify the Session: just clear the marker. if (count.intValue() > 1) { request.setAttribute(participateAttributeName, new Integer(count.intValue() - 1)); } else { request.removeAttribute(participateAttributeName); } } else { if (isSingleSession()) { // single session mode SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(getSessionFactory()); logger.debug("Closing single Hibernate Session in OpenSessionInViewInterceptor"); SessionFactoryUtils.releaseSession(sessionHolder.getSession(), getSessionFactory()); } else { // deferred close mode SessionFactoryUtils.processDeferredClose(getSessionFactory()); } } } /** * Return the name of the request attribute that identifies that a request is * already filtered. Default implementation takes the toString representation * of the SessionFactory instance and appends ".PARTICIPATE". * @see #PARTICIPATE_SUFFIX */ protected String getParticipateAttributeName() { return getSessionFactory().toString() + PARTICIPATE_SUFFIX; } } ===================================================================== Found a 112 line (431 tokens) duplication in the following files: Starting at line 42 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/SessionHolder.java Starting at line 42 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/SessionHolder.java public class SessionHolder extends ResourceHolderSupport { private static final Object DEFAULT_KEY = new Object(); /** * This Map needs to be synchronized because there might be multi-threaded * access in the case of JTA with remote transaction propagation. */ private final Map sessionMap = Collections.synchronizedMap(new HashMap(1)); private Transaction transaction; private FlushMode previousFlushMode; public SessionHolder(Session session) { addSession(session); } public SessionHolder(Object key, Session session) { addSession(key, session); } public Session getSession() { return getSession(DEFAULT_KEY); } public Session getSession(Object key) { return (Session) this.sessionMap.get(key); } public Session getValidatedSession() { return getValidatedSession(DEFAULT_KEY); } public Session getValidatedSession(Object key) { Session session = (Session) this.sessionMap.get(key); // Check for dangling Session that's around but already closed. // Effectively an assertion: that should never happen in practice. // We'll seamlessly remove the Session here, to not let it cause // any side effects. if (session != null && !session.isOpen()) { this.sessionMap.remove(key); session = null; } return session; } public Session getAnySession() { synchronized (this.sessionMap) { if (!this.sessionMap.isEmpty()) { return (Session) this.sessionMap.values().iterator().next(); } return null; } } public void addSession(Session session) { addSession(DEFAULT_KEY, session); } public void addSession(Object key, Session session) { Assert.notNull(key, "Key must not be null"); Assert.notNull(session, "Session must not be null"); this.sessionMap.put(key, session); } public Session removeSession(Object key) { return (Session) this.sessionMap.remove(key); } public boolean containsSession(Session session) { return this.sessionMap.containsValue(session); } public boolean isEmpty() { return this.sessionMap.isEmpty(); } public boolean doesNotHoldNonDefaultSession() { synchronized (this.sessionMap) { return this.sessionMap.isEmpty() || (this.sessionMap.size() == 1 && this.sessionMap.containsKey(DEFAULT_KEY)); } } public void setTransaction(Transaction transaction) { this.transaction = transaction; } public Transaction getTransaction() { return transaction; } public void setPreviousFlushMode(FlushMode previousFlushMode) { this.previousFlushMode = previousFlushMode; } public FlushMode getPreviousFlushMode() { return previousFlushMode; } public void clear() { super.clear(); this.transaction = null; this.previousFlushMode = null; } } ===================================================================== Found a 248 line (403 tokens) duplication in the following files: Starting at line 115 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/HibernateTemplate.java Starting at line 114 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/HibernateTemplate.java public class HibernateTemplate extends HibernateAccessor implements HibernateOperations { private boolean allowCreate = true; private boolean alwaysUseNewSession = false; private boolean exposeNativeSession = false; private boolean checkWriteOperations = true; private boolean cacheQueries = false; private String queryCacheRegion; private int fetchSize = 0; private int maxResults = 0; /** * Create a new HibernateTemplate instance. */ public HibernateTemplate() { } /** * Create a new HibernateTemplate instance. * @param sessionFactory SessionFactory to create Sessions */ public HibernateTemplate(SessionFactory sessionFactory) { setSessionFactory(sessionFactory); afterPropertiesSet(); } /** * Create a new HibernateTemplate instance. * @param sessionFactory SessionFactory to create Sessions * @param allowCreate if a non-transactional Session should be created when no * transactional Session can be found for the current thread */ public HibernateTemplate(SessionFactory sessionFactory, boolean allowCreate) { setSessionFactory(sessionFactory); setAllowCreate(allowCreate); afterPropertiesSet(); } /** * Set if a new Session should be created when no transactional Session * can be found for the current thread. *

HibernateTemplate is aware of a corresponding Session bound to the * current thread, for example when using HibernateTransactionManager. * If allowCreate is true, a new non-transactional Session will be created * if none found, which needs to be closed at the end of the operation. * If false, an IllegalStateException will get thrown in this case. * @see SessionFactoryUtils#getSession(SessionFactory, boolean) */ public void setAllowCreate(boolean allowCreate) { this.allowCreate = allowCreate; } /** * Return if a new Session should be created if no thread-bound found. */ public boolean isAllowCreate() { return allowCreate; } /** * Set whether to always use a new Hibernate Session for this template. * Default is "false"; if activated, all operations on this template will * work on a new Hibernate Session even in case of a pre-bound Session * (for example, within a transaction or OpenSessionInViewFilter). *

Within a transaction, a new Hibernate Session used by this template * will participate in the transaction through using the same JDBC * Connection. In such a scenario, multiple Sessions will participate * in the same database transaction. *

Turn this on for operations that are supposed to always execute * independently, without side effects caused by a shared Hibernate Session. */ public void setAlwaysUseNewSession(boolean alwaysUseNewSession) { this.alwaysUseNewSession = alwaysUseNewSession; } /** * Return whether to always use a new Hibernate Session for this template. */ public boolean isAlwaysUseNewSession() { return alwaysUseNewSession; } /** * Set whether to expose the native Hibernate Session to HibernateCallback * code. Default is "false": a Session proxy will be returned, * suppressing close calls and automatically applying * query cache settings and transaction timeouts. * @see HibernateCallback * @see net.sf.hibernate.Session * @see #setCacheQueries * @see #setQueryCacheRegion * @see #prepareQuery * @see #prepareCriteria */ public void setExposeNativeSession(boolean exposeNativeSession) { this.exposeNativeSession = exposeNativeSession; } /** * Return whether to expose the native Hibernate Session to HibernateCallback * code, or rather a Session proxy. */ public boolean isExposeNativeSession() { return exposeNativeSession; } /** * Set whether to check that the Hibernate Session is not in read-only mode * in case of write operations (save/update/delete). *

Default is "true", for fail-fast behavior when attempting write operations * within a read-only transaction. Turn this off to allow save/update/delete * on a Session with flush mode NEVER. * @see #setFlushMode * @see #checkWriteOperationAllowed * @see org.springframework.transaction.TransactionDefinition#isReadOnly */ public void setCheckWriteOperations(boolean checkWriteOperations) { this.checkWriteOperations = checkWriteOperations; } /** * Return whether to check that the Hibernate Session is not in read-only * mode in case of write operations (save/update/delete). */ public boolean isCheckWriteOperations() { return checkWriteOperations; } /** * Set whether to cache all queries executed by this template. * If this is true, all Query and Criteria objects created by * this template will be marked as cacheable (including all * queries through find methods). *

To specify the query region to be used for queries cached * by this template, set the "queryCacheRegion" property. * @see #setQueryCacheRegion * @see net.sf.hibernate.Query#setCacheable * @see net.sf.hibernate.Criteria#setCacheable */ public void setCacheQueries(boolean cacheQueries) { this.cacheQueries = cacheQueries; } /** * Return whether to cache all queries executed by this template. */ public boolean isCacheQueries() { return cacheQueries; } /** * Set the name of the cache region for queries executed by this template. * If this is specified, it will be applied to all Query and Criteria objects * created by this template (including all queries through find methods). *

The cache region will not take effect unless queries created by this * template are configured to be cached via the "cacheQueries" property. * @see #setCacheQueries * @see net.sf.hibernate.Query#setCacheRegion * @see net.sf.hibernate.Criteria#setCacheRegion */ public void setQueryCacheRegion(String queryCacheRegion) { this.queryCacheRegion = queryCacheRegion; } /** * Return the name of the cache region for queries executed by this template. */ public String getQueryCacheRegion() { return queryCacheRegion; } /** * Set the fetch size for this HibernateTemplate. This is important for processing * large result sets: Setting this higher than the default value will increase * processing speed at the cost of memory consumption; setting this lower can * avoid transferring row data that will never be read by the application. *

Default is 0, indicating to use the JDBC driver's default. */ public void setFetchSize(int fetchSize) { this.fetchSize = fetchSize; } /** * Return the fetch size specified for this HibernateTemplate. */ public int getFetchSize() { return fetchSize; } /** * Set the maximum number of rows for this HibernateTemplate. This is important * for processing subsets of large result sets, avoiding to read and hold * the entire result set in the database or in the JDBC driver if we're * never interested in the entire result in the first place (for example, * when performing searches that might return a large number of matches). *

Default is 0, indicating to use the JDBC driver's default. */ public void setMaxResults(int maxResults) { this.maxResults = maxResults; } /** * Return the maximum number of rows specified for this HibernateTemplate. */ public int getMaxResults() { return maxResults; } public Object execute(HibernateCallback action) throws DataAccessException { return execute(action, isExposeNativeSession()); } public List executeFind(HibernateCallback action) throws DataAccessException { Object result = execute(action, isExposeNativeSession()); if (result != null && !(result instanceof List)) { throw new InvalidDataAccessApiUsageException( "Result object returned from HibernateCallback isn't a List: [" + result + "]"); } return (List) result; } /** * Execute the action specified by the given action object within a Session. * @param action callback object that specifies the Hibernate action * @param exposeNativeSession whether to expose the native Hibernate Session * to callback code * @return a result object returned by the action, or null * @throws org.springframework.dao.DataAccessException in case of Hibernate errors */ public Object execute(HibernateCallback action, boolean exposeNativeSession) throws DataAccessException { Session session = getSession(); boolean existingTransaction = SessionFactoryUtils.isSessionTransactional(session, getSessionFactory()); if (existingTransaction) { logger.debug("Found thread-bound Session for HibernateTemplate"); } FlushMode previousFlushMode = null; try { previousFlushMode = applyFlushMode(session, existingTransaction); ===================================================================== Found a 107 line (398 tokens) duplication in the following files: Starting at line 644 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/SessionFactoryUtils.java Starting at line 592 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/SessionFactoryUtils.java return new HibernateOptimisticLockingFailureException((StaleObjectStateException) ex); } if (ex instanceof QueryException) { return new HibernateQueryException((QueryException) ex); } if (ex instanceof PersistentObjectException) { return new InvalidDataAccessApiUsageException(ex.getMessage(), ex); } if (ex instanceof TransientObjectException) { return new InvalidDataAccessApiUsageException(ex.getMessage(), ex); } // fallback return new HibernateSystemException(ex); } /** * Return if deferred close is active for the current thread * and the given SessionFactory. * @param sessionFactory the Hibernate SessionFactory to check */ public static boolean isDeferredCloseActive(SessionFactory sessionFactory) { Assert.notNull(sessionFactory, "No SessionFactory specified"); Map holderMap = (Map) deferredCloseHolder.get(); return (holderMap != null && holderMap.containsKey(sessionFactory)); } /** * Initialize deferred close for the current thread and the given SessionFactory. * Sessions will not be actually closed on close calls then, but rather at a * processDeferredClose call at a finishing point (like request completion). *

Used by OpenSessionInViewFilter and OpenSessionInViewInterceptor * when not configured for a single session. * @param sessionFactory Hibernate SessionFactory * @see #processDeferredClose * @see #releaseSession * @see org.springframework.orm.hibernate.support.OpenSessionInViewFilter#setSingleSession * @see org.springframework.orm.hibernate.support.OpenSessionInViewInterceptor#setSingleSession */ public static void initDeferredClose(SessionFactory sessionFactory) { Assert.notNull(sessionFactory, "No SessionFactory specified"); logger.debug("Initializing deferred close of Hibernate Sessions"); Map holderMap = (Map) deferredCloseHolder.get(); if (holderMap == null) { holderMap = new HashMap(); deferredCloseHolder.set(holderMap); } holderMap.put(sessionFactory, new HashSet()); } /** * Process Sessions that have been registered for deferred close * for the given SessionFactory. * @param sessionFactory Hibernate SessionFactory * @see #initDeferredClose * @see #releaseSession */ public static void processDeferredClose(SessionFactory sessionFactory) { Assert.notNull(sessionFactory, "No SessionFactory specified"); Map holderMap = (Map) deferredCloseHolder.get(); if (holderMap == null || !holderMap.containsKey(sessionFactory)) { throw new IllegalStateException("Deferred close not active for SessionFactory [" + sessionFactory + "]"); } logger.debug("Processing deferred close of Hibernate Sessions"); Set sessions = (Set) holderMap.remove(sessionFactory); for (Iterator it = sessions.iterator(); it.hasNext();) { doClose((Session) it.next()); } if (holderMap.isEmpty()) { deferredCloseHolder.set(null); } } /** * Close the given Session, created via the given factory, * if it is not managed externally (i.e. not bound to the thread). * @param session the Hibernate Session to close * @param sessionFactory Hibernate SessionFactory that the Session was created with * (can be null) */ public static void releaseSession(Session session, SessionFactory sessionFactory) { if (session == null) { return; } // Only close non-transactional Sessions. if (!isSessionTransactional(session, sessionFactory)) { closeSessionOrRegisterDeferredClose(session, sessionFactory); } } /** * Close the given Session or register it for deferred close. * @param session the Hibernate Session to close * @param sessionFactory Hibernate SessionFactory that the Session was created with * (can be null) * @see #initDeferredClose * @see #processDeferredClose */ static void closeSessionOrRegisterDeferredClose(Session session, SessionFactory sessionFactory) { Map holderMap = (Map) deferredCloseHolder.get(); if (holderMap != null && sessionFactory != null && holderMap.containsKey(sessionFactory)) { logger.debug("Registering Hibernate Session for deferred close"); Set sessions = (Set) holderMap.get(sessionFactory); sessions.add(session); ===================================================================== Found a 139 line (361 tokens) duplication in the following files: Starting at line 272 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/HibernateTransactionManager.java Starting at line 225 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/HibernateTransactionManager.java } /** * Set the bean name of a Hibernate entity interceptor that allows to inspect * and change property values before writing to and reading from the database. * Will get applied to any new Session created by this transaction manager. *

Requires the bean factory to be known, to be able to resolve the bean * name to an interceptor instance on session creation. Typically used for * prototype interceptors, i.e. a new interceptor instance per session. *

Can also be used for shared interceptor instances, but it is recommended * to set the interceptor reference directly in such a scenario. * @param entityInterceptorBeanName the name of the entity interceptor in * the bean factory * @see #setBeanFactory * @see #setEntityInterceptor */ public void setEntityInterceptorBeanName(String entityInterceptorBeanName) { this.entityInterceptor = entityInterceptorBeanName; } /** * Set a Hibernate entity interceptor that allows to inspect and change * property values before writing to and reading from the database. * Will get applied to any new Session created by this transaction manager. *

Such an interceptor can either be set at the SessionFactory level, * i.e. on LocalSessionFactoryBean, or at the Session level, i.e. on * HibernateTemplate, HibernateInterceptor, and HibernateTransactionManager. * It's preferable to set it on LocalSessionFactoryBean or HibernateTransactionManager * to avoid repeated configuration and guarantee consistent behavior in transactions. * @see LocalSessionFactoryBean#setEntityInterceptor * @see HibernateTemplate#setEntityInterceptor * @see HibernateInterceptor#setEntityInterceptor */ public void setEntityInterceptor(Interceptor entityInterceptor) { this.entityInterceptor = entityInterceptor; } /** * Return the current Hibernate entity interceptor, or null if none. * Resolves an entity interceptor bean name via the bean factory, * if necessary. * @throws IllegalStateException if bean name specified but no bean factory set * @throws BeansException if bean name resolution via the bean factory failed * @see #setEntityInterceptor * @see #setEntityInterceptorBeanName * @see #setBeanFactory */ public Interceptor getEntityInterceptor() throws IllegalStateException, BeansException { if (this.entityInterceptor instanceof Interceptor) { return (Interceptor) entityInterceptor; } else if (this.entityInterceptor instanceof String) { if (this.beanFactory == null) { throw new IllegalStateException("Cannot get entity interceptor via bean name if no bean factory set"); } String beanName = (String) this.entityInterceptor; return (Interceptor) this.beanFactory.getBean(beanName, Interceptor.class); } else { return null; } } /** * Set the JDBC exception translator for this transaction manager. * Applied to SQLExceptions (wrapped by Hibernate's JDBCException) * thrown by flushing on commit. *

The default exception translator is either a SQLErrorCodeSQLExceptionTranslator * if a DataSource is available, or a SQLStateSQLExceptionTranslator else. * @param jdbcExceptionTranslator the exception translator * @see java.sql.SQLException * @see net.sf.hibernate.JDBCException * @see SessionFactoryUtils#newJdbcExceptionTranslator * @see org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator * @see org.springframework.jdbc.support.SQLStateSQLExceptionTranslator */ public void setJdbcExceptionTranslator(SQLExceptionTranslator jdbcExceptionTranslator) { this.jdbcExceptionTranslator = jdbcExceptionTranslator; } /** * Return the JDBC exception translator for this transaction manager. *

Creates a default SQLErrorCodeSQLExceptionTranslator or SQLStateSQLExceptionTranslator * for the specified SessionFactory, if no exception translator explicitly specified. * @see #setJdbcExceptionTranslator */ public SQLExceptionTranslator getJdbcExceptionTranslator() { if (this.jdbcExceptionTranslator == null) { if (getDataSource() != null) { this.jdbcExceptionTranslator = new SQLErrorCodeSQLExceptionTranslator(getDataSource()); } else { this.jdbcExceptionTranslator = SessionFactoryUtils.newJdbcExceptionTranslator(getSessionFactory()); } } return this.jdbcExceptionTranslator; } /** * The bean factory just needs to be known for resolving entity interceptor * bean names. It does not need to be set for any other mode of operation. * @see #setEntityInterceptorBeanName */ public void setBeanFactory(BeanFactory beanFactory) { this.beanFactory = beanFactory; } public void afterPropertiesSet() { if (getSessionFactory() == null) { throw new IllegalArgumentException("sessionFactory is required"); } if (this.entityInterceptor instanceof String && this.beanFactory == null) { throw new IllegalArgumentException("beanFactory is required for entityInterceptorBeanName"); } // Check for SessionFactory's DataSource. if (this.autodetectDataSource && getDataSource() == null) { DataSource sfds = SessionFactoryUtils.getDataSource(getSessionFactory()); if (sfds != null) { // Use the SessionFactory's DataSource for exposing transactions to JDBC code. if (logger.isInfoEnabled()) { logger.info("Using DataSource [" + sfds + "] of Hibernate SessionFactory for HibernateTransactionManager"); } setDataSource(sfds); } } } protected Object doGetTransaction() { HibernateTransactionObject txObject = new HibernateTransactionObject(); txObject.setSavepointAllowed(isNestedTransactionAllowed()); if (TransactionSynchronizationManager.hasResource(getSessionFactory())) { SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory()); if (logger.isDebugEnabled()) { logger.debug("Found thread-bound Session [" + sessionHolder.getSession() + ===================================================================== Found a 145 line (331 tokens) duplication in the following files: Starting at line 94 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/support/OpenSessionInViewFilter.java Starting at line 94 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/support/OpenSessionInViewFilter.java public class OpenSessionInViewFilter extends OncePerRequestFilter { public static final String DEFAULT_SESSION_FACTORY_BEAN_NAME = "sessionFactory"; private String sessionFactoryBeanName = DEFAULT_SESSION_FACTORY_BEAN_NAME; private boolean singleSession = true; /** * Set the bean name of the SessionFactory to fetch from Spring's * root application context. Default is "sessionFactory". * @see #DEFAULT_SESSION_FACTORY_BEAN_NAME */ public void setSessionFactoryBeanName(String sessionFactoryBeanName) { this.sessionFactoryBeanName = sessionFactoryBeanName; } /** * Return the bean name of the SessionFactory to fetch from Spring's * root application context. */ protected String getSessionFactoryBeanName() { return sessionFactoryBeanName; } /** * Set whether to use a single session for each request. Default is "true". *

If set to false, each data access operation or transaction will use * its own session (like without Open Session in View). Each of those * sessions will be registered for deferred close, though, actually * processed at request completion. * @see SessionFactoryUtils#initDeferredClose * @see SessionFactoryUtils#processDeferredClose */ public void setSingleSession(boolean singleSession) { this.singleSession = singleSession; } /** * Return whether to use a single session for each request. */ protected boolean isSingleSession() { return singleSession; } protected void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { SessionFactory sessionFactory = lookupSessionFactory(request); Session session = null; boolean participate = false; if (isSingleSession()) { // single session mode if (TransactionSynchronizationManager.hasResource(sessionFactory)) { // Do not modify the Session: just set the participate flag. participate = true; } else { logger.debug("Opening single Hibernate Session in OpenSessionInViewFilter"); session = getSession(sessionFactory); TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); } } else { // deferred close mode if (SessionFactoryUtils.isDeferredCloseActive(sessionFactory)) { // Do not modify deferred close: just set the participate flag. participate = true; } else { SessionFactoryUtils.initDeferredClose(sessionFactory); } } try { filterChain.doFilter(request, response); } finally { if (!participate) { if (isSingleSession()) { // single session mode TransactionSynchronizationManager.unbindResource(sessionFactory); logger.debug("Closing single Hibernate Session in OpenSessionInViewFilter"); try { closeSession(session, sessionFactory); } catch (RuntimeException ex) { logger.error("Unexpected exception on closing Hibernate Session", ex); } } else { // deferred close mode SessionFactoryUtils.processDeferredClose(sessionFactory); } } } } /** * Look up the SessionFactory that this filter should use, * taking the current HTTP request as argument. *

Default implementation delegates to the lookupSessionFactory * without arguments. * @return the SessionFactory to use * @see #lookupSessionFactory() */ protected SessionFactory lookupSessionFactory(HttpServletRequest request) { return lookupSessionFactory(); } /** * Look up the SessionFactory that this filter should use. *

Default implementation looks for a bean with the specified name * in Spring's root application context. * @return the SessionFactory to use * @see #getSessionFactoryBeanName */ protected SessionFactory lookupSessionFactory() { if (logger.isDebugEnabled()) { logger.debug("Using SessionFactory '" + getSessionFactoryBeanName() + "' for OpenSessionInViewFilter"); } WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()); return (SessionFactory) wac.getBean(getSessionFactoryBeanName(), SessionFactory.class); } /** * Get a Session for the SessionFactory that this filter uses. * Note that this just applies in single session mode! *

The default implementation delegates to SessionFactoryUtils' * getSession method and sets the Session's flushMode to NEVER. *

Can be overridden in subclasses for creating a Session with a custom * entity interceptor or JDBC exception translator. * @param sessionFactory the SessionFactory that this filter uses * @return the Session to use * @throws DataAccessResourceFailureException if the Session could not be created * @see org.springframework.orm.hibernate.SessionFactoryUtils#getSession(SessionFactory, boolean) * @see net.sf.hibernate.FlushMode#NEVER */ protected Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException { ===================================================================== Found a 76 line (330 tokens) duplication in the following files: Starting at line 508 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/HibernateTemplate.java Starting at line 467 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/HibernateTemplate.java return session.load(entityClass, id); } } }, true); } public List loadAll(final Class entityClass) throws DataAccessException { return (List) execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { Criteria criteria = session.createCriteria(entityClass); prepareCriteria(criteria); return criteria.list(); } }, true); } public void load(final Object entity, final Serializable id) throws DataAccessException { execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { session.load(entity, id); return null; } }, true); } public void refresh(final Object entity) throws DataAccessException { refresh(entity, null); } public void refresh(final Object entity, final LockMode lockMode) throws DataAccessException { execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { if (lockMode != null) { session.refresh(entity, lockMode); } else { session.refresh(entity); } return null; } }, true); } public boolean contains(final Object entity) throws DataAccessException { Boolean result = (Boolean) execute(new HibernateCallback() { public Object doInHibernate(Session session) { return new Boolean(session.contains(entity)); } }, true); return result.booleanValue(); } public void evict(final Object entity) throws DataAccessException { execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { session.evict(entity); return null; } }, true); } public void initialize(Object proxy) throws DataAccessException { try { Hibernate.initialize(proxy); } catch (HibernateException ex) { throw SessionFactoryUtils.convertHibernateAccessException(ex); } } //------------------------------------------------------------------------- // Convenience methods for storing individual objects //------------------------------------------------------------------------- public void lock(final Object entity, final LockMode lockMode) throws DataAccessException { ===================================================================== Found a 52 line (305 tokens) duplication in the following files: Starting at line 524 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/HibernateTransactionManager.java Starting at line 435 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/HibernateTransactionManager.java ConnectionHolder conHolder = new ConnectionHolder(con); if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) { conHolder.setTimeoutInSeconds(definition.getTimeout()); } if (logger.isDebugEnabled()) { logger.debug("Exposing Hibernate transaction as JDBC transaction [" + con + "]"); } TransactionSynchronizationManager.bindResource(getDataSource(), conHolder); txObject.setConnectionHolder(conHolder); } // Bind the session holder to the thread. if (txObject.isNewSessionHolder()) { TransactionSynchronizationManager.bindResource(getSessionFactory(), txObject.getSessionHolder()); } } catch (Exception ex) { SessionFactoryUtils.releaseSession(session, getSessionFactory()); throw new CannotCreateTransactionException("Could not open Hibernate Session for transaction", ex); } } protected Object doSuspend(Object transaction) { HibernateTransactionObject txObject = (HibernateTransactionObject) transaction; txObject.setSessionHolder(null, false); SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(getSessionFactory()); ConnectionHolder connectionHolder = null; if (getDataSource() != null) { connectionHolder = (ConnectionHolder) TransactionSynchronizationManager.unbindResource(getDataSource()); } return new SuspendedResourcesHolder(sessionHolder, connectionHolder); } protected void doResume(Object transaction, Object suspendedResources) { SuspendedResourcesHolder resourcesHolder = (SuspendedResourcesHolder) suspendedResources; if (TransactionSynchronizationManager.hasResource(getSessionFactory())) { // From non-transactional code running in active transaction synchronization // -> can be safely removed, will be closed on transaction completion. TransactionSynchronizationManager.unbindResource(getSessionFactory()); } TransactionSynchronizationManager.bindResource(getSessionFactory(), resourcesHolder.getSessionHolder()); if (getDataSource() != null) { TransactionSynchronizationManager.bindResource(getDataSource(), resourcesHolder.getConnectionHolder()); } } protected void doCommit(DefaultTransactionStatus status) { HibernateTransactionObject txObject = (HibernateTransactionObject) status.getTransaction(); if (status.isDebug()) { logger.debug("Committing Hibernate transaction on Session [" + ===================================================================== Found a 73 line (291 tokens) duplication in the following files: Starting at line 134 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/SpringSessionSynchronization.java Starting at line 134 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/SpringSessionSynchronization.java "Hibernate transaction synchronization: " + ex.getMessage(), null, ex.getSQLException()); } else { throw new HibernateJdbcException(ex); } } catch (HibernateException ex) { throw SessionFactoryUtils.convertHibernateAccessException(ex); } } } } public void beforeCompletion() { if (this.jtaTransaction != null) { // Typically in case of a suspended JTA transaction: // Remove the Session for the current JTA transaction, but keep the holder. Session session = this.sessionHolder.removeSession(this.jtaTransaction); if (session != null) { if (this.sessionHolder.isEmpty()) { // No Sessions for JTA transactions bound anymore -> could remove it. if (TransactionSynchronizationManager.hasResource(this.sessionFactory)) { // Explicit check necessary because of remote transaction propagation: // The synchronization callbacks will execute in a different thread // in such a scenario, as they're triggered by a remote server. // The best we can do is to leave the SessionHolder bound to the // thread that originally performed the data access. It will be // reused when a new data access operation starts on that thread. TransactionSynchronizationManager.unbindResource(this.sessionFactory); } this.holderActive = false; } // Do not close a pre-bound Session. In that case, we'll find the // transaction-specific Session the same as the default Session. if (session != this.sessionHolder.getSession()) { SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, this.sessionFactory); } else if (this.sessionHolder.getPreviousFlushMode() != null) { // In case of pre-bound Session, restore previous flush mode. session.setFlushMode(this.sessionHolder.getPreviousFlushMode()); } return; } } // We'll only get here if there was no specific JTA transaction to handle. if (this.newSession) { // Default behavior: unbind and close the thread-bound Hibernate Session. TransactionSynchronizationManager.unbindResource(this.sessionFactory); this.holderActive = false; if (this.hibernateTransactionCompletion) { // Close the Hibernate Session here in case of a Hibernate TransactionManagerLookup: // Hibernate will automatically defer the actual closing to JTA transaction completion. // Else, the Session will be closed in the afterCompletion method, to provide the // correct transaction status for releasing the Session's cache locks. SessionFactoryUtils.closeSessionOrRegisterDeferredClose(this.sessionHolder.getSession(), this.sessionFactory); } } else if (this.sessionHolder.getPreviousFlushMode() != null) { // In case of pre-bound Session, restore previous flush mode. this.sessionHolder.getSession().setFlushMode(this.sessionHolder.getPreviousFlushMode()); } } public void afterCompletion(int status) { if (!this.hibernateTransactionCompletion || !this.newSession) { // No Hibernate TransactionManagerLookup: apply afterTransactionCompletion callback. // Always perform explicit afterTransactionCompletion callback for pre-bound Session, // even with Hibernate TransactionManagerLookup (which only applies to new Sessions). Session session = this.sessionHolder.getSession(); // Provide correct transaction status for releasing the Session's cache locks, // if possible. Else, closing will release all cache locks assuming a rollback. if (session instanceof SessionImplementor) { ((SessionImplementor) session).afterTransactionCompletion(status == STATUS_COMMITTED); ===================================================================== Found a 91 line (286 tokens) duplication in the following files: Starting at line 554 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/SessionFactoryUtils.java Starting at line 504 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/SessionFactoryUtils.java } /** * Return whether the given Hibernate Session is transactional, that is, * bound to the current thread by Spring's transaction facilities. * @param session the Hibernate Session to check * @param sessionFactory Hibernate SessionFactory that the Session was created with * (can be null) * @return whether the Session is transactional */ public static boolean isSessionTransactional(Session session, SessionFactory sessionFactory) { if (sessionFactory == null) { return false; } SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory); return (sessionHolder != null && sessionHolder.containsSession(session)); } /** * Apply the current transaction timeout, if any, to the given * Hibernate Query object. * @param query the Hibernate Query object * @param sessionFactory Hibernate SessionFactory that the Query was created for * (can be null) * @see net.sf.hibernate.Query#setTimeout */ public static void applyTransactionTimeout(Query query, SessionFactory sessionFactory) { Assert.notNull(query, "No Query object specified"); if (sessionFactory != null) { SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory); if (sessionHolder != null && sessionHolder.hasTimeout()) { query.setTimeout(sessionHolder.getTimeToLiveInSeconds()); } } } /** * Apply the current transaction timeout, if any, to the given * Hibernate Criteria object. * @param criteria the Hibernate Criteria object * @param sessionFactory Hibernate SessionFactory that the Criteria was created for * @see net.sf.hibernate.Criteria#setTimeout */ public static void applyTransactionTimeout(Criteria criteria, SessionFactory sessionFactory) { Assert.notNull(criteria, "No Criteria object specified"); SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory); if (sessionHolder != null && sessionHolder.hasTimeout()) { criteria.setTimeout(sessionHolder.getTimeToLiveInSeconds()); } } /** * Convert the given HibernateException to an appropriate exception from the * org.springframework.dao hierarchy. Note that it is advisable to * handle JDBCException specifically by using a SQLExceptionTranslator for the * underlying SQLException. * @param ex HibernateException that occured * @return the corresponding DataAccessException instance * @see HibernateAccessor#convertHibernateAccessException * @see HibernateAccessor#convertJdbcAccessException * @see HibernateTransactionManager#convertHibernateAccessException * @see HibernateTransactionManager#convertJdbcAccessException * @see net.sf.hibernate.JDBCException#getSQLException * @see org.springframework.jdbc.support.SQLExceptionTranslator */ public static DataAccessException convertHibernateAccessException(HibernateException ex) { if (ex instanceof JDBCException) { // SQLException during Hibernate access: only passed in here from custom code, // as HibernateTemplate etc will use SQLExceptionTranslator-based handling. return new HibernateJdbcException((JDBCException) ex); } if (ex instanceof UnresolvableObjectException) { return new HibernateObjectRetrievalFailureException((UnresolvableObjectException) ex); } if (ex instanceof ObjectNotFoundException) { return new HibernateObjectRetrievalFailureException((ObjectNotFoundException) ex); } if (ex instanceof ObjectDeletedException) { return new HibernateObjectRetrievalFailureException((ObjectDeletedException) ex); } if (ex instanceof WrongClassException) { return new HibernateObjectRetrievalFailureException((WrongClassException) ex); } if (ex instanceof StaleObjectStateException) { return new HibernateOptimisticLockingFailureException((StaleObjectStateException) ex); } if (ex instanceof QueryException) { ===================================================================== Found a 59 line (254 tokens) duplication in the following files: Starting at line 730 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/HibernateTemplate.java Starting at line 613 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/HibernateTemplate.java return session.saveOrUpdateCopy(entity); } }, true); } public void delete(Object entity) throws DataAccessException { delete(entity, null); } public void delete(final Object entity, final LockMode lockMode) throws DataAccessException { execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { checkWriteOperationAllowed(session); if (lockMode != null) { session.lock(entity, lockMode); } session.delete(entity); return null; } }, true); } public void deleteAll(final Collection entities) throws DataAccessException { execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { checkWriteOperationAllowed(session); for (Iterator it = entities.iterator(); it.hasNext();) { session.delete(it.next()); } return null; } }, true); } public void flush() throws DataAccessException { execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { session.flush(); return null; } }, true); } public void clear() throws DataAccessException { execute(new HibernateCallback() { public Object doInHibernate(Session session) { session.clear(); return null; } }, true); } //------------------------------------------------------------------------- // Convenience finder methods for HQL strings //------------------------------------------------------------------------- public List find(String queryString) throws DataAccessException { return find(queryString, (Object[]) null, (Type[]) null); ===================================================================== Found a 76 line (240 tokens) duplication in the following files: Starting at line 382 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/HibernateTemplate.java Starting at line 379 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/HibernateTemplate.java logger.debug("Not closing pre-bound Hibernate Session after HibernateTemplate"); if (previousFlushMode != null) { session.setFlushMode(previousFlushMode); } } else { SessionFactoryUtils.releaseSession(session, getSessionFactory()); } } } /** * Return a Session for use by this template. *

Returns a new Session in case of "alwaysUseNewSession" (using the same * JDBC Connection as a transactional Session, if applicable), a pre-bound * Session in case of "allowCreate" turned off, and a pre-bound or new Session * else (new only if no transactional or otherwise pre-bound Session exists). * @see SessionFactoryUtils#getSession * @see SessionFactoryUtils#getNewSession * @see #setAlwaysUseNewSession * @see #setAllowCreate */ protected Session getSession() { if (isAlwaysUseNewSession()) { return SessionFactoryUtils.getNewSession(getSessionFactory(), getEntityInterceptor()); } else if (!isAllowCreate()) { return SessionFactoryUtils.getSession(getSessionFactory(), false); } else { return SessionFactoryUtils.getSession( getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator()); } } /** * Create a close-suppressing proxy for the given Hibernate Session. * The proxy also prepares returned Query and Criteria objects. * @param session the Hibernate Session to create a proxy for * @return the Session proxy * @see net.sf.hibernate.Session#close() * @see #prepareQuery * @see #prepareCriteria */ protected Session createSessionProxy(Session session) { return (Session) Proxy.newProxyInstance( getClass().getClassLoader(), new Class[] {Session.class}, new CloseSuppressingInvocationHandler(session)); } //------------------------------------------------------------------------- // Convenience methods for loading individual objects //------------------------------------------------------------------------- public Object get(Class entityClass, Serializable id) throws DataAccessException { return get(entityClass, id, null); } public Object get(final Class entityClass, final Serializable id, final LockMode lockMode) throws DataAccessException { return execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { if (lockMode != null) { return session.get(entityClass, id, lockMode); } else { return session.get(entityClass, id); } } }, true); } public Object load(Class entityClass, Serializable id) throws DataAccessException { ===================================================================== Found a 86 line (237 tokens) duplication in the following files: Starting at line 1027 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/HibernateTemplate.java Starting at line 952 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/HibernateTemplate.java return deleteCount.intValue(); } //------------------------------------------------------------------------- // Helper methods used by the operations above //------------------------------------------------------------------------- /** * Check whether write operations are allowed on the given Session. *

Default implementation throws an InvalidDataAccessApiUsageException * in case of FlushMode.NEVER. Can be overridden in subclasses. * @param session current Hibernate Session * @throws InvalidDataAccessApiUsageException if write operations are not allowed * @see #setCheckWriteOperations * @see #getFlushMode * @see #FLUSH_EAGER * @see net.sf.hibernate.Session#getFlushMode * @see net.sf.hibernate.FlushMode#NEVER */ protected void checkWriteOperationAllowed(Session session) throws InvalidDataAccessApiUsageException { if (isCheckWriteOperations() && getFlushMode() != FLUSH_EAGER && FlushMode.NEVER.equals(session.getFlushMode())) { throw new InvalidDataAccessApiUsageException( "Write operations are not allowed in read-only mode (FlushMode.NEVER) - turn your Session " + "into FlushMode.AUTO or remove 'readOnly' marker from transaction definition"); } } /** * Prepare the given Query object, applying cache settings and/or * a transaction timeout. * @param queryObject the Query object to prepare * @see #setCacheQueries * @see #setQueryCacheRegion * @see SessionFactoryUtils#applyTransactionTimeout */ protected void prepareQuery(Query queryObject) { if (isCacheQueries()) { queryObject.setCacheable(true); if (getQueryCacheRegion() != null) { queryObject.setCacheRegion(getQueryCacheRegion()); } } if (getFetchSize() > 0) { queryObject.setFetchSize(getFetchSize()); } if (getMaxResults() > 0) { queryObject.setMaxResults(getMaxResults()); } SessionFactoryUtils.applyTransactionTimeout(queryObject, getSessionFactory()); } /** * Prepare the given Criteria object, applying cache settings and/or * a transaction timeout. * @param criteria the Criteria object to prepare * @see #setCacheQueries * @see #setQueryCacheRegion * @see SessionFactoryUtils#applyTransactionTimeout */ protected void prepareCriteria(Criteria criteria) { if (isCacheQueries()) { criteria.setCacheable(true); if (getQueryCacheRegion() != null) { criteria.setCacheRegion(getQueryCacheRegion()); } } if (getFetchSize() > 0) { criteria.setFetchSize(getFetchSize()); } if (getMaxResults() > 0) { criteria.setMaxResults(getMaxResults()); } SessionFactoryUtils.applyTransactionTimeout(criteria, getSessionFactory()); } /** * Apply the given name parameter to the given Query object. * @param queryObject the Query object * @param paramName the name of the parameter * @param value the value of the parameter * @param type Hibernate type of the parameter (or null if none specified) * @throws HibernateException if thrown by the Query object */ protected void applyNamedParameterToQuery(Query queryObject, String paramName, Object value, Type type) ===================================================================== Found a 151 line (236 tokens) duplication in the following files: Starting at line 58 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/support/HibernateDaoSupport.java Starting at line 58 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/support/HibernateDaoSupport.java public abstract class HibernateDaoSupport extends DaoSupport { private HibernateTemplate hibernateTemplate; /** * Set the Hibernate SessionFactory to be used by this DAO. * Will automatically create a HibernateTemplate for the given SessionFactory. * @see #createHibernateTemplate * @see #setHibernateTemplate */ public final void setSessionFactory(SessionFactory sessionFactory) { this.hibernateTemplate = createHibernateTemplate(sessionFactory); } /** * Create a HibernateTemplate for the given SessionFactory. * Only invoked if populating the DAO with a SessionFactory reference! *

Can be overridden in subclasses to provide a HibernateTemplate instance * with different configuration, or a custom HibernateTemplate subclass. * @param sessionFactory the Hibernate SessionFactory to create a HibernateTemplate for * @return the new HibernateTemplate instance * @see #setSessionFactory */ protected HibernateTemplate createHibernateTemplate(SessionFactory sessionFactory) { return new HibernateTemplate(sessionFactory); } /** * Return the Hibernate SessionFactory used by this DAO. */ public final SessionFactory getSessionFactory() { return (this.hibernateTemplate != null ? this.hibernateTemplate.getSessionFactory() : null); } /** * Set the HibernateTemplate for this DAO explicitly, * as an alternative to specifying a SessionFactory. * @see #setSessionFactory */ public final void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } /** * Return the HibernateTemplate for this DAO, * pre-initialized with the SessionFactory or set explicitly. */ public final HibernateTemplate getHibernateTemplate() { return hibernateTemplate; } protected final void checkDaoConfig() { if (this.hibernateTemplate == null) { throw new IllegalArgumentException("sessionFactory or hibernateTemplate is required"); } } /** * Get a Hibernate Session, either from the current transaction or a new one. * The latter is only allowed if the "allowCreate" setting of this bean's * HibernateTemplate is true. *

Note that this is not meant to be invoked from HibernateTemplate code * but rather just in plain Hibernate code. Either rely on a thread-bound * Session (via HibernateInterceptor), or use it in combination with * releaseSession. *

In general, it is recommended to use HibernateTemplate, either with * the provided convenience operations or with a custom HibernateCallback * that provides you with a Session to work on. HibernateTemplate will care * for all resource management and for proper exception conversion. * @return the Hibernate Session * @throws DataAccessResourceFailureException if the Session couldn't be created * @throws IllegalStateException if no thread-bound Session found and allowCreate false * @see #releaseSession * @see org.springframework.orm.hibernate.SessionFactoryUtils#getSession(SessionFactory, boolean) * @see org.springframework.orm.hibernate.HibernateInterceptor * @see org.springframework.orm.hibernate.HibernateTemplate * @see org.springframework.orm.hibernate.HibernateCallback */ protected final Session getSession() throws DataAccessResourceFailureException, IllegalStateException { return getSession(this.hibernateTemplate.isAllowCreate()); } /** * Get a Hibernate Session, either from the current transaction or * a new one. The latter is only allowed if "allowCreate" is true. *

Note that this is not meant to be invoked from HibernateTemplate code * but rather just in plain Hibernate code. Either rely on a thread-bound * Session (via HibernateInterceptor), or use it in combination with * releaseSession. *

In general, it is recommended to use HibernateTemplate, either with * the provided convenience operations or with a custom HibernateCallback * that provides you with a Session to work on. HibernateTemplate will care * for all resource management and for proper exception conversion. * @param allowCreate if a non-transactional Session should be created when no * transactional Session can be found for the current thread * @return the Hibernate Session * @throws DataAccessResourceFailureException if the Session couldn't be created * @throws IllegalStateException if no thread-bound Session found and allowCreate false * @see #releaseSession * @see org.springframework.orm.hibernate.SessionFactoryUtils#getSession(SessionFactory, boolean) * @see org.springframework.orm.hibernate.HibernateInterceptor * @see org.springframework.orm.hibernate.HibernateTemplate * @see org.springframework.orm.hibernate.HibernateCallback */ protected final Session getSession(boolean allowCreate) throws DataAccessResourceFailureException, IllegalStateException { return (!allowCreate ? SessionFactoryUtils.getSession(getSessionFactory(), false) : SessionFactoryUtils.getSession( getSessionFactory(), this.hibernateTemplate.getEntityInterceptor(), this.hibernateTemplate.getJdbcExceptionTranslator())); } /** * Convert the given HibernateException to an appropriate exception from the * org.springframework.dao hierarchy. Will automatically detect * wrapped SQLExceptions and convert them accordingly. *

Delegates to the convertHibernateAccessException * method of this DAO's HibernateTemplate. *

Typically used in plain Hibernate code, in combination with * getSession and releaseSession. * @param ex HibernateException that occured * @return the corresponding DataAccessException instance * @see #setHibernateTemplate * @see #getSession * @see #releaseSession * @see org.springframework.orm.hibernate.HibernateTemplate#convertHibernateAccessException */ protected final DataAccessException convertHibernateAccessException(HibernateException ex) { return this.hibernateTemplate.convertHibernateAccessException(ex); } /** * Close the given Hibernate Session, created via this DAO's SessionFactory, * if it isn't bound to the thread. *

Typically used in plain Hibernate code, in combination with * getSession and convertHibernateAccessException. * @param session Session to close * @see org.springframework.orm.hibernate.SessionFactoryUtils#releaseSession */ protected final void releaseSession(Session session) { SessionFactoryUtils.releaseSession(session, getSessionFactory()); } } ===================================================================== Found a 69 line (229 tokens) duplication in the following files: Starting at line 46 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/SpringSessionSynchronization.java Starting at line 46 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/SpringSessionSynchronization.java class SpringSessionSynchronization implements TransactionSynchronization, Ordered { private final SessionHolder sessionHolder; private final SessionFactory sessionFactory; private final SQLExceptionTranslator jdbcExceptionTranslator; private final boolean newSession; /** * Whether Hibernate has a looked-up JTA TransactionManager that it will * automatically register CacheSynchronizations with on Session connect. */ private boolean hibernateTransactionCompletion = false; private Transaction jtaTransaction; private boolean holderActive = true; public SpringSessionSynchronization( SessionHolder sessionHolder, SessionFactory sessionFactory, SQLExceptionTranslator jdbcExceptionTranslator, boolean newSession) { this.sessionHolder = sessionHolder; this.sessionFactory = sessionFactory; this.jdbcExceptionTranslator = jdbcExceptionTranslator; this.newSession = newSession; // Check whether the SessionFactory has a JTA TransactionManager. TransactionManager jtaTm = SessionFactoryUtils.getJtaTransactionManager(sessionFactory, sessionHolder.getAnySession()); if (jtaTm != null) { this.hibernateTransactionCompletion = true; // Fetch current JTA Transaction object // (just necessary for JTA transaction suspension, with an individual // Hibernate Session per currently active/suspended transaction). try { int jtaStatus = jtaTm.getStatus(); if (jtaStatus == Status.STATUS_ACTIVE || jtaStatus == Status.STATUS_MARKED_ROLLBACK) { this.jtaTransaction = jtaTm.getTransaction(); } } catch (SystemException ex) { throw new DataAccessResourceFailureException("Could not check JTA transaction", ex); } } } public int getOrder() { return SessionFactoryUtils.SESSION_SYNCHRONIZATION_ORDER; } public void suspend() { if (this.holderActive) { TransactionSynchronizationManager.unbindResource(this.sessionFactory); } } public void resume() { if (this.holderActive) { TransactionSynchronizationManager.bindResource(this.sessionFactory, this.sessionHolder); } } public void beforeCommit(boolean readOnly) throws DataAccessException { if (!readOnly) { ===================================================================== Found a 76 line (225 tokens) duplication in the following files: Starting at line 70 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/core/NestedRuntimeException.java Starting at line 70 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/core/NestedCheckedException.java public NestedCheckedException(String msg, Throwable ex) { super(msg); this.cause = ex; } /** * Return the nested cause, or null if none. */ public Throwable getCause() { // Even if you cannot set the cause of this exception other than through // the constructor, we check for the cause being "this" here, as the cause // could still be set to "this" via reflection: for example, by a remoting // deserializer like Hessian's. return (this.cause == this ? null : this.cause); } /** * Return the detail message, including the message from the nested exception * if there is one. */ public String getMessage() { if (getCause() == null) { return super.getMessage(); } else { return super.getMessage() + "; nested exception is " + getCause().getClass().getName() + ": " + getCause().getMessage(); } } /** * Print the composite message and the embedded stack trace to the specified stream. * @param ps the print stream */ public void printStackTrace(PrintStream ps) { if (getCause() == null) { super.printStackTrace(ps); } else { ps.println(this); getCause().printStackTrace(ps); } } /** * Print the composite message and the embedded stack trace to the specified print writer. * @param pw the print writer */ public void printStackTrace(PrintWriter pw) { if (getCause() == null) { super.printStackTrace(pw); } else { pw.println(this); getCause().printStackTrace(pw); } } /** * Check whether this exception contains an exception of the given class: * either it is of the given class itself or it contains a nested cause * of the given class. *

Currently just traverses NestedCheckedException causes. Will use * the JDK 1.4 exception cause mechanism once Spring requires JDK 1.4. * @param exClass the exception class to look for */ public boolean contains(Class exClass) { if (exClass == null) { return false; } Throwable ex = this; while (ex != null) { if (exClass.isInstance(ex)) { return true; } if (ex instanceof NestedCheckedException) { ===================================================================== Found a 105 line (220 tokens) duplication in the following files: Starting at line 82 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/SessionFactoryUtils.java Starting at line 83 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/SessionFactoryUtils.java public abstract class SessionFactoryUtils { /** * Order value for TransactionSynchronization objects that clean up Hibernate * Sessions. Return DataSourceUtils.CONNECTION_SYNCHRONIZATION_ORDER - 100 * to execute Session cleanup before JDBC Connection cleanup, if any. * @see org.springframework.jdbc.datasource.DataSourceUtils#CONNECTION_SYNCHRONIZATION_ORDER */ public static final int SESSION_SYNCHRONIZATION_ORDER = DataSourceUtils.CONNECTION_SYNCHRONIZATION_ORDER - 100; static final Log logger = LogFactory.getLog(SessionFactoryUtils.class); private static ThreadLocal deferredCloseHolder = new ThreadLocal(); /** * Determine the DataSource of the given SessionFactory. * @param sessionFactory the SessionFactory to check * @return the DataSource, or null if none found * @see net.sf.hibernate.engine.SessionFactoryImplementor#getConnectionProvider * @see LocalDataSourceConnectionProvider */ public static DataSource getDataSource(SessionFactory sessionFactory) { if (sessionFactory instanceof SessionFactoryImplementor) { ConnectionProvider cp = ((SessionFactoryImplementor) sessionFactory).getConnectionProvider(); if (cp instanceof LocalDataSourceConnectionProvider) { return ((LocalDataSourceConnectionProvider) cp).getDataSource(); } } return null; } /** * Create an appropriate SQLExceptionTranslator for the given SessionFactory. * If a DataSource is found, a SQLErrorCodeSQLExceptionTranslator for the DataSource * is created; else, a SQLStateSQLExceptionTranslator as fallback. * @param sessionFactory the SessionFactory to create the translator for * @return the SQLExceptionTranslator * @see #getDataSource * @see org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator * @see org.springframework.jdbc.support.SQLStateSQLExceptionTranslator */ public static SQLExceptionTranslator newJdbcExceptionTranslator(SessionFactory sessionFactory) { DataSource ds = getDataSource(sessionFactory); if (ds != null) { return new SQLErrorCodeSQLExceptionTranslator(ds); } return new SQLStateSQLExceptionTranslator(); } /** * Try to retrieve the JTA TransactionManager from the given SessionFactory * and/or Session. Check the passed-in SessionFactory for implementing * SessionFactoryImplementor (the usual case), falling back to the * SessionFactory reference that the Session itself carries (for example, * when using Hibernate's JCA Connector, i.e. JCASessionFactoryImpl). * @param sessionFactory Hibernate SessionFactory * @param session Hibernate Session (can also be null) * @return the JTA TransactionManager, if any * @see javax.transaction.TransactionManager * @see SessionFactoryImplementor#getTransactionManager * @see Session#getSessionFactory * @see net.sf.hibernate.impl.SessionFactoryImpl * @see net.sf.hibernate.jca.JCASessionFactoryImpl */ public static TransactionManager getJtaTransactionManager(SessionFactory sessionFactory, Session session) { SessionFactoryImplementor sessionFactoryImpl = null; if (sessionFactory instanceof SessionFactoryImplementor) { sessionFactoryImpl = ((SessionFactoryImplementor) sessionFactory); } else if (session != null) { SessionFactory internalFactory = session.getSessionFactory(); if (internalFactory instanceof SessionFactoryImplementor) { sessionFactoryImpl = (SessionFactoryImplementor) internalFactory; } } return (sessionFactoryImpl != null ? sessionFactoryImpl.getTransactionManager() : null); } /** * Get a Hibernate Session for the given SessionFactory. Is aware of and will * return any existing corresponding Session bound to the current thread, for * example when using HibernateTransactionManager. Will create a new Session * otherwise, if allowCreate is true. *

This is the getSession method used by typical data access code, * in combination with releaseSession called when done with * the Session. Note that HibernateTemplate allows to write data access code * without caring about such resource handling. *

Supports synchronization with both Spring-managed JTA transactions * (i.e. JtaTransactionManager) and non-Spring JTA transactions (i.e. plain JTA * or EJB CMT). See the getSession version with all parameters * for details. * @param sessionFactory Hibernate SessionFactory to create the session with * @param allowCreate if a non-transactional Session should be created when no * transactional Session can be found for the current thread * @return the Hibernate Session * @throws DataAccessResourceFailureException if the Session couldn't be created * @throws IllegalStateException if no thread-bound Session found and allowCreate false * @see #releaseSession * @see HibernateTemplate */ public static Session getSession(SessionFactory sessionFactory, boolean allowCreate) throws DataAccessResourceFailureException, IllegalStateException { ===================================================================== Found a 65 line (220 tokens) duplication in the following files: Starting at line 167 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/support/AbstractLobType.java Starting at line 136 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/support/AbstractLobType.java return nullSafeGetInternal(rs, rs.findColumn(names[0]), this.lobHandler); } catch (IOException ex) { throw new HibernateException("I/O errors during LOB access", ex); } } /** * This implementation delegates to nullSafeSetInternal, * passing in a transaction-synchronized LobCreator for the * LobHandler of this type. * @see #nullSafeSetInternal */ public final void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException { if (this.lobHandler == null) { throw new IllegalStateException("No LobHandler found for configuration - " + "lobHandler property must be set on LocalSessionFactoryBean"); } LobCreator lobCreator = this.lobHandler.getLobCreator(); try { nullSafeSetInternal(st, index, value, lobCreator); } catch (IOException ex) { throw new HibernateException("I/O errors during LOB access", ex); } if (TransactionSynchronizationManager.isSynchronizationActive()) { logger.debug("Registering Spring transaction synchronization for Hibernate LOB type"); TransactionSynchronizationManager.registerSynchronization( new SpringLobCreatorSynchronization(lobCreator)); } else { if (this.jtaTransactionManager != null) { try { int jtaStatus = this.jtaTransactionManager.getStatus(); if (jtaStatus == Status.STATUS_ACTIVE || jtaStatus == Status.STATUS_MARKED_ROLLBACK) { logger.debug("Registering JTA transaction synchronization for Hibernate LOB type"); this.jtaTransactionManager.getTransaction().registerSynchronization( new JtaLobCreatorSynchronization(lobCreator)); return; } } catch (Exception ex) { throw new DataAccessResourceFailureException( "Could not register synchronization with JTA TransactionManager", ex); } } throw new IllegalStateException("Active Spring transaction synchronization or active " + "JTA transaction with 'jtaTransactionManager' on LocalSessionFactoryBean required"); } } /** * Template method to extract a value from the given result set. * @param rs the ResultSet to extract from * @param index the index in the ResultSet * @param lobHandler the LobHandler to use * @return the extracted value * @throws SQLException if thrown by JDBC methods * @throws IOException if thrown by streaming methods * @throws HibernateException in case of any other exceptions */ protected abstract Object nullSafeGetInternal(ResultSet rs, int index, LobHandler lobHandler) ===================================================================== Found a 139 line (213 tokens) duplication in the following files: Starting at line 137 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/HibernateAccessor.java Starting at line 126 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/HibernateAccessor.java private BeanFactory beanFactory; /** * Set the Hibernate SessionFactory that should be used to create * Hibernate Sessions. */ public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } /** * Return the Hibernate SessionFactory that should be used to create * Hibernate Sessions. */ public SessionFactory getSessionFactory() { return sessionFactory; } /** * Set the bean name of a Hibernate entity interceptor that allows to inspect * and change property values before writing to and reading from the database. * Will get applied to any new Session created by this transaction manager. *

Requires the bean factory to be known, to be able to resolve the bean * name to an interceptor instance on session creation. Typically used for * prototype interceptors, i.e. a new interceptor instance per session. *

Can also be used for shared interceptor instances, but it is recommended * to set the interceptor reference directly in such a scenario. * @param entityInterceptorBeanName the name of the entity interceptor in * the bean factory * @see #setBeanFactory * @see #setEntityInterceptor */ public void setEntityInterceptorBeanName(String entityInterceptorBeanName) { this.entityInterceptor = entityInterceptorBeanName; } /** * Set a Hibernate entity interceptor that allows to inspect and change * property values before writing to and reading from the database. * Will get applied to any new Session created by this object. *

Such an interceptor can either be set at the SessionFactory level, * i.e. on LocalSessionFactoryBean, or at the Session level, i.e. on * HibernateTemplate, HibernateInterceptor, and HibernateTransactionManager. * It's preferable to set it on LocalSessionFactoryBean or HibernateTransactionManager * to avoid repeated configuration and guarantee consistent behavior in transactions. * @see #setEntityInterceptorBeanName * @see LocalSessionFactoryBean#setEntityInterceptor * @see HibernateTransactionManager#setEntityInterceptor */ public void setEntityInterceptor(Interceptor entityInterceptor) { this.entityInterceptor = entityInterceptor; } /** * Return the current Hibernate entity interceptor, or null if none. * Resolves an entity interceptor bean name via the bean factory, * if necessary. * @throws IllegalStateException if bean name specified but no bean factory set * @throws org.springframework.beans.BeansException if bean name resolution via the bean factory failed * @see #setEntityInterceptor * @see #setEntityInterceptorBeanName * @see #setBeanFactory */ public Interceptor getEntityInterceptor() throws IllegalStateException, BeansException { if (this.entityInterceptor instanceof String) { if (this.beanFactory == null) { throw new IllegalStateException("Cannot get entity interceptor via bean name if no bean factory set"); } return (Interceptor) this.beanFactory.getBean((String) this.entityInterceptor, Interceptor.class); } return (Interceptor) this.entityInterceptor; } /** * Set the JDBC exception translator for this instance. * Applied to SQLExceptions thrown by callback code, be it direct * SQLExceptions or wrapped Hibernate JDBCExceptions. *

The default exception translator is either a SQLErrorCodeSQLExceptionTranslator * if a DataSource is available, or a SQLStateSQLExceptionTranslator else. * @param jdbcExceptionTranslator the exception translator * @see java.sql.SQLException * @see net.sf.hibernate.JDBCException * @see SessionFactoryUtils#newJdbcExceptionTranslator * @see org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator * @see org.springframework.jdbc.support.SQLStateSQLExceptionTranslator */ public void setJdbcExceptionTranslator(SQLExceptionTranslator jdbcExceptionTranslator) { this.jdbcExceptionTranslator = jdbcExceptionTranslator; } /** * Return the JDBC exception translator for this instance. *

Creates a default SQLErrorCodeSQLExceptionTranslator or SQLStateSQLExceptionTranslator * for the specified SessionFactory, if no exception translator explicitly specified. */ public SQLExceptionTranslator getJdbcExceptionTranslator() { if (this.jdbcExceptionTranslator == null) { this.jdbcExceptionTranslator = SessionFactoryUtils.newJdbcExceptionTranslator(getSessionFactory()); } return this.jdbcExceptionTranslator; } /** * Set the flush behavior by the name of the respective constant * in this class, e.g. "FLUSH_AUTO". Default is FLUSH_AUTO. * Will get applied to any new Session created by this object. * @param constantName name of the constant * @see #setFlushMode * @see #FLUSH_AUTO */ public void setFlushModeName(String constantName) { setFlushMode(constants.asNumber(constantName).intValue()); } /** * Set the flush behavior to one of the constants in this class. * Default is FLUSH_AUTO. Will get applied to any new Session * created by this object. * @see #setFlushModeName * @see #FLUSH_AUTO */ public void setFlushMode(int flushMode) { this.flushMode = flushMode; } /** * Return if a flush should be forced after executing the callback code. */ public int getFlushMode() { return flushMode; } /** * The bean factory just needs to be known for resolving entity interceptor * bean names. It does not need to be set for any other mode of operation. * @see #setEntityInterceptorBeanName */ public void setBeanFactory(BeanFactory beanFactory) { ===================================================================== Found a 75 line (203 tokens) duplication in the following files: Starting at line 723 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/HibernateTransactionManager.java Starting at line 599 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/HibernateTransactionManager.java "Hibernate operation: " + ex.getMessage(), null, ex.getSQLException()); } /** * Hibernate transaction object, representing a SessionHolder. * Used as transaction object by HibernateTransactionManager. * *

Derives from JdbcTransactionObjectSupport to inherit the capability * to manage JDBC 3.0 Savepoints for underlying JDBC Connections. * * @see SessionHolder */ private static class HibernateTransactionObject extends JdbcTransactionObjectSupport { private SessionHolder sessionHolder; private boolean newSessionHolder; public void setSessionHolder(SessionHolder sessionHolder, boolean newSessionHolder) { this.sessionHolder = sessionHolder; this.newSessionHolder = newSessionHolder; } public SessionHolder getSessionHolder() { return sessionHolder; } public boolean isNewSessionHolder() { return newSessionHolder; } public boolean hasTransaction() { return (this.sessionHolder != null && this.sessionHolder.getTransaction() != null); } public void setRollbackOnly() { getSessionHolder().setRollbackOnly(); if (getConnectionHolder() != null) { getConnectionHolder().setRollbackOnly(); } } public boolean isRollbackOnly() { return getSessionHolder().isRollbackOnly() || (getConnectionHolder() != null && getConnectionHolder().isRollbackOnly()); } } /** * Holder for suspended resources. * Used internally by doSuspend and doResume. */ private static class SuspendedResourcesHolder { private final SessionHolder sessionHolder; private final ConnectionHolder connectionHolder; private SuspendedResourcesHolder(SessionHolder sessionHolder, ConnectionHolder conHolder) { this.sessionHolder = sessionHolder; this.connectionHolder = conHolder; } private SessionHolder getSessionHolder() { return sessionHolder; } private ConnectionHolder getConnectionHolder() { return connectionHolder; } } } ===================================================================== Found a 71 line (199 tokens) duplication in the following files: Starting at line 51 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/support/BlobSerializableType.java Starting at line 51 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/support/BlobSerializableType.java public class BlobSerializableType extends AbstractLobType { /** * Initial size for ByteArrayOutputStreams used for serialization output. *

If a serialized object is larger than these 1024 bytes, the size of * the byte array used by the output stream will be doubled each time the * limit is reached. */ private static final int OUTPUT_BYTE_ARRAY_INITIAL_SIZE = 1024; /** * Constructor used by Hibernate: fetches config-time LobHandler and * config-time JTA TransactionManager from LocalSessionFactoryBean. * @see org.springframework.orm.hibernate.LocalSessionFactoryBean#getConfigTimeLobHandler * @see org.springframework.orm.hibernate.LocalSessionFactoryBean#getConfigTimeTransactionManager */ public BlobSerializableType() { super(); } /** * Constructor used for testing: takes an explicit LobHandler * and an explicit JTA TransactionManager (can be null). */ protected BlobSerializableType(LobHandler lobHandler, TransactionManager jtaTransactionManager) { super(lobHandler, jtaTransactionManager); } public int[] sqlTypes() { return new int[] {Types.BLOB}; } public Class returnedClass() { return Serializable.class; } public boolean isMutable() { return true; } public Object deepCopy(Object value) throws HibernateException { try { // Write to new byte array to clone. ByteArrayOutputStream baos = new ByteArrayOutputStream(OUTPUT_BYTE_ARRAY_INITIAL_SIZE); ObjectOutputStream oos = new ObjectOutputStream(baos); try { oos.writeObject(value); } finally { oos.close(); } // Read it back and return a true copy. ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); try { return ois.readObject(); } finally { ois.close(); } } catch (ClassNotFoundException ex) { throw new HibernateException("Couldn't clone BLOB contents", ex); } catch (IOException ex) { throw new HibernateException("Couldn't clone BLOB contents", ex); } } protected Object nullSafeGetInternal(ResultSet rs, int index, LobHandler lobHandler) ===================================================================== Found a 72 line (197 tokens) duplication in the following files: Starting at line 35 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/JtaSessionSynchronization.java Starting at line 35 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/JtaSessionSynchronization.java class JtaSessionSynchronization implements Synchronization { private final SpringSessionSynchronization springSessionSynchronization; private final TransactionManager jtaTransactionManager; private boolean beforeCompletionCalled = false; public JtaSessionSynchronization( SpringSessionSynchronization springSessionSynchronization, TransactionManager jtaTransactionManager) { this.springSessionSynchronization = springSessionSynchronization; this.jtaTransactionManager = jtaTransactionManager; } /** * JTA beforeCompletion callback: just invoked on commit. *

In case of an exception, the JTA transaction gets set to rollback-only. * (Synchronization.beforeCompletion is not supposed to throw an exception.) * @see SpringSessionSynchronization#beforeCommit */ public void beforeCompletion() { try { boolean readOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly(); this.springSessionSynchronization.beforeCommit(readOnly); } catch (Throwable ex) { SessionFactoryUtils.logger.error("beforeCommit callback threw exception", ex); try { this.jtaTransactionManager.setRollbackOnly(); } catch (SystemException ex2) { SessionFactoryUtils.logger.error("Could not set JTA transaction rollback-only", ex2); } } // Unbind the SessionHolder from the thread early, to avoid issues // with strict JTA implementations that issue warnings when doing JDBC // operations after transaction completion (e.g. Connection.getWarnings). this.beforeCompletionCalled = true; this.springSessionSynchronization.beforeCompletion(); } /** * JTA afterCompletion callback: invoked after commit/rollback. *

Needs to invoke SpringSessionSynchronization's beforeCompletion * at this late stage, as there's no corresponding callback with JTA. * @see SpringSessionSynchronization#beforeCompletion * @see SpringSessionSynchronization#afterCompletion */ public void afterCompletion(int status) { if (!this.beforeCompletionCalled) { // beforeCompletion not called before (probably because of JTA rollback). // Unbind the SessionHolder from the thread here. this.springSessionSynchronization.beforeCompletion(); } // Reset the synchronizedWithTransaction flag, // and clear the Hibernate Session after a rollback (if necessary). switch (status) { case Status.STATUS_COMMITTED: this.springSessionSynchronization.afterCompletion(TransactionSynchronization.STATUS_COMMITTED); break; case Status.STATUS_ROLLEDBACK: this.springSessionSynchronization.afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK); break; default: this.springSessionSynchronization.afterCompletion(TransactionSynchronization.STATUS_UNKNOWN); } } } ===================================================================== Found a 57 line (193 tokens) duplication in the following files: Starting at line 305 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/HibernateAccessor.java Starting at line 257 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/HibernateAccessor.java } /** * The bean factory just needs to be known for resolving entity interceptor * bean names. It does not need to be set for any other mode of operation. * @see #setEntityInterceptorBeanName */ public void setBeanFactory(BeanFactory beanFactory) { this.beanFactory = beanFactory; } public void afterPropertiesSet() { if (getSessionFactory() == null) { throw new IllegalArgumentException("sessionFactory is required"); } } /** * Apply the flush mode that's been specified for this accessor * to the given Session. * @param session the current Hibernate Session * @param existingTransaction if executing within an existing transaction * @return the previous flush mode to restore after the operation, * or null if none * @see #setFlushMode * @see net.sf.hibernate.Session#setFlushMode */ protected FlushMode applyFlushMode(Session session, boolean existingTransaction) { if (getFlushMode() == FLUSH_NEVER) { if (existingTransaction) { FlushMode previousFlushMode = session.getFlushMode(); if (!previousFlushMode.equals(FlushMode.NEVER)) { session.setFlushMode(FlushMode.NEVER); return previousFlushMode; } } else { session.setFlushMode(FlushMode.NEVER); } } else if (getFlushMode() == FLUSH_EAGER) { if (existingTransaction) { FlushMode previousFlushMode = session.getFlushMode(); if (!previousFlushMode.equals(FlushMode.AUTO)) { session.setFlushMode(FlushMode.AUTO); return previousFlushMode; } } else { // rely on default FlushMode.AUTO } } else if (getFlushMode() == FLUSH_COMMIT) { if (existingTransaction) { FlushMode previousFlushMode = session.getFlushMode(); if (previousFlushMode.equals(FlushMode.AUTO)) { ===================================================================== Found a 49 line (192 tokens) duplication in the following files: Starting at line 42 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/jms/listener/DefaultMessageListenerContainer102.java Starting at line 42 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/jms/listener/SimpleMessageListenerContainer102.java public class SimpleMessageListenerContainer102 extends SimpleMessageListenerContainer { /** * This implementation overrides the superclass method to use JMS 1.0.2 API. */ protected Connection createConnection() throws JMSException { if (isPubSubDomain()) { return ((TopicConnectionFactory) getConnectionFactory()).createTopicConnection(); } else { return ((QueueConnectionFactory) getConnectionFactory()).createQueueConnection(); } } /** * This implementation overrides the superclass method to use JMS 1.0.2 API. */ protected Session createSession(Connection con) throws JMSException { if (isPubSubDomain()) { return ((TopicConnection) con).createTopicSession(isSessionTransacted(), getSessionAcknowledgeMode()); } else { return ((QueueConnection) con).createQueueSession(isSessionTransacted(), getSessionAcknowledgeMode()); } } /** * This implementation overrides the superclass method to use JMS 1.0.2 API. */ protected MessageConsumer createConsumer(Session session, Destination destination) throws JMSException { if (isPubSubDomain()) { return ((TopicSession) session).createSubscriber( (Topic) destination, getMessageSelector(), isPubSubNoLocal()); } else { return ((QueueSession) session).createReceiver((Queue) destination, getMessageSelector()); } } /** * This implementation overrides the superclass method to avoid using * JMS 1.1's Session getAcknowledgeMode() method. * The best we can do here is to check the setting on the template. */ protected boolean isClientAcknowledge(Session session) throws JMSException { return getSessionAcknowledgeMode() == Session.CLIENT_ACKNOWLEDGE; } } ===================================================================== Found a 89 line (191 tokens) duplication in the following files: Starting at line 235 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/support/AbstractLobType.java Starting at line 200 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/support/AbstractLobType.java protected abstract Object nullSafeGetInternal(ResultSet rs, int index, LobHandler lobHandler) throws SQLException, IOException, HibernateException; /** * Template method to set the given parameter value on the given statement. * @param ps the PreparedStatement to set on * @param index the statement parameter index * @param value the value to set * @param lobCreator the LobCreator to use * @throws SQLException if thrown by JDBC methods * @throws IOException if thrown by streaming methods * @throws HibernateException in case of any other exceptions */ protected abstract void nullSafeSetInternal( PreparedStatement ps, int index, Object value, LobCreator lobCreator) throws SQLException, IOException, HibernateException; /** * Callback for resource cleanup at the end of a Spring transaction. * Invokes LobCreator.close to clean up temporary LOBs that might have been created. * @see org.springframework.jdbc.support.lob.LobCreator#close */ private static class SpringLobCreatorSynchronization extends TransactionSynchronizationAdapter { private final LobCreator lobCreator; private boolean beforeCompletionCalled = false; public SpringLobCreatorSynchronization(LobCreator lobCreator) { this.lobCreator = lobCreator; } public int getOrder() { return LOB_CREATOR_SYNCHRONIZATION_ORDER; } public void beforeCompletion() { // Close the LobCreator early if possible, to avoid issues with strict JTA // implementations that issue warnings when doing JDBC operations after // transaction completion. this.beforeCompletionCalled = true; this.lobCreator.close(); } public void afterCompletion(int status) { if (!this.beforeCompletionCalled) { // beforeCompletion not called before (probably because of flushing on commit // in HibernateTransactionManager, after the chain of beforeCompletion calls). // Close the LobCreator here. this.lobCreator.close(); } } } /** * Callback for resource cleanup at the end of a JTA transaction. * Invokes LobCreator.close to clean up temporary LOBs that might have been created. * @see org.springframework.jdbc.support.lob.LobCreator#close */ private static class JtaLobCreatorSynchronization implements Synchronization { private final LobCreator lobCreator; private boolean beforeCompletionCalled = false; public JtaLobCreatorSynchronization(LobCreator lobCreator) { this.lobCreator = lobCreator; } public void beforeCompletion() { // Close the LobCreator early if possible, to avoid issues with strict JTA // implementations that issue warnings when doing JDBC operations after // transaction completion. this.beforeCompletionCalled = true; this.lobCreator.close(); } public void afterCompletion(int status) { if (!this.beforeCompletionCalled) { // beforeCompletion not called before (probably because of JTA rollback). // Close the LobCreator here. this.lobCreator.close(); } } } } ===================================================================== Found a 48 line (191 tokens) duplication in the following files: Starting at line 43 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/support/BlobByteArrayType.java Starting at line 43 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/support/BlobByteArrayType.java public class BlobByteArrayType extends AbstractLobType { /** * Constructor used by Hibernate: fetches config-time LobHandler and * config-time JTA TransactionManager from LocalSessionFactoryBean. * @see org.springframework.orm.hibernate.LocalSessionFactoryBean#getConfigTimeLobHandler * @see org.springframework.orm.hibernate.LocalSessionFactoryBean#getConfigTimeTransactionManager */ public BlobByteArrayType() { super(); } /** * Constructor used for testing: takes an explicit LobHandler * and an explicit JTA TransactionManager (can be null). */ protected BlobByteArrayType(LobHandler lobHandler, TransactionManager jtaTransactionManager) { super(lobHandler, jtaTransactionManager); } public int[] sqlTypes() { return new int[] {Types.BLOB}; } public Class returnedClass() { return byte[].class; } public boolean isMutable() { return true; } public boolean equals(Object x, Object y) { return (x == y) || (x instanceof byte[] && y instanceof byte[] && Arrays.equals((byte[]) x, (byte[]) y)); } public Object deepCopy(Object value) { if (value == null) { return null; } byte[] original = (byte[]) value; byte[] copy = new byte[original.length]; System.arraycopy(original, 0, copy, 0, original.length); return copy; } protected Object nullSafeGetInternal(ResultSet rs, int index, LobHandler lobHandler) ===================================================================== Found a 55 line (185 tokens) duplication in the following files: Starting at line 1122 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/HibernateTemplate.java Starting at line 1063 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/HibernateTemplate.java } } /** * Invocation handler that suppresses close calls on Hibernate Sessions. * Also prepares returned Query and Criteria objects. * @see net.sf.hibernate.Session#close */ private class CloseSuppressingInvocationHandler implements InvocationHandler { private final Session target; public CloseSuppressingInvocationHandler(Session target) { this.target = target; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Invocation on Session interface coming in... if (method.getName().equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0] ? Boolean.TRUE : Boolean.FALSE); } else if (method.getName().equals("hashCode")) { // Use hashCode of Session proxy. return new Integer(hashCode()); } else if (method.getName().equals("close")) { // Handle close method: suppress, not valid. return null; } // Invoke method on target Session. try { Object retVal = method.invoke(this.target, args); // If return value is a Query or Criteria, apply transaction timeout. // Applies to createQuery, getNamedQuery, createCriteria. if (retVal instanceof Query) { prepareQuery(((Query) retVal)); } if (retVal instanceof Criteria) { prepareCriteria(((Criteria) retVal)); } return retVal; } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } } } ===================================================================== Found a 37 line (179 tokens) duplication in the following files: Starting at line 411 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/HibernateTransactionManager.java Starting at line 363 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/HibernateTransactionManager.java logger.debug("Found thread-bound Session [" + sessionHolder.getSession() + "] for Hibernate transaction"); } txObject.setSessionHolder(sessionHolder, false); if (getDataSource() != null) { ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(getDataSource()); txObject.setConnectionHolder(conHolder); } } return txObject; } protected boolean isExistingTransaction(Object transaction) { return ((HibernateTransactionObject) transaction).hasTransaction(); } protected void doBegin(Object transaction, TransactionDefinition definition) { if (getDataSource() != null && TransactionSynchronizationManager.hasResource(getDataSource())) { throw new IllegalTransactionStateException( "Pre-bound JDBC Connection found - HibernateTransactionManager does not support " + "running within DataSourceTransactionManager if told to manage the DataSource itself. " + "It is recommended to use a single HibernateTransactionManager for all transactions " + "on a single DataSource, no matter whether Hibernate or JDBC access."); } Session session = null; try { HibernateTransactionObject txObject = (HibernateTransactionObject) transaction; if (txObject.getSessionHolder() == null) { Interceptor entityInterceptor = getEntityInterceptor(); Session newSession = (entityInterceptor != null ? getSessionFactory().openSession(entityInterceptor) : getSessionFactory().openSession()); if (logger.isDebugEnabled()) { logger.debug("Opened new Session [" + newSession + "] for Hibernate transaction"); ===================================================================== Found a 41 line (170 tokens) duplication in the following files: Starting at line 324 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/SessionFactoryUtils.java Starting at line 287 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/SessionFactoryUtils.java logger.debug("Opening Hibernate Session"); Session session = (entityInterceptor != null ? sessionFactory.openSession(entityInterceptor) : sessionFactory.openSession()); // Set Session to FlushMode.NEVER if we're within a read-only transaction. // Use same Session for further Hibernate actions within the transaction. // Thread object will get removed by synchronization at transaction completion. if (TransactionSynchronizationManager.isSynchronizationActive()) { // We're within a Spring-managed transaction, possibly from JtaTransactionManager. logger.debug("Registering Spring transaction synchronization for new Hibernate Session"); SessionHolder holderToUse = sessionHolder; if (holderToUse == null) { holderToUse = new SessionHolder(session); } else { holderToUse.addSession(session); } if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { session.setFlushMode(FlushMode.NEVER); } TransactionSynchronizationManager.registerSynchronization( new SpringSessionSynchronization(holderToUse, sessionFactory, jdbcExceptionTranslator, true)); holderToUse.setSynchronizedWithTransaction(true); if (holderToUse != sessionHolder) { TransactionSynchronizationManager.bindResource(sessionFactory, holderToUse); } } else { // No Spring transaction management active -> try JTA transaction synchronization. registerJtaSynchronization(session, sessionFactory, jdbcExceptionTranslator, sessionHolder); } // Check whether we are allowed to return the Session. if (!allowCreate && !isSessionTransactional(session, sessionFactory)) { doClose(session); throw new IllegalStateException("No Hibernate Session bound to thread, " + "and configuration does not allow creation of non-transactional one here"); } return session; } ===================================================================== Found a 58 line (170 tokens) duplication in the following files: Starting at line 135 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/remoting/rmi/RmiRegistryFactoryBean.java Starting at line 246 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/remoting/rmi/RmiServiceExporter.java this.registry.rebind(this.serviceName, this.exportedObject); } /** * Locate or create the RMI registry for this exporter. * @param registryHost the registry host to use (if this is specified, * no implicit creation of a RMI registry will happen) * @param registryPort the registry port to use * @param clientSocketFactory the RMI client socket factory for the registry (if any) * @param serverSocketFactory the RMI server socket factory for the registry (if any) * @return the RMI registry * @throws RemoteException if the registry couldn't be located or created */ protected Registry getRegistry(String registryHost, int registryPort, RMIClientSocketFactory clientSocketFactory, RMIServerSocketFactory serverSocketFactory) throws RemoteException { if (registryHost != null) { // Host explictly specified: only lookup possible. if (logger.isInfoEnabled()) { logger.info("Looking for RMI registry at port '" + registryPort + "' of host [" + registryHost + "]"); } Registry reg = LocateRegistry.getRegistry(registryHost, registryPort, clientSocketFactory); testRegistry(reg); return reg; } else { return getRegistry(registryPort, clientSocketFactory, serverSocketFactory); } } /** * Locate or create the RMI registry for this exporter. * @param registryPort the registry port to use * @param clientSocketFactory the RMI client socket factory for the registry (if any) * @param serverSocketFactory the RMI server socket factory for the registry (if any) * @return the RMI registry * @throws RemoteException if the registry couldn't be located or created */ protected Registry getRegistry( int registryPort, RMIClientSocketFactory clientSocketFactory, RMIServerSocketFactory serverSocketFactory) throws RemoteException { if (clientSocketFactory != null) { if (logger.isInfoEnabled()) { logger.info("Looking for RMI registry at port '" + registryPort + "', using custom socket factory"); } try { // Retrieve existing registry. Registry reg = LocateRegistry.getRegistry(null, registryPort, clientSocketFactory); testRegistry(reg); return reg; } catch (RemoteException ex) { logger.debug("RMI registry access threw exception", ex); logger.warn("Could not detect RMI registry - creating new one"); ===================================================================== Found a 59 line (156 tokens) duplication in the following files: Starting at line 38 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/LocalDataSourceConnectionProvider.java Starting at line 38 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/LocalDataSourceConnectionProvider.java public class LocalDataSourceConnectionProvider implements ConnectionProvider { private DataSource dataSource; private DataSource dataSourceToUse; public void configure(Properties props) throws HibernateException { this.dataSource = LocalSessionFactoryBean.getConfigTimeDataSource(); // absolutely needs thread-bound DataSource to initialize if (this.dataSource == null) { throw new HibernateException("No local DataSource found for configuration - " + "dataSource property must be set on LocalSessionFactoryBean"); } this.dataSourceToUse = getDataSourceToUse(this.dataSource); } /** * Return the DataSource to use for retrieving Connections. *

This implementation returns the passed-in DataSource as-is. * @param originalDataSource the DataSource as configured by the user * on LocalSessionFactoryBean * @return the DataSource to actually retrieve Connections from * (potentially wrapped) * @see LocalSessionFactoryBean#setDataSource */ protected DataSource getDataSourceToUse(DataSource originalDataSource) { return originalDataSource; } /** * Return the DataSource that this ConnectionProvider wraps. */ public DataSource getDataSource() { return dataSource; } public Connection getConnection() throws SQLException { try { return this.dataSourceToUse.getConnection(); } catch (SQLException ex) { JDBCExceptionReporter.logExceptions(ex); throw ex; } } public void closeConnection(Connection con) throws SQLException { try { con.close(); } catch (SQLException ex) { JDBCExceptionReporter.logExceptions(ex); throw ex; } } public void close() { // Do nothing here - it's an externally managed DataSource. } ===================================================================== Found a 39 line (151 tokens) duplication in the following files: Starting at line 125 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/support/BlobSerializableType.java Starting at line 124 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/support/BlobSerializableType.java InputStream is = lobHandler.getBlobAsBinaryStream(rs, index); if (is != null) { ObjectInputStream ois = new ObjectInputStream(is); try { return ois.readObject(); } catch (ClassNotFoundException ex) { throw new HibernateException("Could not deserialize BLOB contents", ex); } finally { ois.close(); } } else { return null; } } protected void nullSafeSetInternal(PreparedStatement ps, int index, Object value, LobCreator lobCreator) throws SQLException, IOException { if (value != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(OUTPUT_BYTE_ARRAY_INITIAL_SIZE); ObjectOutputStream oos = new ObjectOutputStream(baos); try { oos.writeObject(value); oos.flush(); lobCreator.setBlobAsBytes(ps, index, baos.toByteArray()); } finally { oos.close(); } } else { lobCreator.setBlobAsBytes(ps, index, null); } } } ===================================================================== Found a 29 line (133 tokens) duplication in the following files: Starting at line 627 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/jdo/JdoTemplate.java Starting at line 1135 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/HibernateTemplate.java public CloseSuppressingInvocationHandler(Session target) { this.target = target; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Invocation on Session interface coming in... if (method.getName().equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0] ? Boolean.TRUE : Boolean.FALSE); } else if (method.getName().equals("hashCode")) { // Use hashCode of Session proxy. return new Integer(hashCode()); } else if (method.getName().equals("close")) { // Handle close method: suppress, not valid. return null; } // Invoke method on target Session. try { Object retVal = method.invoke(this.target, args); // If return value is a Query or Criteria, apply transaction timeout. // Applies to createQuery, getNamedQuery, createCriteria. if (retVal instanceof Query) { prepareQuery(((Query) retVal)); } ===================================================================== Found a 35 line (132 tokens) duplication in the following files: Starting at line 114 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/jdo/support/OpenPersistenceManagerInViewInterceptor.java Starting at line 113 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/jdo/support/PortletOpenPersistenceManagerInViewInterceptor.java public void afterCompletion(PortletRequest request, PortletResponse response, Object handler, Exception ex) throws DataAccessException { String participateAttributeName = getParticipateAttributeName(); Integer count = (Integer) request.getAttribute(participateAttributeName); if (count != null) { // Do not modify the PersistenceManager: just clear the marker. if (count.intValue() > 1) { request.setAttribute(participateAttributeName, new Integer(count.intValue() - 1)); } else { request.removeAttribute(participateAttributeName); } } else { PersistenceManagerHolder pmHolder = (PersistenceManagerHolder) TransactionSynchronizationManager.unbindResource(getPersistenceManagerFactory()); logger.debug("Closing JDO persistence manager in OpenPersistenceManagerInViewInterceptor"); PersistenceManagerFactoryUtils.releasePersistenceManager( pmHolder.getPersistenceManager(), getPersistenceManagerFactory()); } } /** * Return the name of the request attribute that identifies that a request is * already filtered. Default implementation takes the toString representation * of the PersistenceManagerFactory instance and appends ".FILTERED". * @see #PARTICIPATE_SUFFIX */ protected String getParticipateAttributeName() { return getPersistenceManagerFactory().toString() + PARTICIPATE_SUFFIX; } } ===================================================================== Found a 24 line (125 tokens) duplication in the following files: Starting at line 672 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/LocalSessionFactoryBean.java Starting at line 457 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/LocalSessionFactoryBean.java config.addInputStream(this.mappingLocations[i].getInputStream()); } } if (this.mappingJarLocations != null) { // Register given Hibernate mapping definitions, contained in jar files. for (int i = 0; i < this.mappingJarLocations.length; i++) { Resource resource = this.mappingJarLocations[i]; config.addJar(resource.getFile()); } } if (this.mappingDirectoryLocations != null) { // Register all Hibernate mapping definitions in the given directories. for (int i = 0; i < this.mappingDirectoryLocations.length; i++) { File file = this.mappingDirectoryLocations[i].getFile(); if (!file.isDirectory()) { throw new IllegalArgumentException( "Mapping directory location [" + this.mappingDirectoryLocations[i] + "] does not denote a directory"); } config.addDirectory(file); } } ===================================================================== Found a 45 line (119 tokens) duplication in the following files: Starting at line 81 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/jdbc/support/incrementer/HsqlMaxValueIncrementer.java Starting at line 88 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/jdbc/support/incrementer/MySQLMaxValueIncrementer.java public MySQLMaxValueIncrementer(DataSource ds, String incrementerName, String columnName) { setDataSource(ds); setIncrementerName(incrementerName); this.columnName = columnName; afterPropertiesSet(); } /** * Set the name of the column in the sequence table. */ public void setColumnName(String columnName) { this.columnName = columnName; } /** * Return the name of the column in the sequence table. */ public String getColumnName() { return this.columnName; } /** * Set the number of buffered keys. */ public void setCacheSize(int cacheSize) { this.cacheSize = cacheSize; } /** * Return the number of buffered keys. */ public int getCacheSize() { return this.cacheSize; } public void afterPropertiesSet() { super.afterPropertiesSet(); if (this.columnName == null) { throw new IllegalArgumentException("columnName is required"); } } protected synchronized long getNextKey() throws DataAccessException { if (this.maxId == this.nextId) { ===================================================================== Found a 32 line (115 tokens) duplication in the following files: Starting at line 83 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/ejb/access/SimpleRemoteStatelessSessionProxyFactoryBean.java Starting at line 71 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/ejb/access/LocalStatelessSessionProxyFactoryBean.java public void setBusinessInterface(Class businessInterface) { this.businessInterface = businessInterface; } /** * Return the business interface of the EJB we're proxying. */ public Class getBusinessInterface() { return businessInterface; } public void afterPropertiesSet() throws NamingException { super.afterPropertiesSet(); if (this.businessInterface == null) { throw new IllegalArgumentException("businessInterface is required"); } this.proxy = ProxyFactory.getProxy(this.businessInterface, this); } public Object getObject() { return this.proxy; } public Class getObjectType() { return (this.proxy != null) ? this.proxy.getClass() : this.businessInterface; } public boolean isSingleton() { return true; } } ===================================================================== Found a 23 line (114 tokens) duplication in the following files: Starting at line 91 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/jdo/support/OpenPersistenceManagerInViewInterceptor.java Starting at line 91 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/jdo/support/PortletOpenPersistenceManagerInViewInterceptor.java public boolean preHandle(PortletRequest request, PortletResponse response, Object handler) throws DataAccessException { if (TransactionSynchronizationManager.hasResource(getPersistenceManagerFactory())) { // Do not modify the PersistenceManager: just mark the request accordingly. String participateAttributeName = getParticipateAttributeName(); Integer count = (Integer) request.getAttribute(participateAttributeName); int newCount = (count != null) ? count.intValue() + 1 : 1; request.setAttribute(getParticipateAttributeName(), new Integer(newCount)); } else { logger.debug("Opening JDO persistence manager in OpenPersistenceManagerInViewInterceptor"); PersistenceManager pm = PersistenceManagerFactoryUtils.getPersistenceManager(getPersistenceManagerFactory(), true); TransactionSynchronizationManager.bindResource( getPersistenceManagerFactory(), new PersistenceManagerHolder(pm)); } return true; } public void afterCompletion(PortletRequest request, PortletResponse response, Object handler, Exception ex) ===================================================================== Found a 28 line (113 tokens) duplication in the following files: Starting at line 61 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/transaction/interceptor/MethodMapTransactionAttributeSource.java Starting at line 55 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/transaction/interceptor/NameMatchTransactionAttributeSource.java Iterator it = nameMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); String name = (String) entry.getKey(); // Check whether we need to convert from String to TransactionAttribute. TransactionAttribute attr = null; if (entry.getValue() instanceof TransactionAttribute) { attr = (TransactionAttribute) entry.getValue(); } else { TransactionAttributeEditor editor = new TransactionAttributeEditor(); editor.setAsText(entry.getValue().toString()); attr = (TransactionAttribute) editor.getValue(); } addTransactionalMethod(name, attr); } } /** * Parses the given properties into a name/attribute map. * Expects method names as keys and String attributes definitions as values, * parsable into TransactionAttribute instances via TransactionAttributeEditor. * @see #setNameMap * @see TransactionAttributeEditor */ public void setProperties(Properties transactionAttributes) { ===================================================================== Found a 36 line (113 tokens) duplication in the following files: Starting at line 93 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/ObjectOptimisticLockingFailureException.java Starting at line 92 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/ObjectRetrievalFailureException.java public ObjectRetrievalFailureException( String persistentClassName, Object identifier, String msg, Throwable ex) { super(msg, ex); this.persistentClass = persistentClassName; this.identifier = identifier; } /** * Return the persistent class of the object that was not found. * If no Class was specified, this method returns null. */ public Class getPersistentClass() { return (this.persistentClass instanceof Class ? (Class) this.persistentClass : null); } /** * Return the name of the persistent class of the object that was not found. * Will work for both Class objects and String names. */ public String getPersistentClassName() { if (this.persistentClass instanceof Class) { return ((Class) this.persistentClass).getName(); } return (this.persistentClass != null ? this.persistentClass.toString() : null); } /** * Return the identifier of the object that was not found. */ public Object getIdentifier() { return identifier; } } ===================================================================== Found a 58 line (113 tokens) duplication in the following files: Starting at line 62 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/support/AbstractLobType.java Starting at line 60 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/support/AbstractLobType.java public abstract class AbstractLobType implements UserType { /** * Order value for TransactionSynchronization objects that clean up LobCreators. * Return SessionFactoryUtils.SESSION_SYNCHRONIZATION_ORDER - 100 to execute * LobCreator cleanup before Hibernate Session and JDBC Connection cleanup, if any. * @see org.springframework.orm.hibernate.SessionFactoryUtils#SESSION_SYNCHRONIZATION_ORDER */ public static final int LOB_CREATOR_SYNCHRONIZATION_ORDER = SessionFactoryUtils.SESSION_SYNCHRONIZATION_ORDER - 100; protected final Log logger = LogFactory.getLog(getClass()); private final LobHandler lobHandler; private final TransactionManager jtaTransactionManager; /** * Constructor used by Hibernate: fetches config-time LobHandler and * config-time JTA TransactionManager from LocalSessionFactoryBean. * @see org.springframework.orm.hibernate.LocalSessionFactoryBean#getConfigTimeLobHandler * @see org.springframework.orm.hibernate.LocalSessionFactoryBean#getConfigTimeTransactionManager */ protected AbstractLobType() { this(LocalSessionFactoryBean.getConfigTimeLobHandler(), LocalSessionFactoryBean.getConfigTimeTransactionManager()); } /** * Constructor used for testing: takes an explicit LobHandler * and an explicit JTA TransactionManager (can be null). */ protected AbstractLobType(LobHandler lobHandler, TransactionManager jtaTransactionManager) { this.lobHandler = lobHandler; this.jtaTransactionManager = jtaTransactionManager; } /** * This implementation returns false. */ public boolean isMutable() { return false; } /** * This implementation delegates to the Hibernate EqualsHelper. * @see net.sf.hibernate.util.EqualsHelper#equals */ public boolean equals(Object x, Object y) throws HibernateException { return EqualsHelper.equals(x, y); } /** * This implementation returns the passed-in value as-is. */ public Object deepCopy(Object value) throws HibernateException { ===================================================================== Found a 33 line (112 tokens) duplication in the following files: Starting at line 206 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/remoting/rmi/RmiClientInterceptor.java Starting at line 259 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/remoting/rmi/JndiRmiClientInterceptor.java throw new RemoteLookupFailureException("RMI lookup for service [" + getJndiName() + "] failed", ex); } try { return doInvoke(invocation, stub); } catch (RemoteConnectFailureException ex) { return handleRemoteConnectFailure(invocation, ex); } catch (RemoteException ex) { if (isConnectFailure(ex)) { return handleRemoteConnectFailure(invocation, ex); } else { throw ex; } } } /** * Determine whether the given RMI exception indicates a connect failure. * Default implementation delegates to RmiClientInterceptorUtils. * @param ex the RMI exception to check * @return whether the exception should be treated as connect failure * @see org.springframework.remoting.rmi.RmiClientInterceptorUtils#isConnectFailure */ protected boolean isConnectFailure(RemoteException ex) { return RmiClientInterceptorUtils.isConnectFailure(ex); } private Object handleRemoteConnectFailure(MethodInvocation invocation, Exception ex) throws Throwable { if (this.refreshStubOnConnectFailure) { if (logger.isDebugEnabled()) { logger.debug("Could not connect to RMI service [" + getJndiName() + "] - retrying", ex); ===================================================================== Found a 18 line (110 tokens) duplication in the following files: Starting at line 1079 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/jdbc/core/JdbcTemplate.java Starting at line 141 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/jdbc/datasource/TransactionAwareDataSourceProxy.java } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Invocation on ConnectionProxy interface coming in... if (method.getName().equals("getTargetConnection")) { // Handle getTargetConnection method: return underlying Connection. return this.target; } else if (method.getName().equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0] ? Boolean.TRUE : Boolean.FALSE); } else if (method.getName().equals("hashCode")) { // Use hashCode of Connection proxy. return new Integer(hashCode()); } else if (method.getName().equals("close")) { ===================================================================== Found a 47 line (107 tokens) duplication in the following files: Starting at line 379 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/HibernateAccessor.java Starting at line 319 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/HibernateAccessor.java session.setFlushMode(FlushMode.COMMIT); } } return null; } /** * Flush the given Hibernate Session if necessary. * @param session the current Hibernate Session * @param existingTransaction if executing within an existing transaction * @throws HibernateException in case of Hibernate flushing errors */ protected void flushIfNecessary(Session session, boolean existingTransaction) throws HibernateException { if (getFlushMode() == FLUSH_EAGER || (!existingTransaction && getFlushMode() != FLUSH_NEVER)) { logger.debug("Eagerly flushing Hibernate session"); session.flush(); } } /** * Convert the given HibernateException to an appropriate exception from the * org.springframework.dao hierarchy. Will automatically detect * wrapped SQLExceptions and convert them accordingly. *

The default implementation delegates to SessionFactoryUtils * and convertJdbcAccessException. Can be overridden in subclasses. * @param ex HibernateException that occured * @return the corresponding DataAccessException instance * @see #convertJdbcAccessException(net.sf.hibernate.JDBCException) * @see SessionFactoryUtils#convertHibernateAccessException */ public DataAccessException convertHibernateAccessException(HibernateException ex) { if (ex instanceof JDBCException) { return convertJdbcAccessException((JDBCException) ex); } return SessionFactoryUtils.convertHibernateAccessException(ex); } /** * Convert the given JDBCException to an appropriate exception from the * org.springframework.dao hierarchy. Can be overridden in subclasses. * @param ex JDBCException that occured, wrapping a SQLException * @return the corresponding DataAccessException instance * @see #setJdbcExceptionTranslator */ protected DataAccessException convertJdbcAccessException(JDBCException ex) { return getJdbcExceptionTranslator().translate( "Hibernate operation: " + ex.getMessage(), null, ex.getSQLException()); ===================================================================== Found a 123 line (106 tokens) duplication in the following files: Starting at line 290 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/LocalSessionFactoryBean.java Starting at line 215 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/LocalSessionFactoryBean.java } /** * Set locations of jar files that contain Hibernate mapping resources, * like "WEB-INF/lib/example.hbm.jar". *

Can be used to add to mappings from a Hibernate XML config file, * or to specify all mappings locally. * @see net.sf.hibernate.cfg.Configuration#addJar(java.io.File) */ public void setMappingJarLocations(Resource[] mappingJarLocations) { this.mappingJarLocations = mappingJarLocations; } /** * Set locations of directories that contain Hibernate mapping resources, * like "WEB-INF/mappings". *

Can be used to add to mappings from a Hibernate XML config file, * or to specify all mappings locally. * @see net.sf.hibernate.cfg.Configuration#addDirectory(java.io.File) */ public void setMappingDirectoryLocations(Resource[] mappingDirectoryLocations) { this.mappingDirectoryLocations = mappingDirectoryLocations; } /** * Set Hibernate properties, like "hibernate.dialect". *

Can be used to override values in a Hibernate XML config file, * or to specify all necessary properties locally. *

Note: Do not specify a transaction provider here when using * Spring-driven transactions. It is also advisable to omit connection * provider settings and use a Spring-set DataSource instead. * @see #setDataSource */ public void setHibernateProperties(Properties hibernateProperties) { this.hibernateProperties = hibernateProperties; } /** * Return the Hibernate properties, if any. Mainly available for * configuration through property paths that specify individual keys. */ public Properties getHibernateProperties() { if (this.hibernateProperties == null) { this.hibernateProperties = new Properties(); } return this.hibernateProperties; } /** * Set the DataSource to be used by the SessionFactory. * If set, this will override corresponding settings in Hibernate properties. *

Note: If this is set, the Hibernate settings should not define * a connection provider to avoid meaningless double configuration. *

If using HibernateTransactionManager as transaction strategy, consider * proxying your target DataSource with a LazyConnectionDataSourceProxy. * This defers fetching of an actual JDBC Connection until the first JDBC * Statement gets executed, even within JDBC transactions (as performed by * HibernateTransactionManager). Such lazy fetching is particularly beneficial * for read-only operations, in particular if the chances of resolving the * result in the second-level cache are high. *

As JTA and transactional JNDI DataSources already provide lazy enlistment * of JDBC Connections, LazyConnectionDataSourceProxy does not add value with * JTA (i.e. Spring's JtaTransactionManager) as transaction strategy. * @see #setUseTransactionAwareDataSource * @see LocalDataSourceConnectionProvider * @see HibernateTransactionManager * @see org.springframework.transaction.jta.JtaTransactionManager * @see org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy */ public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } /** * Set whether to use a transaction-aware DataSource for the SessionFactory, * i.e. whether to automatically wrap the passed-in DataSource with Spring's * TransactionAwareDataSourceProxy. *

Default is "false": LocalSessionFactoryBean is usually used with Spring's * HibernateTransactionManager or JtaTransactionManager, both of which work nicely * on a plain JDBC DataSource. Hibernate Sessions and their JDBC Connections are * fully managed by the Hibernate/JTA transaction infrastructure in such a scenario. *

If you switch this flag to "true", Spring's Hibernate access will be able to * participate in JDBC-based transactions managed outside of Hibernate * (for example, by Spring's DataSourceTransactionManager). This can be convenient * if you need a different local transaction strategy for another O/R mapping tool, * for example, but still want Hibernate access to join into those transactions. *

A further benefit of this option is that plain Sessions opened directly * via the SessionFactory, outside of Spring's Hibernate support, will still * participate in active Spring-managed transactions. *

As a further effect, using a transaction-aware DataSource will apply * remaining transaction timeouts to all created JDBC Statements. This means * that all operations performed by the SessionFactory will automatically * participate in Spring-managed transaction timeouts, not just queries. * This adds value even for HibernateTransactionManager. *

WARNING: Be aware of side effects when using a transaction-aware * DataSource in combination with OpenSessionInViewFilter/Interceptor. * This combination is only properly supported with HibernateTransactionManager * transactions. PROPAGATION_SUPPORTS with HibernateTransactionManager and * JtaTransactionManager in general are only supported on Hibernate3, which * introduces (optional) aggressive release of Connections. * @see #setDataSource * @see org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy * @see org.springframework.jdbc.datasource.DataSourceTransactionManager * @see org.springframework.orm.hibernate.support.OpenSessionInViewFilter * @see org.springframework.orm.hibernate.support.OpenSessionInViewInterceptor * @see HibernateTransactionManager * @see org.springframework.transaction.jta.JtaTransactionManager * @see org.springframework.orm.hibernate3.LocalSessionFactoryBean#setUseTransactionAwareDataSource */ public void setUseTransactionAwareDataSource(boolean useTransactionAwareDataSource) { this.useTransactionAwareDataSource = useTransactionAwareDataSource; } /** * Set the JTA TransactionManager to be used for Hibernate's * TransactionManagerLookup. If set, this will override corresponding * settings in Hibernate properties. Allows to use a Spring-managed * JTA TransactionManager for Hibernate's cache synchronization. *

Note: If this is set, the Hibernate settings should not define a * transaction manager lookup to avoid meaningless double configuration. * @see LocalTransactionManagerLookup */ public void setJtaTransactionManager(TransactionManager jtaTransactionManager) { ===================================================================== Found a 25 line (105 tokens) duplication in the following files: Starting at line 47 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/jms/listener/DefaultMessageListenerContainer102.java Starting at line 149 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/jms/core/JmsTemplate102.java protected Connection createConnection() throws JMSException { if (isPubSubDomain()) { return ((TopicConnectionFactory) getConnectionFactory()).createTopicConnection(); } else { return ((QueueConnectionFactory) getConnectionFactory()).createQueueConnection(); } } /** * This implementation overrides the superclass method to use JMS 1.0.2 API. */ protected Session createSession(Connection con) throws JMSException { if (isPubSubDomain()) { return ((TopicConnection) con).createTopicSession(isSessionTransacted(), getSessionAcknowledgeMode()); } else { return ((QueueConnection) con).createQueueSession(isSessionTransacted(), getSessionAcknowledgeMode()); } } /** * This implementation overrides the superclass method to use JMS 1.0.2 API. */ protected MessageProducer doCreateProducer(Session session, Destination destination) throws JMSException { ===================================================================== Found a 22 line (104 tokens) duplication in the following files: Starting at line 300 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/SessionFactoryUtils.java Starting at line 263 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/SessionFactoryUtils.java if (!sessionHolder.isSynchronizedWithTransaction()) { logger.debug("Registering Spring transaction synchronization for existing Hibernate Session"); TransactionSynchronizationManager.registerSynchronization( new SpringSessionSynchronization(sessionHolder, sessionFactory, jdbcExceptionTranslator, false)); sessionHolder.setSynchronizedWithTransaction(true); // Switch to FlushMode.AUTO if we're not within a read-only transaction. FlushMode flushMode = session.getFlushMode(); if (FlushMode.NEVER.equals(flushMode) && !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { session.setFlushMode(FlushMode.AUTO); sessionHolder.setPreviousFlushMode(flushMode); } } } else { // No Spring transaction management active -> try JTA transaction synchronization. session = getJtaSynchronizedSession(sessionHolder, sessionFactory, jdbcExceptionTranslator); } if (session != null) { return session; } } ===================================================================== Found a 21 line (103 tokens) duplication in the following files: Starting at line 196 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/support/OpenSessionInViewInterceptor.java Starting at line 198 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/support/PortletOpenSessionInViewInterceptor.java PortletRequest request, PortletResponse response, Object handler, Exception ex) throws DataAccessException { String participateAttributeName = getParticipateAttributeName(); Integer count = (Integer) request.getAttribute(participateAttributeName); if (count != null) { // Do not modify the Session: just clear the marker. if (count.intValue() > 1) { request.setAttribute(participateAttributeName, new Integer(count.intValue() - 1)); } else { request.removeAttribute(participateAttributeName); } } else { if (isSingleSession()) { // single session mode SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(getSessionFactory()); logger.debug("Closing single Hibernate Session in PortletOpenSessionInViewInterceptor"); ===================================================================== Found a 15 line (103 tokens) duplication in the following files: Starting at line 692 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/HibernateTemplate.java Starting at line 897 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/HibernateTemplate.java return (Iterator) execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { Query queryObject = session.createQuery(queryString); prepareQuery(queryObject); if (values != null) { for (int i = 0; i < values.length; i++) { if (types != null && types[i] != null) { queryObject.setParameter(i, values[i], types[i]); } else { queryObject.setParameter(i, values[i]); } } } return queryObject.iterate(); ===================================================================== Found a 21 line (103 tokens) duplication in the following files: Starting at line 196 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/support/OpenSessionInViewInterceptor.java Starting at line 198 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/support/PortletOpenSessionInViewInterceptor.java PortletRequest request, PortletResponse response, Object handler, Exception ex) throws DataAccessException { String participateAttributeName = getParticipateAttributeName(); Integer count = (Integer) request.getAttribute(participateAttributeName); if (count != null) { // Do not modify the Session: just clear the marker. if (count.intValue() > 1) { request.setAttribute(participateAttributeName, new Integer(count.intValue() - 1)); } else { request.removeAttribute(participateAttributeName); } } else { if (isSingleSession()) { // single session mode SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(getSessionFactory()); logger.debug("Closing single Hibernate Session in PortletOpenSessionInViewInterceptor"); ===================================================================== Found a 28 line (103 tokens) duplication in the following files: Starting at line 828 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/HibernateTemplate.java Starting at line 745 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/HibernateTemplate.java applyNamedParameterToQuery(queryObject, paramNames[i], values[i], (types != null ? types[i] : null)); } } return queryObject.list(); } }, true); } public List findByValueBean(final String queryString, final Object valueBean) throws DataAccessException { return (List) execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { Query queryObject = session.createQuery(queryString); prepareQuery(queryObject); queryObject.setProperties(valueBean); return queryObject.list(); } }, true); } //------------------------------------------------------------------------- // Convenience finder methods for named queries //------------------------------------------------------------------------- public List findByNamedQuery(String queryName) throws DataAccessException { return findByNamedQuery(queryName, (Object[]) null, (Type[]) null); ===================================================================== Found a 53 line (102 tokens) duplication in the following files: Starting at line 118 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate3/LocalSessionFactoryBean.java Starting at line 95 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/orm/hibernate/LocalSessionFactoryBean.java public class LocalSessionFactoryBean implements FactoryBean, InitializingBean, DisposableBean { private static ThreadLocal configTimeDataSourceHolder = new ThreadLocal(); private static ThreadLocal configTimeTransactionManagerHolder = new ThreadLocal(); private static ThreadLocal configTimeLobHandlerHolder = new ThreadLocal(); /** * Return the DataSource for the currently configured Hibernate SessionFactory, * to be used by LocalDataSourceConnectionProvoder. *

This instance will be set before initialization of the corresponding * SessionFactory, and reset immediately afterwards. It is thus only available * during configuration. * @see #setDataSource * @see LocalDataSourceConnectionProvider */ public static DataSource getConfigTimeDataSource() { return (DataSource) configTimeDataSourceHolder.get(); } /** * Return the JTA TransactionManager for the currently configured Hibernate * SessionFactory, to be used by LocalTransactionManagerLookup. *

This instance will be set before initialization of the corresponding * SessionFactory, and reset immediately afterwards. It is thus only available * during configuration. * @see #setJtaTransactionManager * @see LocalTransactionManagerLookup */ public static TransactionManager getConfigTimeTransactionManager() { return (TransactionManager) configTimeTransactionManagerHolder.get(); } /** * Return the LobHandler for the currently configured Hibernate SessionFactory, * to be used by UserType implementations like ClobStringType. *

This instance will be set before initialization of the corresponding * SessionFactory, and reset immediately afterwards. It is thus only available * during configuration. * @see #setLobHandler * @see org.springframework.orm.hibernate.support.ClobStringType * @see org.springframework.orm.hibernate.support.BlobByteArrayType * @see org.springframework.orm.hibernate.support.BlobSerializableType */ public static LobHandler getConfigTimeLobHandler() { return (LobHandler) configTimeLobHandlerHolder.get(); } protected final Log logger = LogFactory.getLog(getClass()); private Resource configLocation; ===================================================================== Found a 33 line (102 tokens) duplication in the following files: Starting at line 174 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/remoting/rmi/RmiClientInterceptor.java Starting at line 227 of /home/tom/pmd/pmd-web/src/spring/src/org/springframework/remoting/rmi/JndiRmiClientInterceptor.java protected Remote getStub() throws NamingException { if (!this.cacheStub || (this.lookupStubOnStartup && !this.refreshStubOnConnectFailure)) { return (this.cachedStub != null ? this.cachedStub : lookupStub()); } else { synchronized (this) { if (this.cachedStub == null) { this.cachedStub = lookupStub(); } return this.cachedStub; } } } /** * Fetches an RMI stub and delegates to doInvoke. * If configured to refresh on connect failure, it will call * refreshAndRetry on corresponding RMI exceptions. * @see #getStub * @see #doInvoke * @see #refreshAndRetry * @see java.rmi.ConnectException * @see java.rmi.ConnectIOException * @see java.rmi.NoSuchObjectException */ public Object invoke(MethodInvocation invocation) throws Throwable { Remote stub = null; try { stub = getStub(); } catch (Throwable ex) { throw new RemoteLookupFailureException("RMI lookup for service [" + getJndiName() + "] failed", ex);