Skip to content

Archive

Tag: ejb

Abstract

About two years ago, I published an article about Exposing the Functionality implemented in Stateless Session Beans (EJB 2.1) using Web Services. J2EE 1.4 times are over and the new version of the Java Enterprise framework, called Java Enterprise Edition 5 (JavaEE 5, or simply JEE) has emerged. In this article the same business scenario is repeated in the new framework.

Requirements

Before we dive into code examples, some software is required. The good news about the software is, that it also evolved over time. Here is what we use:

  • Sun’s Java 6 SDK
  • JBoss AS 5.1.0 GA for JDK6
  • Eclipse Galileo 3.5.1 for JEE development

continue reading…

_MG_6980_MG_6978

Yesterday, the second Adam Bien event in Lehmanns Bookstore took place. Again, the event was a full success. I arrived half-an-hour earlier and got a seat only in the tenth row.
Adam spoke about new features of EJB 3.1 and Glassfish. He showed examples running on a developer build of Glassfish V3, promising that the features will work without exceptions…
Here are some topics, I remember:

  • Singleton Beans: usefull a s a central point of the application, e.G. central cache etc…
  • Async Methods: allows asynchronous execution of time-consuming methods. Especially, it is possible to abort the execution
  • Deploying Beans in WARs: could be helpful for small applications
  • Global JNDI-Namespace
  • No interface view: simplifies the access to beans, if needed
  • EJBCOntainer.getEJBContainer().getContext(): allows external initialization of bean context, which is nice for testing

Later, Adam discussed some Core J2EE patters, that become absolete with EJB 3.1 and others which are still valid.

After the talk, I spoke with Adam about the OSGi as a module architecture inside JEE application, which seems interesting to me.

The pictures are as usual available in my FlickR Gallery.

Marco published a video on Loroma.

JUGHHThe holiday season is over and we can enjoy an event every week. After Maven 2, Eclipse Stammtisch and reasoning on modularity an event on enterprise systems can be visited. It seems that after the last visit on Java EE 5 Hacking Adam want to tell something on Java EE 6 Hacking…

This session will be interactive / openspace like. He will walk through the new EJB 3.1 APIs and explain some interesting stuff as well. It is the logical conduction of the first JUG HH session in May 2008.

Location: Lehmanns Fachbuchhandlung (Hamburg Hauptbahnhof), Kurze Mühren 6, 20095 Hamburg

Date and Time: 16.09.2008, 20:00
Topic: Productive Java EE 6 – Rethinking Best Practices And Bashing On Patterns, Cluster One

Abstract: Java EE 6 is great, but many questions like:

  • Are DAOs dead?
  • Do JSF really suck?
  • Are anemic JPA-entities a best practice?
  • Are XML deployment descriptors legacy?
  • Are EJBs lightweight?
  • How to test EJBs?
  • Is layering an antipattern?
  • Do we need factories?
  • How to integrate with RESTFul services?
  • Is it possible to deploy EJBs into a …WAR?
  • Are “plain old web containers” dead?
  • Services or Objects – what is the way to go?

still remain open. These and many other questions will be discussed interactively with …code.

Speaker: Adam Bien

About the speaker: Java Champion Adam Bien is a self-employed consultant, lecturer, software architect, developer, and author in the enterprise Java sector in Germany who implements Java technology on a large scale. He is also the author of several books and articles on Java and J2EE technology, as well as distributed Java programming. His books include J2EE Patterns, J2EE HotSpots, Java EE 5 Architectures, Enterprise Architectures, Enterprise Java Frameworks, SOA Expert Knowledge, and Struts, all published in German.

As BEA technical director, Bien is also a member of the NetBeans Dream Team; an Expert Group member of the Java Community Process for EJB 3.1, JPA 2.0, and Java EE 6; and involved in embedded Java, Grid, and P2P technology. He currently works as an architect and developer in several J2EE-Java EE Model-Driven Architecture (MDA) and EAI component architecture projects for the Java EE platform and .NET.

Abstract

In this article we describe how to implement a simple Web Service using old fashioned Java EE 1.4. The dummy functionality is implemented in Session Beans and exposed via document-literal Web Service following the recommendations of W3C and WS-I.

Introduction

Before we get in to technical details about the implementation a short overview of planned is helpful. The main idea of this article is to show how a web service can be implemented using Java Enterprise Edition. Especially, this article tries to achieve two goals: show how existing EJB functionality can be exposed using Web Service technology and how Web Service technology can be linked to something stable, most of us have experience with. Many people follow the new trend of saying that EJB is ineffective and heavyweight – we don’t want to argue about this thesis. In this article we show a progmatic EJB development approach using “code-by-convention” combined with Generative-Programming techniques. We develop the EJB functionality and Web Service definition independent from each other and link them later together – we are sure that this is the only approach to keep both parts simple, clean and reusable. During the WSDL design we follow a certain style of type and element selection, that results from some experiences of using generators and integration with non-Java environments. Our use case is a little synthetic in order to show the variety of types and seems to introduce structural complexity, which can be avoided. We implement the examples using open source products only.

The article starts with a short introduction which could look a little lyrical for some technicians of you. Then the requirements to the selected software are listed, followed by the practical use case. Then we jumpstart the EJB development cycle, design the Web Service and finally put both implementations together. In the outline, we discuss the testing possibilities…

Requirements

In order to develop, generate, package and finally deploy and run the component, exposing its functionality we need special software. Following selections has been made:

  • Sun’s JDK (> 1.4.2)
  • Apache Ant (> 1.6.5)
  • XDoclet (1.2.3)
  • Sun’s Java Web Service Developer Pack (1.6)
  • JBoss AS (4.0.5 GA)
  • Eclipse IDE (> 3.3), recommended WTP installation

First of all we need to setup our environment. In order to make development under MS Windows convenient, we used to setup the entire environment variables in a single shell script:

@echo off
echo ----------------------------------------
echo Project Environment
echo ----------------------------------------
set DEVEL=c:\environment
set ANT_HOME=%DEVEL%\libraries\ant\1.6.5
set JAVA_HOME=%DEVEL%\compiler\j2sdk1.5.0_01
set JAVAC_EXEC=%DEVEL%\compiler\j2sdk1.5.0_01\bin\javac.exe
set JWSDP_HOME=%DEVEL%\compiler\jwsdp-1.6
set PATH=%JAVA_HOME%\bin;%ANT_HOME%\bin;%PATH%;%DEVEL%\bin;%JWSDP_HOME%\jaxrpc\bin
echo Environment variables:
echo ANT home : %ANT_HOME%
echo JAVA home : %JAVA_HOME%
echo PATH set to : echo %PATH%
echo ----------------------------------------
echo CLASSPATH set to : echo %CLASSPATH%
echo ----------------------------------------
cmd

For usage under Linux/MacOS the script should be adjusted correspondingly.

Eclipse is used as IDE for the whole development. In order to avoid any dependency to certain Eclipse functionalities we use Apache Ant as a build tool. In order to use the build tools these should be configured. In Preferences of Eclipse we set up Apache Ant and XDoclet. In Window -> Preferences -> Ant -> Runtime set up the Ant Home pointing to the Ant installation directory. In Window -> Preferences -> XDoclet set up XDoclet Home to XDoclet installation directory and set the version to 1.2.3.

Project Setup

Even if we don’t want to rely on the build and shortcommings of Eclipse in the area of EJB development, we want to use maximum of support if possible.

Create a new EJB Project and select the following Project Facets: EJB Module 2.1, XDoclet 1.2.3 and Java 1.4. We use the following project structure: all hand-written Java files go to /java/src directory, all Doclet-generated goes to /java/generated, the compiled files go to /java/class and the resulting archives (jars and ears) go to /java/build. The additional /metadata directory contains source and descriptor files needed for the project. To set all this up go to Project Properties -> Java Build Path. As long as we control XDoclet from an Ant script, we deactivate the XDoclet Builder in Project Preferencies -> XDoclet and in Project Preferences -> Builders. Before we begin with the implementation we have to set up the Ant script, that will build and package our project. The script unifies different tools we use to a single toolchain and contains several targets. These are EJB-Doclet generation target, WS-Compile target, Web-Doclet target, target for compilation of the Java classes and, finally, creation of a JAR and EAR files. In order to hold the build file project independent we use properties files that contain project specific settings. In order to access XDoclet and WSCompile from Ant the corresponding task definitions must be included and the libraries must be put to directories in classpath. For this purpose we used to create a library project in the same workspace, containing the libraries (called general).

...
<path id="class.path.local">
  <fileset dir="../general/lib">
    <include name="**/*.jar"></include>
    <include name="**/*.zip"></include>
  </fileset>
</path>
<path id="class.path.jwsdp">
  <path refid="class.path.local"></path>
</path>
<path id="class.path.doclet">
  <path refid="class.path.ant"></path>
</path>
<taskdef name="wscompile" classname="com.sun.xml.rpc.tools.ant.Wscompile" classpathref="class.path.jwsdp"></taskdef>
<taskdef name="xdoclet" classname="xdoclet.DocletTask" classpathref="class.path.doclet"></taskdef>
<taskdef name="ejbdoclet" classname="xdoclet.modules.ejb.EjbDocletTask" classpathref="class.path.doclet"></taskdef>
<taskdef name="wseedoclet" classname="xdoclet.modules.wsee.WseeDocletTask" classpathref="class.path.doclet"></taskdef>
...

In order to demonstrate the implementation we introduce a use case. This is sonstructed for the demonstration purposes and shows the usage of different types.

Use Case

The constructed system is capable of providing the measurements of some sensors. The sensors are identified by numers and can be queried by the user by providing the timespan of measurements. As a result, the systems delivers the set of measurements for the given timespan with one measurement per minute but at most sixty measurements. Every measurement contain the id of sensor from which it has been recorded, the timestamp, the value as a byte array, the measurement unit and finally the flag if the measurement exceeds the expectation and has alarming values.

We start with typical EJB implementation and then adopt the resulting types to those, that should be used in a Web Service.

First Session Bean powered by XDoclet

Following the EJB 2.1 specification the stateless session bean class must implement the javax.ejb.SessionBean interface. We follow the Class Adapter design pattern and create an abstract session bean that serves as a super class of all session beans.

public abstract class AbstractSessionBean implements SessionBean
{
	/** Logging facility */
	protected static Logger LOG = Logger.getLogger(AbstractSessionBean.class);
	/** Session context */
	protected SessionContext	sessionContext;

	/**
	 * @see javax.ejb.SessionBean#ejbActivate()
	 */
	public void ejbActivate() throws EJBException, RemoteException
	{
	}

	/**
	 * @see javax.ejb.SessionBean#ejbPassivate()
	 */
	public void ejbPassivate() throws EJBException, RemoteException
	{
	}

	/**
	 * @see javax.ejb.SessionBean#ejbRemove()
	 */
	public void ejbRemove() throws EJBException, RemoteException
	{
	}

	/**
	 * @see javax.ejb.SessionBean#setSessionContext(javax.ejb.SessionContext)
	 */
	public void setSessionContext(SessionContext sessionContext) throws EJBException, RemoteException
	{
		this.sessionContext = sessionContext;
	}
}

Using such an adapter we can avoid code repetition in functional session beans. It could be also a good idea to put the logging facility into this abstract class. Any functional bean extends AbstractSessionBean and overwrites the ejbCreate() method which is used to setup the working copy of a Bean. Mostly, references to other beans are initialized in this method. Due to the usage of XDoclet, we follow the Factory pattern implemented in the EJB-Util class, which simplifies access to other EJBs.

