Spring testing framework - JNDI resource - spring

I am toying a bit with Spring testing framework, but I have one problem. Normally when application is deployed on Tomcat we have
<Resource
name="jdbc/sqliteDS"
auth="Container"
type="javax.sql.DataSource"
maxActive="4"
maxIdle="2"
username="x"
maxWait="5000"
driverClassName="org.sqlite.JDBC"
password="x"
url="jdbc:sqlite:/home/xxx/db.sqlite"/>
</Context>
in Tomcat context.xml,
<resource-ref>
<description>sqlite DataSource</description>
<res-ref-name>jdbc/sqliteDS</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
in web.xml and
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:/comp/env/jdbc/sqliteDS" />
</bean>
in data-context.xml
for getting data source, but how can I emulate JNDI resource for Spring test framework, because now during the initialization I am getting errors that data source is not found, and he is right.
Also, it would be great if one can do that without writing another .xml file.

I had to deal with this question a while ago, and I didn't find a suitable solution, but a workaroud which implies another xml file :
First you create a Spring configuration file defining your JNDI infos (jndi.xml) :
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#server:port:instance" />
<property name="username" value="user" />
<property name="password" value="pwd" />
</bean>
</beans>
Then a static class to bind your JNDI variable :
public class Initialize {
public static void initializeJndi() throws Exception {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("jndi.xml");
SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
builder.bind("java:comp/env/jdbc/foo", applicationContext.getBean("dataSource"));
builder.activate();
}
}
Then in your test class, you add the following :
#BeforeClass
public static void initJndi() throws Exception {
Initialize.initializeJndi();
}
So that when you load your Spring main configuration file, the JNDI resource is accessible.
Maybe this is not the best way to do it but it surely works.
By the way, having a specific configuration file seems to be a good idea because you may not want to run your unit test on the final database. Doing so is more considered as integration testing than unit testing.
Hope it helps,
Mouwah

Related

ActiveMQ Messages are not consumed spring boot, camel

I am trying to configure Spring Boot, Apache Camel, ActiveMQ all togheter. This is what I did so far:
I run ActiveMQ using activemq.bat
I log into the console to monitor messages
I start backend service (sources below)
I start frontend service (Backend and Frontend are different spring boot projects)
I sucesfully send message into the que from frontend but after 20s I am getting timeout. The message appears in ActiveMQ console but it's not consumed by backend.
Here's how I configured backend:
build.gradle:
dependencies {
compile("org.apache.camel:camel-spring-boot:2.16.0")
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.springframework.boot:spring-boot-starter-websocket")
compile("org.springframework:spring-messaging")
compile("org.springframework:spring-jms")
compile("org.springframework.security:spring-security-web")
compile("org.springframework.security:spring-security-config")
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile('org.apache.camel:camel-jms:2.16.0')
compile("org.hibernate:hibernate-core:4.0.1.Final")
compile("mysql:mysql-connector-java:5.1.37")
compile("log4j:log4j:1.2.16")
compile("junit:junit:4.12")
compile("org.mockito:mockito-all:1.8.4")
compile('org.apache.activemq:activemq-core:5.7.0')
compile('com.epam.training.auction:auction_common:1.0')
testCompile("junit:junit")
}
Route Config: (I use UsersServiceImpl for testing and both ways of defining it don't work)
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.epam.training.auction_backend.services.UsersServiceImpl;
#Configuration
public class MyRouterConfiguration {
#Bean
public RoutesBuilder myRouter() {
return new RouteBuilder() {
#Override
public void configure() throws Exception {
from("jms:queue:auctions").to("bean:auctionsServiceImpl");
from("jms:queue:users").bean(UsersServiceImpl.class);
from("jms:queue:bidding").to("bean:biddingServiceImpl");
}
};
}
}
Client side, invoking method
#Override
public void registerUser(String username, String password) {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("camel-client-remoting.xml");
UsersService usersService = context.getBean("usersServiceImpl", UsersService.class);
System.out.println("Invoking the logging");
UserTransferObject userTransferObject = new UserTransferObject("user", "pass");
usersService.addUser(userTransferObject);
System.out.println("User is logged");
IOHelper.close(context);
}
Client xml camel config
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:camel="http://camel.apache.org/schema/spring"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<camel:camelContext id="camel-client">
<camel:template id="camelTemplate"/>
<camel:proxy
id="auctionsServiceImpl"
serviceInterface="com.epam.training.auction.common.AuctionsService"
serviceUrl="jms:queue:auctions"/>
<camel:proxy
id="usersServiceImpl"
serviceInterface="com.epam.training.auction.common.UsersService"
serviceUrl="jms:queue:users"/>
<camel:proxy
id="biddingServiceImpl"
serviceInterface="com.epam.training.auction.common.BiddingService"
serviceUrl="jms:queue:bidding"/>
</camel:camelContext>
<bean id="jmsConnectionFactory"
class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="tcp://localhost:61616"/>
</bean>
<bean id="pooledConnectionFactory"
class="org.apache.activemq.pool.PooledConnectionFactory"
init-method="start" destroy-method="stop">
<property name="maxConnections" value="8"/>
<property name="connectionFactory" ref="jmsConnectionFactory"/>
</bean>
<bean id="jmsConfig"
class="org.apache.camel.component.jms.JmsConfiguration">
<property name="connectionFactory" ref="pooledConnectionFactory"/>
<property name="concurrentConsumers" value="10"/>
</bean>
<bean id="jms"
class="org.apache.activemq.camel.component.ActiveMQComponent">
<property name="configuration" ref="jmsConfig"/>
<property name="transacted" value="true"/>
<property name="cacheLevelName" value="CACHE_CONSUMER"/>
</bean>
</beans>
During sending I also get warning:
2015-11-02 11:56:21.547 WARN 16328 --- [nio-8181-exec-5] o.s.b.f.s.DefaultListableBeanFactory : Bean creation exception on FactoryBean type check: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usersServiceImpl': Invocation of init method failed; nested exception is org.apache.camel.ResolveEndpointFailedException: Failed to resolve endpoint: jms://queue:users due to: Cannot auto create component: jms
Common interfaces nad transfer objects are defined in 3rd project which is a dependency for both backend and frontend projects.
I feel that there's one missing part of this configuration. Please tell me what could it be.
Thanks in advance.
You need to change
<bean id="activemq"
class="org.apache.activemq.camel.component.ActiveMQComponent">
to
<bean id="jms"
class="org.apache.activemq.camel.component.ActiveMQComponent">
or change your endpoint urls to .to("activemq:queue:users").
The id of your ActiveMQComponent is the name used in the .to() to identify to camel that you want to use that component definition.

Spring Transactions not working (JDBC and Tomcat)

I am trying to incorporate Spring transactions into my project, and it seems that they are not working. I went through some tutorials nad Spring docs, and for me everything seems OK.
What I have:
1) context file:
<?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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="jdbcTemplate" class="webapp.dataaccess.commons.JdbcTemplateProvider">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- dao section -->
<bean id="modesDao" class="webapp.dataaccess.opcalc.basicdao.CalcModesData">
<property name="jdbc" ref="jdbcTemplate" />
</bean>
<!-- lots of DAO beans defined same way -->
2) data source defined on server:
<Resource name="jdbc/calc_webapp" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="user" password="password" driverClassName="org.postgresql.Driver"
url="jdbc:postgresql://localhost:5432/service" defaultAutoCommit = "true" />
3) and finally in one of the DAO beans I have this method:
#Transactional(propagation=Propagation.REQUIRED)
public Boolean saveFullOrganization(OrganizationLevel org) throws Exception{
Boolean out = true;
try{
Integer adminPermKey = permDao.saveAdminPermissions(org.getPermissions().getAdminPermission());
org.getPermissions().setAdminPermissionKey(adminPermKey);
Integer sellPermKey = permDao.saveSellingPermissions(org.getPermissions().getSellingPermission());
org.getPermissions().setSellingPermissionKey(sellPermKey);
Integer dszPermKey = permDao.saveDszPermissions(org.getPermissions().getDszPermission());
org.getPermissions().setDszPermissionKey(dszPermKey);
Integer reportPermKey = permDao.saveReportingPermissions(org.getPermissions().getReportingPermission());
org.getPermissions().setReportingPermissionKey(reportPermKey);
if(org.getPermissions().getKey()==null){
Integer permissions = permDao.savePermissionsSet(org.getPermissions(), null);
org.setPermissionsKey(permissions);
}
saveOrganizationUnit(org, org.getKey());
}catch(Exception e){
e.printStackTrace();
throw e;
}
return out;
}
Flow is rather intuitive - first part of method prepares permission entries for organization unit (each operation in bean permDao is also transactional), then finally calls "saveOrganizationUnit" to finalize adding new entry. I assumed that with transaction management if any exception occure in the middle of that procedure, then no data from it will go to DB. But my tests proved that if I trigger artificial exception before "saveOrganizationUnit" operation (which interrupts whole process nad jumps out of the method) the permission part lands in DB anyway. So, as I understand, transactions are not working in my solution.
I am not sure what should I check and what can be wrong (I am kind of Spring noob, so please, don't kick if its something obvious).
Default behavour of #Transactional is defined as follows:
Any RuntimeException triggers rollback, and any checked Exception does not.
So, I guess you are throwing a checked exception. If you want to trigger rollback in this case, you need to configure #Transactional accordingly:
#Transactional(propagation=Propagation.REQUIRED, rollbackFor = Exception.class) ...

JUnit Reads applicationContext.xml but claims <context:property-placeholder location="/WEB-INF/jdbc.properties"/> does not exist

I created an STS Spring MVC Template application and wanted to wire in and test my Dao's using JUnit. The project loads fine in Tomcat Here is my servlet context:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- JDBC Datasource Configuration Bean -->
<beans:bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName" value="${jdbc.driverClassName}" />
<beans:property name="url" value="${jdbc.url}" />
<beans:property name="username" value="${jdbc.username}" />
<beans:property name="password" value="${jdbc.password}" />
</beans:bean>
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:property-placeholder location="/WEB-INF/jdbc.properties"/>
<context:component-scan base-package="com.example" />
The context:property jdbc.properties loads fine until it gets read in by the #ContextConfiguration
Here is my JUnit test:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml"})
public class ControllerTest{
#Autowired
ApplicationContext applicationContext;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private HandlerAdapter handlerAdapter;
#Autowired
private HomeController homeController;
#Before
public void setUp() {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
handlerAdapter = new AnnotationMethodHandlerAdapter();
}
#Test
public void testHallo() throws Exception {
request.setRequestURI("/");
request.setMethod("GET");
final ModelAndView mav = handlerAdapter.handle(request, response,
homeController);
System.out.println("TEST " + mav.getModelMap());
}
}
If I comment out the jdbc.properties file it works fine
The error I am getting is:
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanInitializationException: Could not load properties; nested exception is java.io.FileNotFoundException: class path resource [WEB-INF/jdbc.properties] cannot be opened because it does not exist
The project runs fine but JUnit cannot find the database properties .
Here is what I have tried:
<context:property-placeholder location="file:/WEB-INF/jdbc.properties"/>
Also
However, that causes Tomcat to throw an Exception.
I think this because paths are not read the same way when using JUnit and Servlet container.
In fact when using Tomcat, the WEB-INF folder is placed under the root web application folder. And for this, using /WEB-INF/jdbc.properties will work fine.
But when using JUnit, this won't be the case, since you will be using your Maven project as directory structure.
One solution for this situation, would be to separate properties files used for JUnit tests (even if they are the same as production properties files) and place them under: src/test/resources.
Then in your Spring configs, use:
<context:property-placeholder location="classpath:jdbc.properties"/>
By now, both under Tomcat and JUnit Spring should be able to find your files
In your spring applicationContext.xml file, Please check
<context:component-scan base-package="xxx.controller"/>
component-scan should not contain component which has #Controller annotation

Hibernate-Spring Web container error

Hello I'm new to Hibernate.
I have generated with Hibernate Tools a database access module. The generator generates the code of the DAOS and Hibernate Beans.
When I test this module in a simple Java application all works fine, but when I test it in a Spring Web application I get a very strange error. Since my module is an independent jar it should access the database without regarding the circumstance of being executed in a simple Java application or a Web application. The code of my web application is:
#Controller
#RequestMapping("/")
public class Controller implements ApplicationContextAware
{
private ApplicationContext applicationContext;
#RequestMapping(value = "/purchased/songs", method = RequestMethod.GET)
public String home(Model model)
{
SessionManager.startOperation();
ChargeTryDAOBase ctdb=new ChargeTryDAOBase();
List <ChargeTry> data=ctdb.findByRemoteId("dsfsdfsdf8");
SessionManager.endOperation();
model.addAttribute("result", "data" );
return "home";
}
#Override
public void setApplicationContext(ApplicationContext arg0) throws BeansException
{
this.applicationContext = arg0;
}
}
When running this code on Tomcat I get following error:
org.springframework.web.util.NestedServletException: Handler processing
nested exception is java.lang.NoSuchMethodError:
org.hibernate.SessionFactory.getCurrentSession()Lorg/hibernate/Session;
.....
java.lang.NoSuchMethodError:
org.hibernate.SessionFactory.getCurrentSession()Lorg/hibernate/Session;
When I change some Hibernate dependencies I get following error:
java.lang.IllegalStateException: Could not locate SessionFactory in JNDI
When I test the above code in a simple Java application all works fine.
Is this a spring-hibernate configuration problem?
Thank you for your help.
Please study
1: http://www.javatpoint.com/hibernate-and-spring-integration
and
2 http://viralpatel.net/blogs/spring3-mvc-hibernate-maven-tutorial-eclipse-example/
to get insight of Spring MVC and Hibernate Integration.
You can work with Hibernate Configuration file - here is the link -
Spring and hibernate.cfg.xml
But as your application is within a spring managed container, We will highly recommend to use applicationcontext.xml for better maintenance and management of codebase and performance.
thank you for your help finally I got all working. I followed your link and googled a little bit. The problem was that I didn't enable in my hibernate.cfg.xml file the datasource parameter, I also have configured C3P0 jdbc connection provider.
My final hibernate.cfg.xml file is:
<hibernate-configuration>
<session-factory>
<property name="hibernate.bytecode.use_reflection_optimizer">true</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydb</property>
<property name="hibernate.connection.username">userdb</property>
<property name="hibernate.connection.password">12345</property>
<property name="hibernate.connection.datasource">java:comp/env/jdbc/mydb</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.use_sql_comments">true</property>
<property name="hibernate.connection.provider_class">org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider</property>
<property name="hibernate.c3p0.min_size">2</property>
<property name="hibernate.c3p0.numHelperThreads">4</property>
<property name="hibernate.c3p0.max_size">10</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">100</property>
<property name="hibernate.c3p0.idle_test_period">1800</property>
<property name="hibernate.c3p0.acquire_increment">2</property>
<hibernate-configuration>
<session-factory>
In my web.xml I have added following lines:
<resource-ref>
<description>This is a MySQL database connection</description>
<res-ref-name>jdbc/mydb</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
In the Spring context file I have added following lines:
<beans:bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<beans:property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
<beans:property name="username" value="userdb"/>
<beans:property name="password" value="12345"/>
</beans:bean>
<beans:bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="configLocation">
<beans:value>classpath:hibernate.cfg.xml</beans:value>
</beans:property>
</beans:bean>
The strange thing is, that with the default Hibernate connection provider, the above solution didn't work but when I configured C3P0 all started to work.
Thank you for your help.

Ant task for Spring Validation

I need an ANT task to validate spring configuration. I need to find problems at build time before runtime ? For example, In spring context file contains a property a bean, but this bean doesnt have this property.
In eclipse, there is a tool Spring Explorer that do this validation.
thanks,
org.springframework.web.context.ContextLoaderListener failed: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'readController' defined in class path resource [applicationContext.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'productOperations' of bean class [com.bee.view.json.ReadController]: Bean property 'productOperations' is not writable or has an invalid setter method.
Does the parameter type of the setter match the return type of the getter?.
An easy way to ensure that your context is valid would be to create a JUnit test, which loads the context. Using the spring-test.jar support classes makes that easy:
public class MyTest extends AbstractDependencyInjectionSpringContextTests {
// this will be injected by Spring
private QueryDao queryDao;
private MyBusinessObject myBusinessObject;
// ensure that spring will inject the objects to test by name
public MyTest () {
setAutowireMode(AUTOWIRE_BY_NAME);
}
#Override
protected String[] getConfigLocations() {
return new String[] { "applicationContextJUnit.xml" };
}
public void testQueryDao() {
List<SomeData> list = queryDao.findSomeData();
assertNotNull(list);
// etc
}
public void testMyBusinessObject() {
myBusinessObject.someMethod();
}
public void setQueryDao(QueryDao queryDao) {
this.queryDao = queryDao;
}
}
The problem with loading a context that is used in a web application is that JUnit does not necessarily have access to the same resources (e.g. JNDI data sources), so if you've got the following in your "applicationContext.xml":
<beans ...>
<bean id="myBusinessObject" class="com.test.MyBusinessObject">
<property name="queryDao" ref="queryDao"/>
</bean>
<bean id="queryDao" class="com.test.QueryDao">
<property name="dataSource" ref="dataSource"/>
</bean>
<jee:jndi-lookup
id="dataSource"
jndi-name="jdbc/mydatasource"
resource-ref="true"
cache="true"
lookup-on-startup="false"
proxy-interface="javax.sql.DataSource"/>
</beans>
and your "applicationContextJUnit.xml" would import your "real" application context and redefine resources:
<beans ...>
<import resource="classpath:applicationContext.xml"/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:..."/>
<property name="username" value="scott"/>
<property name="password" value="tiger"/>
</bean>
</beans>
That way your unit tests will load the application context (even the ones that you don't explicitly test in your unit test), and you can have the confidence that your context is correct, because Spring itself loaded it. If you have an error, then the unit tests will fail.

Resources