How to unit test Hibernate DAO’s with H2 and Spring
Source can be downloaded from link;
Writing Unit test cases are very common these days.We can write a Unit test for the functionality with Mocking.I personally feel we should not do Mocking while testing DAO.I prefer to write test cases for the DAO’s by pointing to the Database itself.Here the problem is we cannot execute tests on the production or development database since it will spoil the existing data, because we can build the same project any number of time, especially when we configure continues integration.
In memory databases or file based database comes in handy in this particular situation.There are lot many databases available of this kind like h2, HSQLDB e.t.c.
Here below i have extended a sample created in the below post and have written unit test with h2 database.
Link : http://examples.javacodegeeks.com/enterprise-java/spring/jpaorm/spring-hibernate-mysql-and-maven-showcase/
Project Structure
Create a test class with the similar package structure as source class in src/test/java
Sample Insert.sql below.
Sample delete.sql below
Now the main part come into the picture.applicationcontext.xml
We need to configure the h2 database data source as per below.
and the Session Factory as per below.
and we have to add spring-test dependency to the pom file.
Performance optimizations for Apache Camel
All working sample in the above code can be found in the below URL’s
- https://codeload.github.com/muellerc/camel-in-daily-use/zip/master
- https://codeload.github.com/muellerc/camel/zip/trunk
- https://codeload.github.com/muellerc/apachecon-na-2013/zip/master
- https://codeload.github.com/muellerc/camel-in-transaction/zip/master
- http://camelinaction.googlecode.com/files/camelinaction-source-2121b.zip
- http://apache.cs.utah.edu/camel/apache-camel/2.13.0/apache-camel-2.13.0-src.zip
Refer Camel In Action
Thanks to Christian Müller for your wonderful work.
Integrating WebDav enabled server to a java applications
HI Guys, this time my task is to integrate a WebDav enabled server to my java application.First of all, what is WevDav, sound completely new? with a quick google search I landed on this link.
Web Distributed Authoring and Versioning (WebDAV) is an extension of the Hypertext Transfer Protocol (HTTP) that facilitates collaboration between users in editing and managing documents and files stored on World Wide Web servers.
I am not going much into details about the WevDav.But it’s a really cool standard for collaboration over Http.
By implementing WebDAV we can make our web server/application server to behave like a cloud storage.
Link for converting tomcat to a WebDav Server
similar way we can convert Apache HTTP server as a WebDAV server.
The browser is the best client to navigate through the webdav server.but it you want to integrate with your java application, Home :there are quite a few apis available like Sardine, Jackrabbit e.t.c.After a long research i found Saradine in is the most easiest api to use.so i continued with saradine.
Note : Disadvantage of Saradine is most of the security protocols are implemented,but i faced few problems with NTML authentication.now i am testing it,will post the results once it is completed.
Below are the few useful links for using sardine.
PrHome:https://github.com/lookfirst/sardine
working with saradine is straightforward.check out the code and have a look at its test.
Restrictions :
Sardine validates https certificates very strictly.if you want to ignore the certificated u have to implement your own httpclient object and pass it to the SaradineImpl class and construct.
please leave a post if any one needs some help while implementing this.
Integrating Ubuntu One drive to a java Application.
HI Guys,I have been working for a while on integrating Ubuntu One cloud storage and i would like to share my experiences here.
First of all What is Ubuntu One ? Ubuntu One is a cloud space provided by ubuntu, like dropbox,google drive e.t.c.The advantage Ubuntu One gives
- Gives you 5Gb of free space,to store any thing whatever you would like.
- All latest versions of Ubunutu distributions comes with Ubuntu One pre-installed.so not need to install any extra clients.
- It has provided a rich set of apis for application integration as REST services.
- Web client,where you can view,download and upload files without installing any of the client.
Now the pain points :
- even though Ubuntu One has provided apis with documentation,its really hard to find out quick samples for java.so,after a long struggle i have found out few projects in the Ubuntu Code Space.
Ubuntu One uses OAuth 1.0 authentication while communicating with their apis.
Below are the Useful Links.
Ubuntu One api Documentation : https://one.ubuntu.com/developer/
Ubuntu One java api : https://launchpad.net/ubuntuone-files-java-library
Ubuntu One java api source : http://bazaar.launchpad.net/~ubuntuone-client-engineering/ubuntuone-files-java-library/trunk1.x/files
You can download the code,modify and use it.
Note : Check the license,before you redistribute this.
I will post few examples and sample projects in my next posts.
Good Links
Interview Preparation
Data Structures and Algorithms
Sample Questions: http://www.qubeet.com/
Linked List: http://giridhar-mb.blogspot.in/2012/11/linked-list-implementation-in-java.html?_sm_au_=iNsvkqGtW40Fn0st
Quick Sort: http://www.vogella.com/articles/JavaAlgorithmsQuicksort/article.html?_sm_au_=iNsvkqGtW40Fn0st
Bubble Sort: http://www.cs.rit.edu/~atk/Java/Sorting/sorting.html?_sm_au_=iNsvkqGtW40Fn0st
Java
http://javarevisited.blogspot.in/
http://howtodoinjava.com/?_sm_au_=i7s4kDQ0LfD1sfNM
Java Threads and Concurrency
http://jlunaquiroga.blogspot.in/2013/04/java-concurrency-part-1.html?_sm_au_=i7s4kDQ0LfD1sfNM
Java Collections
Spring
http://javacodebook.com/category/spring/spring-book/?_sm_au_=i7s4kDQ0LfD1sfNM#
Hibernate Exception – No CurrentSessionContext configured
Exception :
Exception in thread “main” org.hibernate.HibernateException: No CurrentSessionContext configured!
at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:620)
at org.hibernate.tutorial.web.EventManager.createAndStoreEvent(EventManager.java:52)
at org.hibernate.tutorial.web.EventManager.main(EventManager.java:20)
Solution :
The below solution worked for me.
http://stackoverflow.com/questions/11160463/no-currentsessioncontext-configured-threadlocalsessioncontext-bindsession-i?_sm_au_=iNsb6K5st4Zsv7RD
Java – Response was of unexpected text/html ContentType. Incoming portion of HTML stream: (none)
Exception :
javax.xml.ws.soap.SOAPFaultException: Response was of unexpected text/html ContentType. Incoming portion of HTML stream: (none)
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:146)
at $Proxy701.processThirdPartyRequest(Unknown Source)
at com.mt.tpi.event.processor.TpiResponseProcessor.process(TpiResponseProcessor.java:112)
at com.mt.tpi.event.processor.TpiResponseProcessor.process(TpiResponseProcessor.java:31)
at com.mt.event.jms.receiver.JMSMessageReceiver.onMessage(JMSMessageReceiver.java:73)
at org.springframework.jms.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:518)
at org.springframework.jms.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:479)
at org.springframework.jms.listener.AbstractMessageListenerContainer.doExecuteListener(AbstractMessageListenerContainer.java:451)
at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.doReceiveAndExecute(AbstractPollingMessageListenerContainer.java:323)
at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.receiveAndExecute(AbstractPollingMessageListenerContainer.java:261)
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.invokeListener(DefaultMessageListenerContainer.java:982)
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.executeOngoingLoop(DefaultMessageListenerContainer.java:974)
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:876)
at java.lang.Thread.run(Thread.java:662)
Caused by: org.apache.cxf.interceptor.Fault: Response was of unexpected text/html ContentType. Incoming portion of HTML stream: (none)
at org.apache.cxf.interceptor.StaxInInterceptor.handleMessage(StaxInInterceptor.java:79)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:263)
at org.apache.cxf.endpoint.ClientImpl.onMessage(ClientImpl.java:762)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponseInternal(HTTPConduit.java:1582)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponse(HTTPConduit.java:1467)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.close(HTTPConduit.java:1375)
at org.apache.cxf.transport.AbstractConduit.close(AbstractConduit.java:56)
at org.apache.cxf.transport.http.HTTPConduit.close(HTTPConduit.java:623)
at org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(MessageSenderInterceptor.java:62)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:263)
at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:510)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:440)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:343)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:295)
at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:73)
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:124)
… 13 more
~
Solution
Check the WSDL URL.
URL has to be given till ?wsdl
org.apache.cxf.binding.soap.SoapFault: The signature or decryption was invalid
org.apache.cxf.binding.soap.SoapFault: The signature or decryption was
invalid; nested exception is:
org.apache.ws.security.WSSecurityException: The signature or
decryption was invalid
at
org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor.createSoapFault(WSS4JInInterceptor.java:643)
at
org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor.handleMessage(WSS4JInInterceptor.java:307)
at
org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor.handleMessage(WSS4JInInterceptor.java:84)
at
org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:263)
at
org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:118)
at
org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:208)
at
org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:223)
at
org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:205)
at
org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:113)
at
org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:184)
at
org.apache.cxf.transport.servlet.AbstractHTTPServlet.doPost(AbstractHTTPServlet.java:107)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at
org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:163)
at
org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:502)
at
org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:389)
at
org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at
org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
at
org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
at
org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:417)
at
org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:230)
at
org.mortbay.jetty.handler.HandlerCollection.handle(HandlerCollection.java:114)
at
org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:324)
at
org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:535)
at
org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:880)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:834)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at
org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:409)
at
org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:520)
Caused by: org.apache.ws.security.WSSecurityException: The signature or
decryption was invalid; nested exception is:
org.apache.ws.security.WSSecurityException: The signature or
decryption was invalid
at
org.apache.ws.security.processor.SignatureProcessor.verifyXMLSignature(SignatureProcessor.java:378)
at
org.apache.ws.security.processor.SignatureProcessor.handleToken(SignatureProcessor.java:174)
at
org.apache.ws.security.WSSecurityEngine.processSecurityHeader(WSSecurityEngine.java:396)
at
org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor.handleMessage(WSS4JInInterceptor.java:248)
… 28 more
Caused by: org.apache.ws.security.WSSecurityException: The signature or
decryption was invalid
at
org.apache.ws.security.processor.SignatureProcessor.verifyXMLSignature(SignatureProcessor.java:375)
… 31 more
SOLUTION::
*************
Thsi is a problem with inbuilt CXF v2.4.0. It contains
wss4j-1.6.0.jar:1.6.0. This needs to be replace with wss4j-1.6.3.jar.
This worked for me.
How to create SOAP web service client in java with cxf, Spring, Maven
In continuation with my previous post i am showing a way how to invoke a SOAP service from java.
There are different ways to create a SOAP Clinet in java with cxf.Here im giving the most fastest and easiest way to create.
Get the wsdl URL form the server.
open up the pom.xml file.
Add the below wsdl-to-java plugin.This plugin will generate the java code by parsin the wsdl which is given as input to it.
<plugin> <groupId>org.apache.cxf</groupId> <artifactId>cxf-codegen-plugin</artifactId> <version>${cxf.version}</version> <executions> <execution> <id>generate-sources</id> <phase>generate-sources</phase> <configuration> <sourceRoot>generated/cxf</sourceRoot> <wsdlOptions> <wsdlOption> <wsdl>http://localhost:7009/cxf-spring-test/calculatorService?wsdl</wsdl> </wsdlOption> </wsdlOptions> </configuration> <goals> <goal>wsdl2java</goal> </goals> </execution> </executions> </plugin>
now open the commanprompt or terminal,navigate to the project
type mvn clean generate-sources
this will generate the wsdl correspondin code in the <Project Folder>/generated/cxf location.
Add this to the project build path.
now i am writing a simple class and wired to the bean in the application context
Application 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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xmlns:jaxws="http://cxf.apache.org/jaxws" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd"> <!-- Start up bean which will invoke server webservice --> <bean id="calculatorService" init-method="invoke"> <constructor-arg index="0" value="http://localhost:7009/cxf-spring-test/calculatorService?wsdl"/> </bean> </beans>
Java Client Class(As per the above example this will get invoked automatically during start up)
package com.test; import org.apache.cxf.jaxws.JaxWsProxyFactoryBean; public class CalculatorServiceClient { private String targetURL; public CalculatorServiceClient(String targetURL) { this.targetURL = targetURL; } public void invoke() { JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); factory.setServiceClass(CalculatorIntf.class); factory.setAddress(this.targetURL); CalculatorIntf calculatorIntf = (CalculatorIntf) factory.create(); //invoking add web servcie System.out.println("10 + 15 = "+calculatorIntf.add(10, 15)); //invoking subtract web service System.out.println("15 - 5 = "+calculatorIntf.subtract(15, 5)); //invoking multiply web service System.out.println("10 * 5 = "+calculatorIntf.multiply(10,5)); } }
In the next post i will show how to add SSL Support to the above client code.
Source Code Download : cxf_spring_maven.zip
How to create SOAP WebService with spring, cxf, Maven, Java
Steps to create MAVEN SOAP Based Web Service with Eclipse.
Pre-Requsites :
- Java >= 1.5 version
- Maven installation
- Eclipse Maven Plugin
Steps to create :
Create a new Maven Project with packaging type as war
open the pom file and maven and spring dependencies
pom.xml file
4.0.0 com.test cxf-spring-test 0.1 war UTF-8 3.0.5.RELEASE 1.6.4 2.4.1 maven2-repository.java.net Java.net Repository for Maven http://download.java.net/maven/2/ default ${project.artifactId} maven-compiler-plugin 2.3.2 1.6 1.6 org.mortbay.jetty jetty-maven-plugin 7.4.2.v20110526 10 7009 /${project.artifactId} <!-- CXF Dependencies --> jta jta 1.0.1b org.apache.cxf cxf-rt-core ${cxf.version} org.apache.cxf cxf-rt-frontend-simple ${cxf.version} org.apache.cxf cxf-rt-frontend-jaxws ${cxf.version} org.apache.cxf cxf-rt-databinding-aegis ${cxf.version} org.apache.cxf cxf-rt-transports-local ${cxf.version} org.apache.cxf cxf-rt-transports-http ${cxf.version} org.apache.cxf cxf-rt-transports-http-jetty ${cxf.version} org.apache.cxf cxf-rt-transports-jms ${cxf.version} org.apache.cxf cxf-rt-management ${cxf.version} org.apache.cxf cxf-common-utilities ${cxf.version} <!-- End of CXF Dependencies --> org.eclipse.jetty jetty-servlets 7.4.0.v20110414 provided org.eclipse.jetty jetty-client <!-- Spring Dependencies ${spring.version} --> org.springframework spring-beans ${spring.version} org.springframework spring-jdbc ${spring.version} org.springframework spring-web ${spring.version} org.springframework spring-webmvc ${spring.version} org.springframework spring-orm ${spring.version} org.springframework spring-expression ${spring.version} org.apache.geronimo.specs geronimo-annotation_1.0_spec 1.1.1 org.slf4j slf4j-log4j12 ${slf4j.version} jar compile
Create a web.xml file in src/main/webapp/WEB-INF folder
In the web.xml mention the servlet mapping for cxf servlet and add spring listner to load the application context during the webapp startup time.
Web.Xml file
<!--?xml version="1.0" encoding="UTF-8"?--> <!-- Servlet Mapping for CXFServlet --> CXFServlet org.apache.cxf.transport.servlet.CXFServlet CXFServlet /* <!-- Context parameters --> log4jConfigLocation classpath:sitemonitor_log4j.properties log4jExposeWebAppRoot false org.springframework.web.util.Log4jConfigListener contextConfigLocation classpath:sitemonitor_appContext.xml org.springframework.web.context.ContextLoaderListener
Now create a package in the src/main/java folder as mentioned in the pom file
create a interface with the service you want to expose
package com.test; import javax.jws.WebService; @WebService public interface CalculatorIntf { public long add(long num1,long num2); public long subtract(long num1,long num2); public long multiply(long num1,long num2); }
Create a inplementation for this service and implement all the methods of the interface
package com.test; public class CalculatorImpl implements CalculatorIntf { public long add(long num1, long num2) { return (num1 + num2); } public long subtract(long num1, long num2) { return (num1 - num2); } public long multiply(long num1, long num2) { return (num1 * num2); } }
create a spring application context file and add the file to the application class path.
Application Context file
<!--?xml version="1.0" encoding="UTF-8"?--> <!-- Initiliaing Client Webservices --> <!-- JAX-WS Service Endpoint -->
now open the command prompt and navigate to the porject folder in the command prompt
run the maven command : mvn clean package jetty:run -DskipTests (for running the inbuild jetty we need to add this in the pom file.In the above pom has that jetty plugin)
now open the browser and hit http://localhost:7009/cxf-spring-test
now you should see the wsdl link.click on the wsdl link will show you the wsdl file.
you can test the service with soap-ui.
In the comming post i will post how to invoke this wsdl from the java program.