In our example we flatten the exception handling to the minimum and introduce one exception class for every functional bean, which is thrown by any error during processing. Therefore, any functional methods throw this exception. Usually, exceptions should be topic-related instead of being bean-related.

Information needed for XDoclet generation is stored in the corresponding XDoclet tags inside of the JavaDoc comments. For the full list of XDoclet tag please refer to the XDoclet site. We only explain the tags, we use. The ejb.bean tag indicates that a class is an EJB, providing a name, display-name, description as well as JNDI-Names of LocalHome interface and of the bean itself. The visibility is controlled over the view-type tag, the transactionality over transaction-type tag. Every business method we want to be included to business interfaces (Remote or Local) should be tagged with ejb.interface-method with corresponding view-type. Using this simple rule set we can easily implement business logic layer based on the stateless session beans:

/**
 * ...
 * @ejb.bean name="SensorManager"
 *  description="A Bean responsible for sensor operations"
 *  display-name="SensorManagerBean"
 *  jndi-name="techjava/SensorManagerrBean"
 *  local-jndi-name="techjava/SensorManagerLocalHome"
 *  type="Stateless"
 *  transaction-type="Container"
 *  view-type="both"
 * ...
 */
public class SensorManagerBean extends AbstractSessionBean 
{

	/**
	 * Max number of returned values 
	 */
	private static final long MAX_DURATION = 60;
	
	/**
	 * Retrieves data from sensors
	 * @param sensorId id of sensor to query
	 * @param timespanStart start of the time period
	 * @param timespanEnd end of the time period
	 * @return a collection of Measurement POJOs or an empty collection
	 * @throws SensorManagerException if something goes wrong
	 * @ejb.interface-method view-type="both"
	 */
	public Collection getSensorData(Long sensorId, Date timespanStart, Date timespanEnd) 
          throws SensorManagerException
	{
		Collection ret = new Vector();
		LOG.debug("Entering getSensorData()");
		if (sensorId == null || timespanStart == null || timespanEnd == null) 
		{
			throw new SensorManagerException("Missing a mandatory parameter, that was null (not set)");
		} else if (!timespanStart.before(timespanEnd)) {
			throw new SensorManagerException("The timespan is defined by the start that should be before end");
		}
		
		for (long i = 0; i < getNumberOfElements(timespanStart, timespanEnd); i++) 
		{
			Date date = new Date(timespanStart.getTime() + i*1000*60);
			if (date.after(timespanEnd)) 
			{
				break;
			}
			
			Measurement measurement = createMeasurement(sensorId, date, i);
			ret.add(measurement);
		}

		LOG.debug("Leaving getSensorData(). Returning " + ret.size() +" values");
		return ret;
	}

        /**
	 * retrieves the number of measurements in timespan
	 * @param timespanStart
	 * @param timespanEnd
	 * @return
	 */
	public long getNumberOfElements(Date timespanStart, Date timespanEnd) {	... }
	
	/**
	 * Creates a measurement instance
	 * @param sensorId
	 * @param timestamp
	 * @param number
	 * @return
	 */
	public Measurement createMeasurement(Long sensorId, Date timestamp, long number) { ... }
}

In order to generate the artifacts required by the specification from the written bean, we need to call a corresponding EJBDoclet task. The task itself is configuring only main generation options, during the subtasks are invoked for artifact generation. We used to separate classes of different purpose by packages and massively use the packageSubstitution subtask for this purpose. Remote, local, local home and remote home interfaces, util factory class and both EJB and a vendor-specific descriptors are generated using corresponding tasks.

