Maven CXF wsdl2java : WSDL to Java – Example

September 6, 2013 1 comment

Sample POM.xml DOWNLOAD Project

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
	<groupId>com.projects.personal</groupId>
	<artifactId>ws-client</artifactId>
	<version>1.0.0-SNAPSHOT</version>
	<name>ws-client</name>
	<description>Abdul Aziz</description>
	<url>https://j2eeroad.wordpress.com</url>
    
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>      
    <java.version>1.6</java.version>  
    <cxf.version>2.7.6</cxf.version>             
  </properties>
  
  <dependencies>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-common-utilities</artifactId>
            <version>2.2.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-tools-common</artifactId>
            <version>${cxf.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-simple</artifactId>
            <version>${cxf.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-transports-http</artifactId>
            <version>${cxf.version}</version>
        </dependency>
        <dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
    </dependencies>
 
      <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <verbose>true</verbose>
                    <fork>true</fork>
                    <compilerVersion>${java.version}</compilerVersion>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
            
          
          <!-- cxf codegen plugin for WSDL to Java -->          
            <plugin>
                <groupId>org.apache.cxf</groupId>
                <artifactId>cxf-codegen-plugin</artifactId>
                <version>${cxf.version}</version>
                <executions>
                    <execution>
                        <id>stock-quote-service</id>
                        <phase>generate-sources</phase>
                        <configuration>                        	
                            <sourceRoot>${project.basedir}/src/main/generated_java</sourceRoot>
                            <wsdlOptions>                            	
                                <wsdlOption>
                                    <wsdl>${project.basedir}/src/main/resources/META-INF/wsdl/stockquote.wsdl</wsdl>
                                    <wsdlLocation>http://www.webservicex.net/stockquote.asmx?WSDL</wsdlLocation>                                                                       
                                    <serviceName>StockQuote</serviceName>                                                                        
                                    <extraargs>                                      	
                   						<extraarg>-verbose</extraarg> 
                   						<extraarg>-p</extraarg>
                                    	<extraarg>com.projects.webservicex.service</extraarg>                                                      						                                       
                                    </extraargs>
                                </wsdlOption>
                            </wsdlOptions>
                        </configuration>
                        <goals>
                            <goal>wsdl2java</goal>
                        </goals>
                    </execution>
                </executions>
                <dependencies>
                    <dependency>
                        <groupId>xerces</groupId>
                        <artifactId>xercesImpl</artifactId>
                        <version>2.9.1</version>
                    </dependency>
                    <dependency>
                        <groupId>org.apache.cxf</groupId>
                        <artifactId>cxf-xjc-ts</artifactId>
                        <version>2.2.9</version>
                    </dependency>
                </dependencies>
            </plugin>            
            
        </plugins>
    </build>	
</project>


DOWNLOAD Project here

Categories: Uncategorized

Six Lessons

April 8, 2013 Leave a comment
 
Lesson 1:
 
A man is getting into the shower, just as his wife is finishing up her shower, when the doorbell rings.
 
The wife quickly wraps herself in a towel and runs downstairs.
 
When she opens the door, there stands David, the next-door neighbor.
 
Before she says a word, David says, ‘I’ll give you $800 to drop that towel.’
 
After thinking for a moment, the woman drops her towel and stands naked in front of David.
 
After a few seconds, David hands her $800 and leaves.
 
The woman wraps back up in the towel and goes back upstairs.
 
When she gets to the bathroom, her husband asks, ‘ Who was that?’
 
‘It was David, the next door neighbor,’ she replies.
 
‘Great,’ the husband says, ‘did he say anything about the $800 he owes me?’
 
Moral of the story:
 
If you share critical information pertaining to credit and risk with your shareholders in time, you may be in a position to prevent avoidable exposure.
 
Lesson 2:
 
A priest offered a Nun a lift.
 
She got in and crossed her legs, forcing her gown to reveal a leg.
 
The priest nearly had an accident.
 
After controlling the car, he stealthily slid his hand up her leg.
 
The nun said, ‘Father, remember Psalm 129?’
 
The priest removed his hand. But, changing gears, he let his hand slide up her leg again. The nun once again said, ‘Father, remember Psalm 129?’
 
The priest apologized ‘Sorry sister but the flesh is weak.’
 
Arriving at the convent, the nun sighed heavily and went on her way.
 
On his arrival at the church, the priest rushed to look up Psalm 129. It said, ‘Go forth and seek, further up, you will find glory.’
 
Moral of the story:
 
If you are not well informed in your job, you might miss a great opportunity.
 
Lesson 3:
 
A sales rep, an administration clerk, and the manager are walking to lunch when they find an antique oil lamp.
 
They rub it and a Genie comes out. The Genie says, ‘I’ll give each of you just one wish.’
 
‘Me first! Me first!’ says the admin clerk.. ‘I want to be in the Bahamas , driving a speedboat, without a care in the world.’ Poof! She’s gone.
 
‘Me next! Me next!’ says the sales rep. ‘I want to be in Hawaii , relaxing on the beach with my personal masseuse, an endless supply of Pina Coladas, and the love of my life.’ Poof! He’s gone.
 
‘OK, you’re up,’ the Genie says to the manager. The manager says, ‘I want those two back in the office after lunch.’
 
Moral of the story:
 
Always let your boss have the first say.
 
Lesson 4:
 
An eagle was sitting on a tree resting, doing nothing.
 
A small rabbit saw the eagle and asked him, ‘Can I also sit like you and do nothing?’ The eagle answered: ‘Sure, why not.’
 
So, the rabbit sat on the ground below the eagle and rested. All of a sudden, a fox appeared, jumped on the rabbit and ate it.
 
Moral of the story:
 
To be sitting and doing nothing, you must be sitting very, very high up
 
Lesson 5:
 
A turkey was chatting with a bull. ‘I would love to be able to get to the top of that tree’ sighed the turkey, ‘but I haven’t got the energy.’
 
‘Well, why don’t you nibble on some of my droppings?’ replied the bull. ‘It’s full of nutrients.’
 
The turkey pecked at a lump of dung, and found it actually gave him enough strength to reach the lowest branch of the tree.
 
The next day, after eating some more dung, he reached the second branch
 
Finally after a fourth night, the turkey was proudly perched at the top of the tree.
 
He was promptly spotted by a farmer, who shot him out of the tree.
 
Moral of the story:
 
Bull Shit might get you to the top, but it won’t keep you there…
 
Lesson 6:
 
A little bird was flying south for the winter. It was so cold the bird froze and fell to the ground into a large field.
 
While he was lying there, a cow came by and dropped some dung on him.
 
As the frozen bird lay there in the pile of cow dung, he began to realize how warm he was.
 
The dung was actually thawing him out!
 
He lay there all warm and happy, and soon began to sing for joy. A passing cat heard the bird singing and came to investigate.
 
Following the sound, the cat discovered the bird under the pile of cow dung, and promptly dug him out and ate him.
 
Moral of the story:
 
(1) Not everyone who shits on you is your enemy.
 
(2) Not everyone who gets you out of shit is your friend.
 
(3) And when you’re in deep shit, it’s best to keep your mouth shut!
 
 
Categories: Uncategorized

Address already in use: JVM_Bind:8080

July 13, 2011 1 comment

Do this..

To find the application which is using the 80 port number
In “Command Prompt” type the following command:
(1) netstat -o -n -a | findstr 0.0:8080
and then
(2) taskkill /F /PID 988
Change the PID value from 988to your required port value

Developing Web Services using jax-ws, spring and maven

June 15, 2011 13 comments

Using the following steps you can develop soap Web Services using jax-ws, spring and maven plugin

  1. Define service interface
  2. Define service Implementation
  3. Web.xml – add JAX-WS commons spring ext servlet
  4. Spring beans configuration using annotations
  5. Spring configurations for Web Services
  6. pom.xml – Add ‘jaxws-maven-plugin’ plugin
  7. Build deployment using maven
  8. Check the web service
  9. Test web service using sopaUI
  10. Download Source Code mo-ws.zip
    or war file mo-ws.war

(1) Define service interface

//TemperatureService .java
package uk.co.mo.training.ws;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;

import uk.co.mo.training.dto.Weather;

@SuppressWarnings("restriction")
@WebService
public interface TemperatureService {
	
	@WebMethod
	public Weather toCelsius(@WebParam(name="fahrenheit") double fahrenheit);
	@WebMethod
	public Weather toFahrenheit(@WebParam(name="celsius") double celsius);

}

//Weather.java
package uk.co.mo.training.dto;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@SuppressWarnings("restriction")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Weather", propOrder = { "city", "celsius" , "fahrenheit"})
@XmlRootElement(name = "Weather")
public class Weather {
	
	@XmlElement(name = "Ciy", required = false)
	private String city;

	@XmlElement(name = "Celsius", required = true)
	private double celsius;
	@XmlElement(name = "Fahrenheit", required = true)
	private double fahrenheit;
		
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public double getCelsius() {
		return celsius;
	}
	public void setCelsius(double celsius) {
		this.celsius = celsius;
	}
	public double getFahrenheit() {
		return fahrenheit;
	}
	public void setFahrenheit(double fahrenheit) {
		this.fahrenheit = fahrenheit;
	}
	
}

(2) Define service Implementation

//TemperatureServiceImple .java
package uk.co.mo.training.ws;

import javax.jws.WebService;

import org.springframework.stereotype.Service;

import uk.co.mo.training.dto.Weather;

@SuppressWarnings("restriction")
@WebService(endpointInterface = "uk.co.mo.training.ws.TemperatureService",serviceName="temperatureService")
@Service
public class TemperatureServiceImple implements TemperatureService {


	public Weather toCelsius(double fahrenheit) {
		double celsius = (5.0 / 9.0) * (fahrenheit - 32.0);
		//C° = (5 / 9)x (F° - 32)  
		
		Weather w = new Weather();
		w.setCelsius(celsius);
		w.setFahrenheit(fahrenheit);
		return w;
	}


	public Weather toFahrenheit(double celsius) {
		double fahrenheit = (celsius *1.8)+32.0;
		//F° = (C° x 1.8) + 32
		Weather w = new Weather();
		w.setCelsius(celsius);
		w.setFahrenheit(fahrenheit);
		return w;
	}

}

(3) Web.xml – add JAX-WS commons spring ext servlet


<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
   
  <!-- spring framework context configuration -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/conf/main-application-context.xml</param-value>
  </context-param>
 
  
  <!-- Spring Context Listener -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    
  </listener>
  
  <!-- this is for JAX-WS commons spring ext. -->
  <servlet>
      <servlet-name>jaxws-servlet</servlet-name>
      <servlet-class>
        com.sun.xml.ws.transport.http.servlet.WSSpringServlet
      </servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>
   
   <servlet-mapping>
      <servlet-name>jaxws-servlet</servlet-name>
      <url-pattern>/webservice/*</url-pattern>
   </servlet-mapping>
  
</web-app>

(4) Spring beans configuration using annotations

<!-- main-application-context.xml-->
<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:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
	    <!—scan annotations -->         
       <context:component-scan base-package="uk.co.mo.training.ws"/>
       <context:annotation-config/>
       <!-- Web Services -->         
       <import resource="ws-context.xml"/>        
          
</beans>

(5) Spring configurations for Web Services

<!--  ws-context.xml -->
<?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:ws="http://jax-ws.dev.java.net/spring/core"
	xmlns:wss="http://jax-ws.dev.java.net/spring/servlet"
	xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
    http://jax-ws.dev.java.net/spring/core
    http://jax-ws.dev.java.net/spring/core.xsd
    http://jax-ws.dev.java.net/spring/servlet
    http://jax-ws.dev.java.net/spring/servlet.xsd">
   
   <!-- Temperature Web Service -->
	<wss:binding url="/webservice/temperaturewebservice"> 
      <wss:service> 
         <ws:service bean="#temperatureServiceImple">             
         </ws:service> 
      </wss:service> 
   </wss:binding> 

   </beans>

(6) pom.xml – Add ‘jaxws-maven-plugin’ plugin

<!-- pom.xml-->
.....
  <build>
    <finalName>mo-ws</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
          <source>1.5</source>
          <target>1.5</target>
        </configuration>
      </plugin>
      
      	<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>jaxws-maven-plugin</artifactId>
				<version>1.10</version>				
			<executions>
				
				<execution>
					<id>TemperatureWS</id>
					<configuration>
						<sei>uk.co.mo.training.ws.TemperatureServiceImple</sei>
						<genWsdl>true</genWsdl>
						<keep>true</keep>
						<verbose>true</verbose>
					</configuration>
					<phase>package</phase>
					<goals>
						<goal>wsgen</goal>
					</goals>
				</execution>
			</executions>				
      </plugin>
    </plugins>
  </build>
....

(7) Build deployment using maven: Run (1) “mvn clean package” and again (2) “mvn package”

"mvn clean package" - it will create required WSDL files at "/target/jaxws/wsgen/wsdl"
"mvn package" it will create some files at "/target/mo-ws/WEB-INF/classes/uk/co/mo/training/ws/jaxws"

(8) Deploy in the tomcat

<!-- server.xml-->
...
<Context
			docBase="D:/projects/mo-ws-project/target/mo-ws"
			path="/ws">
					
	</Context>
...

(9) Check the web service http://localhost:8080/ws/webservice/temperaturewebservice
OR
http://localhost:8080/mo-ws/webservice/temperaturewebservice

OR
DEMO
http://env-7398619.j.layershift.co.uk/ws/webservice/temperaturewebservice
(10) Using soapUI test web service

(11) Download Source Code mo-ws.zip or war file at mo-ws.war

Testing Using Junit 4, Jmock & Spring mock

February 7, 2010 4 comments

What If the Code Has Dependencies?

The solution is Using Mock Objects

We use mock objects during testing for two main reasons: to isolate the class under test from outside influence and to control dependencies.

If the dependency is a simple POJO, using the new operator is an easy way to create an instance used just for the test. However, if the dependency is not easily created or requires heavyweight resources such as database connections, using the new operator isn’t often possible. Mock objects step in to “mock” the dependency, thus allowing the code under test to operate without invoking outside resources.

Mock objects are used when you need to either replace a heavyweight dependency with a lightweight instance just for testing, or when you need to use an intelligent stub. Those two situations often occur simultaneously, making mock objects a perfect addition to any testing tool belt.

The following example shows how we can test application component that has DAO (heavy weight) dependency using jmock objects  and web layer (Controller)  using spring mock api.

@RunWith(JMock.class)
public class HomeControllerTest {

	Mockery context = new JUnit4Mockery();
	//mock object : ContactDAO (using JMock)
	ContactDAOInterface contactDAO = context.mock(ContactDAOInterface.class);
	// Spring MVC controller
	HomeController cc = new HomeController();
	// mock objects (using spring mock)
	private MockHttpServletRequest request;
	private MockHttpServletResponse response;

	@Before
	public void init() throws Exception
	{
		cc.setContactDAO(contactDAO);
		// mock objects created
		request = new MockHttpServletRequest();
		response = new MockHttpServletResponse();
	}

	@Test
	public void HomePage() throws Exception
	{
		// define expectations for mock object
		context.checking(new Expectations() {{
			ArrayList<ContactData> data = new ArrayList<ContactData>();
			data.add(new ContactData(1,"Abdul Aziz","07525776781"));
	        oneOf (contactDAO).getContacts(); will(returnValue(data));
	    }});

		// test
		request.setMethod("GET");
		ModelAndView mav= cc.handleRequest(request, response);
		Assert.assertEquals("viewContacts", mav.getViewName());
		ArrayList<ContactData> obj=(ArrayList<ContactData>)mav.getModel().get("contacts");
		Assert.assertNotNull(obj);
		Assert.assertEquals(1,obj.size());
		Assert.assertEquals("Abdul Aziz",obj.get(0).getName());
		Assert.assertEquals("07525776781",obj.get(0).getPhone());
	}
}

Spring Security: Authorization (Controlling Access) Configurations

January 23, 2010 Leave a comment

An access decision manager
is responsible for deciding whether the user has the proper privileges to access secured resources. Access decision managers are defined by the

org.acegisecurity.AccessDecisionManager
interface:

 

    public
interface AccessDecisionManager {

 

        public
void
decide(Authentication authentication, Object object,

            ConfigAttributeDefinition config)

            throws AccessDeniedException,

            InsufficientAuthenticationException;

        public
boolean
supports(ConfigAttribute attribute);

        public
boolean
supports(Class clazz);

    }

 

The decide()method is where the ultimate decision is made. If it returns without throwing an AccessDeniedException
or InsufficientAuthenticationException, access to the secured resource is granted. Otherwise, access is denied.

 

Decision by Voting:

Spring Security’s access decision managers are ultimately responsible for determining the access rights for an authenticated user. They poll one or more objects that vote on whether or not a user is granted access to a secured resource. Once all votes are in, the decision manager tallies the votes and arrives at its final decision.

 

 

<bean id=“accessDecisionManager” class=“org.acegisecurity.vote.UnanimousBased”>

<property name=“decisionVoters”>

<list>

<ref bean=“roleVoter”/>

</list>

</property>

</bean>

 

The decisionVoters property is where you provide the access decision manager with its list of voters.

 

<bean id=“roleVoter” class=“org.acegisecurity.vote.RoleVoter”/>

 

RoleVoter only votes when the secured resource has configuration attributes that are prefixed with ROLE_

 

By default, all the access decision managers deny access to a resource if all the voters abstain. However, you can override this default behavior by setting the allowIfAllAbstain
property on the access decision manager to true.

Spring Web Services

January 21, 2010 Leave a comment

Spring provides full support for standard Java web services APIs: Web services using JAX-RPC and
Web services using JAX-WS

 Spring Web Services, a solution for contract-first, document-driven web services;

 

Spring: Security Basics

January 21, 2010 Leave a comment

Spring Security is a security framework that provides declarative security for your Spring-based applications. It provides handling authentication and authorization, at both the web request level and at the method invocation level.

 

For securing web applications, Spring Security uses servlet filters that intercept servlet requests to perform authentication and enforce security. When securing methods, Spring Security uses Spring AOP to proxy objects, applying aspects that ensure that the user has proper authority to invoke the secured methods.

 

 

Security Interceptors:

The actual implementation of a security interceptor will depend on what resource is being secured. If you’re securing a URL in a web application, the security interceptor will be implemented as a servlet filter. But if you’re securing a method invocation, aspects will be used to enforce security. It does not actually apply security rules. Instead, it delegates that responsibility to the various managers.

 

  • Authentication managers
  • Access decisions managers
  • Run-as managers
  • After-invocation managers

 

Authentication managers:

The authentication manager is responsible for determining who you are. It does this by considering your principal
(username) and your credentials
(password). The authentication manager is a pluggable interface-based component. This makes it possible to use Spring Security with virtually any authentication mechanism you can imagine. Spring Security comes with authentication managers.

 

Access decisions managers:

The access decision manager performs authorization, deciding whether to let you in by considering your authentication information and the security attributes that have been associated with the secured resource. The access decision manager is also pluggable.

 

Run-as managers:

A run-as manager can be used to replace your authentication with an authentication that allows you access to the secured objects that are deeper in your application. Run-as managers are an optional security component and are not necessary in many applications secured by Spring Security.

 

After-invocation managers:

The after-invocation manager enforces security after the secured resource is accessed. The after-invocation manager also has the option of altering the returned value to ensure that the user is only able to access certain properties of the returned object. Applications only need an after-invocation manager if the application’s security scheme requires that access be restricted at the domain level on a per-instance basis.


 

Spring Remoting

January 20, 2010 Leave a comment

 

 

Spring and POJO-based remote services

 

Remote Method Invocation (RMI) – Accessing/exposing Java-based services when network constraints aren’t a factor

Hessian or Burlap – Accessing/exposing Java-based services over HTTP when network constraints are a factor

HTTP Invoker – Accessing/exposing Spring-based services over HTTP when network constraints are a factor

JAX-RPC/SOAP – Accessing/exposing platform-neutral, SOAP-based web-services

 

In all models, services can be configured into your application as spring managed beans. This is accomplished using a proxy factory bean that enables you to wire remote services into properties of your other beans as if they were local objects.

 

If the call to the remote service results in a java.rmi.RemoteException, the proxy handles that exception and rethrows it as an unchecked org.springframework.remoting.RemoteAccessException

 

On the service side, you are able to expose the functionality of any spring managed bean as a remote service using any of the models

 

  1. Using the RMI

 

Using spring’s support for RMI, you basically need a configuration similar to remote EJBs, except for the fact that there is no standard support for security context propagation or remote transaction propagation. Spring does provide hooks for such additional invocation context when using the RMI invoker

Using the RmiServiceExporter, The interface can be accessed by using RmiProxyFactoryBean, or via plain RMI in case of a traditional RMI service. The RmiServiceExporter explicitly supports the exposing of any non-RMI services via RMI invokers.

Exposing services:

<bean id="accountService" class="com.example.AccountServiceImpl">


					<!-- any additional properties, maybe a DAO? -->
					

</bean>

 

<bean class=”org.springframework.remoting.rmi.RmiServiceExporter“>


<!– does not necessarily have to be the same name as the bean to be exported –>

<property name=”serviceName” value=”AccountService”/>

<property name=”service” ref=”accountService”/>

<property name=”serviceInterface” value=”com.example.AccountService”/>


<!– defaults to 1099 –>

<property name=”registryPort” value=”1199″/>

</bean>

The service will be bound at rmi://HOST:1199/AccountService We’ll use the URL later on to link in the service at the client side

Linking in the service at the client

<bean class="example.SimpleObject">

    <property name="accountService" ref="accountService"/>

</bean>

 

<bean id="accountService" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">

    <property name="serviceUrl" value="rmi://HOST:1199/AccountService"/>

    <property name="serviceInterface" value="example.AccountService"/>

</bean>

 

 

  1. Using Hessian or Burlap to remotely call services via HTTP

Hessian offers a binary HTTP-based remoting protocol. One of the advantages of Hessian and Burlap is that we can easily apply HTTP basic authentication.

Both protocols are HTTP-based,

Hessian communicates via HTTP and does so using a custom Servlet; So we need a new Servlet configuration

<servlet>

    <servlet-name>remoting</servlet-name>

    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

    <load-on-startup>1</load-on-startup>

</servlet>

 

<servlet-mapping>

    <servlet-name>remoting</servlet-name>

    <url-pattern>/remoting/*</url-pattern>

</servlet-mapping>

 

Exposing Services:

Defined in remoting-servlet.xml

<bean id="accountService" class="example.AccountServiceImpl">


					<!-- any additional properties, maybe a DAO? -->
					

</bean>

 

<bean name="/AccountService" class="org.springframework.remoting.caucho.HessianServiceExporter">

    <property name="service" ref="accountService"/>

    <property name="serviceInterface" value="example.AccountService"/>

</bean>

Now we’re ready to link in the service at the client. No explicit handler mapping is specified, mapping request URLs onto services, so BeanNameUrlHandlerMapping will be used: Hence, the service will be exported at the URL indicated through its bean name within the containing DispatcherServlet’s mapping (as defined above): http://HOST:8080/remoting/AccountService&#8217;.

Alternative Way

Alternatively, consider the use of Spring’s simpler HttpRequestHandlerServlet. This allows you to embed the remote exporter definitions in your root application context (by default in ‘WEB-INF/applicationContext.xml’), with individual servlet definitions pointing to specific exporter beans. Each servlet name needs to match the bean name of its target exporter in this case

Define a corresponding servlet for this exporter in ‘web.xml’; The exporter getting mapped to the request path /remoting/AccountService. Note that the servlet name needs to match the bean name of the target exporter.

<servlet>

    <servlet-name>accountExporter</servlet-name>

    <servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet</servlet-class>

</servlet>

 

<servlet-mapping>

    <servlet-name>accountExporter</servlet-name>

    <url-pattern>/remoting/AccountService</url-pattern>

</servlet-mapping>

 

Create a HessianServiceExporter in your root application context (e.g. in ‘WEB-INF/applicationContext.xml’):

<bean name="accountExporter" class="org.springframework.remoting.caucho.HessianServiceExporter">

    <property name="service" ref="accountService"/>

    <property name="serviceInterface" value="example.AccountService"/>

</bean>

Can be accessed using http://HOST:8080/remoting/AccountService&#8217;

Linking in the service on the client

<bean class="example.SimpleObject">

    <property name="accountService" ref="accountService"/>

</bean>

 

<bean id="accountService" class="org.springframework.remoting.caucho.HessianProxyFactoryBean">

    <property name="serviceUrl" value="http://remotehost:8080/remoting/AccountService"/>

    <property name="serviceInterface" value="example.AccountService"/>

</bean>

 

Applying HTTP basic authentication to a service exposed through Hessian or Burlap

One of the advantages of Hessian and Burlap is that we can easily apply HTTP basic authentication, because both protocols are HTTP-based. Your normal HTTP server security mechanism can easily be applied through using the web.xml security features

 

  1. Using HTTP invokers

Spring Http invokers use the standard Java serialization mechanism to expose services through HTTP

The HTTP invoker is a new remoting model created as part of the Spring Framework to perform remoting across HTTP and using Java’s serialization.

 

To expose the AccountService (mentioned above) within a Spring Web MVC DispatcherServlet, the following configuration needs to be in place in the dispatcher’s application context:

<bean name="/AccountService" class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">

    <property name="service" ref="accountService"/>

    <property name="serviceInterface" value="example.AccountService"/>

</bean>

Such an exporter definition will be exposed through the DispatcherServlet’s standard mapping facilities, as explained in the section on Hessian.

 

Alternatively, create an HttpInvokerServiceExporter in your root application context (e.g. in ‘WEB-INF/applicationContext.xml’):

<bean name="accountExporter" class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">

    <property name="service" ref="accountService"/>

    <property name="serviceInterface" value="example.AccountService"/>

</bean>

Define a corresponding servlet for this exporter in ‘web.xml’, with the servlet name matching the bean name of the target exporter:

<servlet>

<servlet-name>accountExporter</servlet-name>

<servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet</servlet-class>

</servlet>

 

<servlet-mapping>

<servlet-name>accountExporter</servlet-name>

<url-pattern>/remoting/AccountService</url-pattern>

</servlet-mapping>

 

Linking in the service at the client

Linking in the service from the client much resembles the way you would do it when using Hessian or Burlap. Using a proxy, spring will be able to translate your calls to HTTP POST requests to the URL pointing to the exported service.

<bean id=”httpInvokerProxy” class=”org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean“>

<property name=”serviceUrl” value=”http://remotehost:8080/remoting/AccountService”/&gt;

<property name=”serviceInterface” value=”example.AccountService”/>

</bean>

 

Spring’s HTTP invoker presents a best-of-both-worlds remoting solution combining the simplicity of HTTP communication with Java’s built-in object serialization. This makes HTTP invoker services an appealing alternative to either RMI or Hessian/Burlap.
it is a remoting solution offered by the Spring Framework only. This means that both the client and the service must be Spring-enabled applications. This also implies, at least for now, that both the client and the service must be Java based. And because Java serialization is being used, both sides must have the same version of the classes
(much like RMI).

RMI: When using RMI, it’s not possible to access the objects through the HTTP protocol, unless you’re tunneling the RMI traffic. RMI is a fairly heavy-weight protocol in that it support full-object serialization which is important when using a complex data model that needs serialization over the wire. However, RMI-JRMP is tied to Java clients: It is a Java-to-Java remoting solution.

HTTP Invoker: Spring’s HTTP invoker is a good choice if you need HTTP-based remoting but also rely on Java serialization. It shares the basic infrastructure with RMI invokers, just using HTTP as transport. Note that HTTP invokers are not only limited to Java-to-Java remoting but also to Spring on both the client and server side. (The latter also applies to Spring’s RMI invoker for non-RMI interfaces.)

Hessian and/or Burlap might provide significant value when operating in a heterogeneous environment, because they explicitly allow for non-Java clients. However, non-Java support is still limited. Known issues include the serialization of Hibernate objects in combination with lazily-initialized collections. If you have such a data model, consider using RMI or HTTP invokers instead of Hessian.

JMS can be useful for providing clusters of services and allowing the JMS broker to take care of load balancing, discovery and auto-failover. By default: Java serialization is used when using JMS remoting but the JMS provider could use a different mechanism for the wire formatting, such as XStream to allow servers to be implemented in other technologies.

EJB has an advantage over RMI in that it supports standard role-based authentication and authorization and remote transaction propagation. It is possible to get RMI invokers or HTTP invokers to support security context propagation as well, although this is not provided by core Spring: There are just appropriate hooks for plugging in third-party or custom solutions here.

 

Spring RMI: the service interface doesn’t extend java.rmi.Remote
and none of its methods throw java.rmi.RemoteException, this trims the interface down a bit. But more importantly, a client accessing the service through this interface will not have to catch exceptions that they probably won’t be able to deal with.

We have no need to implement java.rmi.Remote and no more java.rmi.RemoteExceptions are being thrown around.

For using this service remotely, we’ll use Spring’s RmiServiceExporter

 

RmiServiceExporter
exports any Spring-managed bean as an RMI service; RmiServiceExporter works by wrapping the bean in an adapter class.

RMI has difficulty working across firewalls.

RMI is Java based so both the client and the service must be written in Java.

RMI uses Java serialization.

The types of the objects being sent across the network must have the exact same version on both sides of the call.

 

Hessian and Burlap that enable lightweight remote services over HTTP.

Hessian, like RMI, uses binary messages to communicate between client and service.

Burlap, on the other hand, is an XML-based remoting technology,

The only difference is that Hessian messages are binary and Burlap messages are XML

 

HessianServiceExporter
is a Spring MVC controller.

 

 

RMI uses Java’s standard object serialization but is difficult to use across firewalls. On the other side, Hessian/Burlap work well across firewalls but use a proprietary object serialization mechanism.

 

HTTP invoker perform remoting across HTTP
and using Java’s serialization

 

 

 

 

 


 

JBOSS: Deploying data sources

December 19, 2009 Leave a comment

Let application server
manage your database connections using a data source. The application server can then manage the database connections by pooling them and by providing connections to the application when it needs them.

 

Deploy, a *-ds.xml file. You can use any name for the file that you like, as long at the suffix is –ds.xml.

 

The <local-tx-datasource>
tag defines a particular type of data source that handles local transactions. Three different data source types are available, each of which handles transactions differently.

 

<local-tx-datasource> : Identifies a data source that uses transactions, even distributed transactions within the local application server, but doesn’t use distributed transactions among multiple application servers.

 

<xa-datasource>:
Identifies a data source that uses distributed transaction among multiple application servers. This option isn’t shown in the example, but would appear in place of the <local-tx-datasource> tag.

 

<no-tx-datasource>: Identifies a data source that doesn’t use transactions.

 

In most cases, you’ll use <local-tx-datasource>
because it handles transactions within a single application server. If you’re clustering your application servers or wanting to use distributed transactions among multiple application servers, then you should use <xa-datasource>.

 

Note that both <local-tx-datasource>
and <xa-datasource> handle distributed transactions involving multiple data sources.

 

The difference is that <local-tx-datasource> handles them only within a single running application server, whereas <xa-datasource> handles them among many running application servers.

 

On the other end of the spectrum, if your applications only read from the database,

Then using <no-tx-datasource>
would be appropriate.

 

<jndi-name> : Name used to look up the data source in the JNDI namespace. The java: prefix is automatically added to this name.

 

<min-pool-size>

<max-pool-size>

<idle-timeout-minutes>

<blocking-timeout-millis>

<exception-sorter-class-name>

<check-valid-connection-sql>

<transaction-isolation>

 

You can define multiple data sources within a single *-ds.xml file

 

The *-ds.xml file goes into the deploy directory. Yes, that’s right; it’s treated as an application, specifically as a service. Second, you must provide the JAR file for the JDBC driver for the database. Place the driver JAR file in the server/xxx/lib directory.

 

Once the data source is deployed, the application server creates several MBeans for the data source

 

You can also place the *-ds.xml file in the EAR file

Categories: Application Server Tags: