Announcement Announcement Module
Collapse
No announcement yet.
ClassPathResource usage Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • ClassPathResource usage

    Hi,
    I am curious to know if my findings are correct or not. If yes, then is there a way to fix it? I have an web application which uses Spring+hibernate 3.0 + struts on Jboss Application server. Application works fine with all the configuration. But when i wrote the TestCase to test the Hibernate DAO's i get the classpath problem.

    my hibernate-db.xml looks like this
    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    	     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	     xmlns:jee="http://www.springframework.org/schema/jee"
    	     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
               http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">
    
    	<!-- DataSource Definition -->
    	<bean id="dataSource"
          	class="org.springframework.jndi.JndiObjectFactoryBean">
    		<property name="jndiName">
    			<value>java:/OracleDS</value>
    		</property>
    	</bean>
    	
    	<bean id="sessionFactory"
          	class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    		<property name="mappingDirectoryLocations">
    			<list>
    				<value>classpath:/cdot/ctis/layer/services/security/data</value>
    			</list>
    		</property>
    		<property name="hibernateProperties">
    			<props>
    				<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
    				<prop key="hibernate.show_sql">true</prop>
    				<prop key="hibernate.cglib.use_reflection_optimizer">true</prop>
    				<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
    				<prop key="hibernate.transaction.factory_class"> org.hibernate.transaction.JTATransactionFactory </prop>
    				<prop key="hibernate.transaction.manager_lookup_class"> org.hibernate.transaction.JBossTransactionManagerLookup </prop>
    			</props>
    		</property>	
    		
    		<property name="dataSource">
    			<ref bean="dataSource"/>
    		</property>
    	</bean>
    	
    	<!-- Hibernate Transaction Manager Definition -->
    	<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    		<property name="sessionFactory"><ref local="sessionFactory"/></property>
    	</bean>
    	
    	
    	<!-- Spring Data Access Exception Translator Defintion -->
    	<bean id="jdbcExceptionTranslator" class="org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator"> 
    		<property name="dataSource"><ref bean="dataSource"/></property> 
    	</bean> 
    
    	<!-- Hibernate Template Defintion -->
    	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> 
    		<property name="sessionFactory"><ref bean="sessionFactory"/></property> 
    		<property name="jdbcExceptionTranslator"><ref bean="jdbcExceptionTranslator"/></property> 
    	</bean> 
    
    	<!-- Catalog DAO Definition: Hibernate implementation -->
    	<bean id="securityUserDao" class="cdot.ctis.layer.services.security.data.SecurityUserDAOImpl">
    		<property name="hibernateTemplate"><ref bean="hibernateTemplate"/></property> 
    	</bean>	
    	
    	<!-- Catalog DAO Definition: Hibernate implementation -->
    	<bean id="ctmsUserDao" class="cdot.ctis.layer.services.security.data.CtmsUserDAOImpl">
    		<property name="hibernateTemplate"><ref bean="hibernateTemplate"/></property> 
    	</bean>	
    </beans>
    and my testcase is like this

    Code:
    /*
     package cdot.ctis.junit.hibernate;
    
    import java.util.Properties;
    
    import javax.management.ObjectName;
    import javax.naming.InitialContext;
    import javax.sql.DataSource;
    
    import junit.framework.AssertionFailedError;
    import junit.framework.TestCase;
    import junit.framework.TestResult;
    
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.hibernate.SessionFactory;
    import org.jboss.jmx.adaptor.rmi.RMIAdaptor;
    import org.springframework.core.io.DefaultResourceLoader;
    import org.springframework.core.io.Resource;
    import org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator;
    import org.springframework.jndi.JndiObjectFactoryBean;
    import org.springframework.orm.hibernate3.HibernateTemplate;
    import org.springframework.orm.hibernate3.HibernateTransactionManager;
    import org.springframework.test.AbstractTransactionalDataSourceSpringContextTests;
    
    /**
     * @author kharbandp
     *
     */
    public class HibernateTestCase extends AbstractTransactionalDataSourceSpringContextTests {
    	Log log = LogFactory.getLog(getClass());
    	private boolean serverSide;
    	private HibernateTemplate hibernatetemplate = new HibernateTemplate();
    
    	
    	/**
    	 * @param methodName
    	 */
    	public HibernateTestCase(String methodName) {
    		super(methodName);
    		
    		serverSide = false;
    	}
    	
    	/**
    	 * @param serverSide
    	 */
    	public void setServerSide(boolean serverSide) {
    		this.serverSide = serverSide;
    	}
    
    	/**
    	 * @return
    	 */
    	public boolean isServerSide() {
    		return serverSide;
    	}
    
    	/* (non-Javadoc)
    	 * @see junit.framework.Test#run(junit.framework.TestResult)
    	 */
    	public void run(TestResult result) {
    		ClassLoader oldClassLoader = null;
    		try {
    			if (!isServerSide()) {
    				oldClassLoader = Thread.currentThread().getContextClassLoader();
    				Thread.currentThread().setContextClassLoader(
    						((Object) this).getClass().getClassLoader());
    			}
    			super.run(result);
    		} finally {
    			if (oldClassLoader != null)
    				Thread.currentThread().setContextClassLoader(oldClassLoader);
    		}
    	}
    
    	/* (non-Javadoc)
    	 * @see junit.framework.TestCase#runBare()
    	 */
    	public void runBare() throws Throwable {
    		//setHibernateConfigurations();
    		if (!isServerSide()) {
    			if (log.isDebugEnabled()) {
    				log.debug("runBare: isServerSide = false");
    			}
    			try {
    				
    				InitialContext ctx = new InitialContext();
    				ObjectName jmxTestRunnerName = new ObjectName("application.system:service=JMXRemoteTestMgr");
    				RMIAdaptor remoteMBeanServer = (RMIAdaptor)ctx.lookup("jmx/invoker/RMIAdaptor");
    				
    				String classToRun = this.getClass().getName();
    				String methodToRun = ((TestCase) this).getName();
    				// invoke the MBean to run the test remotely
    				remoteMBeanServer.invoke(jmxTestRunnerName, 
    							"run", 
    							new Object[] {classToRun, methodToRun}, 
    							new String[] {String.class.getName(), String.class.getName()});
    				
    			} catch (Exception e) {
    				
    				if (e instanceof RemoteTestException) {
    					RemoteTestException ex = (RemoteTestException)e;
    					Throwable remote = ex.getRemoteThrowable();
    					if (remote instanceof AssertionFailedError)
    						throw new RemoteAssertionFailedError(
    								(AssertionFailedError) remote, ex
    										.getRemoteStackTrace());
    					else
    						throw ex;
    				} else {
    					throw e;
    				}
    				
    			} finally {
    				
    			}
    		} else {
    			if (log.isDebugEnabled()) {
    				log.debug("runBare: isServerSide = true");
    			}
    			super.runBare();
    		}
    	}
    	
    	/**
    	 * @throws Exception
    	 */
    	public void setUpHibernate() throws Exception {
    		if (log.isDebugEnabled()) {
    			log.debug("setUpHibernate: "+this.getName());
    		}
    	}
    
    	/**
    	 * @throws Exception
    	 */
    	public void tearDownHibernate() throws Exception {
    		if (log.isDebugEnabled()) {
    			log.debug("tearDownHibernate: "+this.getName());
    		}
    	}
    	
    		/**
    	 * @return Returns the hibernatetemplate.
    	 */
    	public HibernateTemplate getHibernatetemplate() {
    		return hibernatetemplate;
    	}
    
    	/**
    	 * @param hibernatetemplate The hibernatetemplate to set.
    	 */
    	public void setHibernatetemplate(HibernateTemplate hibernatetemplate) {
    		this.hibernatetemplate = hibernatetemplate;
    	}
    
    	protected String[] getConfigLocations() {
    		// TODO Auto-generated method stub
    		return new String[] {"/WEB-INF/hibernate/hibernate-db.xml" , "/WEB-INF/spring/applicationContext.xml"};
    	}
    
    	
    }
    I have a jar file Security.jar which is in the lib directory and has files under cdot/ctis/layer/services/security/data package and all my "hbm.xml" files are in <war.file>/classes/cdot/ctis/layer/services/security/data folder. I was getting FileNotFoundException but when i added my <war.file>/classes classpath as the first item in my classpath the exception was gone. I believe what's happening is the SpringFramework finds the first folder in the classpath and leaves. I think it should iterate thru all the folders with the same name and check for the xml files. Comments?

    Thanks in advance.

    pawan kharbanda

  • #2
    For such cases you should use
    classpath*
    - see the reference documentation which explains the usage but also the cases when it might not work.
    Note that longer paths remove the need to use the * match since the file can be identified in only one classpath root.

    Comment


    • #3
      I tried using classpath*: but then i got the URL not found error.

      Thanks for the reply

      ~pk

      Comment


      • #4
        classpath* should return at least the result found with classpath. I see that in your test you set the TCCL classloader - this might affect the classpath seen by your application.
        To check your classpath, you can do a simple test by looking resources through the getResource() and getResources() using the getClass() and getClass().getClassloader().

        Comment

        Working...
        X