<ejbdoclet destdir="${ejb.distdir}" verbose="true" ejbspec="2.1">
	<fileset dir="${ejb.srcdir}">
		<include name="${ejb.include}" />
	</fileset>
	<fileset dir="${ejb.distdir}">
		<include name="${ejb.include}" />
	</fileset>
	<packageSubstitution packages="ejb.entity" substituteWith="interfaces.entity" />
	<packageSubstitution packages="ejb.session" substituteWith="interfaces.session" />
	<packageSubstitution packages="ejb.facade" substituteWith="interfaces.facade" />

	<remoteinterface pattern="{0}Remote" />
	<localinterface pattern="{0}Local" />
	<homeinterface pattern="{0}Home" />
	<localhomeinterface pattern="{0}LocalHome" />

	<utilobject kind="physical">
		<packageSubstitution packages="ejb.session" substituteWith="util.session" />
		<packageSubstitution packages="ejb.facade" substituteWith="util.facade" />
	</utilobject>

	<deploymentdescriptor 
               destdir="${ejb.descriptor.distdir}" 
               displayname="${ejb.modulename}" 
               description="EJB Module ${ejb.modulename}" 
        />

	<jboss 
		destdir="${ejb.descriptor.distdir}" 
		version="4.0" 
		mergedir="metadata/merge"
	/>			
</ejbdoclet>

After generation of the classes and descriptors, which will be executed in a separate directory, it is a good idea to copy the descriptors back to the primary source folder, in order to allow for Eclipse to work with generated descriptors. Now we can compile the hand written code, together with generated code, put the results in a Java archive and assembly it to an enterprise archive, which can be deployed on an application server.

Hands on the Web Service Definition

The design of the interface definition is in general one of the most important steps in the component development life cycle. Depending on the quality of the interface design the component becomes reuseable or remains in usage only in the application it was initially built for. Therefore, we rely on a human engineering instead of generation.

For the definition of our Web Service, we use a standard language for this purpose, the WSDL. A WSDL file has a following structure:

  • Types
  • Messages
  • Operations
  • Port Type
  • Bindings
  • Services

As long as we intend to use document-literal, SOAP-style Web Services, the Binding and the Service parts are straight forward. The only thing we should pay attention is the Fault definition. We start from the Port Type definition, which is the equivalence of the business interface. A Port Type has a name and a collection of operation definitions, containing references to incoming, outgoing and fault messages. The Message part defines how XML Schema Types are used in the operations. This means that the most important parts of the WSDL file are the introduced Types, which are defined using XML Schema and the Port Types, which defines Operations, which use the Types.

The main purpose of a WSDL file is to define an interface. In order to distinguish it from the others, the interface is named. As long as WSDL defines a web-accessible resource, we use full qualified names, similar to XML target namespace.

<wsdl:definitions name="MeasurementProvider"
	targetNamespace="http://www.techjava.de/2008/ws4j2ee14/measurement/"
	xmlns:tns="http://www.techjava.de/2008/ws4j2ee14/measurement/"
	xmlns:types="http://www.techjava.de/2008/ws4j2ee14/measurement/types/"
	xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
	xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
	xmlns:xsd="http://www.w3.org/2001/XMLSchema">
	<wsdl:types>
		<xsd:schema
			targetNamespace="http://www.techjava.de/2008/ws4j2ee14/measurement/types/"
			xmlns:types="http://www.techjava.de/2008/ws4j2ee14/measurement/types/"
			elementFormDefault="qualified"
		>
			<!-- 
				ID element for sensor
			-->
			<xsd:simpleType name="sensor-id">
				<xsd:restriction base="xsd:long" />
			</xsd:simpleType>
			<!-- 
				Measurement complex type
			 -->
			<xsd:complexType name="Measurement">
				<xsd:sequence>
					<xsd:element name="sensorid" type="types:sensor-id" />
					<xsd:element name="timestamp" type="xsd:dateTime" />
					<xsd:element name="critical" type="xsd:boolean" />
					<xsd:element name="value" type="xsd:base64Binary" />
					<xsd:element name="unit" type="xsd:string" />
				</xsd:sequence>
			</xsd:complexType>

			<!-- 
				Timespan complex type
			 -->
			<xsd:complexType name="Timespan">
				<xsd:sequence>
					<xsd:element name="start" type="xsd:dateTime"
						minOccurs="1" maxOccurs="1" />
					<xsd:element name="end" type="xsd:dateTime"
						minOccurs="1" maxOccurs="1" />					
				</xsd:sequence>
			</xsd:complexType>
			
			<!-- 
				Operation Types
			-->
			<xsd:element name="GetSensorData">
				<xsd:complexType>
					<xsd:sequence>
						<xsd:element name="sensorid" type="types:sensor-id"
							minOccurs="1" maxOccurs="1" />
						<xsd:element name="timespan" type="types:Timespan" 
							minOccurs="1" maxOccurs="1" />
					</xsd:sequence>
				</xsd:complexType>
			</xsd:element>
			
			<xsd:element name="GetSensorDataResponse">
				<xsd:complexType>
					<xsd:sequence>
						<xsd:element name="measurements" type="types:Measurement"
							maxOccurs="unbounded" />
					</xsd:sequence>
				</xsd:complexType>
			</xsd:element>
			<xsd:element name="GetSensorDataFault">
				<xsd:complexType>
					<xsd:sequence minOccurs="1" maxOccurs="1">
						<xsd:element name="reason" type="xsd:string"
							minOccurs="0" maxOccurs="1" />
					</xsd:sequence>
				</xsd:complexType>
			</xsd:element>
			
		</xsd:schema>
	</wsdl:types>
...
	<!-- 
		Port Type (interface declaration)
	-->
	<wsdl:portType name="MeasurementProviderPortType">
		<wsdl:operation name="GetSensorData">
			<wsdl:input message="tns:GetSensorDataRequest" />
			<wsdl:output message="tns:GetSensorDataResponse" />
			<wsdl:fault message="tns:GetSensorDataFaultMessage"
				name="GetSensorDataFault" />
		</wsdl:operation>
	</wsdl:portType>
...
</wsdl:definitions>

Web Service Implementation

The created WSDL file is used for further Java code generation. For this purpose we use WSCompile, a tool supplied with Sun’s Java Web Service Developer Pack. The tool need a configuration file (wsdl-config.xml) storing the location of the WSDL file and namespace-to-package mappings. As a result of its execution, the tool generate Java classes for every custom type defined in XML Schema and the descriptor for JAX-RPC mapping required by the container for serialization and deserialization. In addition, it creates a Service interface, that is a interface to the factory of generated Port Type interfaces. The tool also generate implementation stubs for every Port Type, which can be ignored.

<configuration xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/config">
	<wsdl 
	    location="./metadata/MeasurementProviderService.wsdl" 
	    packageName="de.techjava.sensor.interfaces.stubs" 
	>
	     <namespaceMappingRegistry>
            <namespaceMapping
            	namespace="http://www.techjava.de/2008/ws4j2ee14/measurement/types/"
            	packageName="de.techjava.sensor.valueobjects"
            />
	     </namespaceMappingRegistry>    	
	</wsdl>
</configuration>

The WS Compile is usually called from the command line, but we use the Ant Task for this. Important are the features passed to the generator: documentliteral, wsi, searchschema, serializeinterfaces and explicitcontext. The path to the generated JAX-RPC mapping file is provided by the mapping attribute. Pay attention on the tool call, because depending on parameters given it generates Java classes from WSDL or vice versa.

<wscompile fork="true" import="true" base="java/class" 
	sourceBase="java/generated" verbose="true" 
	features="documentliteral, wsi, searchschema, serializeinterfaces, explicitcontext" 
	mapping="java/generated/META-INF/jaxrpc-mapping.xml" 
	config="metadata/wsdl-config.xml" 
	xSerializable="true"
>
	<classpath>
		<path refid="class.path.local" />
		<path refid="class.path.ant" />
		<pathelement path="${java.class.path}" />
	</classpath>
</wscompile>

After we generated the Java representation of the Web Service interface, we can integrate it with our EJB implementation. In order to do this, we used to create a Facade session bean, that implements the Port Type interface. The methods of the facade bean provide some parameter validation, form the values needed for the calculations, invoke the corresponding EJBs, receive results or exceptions and, finally, form the response object or fault. The XDoclet annotation of the facade bean follows the one discussed above, but differs from it slightly. The view-type attribute of the ejb.bean tag should hold the value remote-service-endpoint. In addition, the ejb.interface tag provide information about the Java Port Type interface and about the special Endpoint interface, that is required for the container. In order to generate the Endpoint interface, we add the service-endpoint subtask to the ejbdoclet task.

...
/**
 * @ejb.interface 
 *  service-endpoint-class="de.techjava.sensor.interfaces.session.MeasurementProviderFacadeConnectorEndpoint"
 *  service-endpoint-extends="de.techjava.sensor.interfaces.stubs.MeasurementProviderPortType"
 * @wsee.port-component 
 * 	name="MeasurementProviderService" 
 * 	local-part="MeasurementProviderService" 
 * 	display-name="MeasurementProviderService" 
 * 	description="MeasurementProvider Bean exposed as a web service"
 */
public class MeasurementProviderFacadeBean 
	extends AbstractSessionBean
	implements MeasurementProviderPortType
{
	private SensorManagerLocal sensorManagerLocal = null;

	/**
	 * Creates a link to SensorManager 
	 * @see de.techjava.sensor.ejb.session.AbstractSessionBean#ejbCreate()
	 */
	public void ejbCreate()
		throws EJBException
	{
		try
		{
			sensorManagerLocal = SensorManagerUtil.getLocalHome().create();
		} catch (CreateException e)
		{
			throw new EJBException("Error creating new Session Manager instance");
		} catch (NamingException e)
		{
			throw new EJBException("Session Manager Local Home could not be found in JNDI");
		}
	}

	/**
         * Method called on web service message receipt
	 * @ejb.interface-method view-type="remote-service-endpoint"
	 */
	public GetSensorDataResponse getSensorData(GetSensorData parameters) 
		throws GetSensorDataFault
	{
		LOG.debug("Received a web service request getSensorData()");
		if (parameters == null 
                  || parameters.getTimespan() == null 
                  || parameters.getTimespan().getEnd() == null 
                  || parameters.getTimespan().getStart() == null) 
		{
			LOG.debug("Leaving getSensorData() with error");
			throw new GetSensorDataFault("Wrong request, check mandatory parameters");
		}
		if (sensorManagerLocal == null) 
		{
			LOG.debug("Leaving getSensorData() with error");
			throw new GetSensorDataFault("Sensor Manager is not available");
		}
		
		Long sensorId = new Long(parameters.getSensorid());
		Date timespanStart = parameters.getTimespan().getStart().getTime();
		Date timespanEnd = parameters.getTimespan().getEnd().getTime();
		
		try
		{
			Collection simpleMeasurements = sensorManagerLocal.getSensorData(sensorId, timespanStart, timespanEnd);
			Vector measurements = new Vector(simpleMeasurements.size()); 
			Iterator simpleMeasurementI = simpleMeasurements.iterator();
			
			// convert types from EJB to generated XSD representations
			while(simpleMeasurementI.hasNext())
			{
				SimpleMeasurement sm = (SimpleMeasurement) simpleMeasurementI.next();
				Measurement measurement = convertMeasurement(sm);
				measurements.add(measurement);
			}
			
			GetSensorDataResponse response = new GetSensorDataResponse();
			response.setMeasurements((Measurement[]) measurements.toArray(new Measurement[measurements.size()]));
			LOG.debug("Leaving getSensorData().");
			return response;
			
		} catch (SensorManagerException e)
		{
			LOG.debug("Leaving getSensorData() with error");
			throw new GetSensorDataFault(e.getMessage());
		}
	}

}

In addition, the special J2EE Web Service descriptor webservices.xml needs to be created. For this purpose we use WSEE-Doclet, that introduces its own tags. The wsee-port-component provides display-name, web-service-description-name and port-component-name in the attributes name, local-part and display-name. The WSEE-Doclet is started from an Ant task and has one subtask wsee-deploymentdescriptor which is used to generate the required webservice.xml file.

...
<wseedoclet destDir="${ejb.descriptor.distdir}" jaxrpcMappingFile="jaxrpc-mapping.xml" wseeSpec="1.1" force="true" verbose="true">
	<fileset dir="${ejb.srcdir}">
		<include name="**/*.java" />
	</fileset>
	<wsee-deploymentdescriptor />
</wseedoclet>
...

Outline

For testing of Web Services is an important step of development. Especially, the resulting SOAP messages should be reviewed at least once, to ensure that the description is completed correctly, and no malformed XML structures are used. In order to play around with fresh-deployed Web Service open a browser of you choice and enter the URL of the web service overview of your application server. If JBoss (>4.0.5) runs locally, this will be http://localhost:8080/jbossws/. You should see a list of deployed web services. By clicking on a wsdl-button you can retrieve the version of WSDL after deployment (containing the target URL of the endpoint interface). Using this WSDL you can run tests of your web service. We use Eclipse’s Web Service Explorer to run developer tests (WTP installation needed). You can access it under Run -> Launch the Web Service Explorer. Switsch to WSDL-Page by clicking on the second button from right, in the upper right corner, enter the URL and hit Go. Fill the form generated for each method, send the request and analsye the response. If you want to create more advanced tests (and test suites) please refer to SOAP-UI Project.
Eclipse's Web Service Explorer

Resources

You can download the zip file ( de.techjava.ws4j2ee14.sensor_20080219_src.zip) containing the example above.

References

  • [2004,techreport] bibtex Go to document
    S. Microsystems, "The Java Web Services Tutorial," 2004.
    @techreport{SUN_2004_JWSTUTORIAL,
      author = {Sun Microsystems},
      title = {The Java Web Services Tutorial},
      month = Jun, year = {2004},
      url = {http://java.sun.com/webservices/docs/1.4/tutorial/doc/index.html}
    }
  • [2003,book] bibtex Go to document
    O. Ihns, S. M. Heldt, R. Wirdemann, and H. Zuzmann, Enterprise JavaBeans komplett, publisher Oldenburg, , 2003.
    @Book{IHNS_2003,
      author = {Oliver Ihns and Stefan M. Heldt and Ralf Wirdemann and Henning Zuzmann},
      title = {Enterprise JavaBeans komplett},
      publisher {Oldenburg},
      year = {2003},
      month = {Oct},
      url = {http://www.ejbkomplett.de/}
    }
  • [2000,book] bibtex
    K. Czarnecki and U. W. Eisenecker, Generative Programming, publisher Addison-Wesley, , 2000.
    @Book{CZARNECKI_2003,
      author = {Krzysztof Czarnecki and Ulrich W. Eisenecker},
      title = {Generative Programming},
      publisher {Addison-Wesley},
      year = {2000},
      month = {May},
      }
  • [1994,book] bibtex
    E. Gamma, R. Helm, R. Johnson, and J. Vlissides, Design Patterns: Elements of Reusable Object-Oriented Software, , 1994.
    @Book{GAMMA_1994,
      author = {Erich Gamma and Richard Helm and Ralph Johnson and John Vlissides},
      title = {Design Patterns: Elements of Reusable Object-Oriented Software},
      year = {1994}
    }
  • [,techreport] bibtex Go to document
    "XDoclet Project,".
    @techreport{XDOCLET,
      author = {},
      title = {XDoclet Project},
      url = {http://xdoclet.sourceforge.net/xdoclet/index.html}
    }