<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>JavaBeat &#187; XML &amp; Web Services</title>
	<atom:link href="http://www.javabeat.net/category/xml-web-services/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.javabeat.net</link>
	<description>Java Technology News</description>
	<lastBuildDate>Fri, 24 May 2013 01:32:07 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Generate XSD from XML files</title>
		<link>http://www.javabeat.net/2012/04/generate-xsd-from-xml-files/</link>
		<comments>http://www.javabeat.net/2012/04/generate-xsd-from-xml-files/#comments</comments>
		<pubDate>Thu, 12 Apr 2012 06:09:26 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[XML]]></category>
		<category><![CDATA[XSD]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=1028</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>XSD is the XML schema definition for defining the XML elements in the XML document. Prior to the XML schemas, DTDs are used which are not XML document and has the limitations. XSD is most popular because of the extensibility and the validations for the XML files. You can set the validation rules for the [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><a id="dd_start"></a><p>XSD is the XML schema definition for defining the XML elements in the XML document. Prior to the XML schemas, DTDs are used which are not XML document and has the limitations. XSD is most popular because of the extensibility and the validations for the XML files. You can set the validation rules for the XML files and the values in the XML documents can be validated using the XSD documents. There are number of tools available in the internet to perform the validation tasks.</p>
<p>There are times when developer wants to generate the XSD from the XML files. In a typical scenario, XSD is written seperately without referring the XML document because XML data can be wrong. In case, if you don&#8217;t have the XSD for an XML document and want to generate the XSD for that XML document, there are tools in the internet. This article is not to explain much detail on how to generate the XSD from XML, but to give an idea on where to get the details on the tools and guiding for the resources on the internet.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<ul>
<li><a href="http://www.ehow.com/how_6907958_convert-xml-xsd-online.html" target="_blank">How to Convert XML to Xsd Online</a></li>
<li><a href="http://www.ehow.com/how_6907958_convert-xml-xsd-online.html" target="_blank">XML-2-XSD</a></li>
<li><a href="http://stackoverflow.com/questions/288236/xsd-code-generator" target="_blank">List of Links</a></li>
</ul>
<p>If you are facing any issues on converting the XML files into the XSD, please post it here.</p>
<div class='dd_outer'><div class='dd_inner'><div id='dd_ajax_float'><div class='dd_button_v'><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="http%3A%2F%2Fwww.javabeat.net%2Fcategory%2Fxml-web-services%2Ffeed%2F" send="false" show_faces="false"  layout="box_count" width="50"  ></fb:like></div><div style='clear:left'></div><div class='dd_button_v'><script type='text/javascript' src='https://apis.google.com/js/plusone.js'></script><g:plusone size='tall' href='http://www.javabeat.net/category/xml-web-services/feed/'></g:plusone></div><div style='clear:left'></div><div class='dd_button_v'><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.javabeat.net/category/xml-web-services/feed/" data-count="vertical" data-text="XML &amp; Web Services" data-via="javabeat" ></a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div style='clear:left'></div><div class='dd_button_extra_v'><script type="text/javascript">jQuery(document).load(function(){ stLight.options({publisher:'bab47279-62c9-46af-addc-79fd1fe8fee0'}); });</script><div class="st_email_custom"><span id='dd_email_text'>email</span></div></div><div style='clear:left'></div><div class='dd_button_extra_v'><div id='dd_print_button'><span id='dd_print_text'><a href='javascript:window:print()'>print</a></span></div></div><div style='clear:left'></div></div></div></div><script type="text/javascript">var dd_offset_from_content = 44; var dd_top_offset_from_content = 0;</script><script type="text/javascript" src="http://www.javabeat.net/wp-content/plugins/digg-digg//js/diggdigg-floating-bar.js?ver=5.3.0"></script><div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/04/generate-xsd-from-xml-files/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java ME and Web services</title>
		<link>http://www.javabeat.net/2011/03/java-me-and-web-services/</link>
		<comments>http://www.javabeat.net/2011/03/java-me-and-web-services/#comments</comments>
		<pubDate>Thu, 31 Mar 2011 13:45:14 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[J2ME]]></category>
		<category><![CDATA[Webservices]]></category>
		<category><![CDATA[WebServices]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=607</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Introduction Java Micro Edition (Java ME) is a platform for running applications on smaller devices such as mobile phones, PDAs etc. These devices have restrictions in terms of Memory and Processing power. Java ME defines various configurations and profiles. Midlets are java applications that operate on Mobile Information Device Profile (MIDP) which is targeted on [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>Introduction</h2>
<p>Java Micro Edition (Java ME) is a platform for running applications on smaller devices such as mobile phones, PDAs etc. These devices have restrictions in terms of Memory and Processing power. Java ME defines various configurations and profiles. Midlets are java applications that operate on Mobile Information Device Profile (MIDP) which is targeted on Mobile phones that has limited memory and processing power. If you are new to Java ME please refer to the articles <strong><a href="http://www.javabeat.net/articles/27-introduction-to-j2me-1.html">Introduction to J2ME</a></strong> and <strong><a href="http://www.javabeat.net/articles/45-j2me-user-interface-1.html">J2ME User Interface</a></strong> in Java Beat.</p>
<p>Due to the limitations on the mobile phones, the midlets can’t be exposed as a web service. But the midlets can consume web services. Java ME provides a subset of JAX-RPC APIs to work with web services. This article will provide a step by step procedure to access web services from a midlet.</p>
<h2>Invoking web services from a Midlet</h2>
<p>To access web services, the Midlet has to make remote calls on the web services. But the Midlets won’t do this directly. A stub has to be created and calls are made via the stub instance. Using wireless toolkit it is made very simple to create stub code. Invocation on web service method is a synchrous process. The parameters for the methods are passes by value instead of pass by references. Similarly the values are returned by web services as pass by value. On the stubs midlets can set some properties like USERNAME_PROPERTY, PASSWORD_PROPERTY (User name and password for authentication), ENDPOINT_ADDRESS_PROPERTY(Address of the endpoint) and SESSION_MAINTAIN_PROPERTY(if true:session will be maintained between endpoint and midlet) using _setProperty method.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">stub._setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY,serviceUrl);
	stub._setProperty(Stub.SESSION_MAINTAIN_PROPERTY, new Boolean(true));</pre></td></tr></table></div>

<p>The generated stub code and the supportive classes have to be bundled in the jar file along with the midlet. While accessing web services the best practice is to write the sub invocation code in a seperate thread. This will avoid your application hanging as your thread will be blocked during web service invocation.</p>
<h2>Example</h2>
<p>This example will help you in understanding how to access web service from a midlet. Netbeans IDE, Glassfish application server and Wireless tool kit 2.5.2 are used.</p>
<h3>Create the web service and deploy it in the application server</h3>
<p><span style="text-decoration: underline;">Web service:</span></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">package mypack;
	import javax.jws.WebMethod;
	import javax.jws.WebParam;
	import javax.jws.WebService;
	@WebService()
	public class HelloService {
		@WebMethod(operationName = &quot;getMessage&quot;)
		public String getMessage(@WebParam(name = &quot;name&quot;)
		String name) {
			return &quot;Hi &quot;+name+&quot;! Welcome to JME Programming&quot;;
		}
	}</pre></td></tr></table></div>

<p><span style="text-decoration: underline;">WSDL URL:</span></p>
<p>http://localhost:17754/HelloWebService/HelloServiceService?WSDL</p>
<h3>Create a Midlet with a form with a text field and command buttons.</h3>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">public class Midlet extends MIDlet implements CommandListener{
		private Form myform;
		private TextField field;
		private Command exit,getMessage;
		private Display d;
		public void startApp() {
			d=Display.getDisplay(this);
			myform=new Form(&quot;Access Webservice&quot;);
			field=new TextField(&quot;Name&quot;, &quot;&quot;, 20, TextField.PLAIN);
			exit=new Command(&quot;Exit&quot;, Command.EXIT, 0);
			getMessage=new Command(&quot;GetMsg&quot;, Command.SCREEN, 1);
			myform.append(field);
			myform.addCommand(exit);
			myform.addCommand(getMessage);
			myform.setCommandListener(this);
			d.setCurrent(myform);
		}
		public void pauseApp() {
		}
		public void destroyApp(boolean unconditional) {
		}
		public void commandAction(Command c, Displayable d) {
			if(c==exit){
				notifyDestroyed();
			}else if(c==getMessage){
				//Code to Access Webservice
			}
		}
	}</pre></td></tr></table></div>

<h3>Use Wireless tool kit tool to create the stub</h3>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/03/113.jpg"><img class="aligncenter size-medium wp-image-1110" title="1" src="http://www.javabeat.net/wp-content/uploads/2011/03/113-300x168.jpg" alt="" width="300" height="168" /></a>a) Open Wireless Toolkit</p>
<p><center></center><a href="http://www.javabeat.net/wp-content/uploads/2011/03/210.jpg"><img class="aligncenter size-medium wp-image-1111" title="2" src="http://www.javabeat.net/wp-content/uploads/2011/03/210-300x167.jpg" alt="" width="300" height="167" /></a></p>
<p>(b) Select File -&gt; Utilities</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/03/35.jpg"><img class="aligncenter size-medium wp-image-1307" title="3" src="http://www.javabeat.net/wp-content/uploads/2011/03/35-300x256.jpg" alt="" width="300" height="256" /></a></p>
<p><center></center>(c) Select Stub Generator</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/03/45.jpg"><img class="aligncenter size-medium wp-image-1306" title="4" src="http://www.javabeat.net/wp-content/uploads/2011/03/45-279x300.jpg" alt="" width="279" height="300" /></a></p>
<p><center></center>d) Provide WSDL URL and the Output folder(src folder in Netbeans project) and the package details. Click on Ok</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/03/52.jpg"><img class="aligncenter size-medium wp-image-1108" title="5" src="http://www.javabeat.net/wp-content/uploads/2011/03/52-300x210.jpg" alt="" width="300" height="210" /></a></p>
<p><center></center>(e) The Stub and the other classes are generated in the src folder</p>
<h3>Access Web service</h3>
<p>For accessing web service,</p>
<ol>
<li>Create a new thread.</li>
<li>In the new thread, Instantiate the stub</li>
<li>Set properties on the stub if required</li>
<li>Invoke the web service methods on the stub</li>
</ol>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">//Extend the code written earlier
	import mypack.HelloService_Stub;
	public class Midlet extends MIDlet implements CommandListener{
		private Form myform;
		private TextField field;
		private Command exit,getMessage;
		private Display d;
		public TextField getField() {
			return field;
		}
		public Form getMyform() {
			return myform;
		}
		....
		public void commandAction(Command c, Displayable d) {
			if(c==exit){
				notifyDestroyed();
			}else if(c==getMessage){
				Thread t=new Thread(new NewThread(this));
				t.start();
			}
		}
	}	
	class NewThread implements Runnable{
		Midlet m;
		NewThread(Midlet m){
			this.m=m;
		}
		public void run() {
			Form frm=m.getMyform();
			TextField txt=m.getField();
			HelloService_Stub stub=new HelloService_Stub();
			String msg=&quot;&quot;;
			try {
				msg = stub.getMessage(txt.getString());
				frm.append(msg);
			} catch (RemoteException ex) {
				frm.append(ex.getMessage());
			}
		}
	}</pre></td></tr></table></div>

<h3>Run the Midlet</h3>
<p>Run the midlet. Provide the Name and select the command button GetMsg. The following output will be displayed.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/03/6.jpg"><img class="aligncenter size-medium wp-image-1308" title="6" src="http://www.javabeat.net/wp-content/uploads/2011/03/6-147x300.jpg" alt="" width="147" height="300" /></a></p>
<h2>Conclusion</h2>
<p>Java ME Midlets can act only as the consumer for web services. It can’t be exposed as a web service. Wireless Tool Kit helps in creating stubs for web services. Midlets by invoking methods on the stub invokes methods on web services. Both simple types and complex types can be passed as parameters to the web services.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2011/03/java-me-and-web-services/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Apache Axis2 Web Services</title>
		<link>http://www.javabeat.net/2011/03/apache-axis2-web-services/</link>
		<comments>http://www.javabeat.net/2011/03/apache-axis2-web-services/#comments</comments>
		<pubDate>Fri, 11 Mar 2011 15:34:20 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Webservices]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=1482</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>&#160; SOA, in practicality web services, is becoming the enabler for application integration. Since the introduction of web services, Apache Software Foundation has played a major role and produced several good web services frameworks. This book covers the defector Java Web Service framework, also known as Apache Axis2. This book covers several important facts that [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>&nbsp;</p>
<p>SOA, in practicality web services, is becoming the enabler for application integration. Since the introduction of web services, Apache Software Foundation has played a major role and produced several good web services frameworks. This book covers the defector Java Web Service framework, also known as Apache Axis2. This book covers several important facts that you would want to know about web services and writing, from simple web services to complex web services. By the end of this book, you will have learned about Axis2, its architectures and features, writing and deploying a simple service, writing service extensions and quality of services, POJO and JAX-WS services, clusters, and secure reliable web services.</p>
<h1>What This Book Covers</h1>
<p><em>Chapter 1, Apache Web Services and Axis2</em> &#8211; Gives you an introduction to web services and the web service stack at Apache.</p>
<p><em>Chapter 2, Looking inside Axis2</em> &#8211; Learn about Axis2 architecture and the importance of its components.</p>
<p><em>Chapter 3, Axis2 XML Model (AXIOM)</em> &#8211; Learn about the heart of a web service framework and learning more about XML processing in Axis2.</p>
<p><em>Chapter 4, Execution Chain</em> &#8211; Learn how to extend the core functionality of the<br />
framework though handlers.</p>
<p><em>Chapter 5, Deployment Mode</em> &#8211; Learn about the new and user friendly deployment model and several ways of deploying a service in Axis2.</p>
<p><em>Chapter 6, Information Model</em> &#8211; Learn how Axis2 stores it static and dynamic data and the importance of it.</p>
<p><em>Chapter 7, Writing an Axis2 Service</em> &#8211; Learn how to write a simple-complex service using Axis2 and how to deploy it</p>
<p><em>Chapter 8, Writing an Axis2 Module</em> &#8211; Learn how to extend Axis2 core functionality<br />
through a self-contained package.</p>
<p><em>Chapter 9, The Client API</em> &#8211; Learn how to use Axis2 to invoke other services, available APIs, and how to use them.</p>
<p><em>Chapter 10, Session Management</em> &#8211; Go beyond single invocation and learn how to use Axis2 features to provide better and more efficient statefull service.</p>
<p><em>Chapter 11, Developing JAX-WS Web Services</em> &#8211; Learn the fundamentals of developing JAXWS based web services, the most popular web service development technology used by Java developers.</p>
<p><em>Chapter 12, Axis2 Clustering</em> &#8211; Learn about clustering Apache Axis2, which will allow<br />
you to deploy Axis2 in large scale production deployments.</p>
<p><em>Chapter 13, Enterprise Integration Patterns</em> &#8211; Learn about some enterprise SOA deployment patterns that make use of the underlying Axis2 clustering infrastructure.</p>
<p><em>Chapter 14, Axis2 Advanced Features and Usage</em> &#8211; Go beyond simple features and learn about REST, MTOM, and several other advanced features.</p>
<p><em>Chapter 15, Building a Secure Reliable Web Service</em> &#8211; Learn how to use Axis2 and<br />
related components to make your service more secure and reliableWriting an Axis2 Module Web services are gaining a lot of popularity in the industry and have become one of the major enabler for application integration. In addition, due to the fl exibility and advantages of using web services, everyone is trying to enable web service support for their applications. As a result, web service frameworks need to support new and more custom requirements. As we have already discussed in the previous chapters, one of the major goals of a web service framework is to deliver incoming messages into the target service. However, just delivering the message to the service is not enough; today&#8217;s applications are required to have reliability, security, transaction, and other quality services.</p>
<p>Due to the popularity of web services, standard bodies are producing new web service standards, and it is hard to support those new standards if the web service framework is not fl exible enough. From the very beginnings of Axis2, fl exibility and extensibility were the two main design considerations. The idea of Axis2 modules is to extend the core functionality of the system without performing any changes to the core system.<br />
For example, Axis2 supports reliability and security as two separate modules, and the core engine is fully independent of those two qualities of service modules.</p>
<p>In this chapter, we will discuss the power of Axis2 modules and how to use them to<br />
extend Axis2 to support for your own requirements. In particular, we will discuss<br />
the following items:</p>
<ul>
<li>Brief history of the Axis2 module</li>
<li>Introducing module concept</li>
<li>Structure of the module</li>
<li>Module configuration file (module.xml)</li>
<li>Optional module implementation class</li>
<li>Steps to writing a module.xml file</li>
<li>Deploying and engaging a module</li>
<li>Brief overview of the WS-Policy and its usage in modules</li>
</ul>
<p>In our approach, we will be using code sample to help us understand the concepts better.</p>
<h2>Brief history of the Axis2 module</h2>
<p>Looking back at the history of Apache Web Services, the Handler concept can be considered as one of the most useful and interesting ideas. Due to the importance and fl exibility of the handler concept, Axis2 has also introduced it into its architecture. Notably, there are some major differences in the way you deploy handlers in Axis1 and Axis2. In Axis1, adding a handler requires you to perform global configuration changes and for an end user, this process may become a little complex. In contrast, Axis2 provides an easy way to deploy handlers. Moreover, in Axis2, deploying a handler is similar to deploying a service and does not require global configuration changes.</p>
<p>At the design stage of Axis2, one of the key considerations was to have a mechanism<br />
to extend the core functionality without doing much. One of the main reasons behind the design decision was due to the lesson learned from supporting WS reliable messaging in Axis1. The process of supporting reliable messaging in Axis1 involved a considerable amount of work, and part of the reason behind the complex process was due to the limited extensibility of Axis1 architecture. Therefore, learning from a session in Axis1, Axis2 introduced a very convenient and fl exible way of extending the core functionality and providing the quality of services. This particular mechanism is known as the module concept.</p>
<h2>Module concept</h2>
<p>In <em>Chapter 4, Execution Chain</em>, we introduced and discussed the handler concepts and how to use handlers. As we discussed there, one of the main ideas behind a handler is to intercept the message fl ow and execute specific logic. In Axis2, the concept of a module is to provide a very convenient way of deploying service extension. We can also consider a <strong>module</strong> as a collection of handlers and required resources to run the handlers (for example, third-party libraries). One can also consider a module as an implementation of a web service standard specification. As an illustration, Apache Sandesha is an implementation of WS-RM specification. Apache Rampart is an implementation of WS-security; likewise, in a general module, is an implementation of a web service specification. One of the most important features and aspects of the Axis2 module is that it provides a very easy way to extend the core functionality and provide better customization of the framework to suit complex business requirements. A simple example would be to write a module to log all the incoming messages or to count the number of messages, if requested.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<h2>Module structure</h2>
<p>As mentioned a few times before in previous chapters, Axis1 is one of the most<br />
popular web service frameworks and it provides very good support for most of the<br />
web service standards. However, when it comes to new and complex specifications,<br />
there is a significant amount of work we need to do to achieve our goals. The problem becomes further complicated when the work we are going to do involves handlers, configuration, and third-party libraries. To overcome this issue, the Axis2 module concept and its structure can be considered as a good candidate. As we discussed in the deployment section, both Axis2 services and modules can be deployed as archive files. Inside any archive file, we can have configuration files, resources, and the other things that the module author would like to have.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">It should be noted here that we have hot deployment and hot update
	support for the service; in other words, you can add a service when the
	system is up and running. However, unfortunately, we cannot deploy
	new modules when the system is running. You can still deploy modules,
	but Axis2 will not make the changes to the runtime system (we can drop
	them into the directory but Axis2 will not recognize that), so we will
	not use hot deployment or hot update. The main reason behind this is
	that unlike services, modules tend to change the system configurations,
	so performing system changes at the runtime to an enterprise-level
	application cannot be considered a good thing at all.</pre></td></tr></table></div>

<p>As we discussed earlier, adding a handler into Axis1 involves global configuration<br />
changes and, obviously, system restart. In contrast, when it comes to Axis2, we can add handlers using modules without doing any global level changes. There are instances where you need to do global configuration changes, which is a very rare situation and you only need to do so if you are trying to add new phases and change the phase orders. You can change the handler chain at the runtime without downer-starting the system.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">As mentioned earlier, changing the handler chain or any global
	configuration at the runtime cannot be considered a good habit. This is
	because in a production environment, changing runtime data may affect
	the whole system. However, at the deployment and testing time this
	comes in handy.</pre></td></tr></table></div>

<p>The structure of a module archive file is almost identical to that of a service archive<br />
file, except for the name of the configuration file. We know that for a service archive<br />
file to be a valid one, it is required to have a services.xml. In the same way, for a module to be a valid module archive, it has to have a module.xml file inside the META-INF directory of the archive. A typical module archive file will take the structure shown in the following screenshot. We will discuss each of the items in detail and create our own module in this chapter as well.</p>
<p>&nbsp;</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2012/04/11.jpg"><img class="aligncenter size-medium wp-image-1485" title="1" src="http://www.javabeat.net/wp-content/uploads/2012/04/11-300x296.jpg" alt="" width="300" height="296" /></a></p>
<p>&nbsp;</p>
<h2>Module configuration file (module.xml)</h2>
<p>As we have already discussed, the module archive file is a self-contained and<br />
self-described file. In other words, it has to have all the configuration required to<br />
be a valid and useful module. Needless to say, that is the beauty of a self-contained<br />
package. The Module configuration file or module.xml file is the configuration file<br />
that Axis2 can understand to do the necessary work.</p>
<p>A simple module.xml file has one or more handlers. In contrast, when it comes to<br />
complex modules, we can have some other configurations (for example, WS policies,<br />
phase rules) in a module.xml. First, let&#8217;s look at the available types of configurations<br />
in a module.xml. For our analysis, we will use a module.xml of a module that counts<br />
all the incoming and outgoing messages. We will be discussing all the important<br />
items in detail and provide a brief description for the other items:</p>
<ul>
<li>Handlers alone with phase rules</li>
<li>Parameters</li>
<li>Description about module</li>
<li>Module implementation class</li>
<li>WS-Policy</li>
<li>End points</li>
</ul>
<h2>Handlers and phase rules</h2>
<p>As we discussed, a module is a collection of handlers, so a module could have one<br />
or more handlers. Irrespective of the number of handlers in a module, module.<br />
xml provides a convenient way to specify handlers. Most importantly, module.<br />
xml can be used to provide enough configuration options to add a handler into the<br />
system and specify the exact location where the module author would like to see the<br />
handler running. In <em>Chapter 4, Execution Chain</em>, we learnt more about phase rules as<br />
a mechanism to tell Axis2 to put handlers into a particular location in the execution<br />
chain, so now it is time to look at them with an example.</p>
<p>Before learning how to write phase rules and specifying handlers in a module.xml,<br />
let&#8217;s look at how to write a handler. There are two ways to write a handler in Axis2:</p>
<ul>
<li>Implement the org.apache.axis2.engine.Handler interface</li>
<li>Extend the org.apache.axis2.handlers.AbstractHandler abstract class</li>
</ul>
<p>In this chapter, we are going to write a simple application to provide a better<br />
understanding of the module. Furthermore, to make the sample application easier,<br />
we are going to ignore some of the difficulties of the Handler API. In our approach,<br />
we will extend the AbstractHandler. When we extend the abstract class, we only<br />
need to implement one method called invoke. So the following sample code will<br />
illustrate how to implement the invoke method:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">public class IncomingCounterHandler extends AbstractHandler implements
	CounterConstants {
		public InvocationResponse invoke(MessageContext messageContext) throws
		AxisFault {
			//get the counter property from the configuration context
			ConfigurationContext configurationContext = messageContext.
				getConfigurationContext();
			Integer count =
				(Integer) configurationContext.getProperty(INCOMING_
				MESSAGE_COUNT_KEY);
			//increment the counter
			count = Integer.valueOf(count.intValue() + 1 + «»);
			//set the new count back to the configuration context
			configurationContext.setProperty(INCOMING_MESSAGE_COUNT_KEY,
				count);
			//print it out
			System.out.println(«The incoming message count is now « +
				count);
			return InvocationResponse.CONTINUE;
		}
	}</pre></td></tr></table></div>

<p>As we can see, the method takes MessageContext as a method parameter and returns InvocationResponse as the response. You can implement the method as follows:</p>
<ol>
<li>First get the configurationContext from the messageContext.</li>
<li>Get the property value specified by the property name.</li>
<li>Then increase the value by one.</li>
<li>Next set it back to configurationContext.</li>
<li>In general, inside the invoke method, as a module author, you have to do<br />
all the logic processing, and depending on the result you get, we can decide<br />
whether you let AxisEngine continue, suspend, or abort. Depending on your<br />
decision, you can return to one of the three following allowed return types:</li>
<ul>
<li>InvocationResponse.CONTINUEGive the signal to continue the message</li>
<li>InvocationResponse.SUSPENDThe message cannot continue as some of the conditions are not<br />
satisfied yet, so you need to pause the execution and wait.</li>
<li>InvocationResponse.ABORTSomething has gone wrong, therefore you need to drop the message<br />
and let the initiator know about it</li>
</ul>
<li>The message cannot continue as some of the conditions are not satisfied yet,<br />
so you need to pause the execution and wait.</li>
<li>InvocationResponse.ABORT.</li>
<li>Something has gone wrong, therefore you need to drop the message and let<br />
the initiator know about it.</li>
</ol>
<p>The corresponding CounterConstants class a just a collection of constants and will<br />
look as follows:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">public interface CounterConstants {
		String INCOMING_MESSAGE_COUNT_KEY = &quot;incoming-message-count&quot;;
		String OUTGOING_MESSAGE_COUNT_KEY = &quot;outgoing-message-count&quot;;
		String COUNT_FILE_NAME_PREFIX = &quot;count_record&quot;;
	}</pre></td></tr></table></div>

<p>As we already mentioned, the sample module we are going to implement is for counting the number of request coming into the system and the number of messages<br />
going out from the system. So far, we have only written the incoming message counter and we need to write the outgoing message counter as well, and the implementation of the out message count hander will look like the following:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">public class OutgoingCounterHandler extends AbstractHandler implements
	CounterConstants {
		public InvocationResponse invoke(MessageContext messageContext)
		throws AxisFault {
			//get the counter property from the configuration context
			ConfigurationContext configurationContext = messageContext.
				getConfigurationContext();
			Integer count =
				(Integer) configurationContext.getProperty(OUTGOING_
				MESSAGE_COUNT_KEY);
			//increment the counter
			count = Integer.valueOf(count.intValue() + 1 + «»);
			//set it back to the configuration
			configurationContext.setProperty(OUTGOING_MESSAGE_COUNT_KEY,
				count);
			//print it out
			System.out.println(«The outgoing message count is now « +
				count);
			return InvocationResponse.CONTINUE;
		}
	}</pre></td></tr></table></div>

<p>The implementation logic will be exactly the same as the incoming handler processing, except for the property name used in two places.</p>
<h2>Module implementation class</h2>
<p>When we work with enterprise-level applications, it is obvious that we have to initialize various settings such as database connections, thread pools, reading property, and so on. Therefore, you should have a place to put that logic in your module. We know that handlers run only when a request comes into the system but not at the system initialization time. The module implementation class provides a way to achieve system initialization logic as well as system shutdown time processing. As we mentioned earlier, module implementation class is optional. A<br />
very good example of a module that does not have a module implementation class is the Axis2 addressing module. However, to understand the concept clearly in our example application, we will implement a module implementation class, as shown below:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">public class CounterModule implements Module, CounterConstants {
		private static final String COUNTS_COMMENT = &quot;Counts&quot;;
		private static final String TIMESTAMP_FORMAT = &quot;yyMMddHHmmss&quot;;
		private static final String FILE_SUFFIX = &quot;.properties&quot;;
		public void init(ConfigurationContext configurationContext,
		AxisModule axisModule) throws AxisFault {
			//initialize our counters
			System.out.println(&quot;inside the init : module&quot;);
			initCounter(configurationContext, INCOMING_MESSAGE_COUNT_KEY);
			initCounter(configurationContext, OUTGOING_MESSAGE_COUNT_KEY);
		}
		private void initCounter(ConfigurationContext
			configurationContext,
			String key) {
			Integer count = (Integer) configurationContext.
				getProperty(key);
			if (count == null) {
				configurationContext.setProperty(key, Integer.
					valueOf(&quot;0&quot;));
			}
		}
		public void engageNotify(AxisDescription axisDescription) throws
			AxisFault {
			System.out.println(&quot;inside the engageNotify &quot; +
				axisDescription);
		}
		public boolean canSupportAssertion(Assertion assertion) {
			//returns whether policy assertions can be supported
			return false;
		}
		public void applyPolicy(Policy policy,
			AxisDescription axisDescription) throws
			AxisFault {
			// Configuure using the passed in policy!
		}
		public void shutdown(ConfigurationContext configurationContext)
			throws AxisFault {
			//do cleanup - in this case we'll write the values of the
			counters to a file
			try {
				SimpleDateFormat format = new SimpleDateFormat(TIMESTAMP_
					FORMAT);
				File countFile = new File(COUNT_FILE_NAME_PREFIX + format.
					format(new Date()) + FILE_SUFFIX);
				if (!countFile.exists()) {
					countFile.createNewFile();
				}
				Properties props = new Properties();
				props.setProperty(INCOMING_MESSAGE_COUNT_KEY,
					configurationContext.getProperty(INCOMING_MESSAGE_
					COUNT_KEY).toString());
				props.setProperty(OUTGOING_MESSAGE_COUNT_KEY,
					configurationContext.getProperty(OUTGOING_MESSAGE_
				COUNT_KEY).toString());
				//write to a file
				props.store(new FileOutputStream(countFile), COUNTS_
					COMMENT);
			} catch (IOException e) {
				//if we have exceptions we'll just print a message and let
				it go
				System.out.println(&quot;Saving counts failed! Error is &quot; +
					e.getMessage());
			}
		}
	}</pre></td></tr></table></div>

<p>As we can see, there are a number of methods in the previous module implementation class. However, notably not all of them are in the module interface.<br />
The module interface has only the following methods, but here we have some other<br />
methods for supporting our counter module-related stuff:</p>
<ul>
<li>init</li>
<li>engageNotify</li>
<li>applyPolicy</li>
<li>shutdown</li>
</ul>
<p>At the system startup time, the init method will be called, and at that time, the module can perform various initialization tasks. In our sample module, we have initialized both in-counter and out-counter.</p>
<p>When we engage this particular module to the whole system, to a service, or to an<br />
operation, the engagNotify method will be called. At that time, a module can decide whether the module can allow this engagement or not; say for an example, we try to engage the security module to a service, and at that time, the module finds out that there is a confl ict in the encryption algorithm. In this case, the module will not be able to engage and the module throws an exception and Axis2 will not engage the module. In this example, we will do nothing inside the engageNotify method.</p>
<p>As you might already know, WS-policy is one of the key standards and plays a major<br />
role in the web service configuration. When you engage a particular module to a service, the module policy should be applied to the service and should be visible when we view the WSDL of that service. So the applyPolicy method sets the module policy to corresponding services or operations when we engage the module.<br />
In this particular example, we do not have any policy associated with the module, so<br />
we do not need to worry about this method as well.</p>
<p>As we discussed in the init method, the method shutdown will be called when the system has to shut down. So if we want to do any kind of processing at that time, we can add this logic into that particular method. In our example, for demonstration<br />
purposes, we have added code to store the counter values in a file.</p>
<h2>Webservices Articles &amp; Books</h2>
<ul>
<li><a href="http://www.javabeat.net/articles/webservice/1/">Webservices Articles</a></li>
<li><a href="http://www.javabeat.net/books/webservice/1/">Webservices Books</a></li>
<li><a href="http://www.javabeat.net/articles/57-accessing-web-services-from-jsf-applications-1.html">Accessing Web Services from JSF applications</a></li>
<li><a href="http://www.javabeat.net/articles/40-creating-webservice-using-jboss-and-eclipse-europa-1.html">Creating Webservice using JBoss and Eclipse Europa</a></li>
<li><a href="http://www.javabeat.net/articles/36-juddi-and-configuration-in-jboss-and-mysql-database-1.html">jUDDI and Configuration in jBoss and MySQL database</a></li>
</ul>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2011/03/apache-axis2-web-services/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Service-Oriented Architecture— An Integration Blueprint</title>
		<link>http://www.javabeat.net/2010/10/service-oriented-architecture-an-integration-blueprint/</link>
		<comments>http://www.javabeat.net/2010/10/service-oriented-architecture-an-integration-blueprint/#comments</comments>
		<pubDate>Fri, 15 Oct 2010 00:30:42 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[SOA]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=1653</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Service-Oriented Architecture— An Integration Blueprint With the widespread use of service-oriented architecture (SOA), the integration of different IT systems has gained a new relevance. The era of isolated business information systems—so-called silos or stove-pipe architectures—is finally over. It is increasingly rare to find applications developed for a specific purpose that do not need to exchange [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><H1><CENTER>Service-Oriented Architecture— An Integration Blueprint</CENTER></H1><br />
<P>With the widespread use of service-oriented architecture (SOA), the integration of<br />
different IT systems has gained a new relevance. The era of isolated business information<br />
systems—so-called silos or stove-pipe architectures—is finally over. It is increasingly<br />
rare to find applications developed for a specific purpose that do not need to exchange<br />
information with other systems. Furthermore, SOA is becoming more and more widely<br />
accepted as a standard architecture. Nearly all organizations and vendors are designing or<br />
implementing applications with SOA capability. SOA represents an end-to-end approach<br />
to the IT system landscape as the support function for business processes. Because of<br />
SOA, functions provided by individual systems are now available in a single standardized<br />
form throughout organizations, and even outside their corporate boundaries. In addition,<br />
SOA is finally offering mechanisms that put the focus on existing systems, and make it<br />
possible to continue to use them. Smart integration mechanisms are needed to allow<br />
existing systems, as well as the functionality provided by individual applications, to be<br />
brought together into a new fully functioning whole. For this reason, it is essential to<br />
transform the abstract concept of integration into concrete, clearly structured, and<br />
practical implementation variants.</P><br />
<P>The Trivadis Integration Architecture Blueprint indicates how integration architectures<br />
can be implemented in practice. It achieves this by representing common integration<br />
approaches, such as Enterprise Application Integration (EAI); Extract, Transform, and<br />
Load (ETL); event-driven architecture (EDA); and others, in a clearly and simply<br />
structured blueprint. It creates transparency in the confused world of product developers<br />
and theoretical concepts.</P><br />
<P>The Trivadis Integration Architecture Blueprint shows how to structure, describe, and<br />
understand existing application landscapes from the perspective of integration. The<br />
process of developing new systems is significantly simplified by dividing the integration<br />
architecture into process, mediation, collection and distribution, and communication<br />
layers. The blueprint makes it possible to implement application systems correctly<br />
without losing sight of the bigger picture: a high performance, flexible, scalable, and<br />
affordable enterprise architecture.</P><br />
<H1>What This Book Covers</H1><br />
<P>Despite the wide variety of useful and comprehensive books and other publications on<br />
the subject of integration, the approaches that they describe often lack practical relevance.<br />
The basic issue involves, on the one hand, deciding how to divide an integration solution<br />
into individual areas so that it meets the customer requirements, and on the other hand,<br />
how it can be implemented with a reasonable amount of effort. In this case, this means<br />
structuring it in such a way that standardized, tried-and-tested basic components can be<br />
combined to form a functioning whole, with the help of tools and products. For this<br />
reason, the Trivadis Integration Architecture Blueprint subdivides the integration layer<br />
into further layers. This kind of layering is not common in technical literature, but it has<br />
been proven to be very useful in practice. It allows any type of integration problem to be<br />
represented, including traditional ETL (Extract, Transform, and Load), classic EAI<br />
(Enterprise Application Integration), EDA (event-driven architecture), and grid<br />
computing. This idea is reflected in the structure of the book.</P><br />
<P><I>Chapter 1, Basic Principles</I>, covers the fundamental integration concepts. This chapter is<br />
intended as an introduction for specialists who have not yet dealt with the subject of<br />
integration.</P><br />
<P><I>Chapter 2, Base Technologies</I>, describes a selection of base technologies. By far the most<br />
important of these are transaction strategies and their implementation, as well as process<br />
modeling. In addition, Java EE Connector Architecture (JCA), Java Business Integration<br />
(JBI), Service Component Architecture (SCA), and Service Data Objects (SDO) are<br />
explained. Many other base technologies are used in real-life integration projects, but<br />
these go beyond the scope of this book.</P><br />
<P><I>Chapter 3, Integration Architecture Blueprint</I>, describes the Trivadis Integration<br />
Architecture Blueprint. The process of layering integration solutions is fully<br />
substantiated, and each step is explained on the basis of the division of work between the<br />
individual layers. After this, each of the layers and their components are described.</P><br />
<P><I>Chapter 4, Implementation Scenarios</I>, demonstrates how the Trivadis Integration<br />
Architecture Blueprint represents the fundamental integration concepts that have been<br />
described in Chapter 1. We will use the blueprint with its notation and visualization to<br />
understand some common integration scenarios in a mostly product-neutral form. We<br />
will cover traditional, as well as modern, SOA-driven integration solutions.</P><br />
<P><I>Chapter 5, Vendor Products for Implementing the Trivadis Blueprint</I>, completes the book<br />
with a mapping of some vendor platforms to the Trivadis Integration Architecture<br />
Blueprint.</P><br />
<H1><CENTER>Integration Architecture Blueprint</CENTER></H1><br />
<P>The <B>Trivadis Integration Architecture Blueprint</B> specifies the building blocks needed<br />
for the effective implementation of integration solutions. It ensures consistent quality in<br />
the implementation of integration strategies as a result of a simple, tried-and-tested<br />
structure, and the use of familiar integration patterns (Hohpe, Wolf 2004).</P><br />
<H1>Standards, components, and patterns used</H1><br />
<P>The Trivadis Integration Architecture Blueprint uses common standardized techniques,<br />
components, and patterns, and is based on the layered architecture principle.</P><br />
<P>A <B>layered architecture</B> divides the overall architecture into different <B>layers</B> with<br />
different responsibilities. Depending on the size of the system and the problem involved,<br />
each layer can be broken down into further layers. Layers represent a logical construct,<br />
and can be distributed across one or more physical tiers. In contrast to <B>levels</B>, layers are<br />
organized hierarchically, and different layers can be located on the same level. Within the<br />
individual layers, the building blocks can be strongly cohesive. Extensive decoupling is<br />
needed between the layers. The rule is that higher-level layers can only be dependent on<br />
the layers beneath them and not vice versa. Each <B>building block</B> in a layer is only<br />
dependent on building blocks in the same layer, or the layers beneath. It is essential to<br />
create a layer structure that isolates the most important cohesive design aspects from one<br />
another, so that the building blocks within the layers are decoupled.</P><br />
<P>The blueprint is process oriented, and its notation and structure are determined by the<br />
blueprint&#8217;s dependencies and information flow in the integration process. An explanation<br />
of how the individual layers, their building blocks, and tasks can be identified from the<br />
requirements of the information flow is given on the basis of a simple scenario. In this<br />
scenario, the information is transported from one source to another target system using an<br />
integration solution.</P><br />
<P>In the blueprint, the building blocks and scenarios are described using familiar design<br />
patterns from different sources:</P><br />
<UL><br />
<LI>(Hohpe, Wolf 2004)</LI><br />
<LI>(Adams et al. 2001)</LI><br />
<LI>(Coral8 2007)</LI><br />
<LI>(Russel et al. 2006)</LI><br />
</UL><br />
<P>These patterns are used in a shared context on different layers. The Trivadis Integration<br />
Architecture Blueprint includes only the integration-related parts of the overall<br />
architecture, and describes the specific view of the <B>technical integration domain</B> in an<br />
overall architecture. It focuses on the information flow between systems in the context of<br />
domain-driven design.</P><br />
<B>Domain-driven design</B> is a means of communication, which is based on a profound<br />
understanding of the relevant business domain. This is subsequently modeled specifically<br />
for the application in question. Domain models contain no technical considerations and<br />
are restricted exclusively to business aspects. Domain models represent an abstraction of<br />
a business domain, which aims to capture the exemplary aspects of a specific<br />
implementation for this domain. The objectives are:</P><br />
<UL><br />
<LI>To significantly simplify communication between domain experts and<br />
developers by using a common language (the domain model)</LI><br />
<LI>To enable the requirements placed on the software to be defined more<br />
accurately and in a more targeted way</LI><br />
<LI>It must be possible to describe, specify, and document the software more<br />
precisely and more comprehensibly, using a clearly defined language, which<br />
will make it easier to maintain</LI><br />
</UL><br />
<P>The technical aspects of architecture can be grouped into domains in order to create<br />
specific views of the overall system. These domains cover security, performance, and<br />
other areas. The integration of systems and information also represents a specific view of<br />
the overall system, and can be turned into a domain.</P><br />
<P><B>Integration domain</B> is used to mean different things in different contexts. One widelyused<br />
meaning is &#8220;application domain&#8221;, in other words, a clearly defined, everyday<br />
problem area where computer systems and software are used. Enterprise architectures are<br />
often divided into business and technical domains:</P><br />
<UL><br />
<LI><B>Business domains</B> may include training, resource management, purchasing,<br />
sales or marketing, for example.</LI><br />
<LI><B>Technical domains</B> are generally areas such as applications, integration,<br />
network, security, platforms, systems, data, and information management.</LI><br />
</UL><br />
<P>The blueprint, however, sees integration as a technical domain, which supports business<br />
domains, and has its own views that can be regarded as complementary to the views of<br />
other architecture descriptions.</P><br />
<P>In accordance with Evans (Evans, 2004), the Trivadis Integration Architecture Blueprint<br />
is a <I>ubiquitous language</I> for describing integration systems. This and the structure of the<br />
integration domain on which it is based, have been tried and tested in a variety of<br />
integration projects using different technologies and products. The blueprint has<br />
demonstrated that it offers an easy-to-use method for structuring and documenting<br />
implementation solutions. As domain models for integration can be formulated<br />
differently depending on the target platform (for example, an object-oriented system or a<br />
classic ETL solution), the domain model is not described in terms of object orientation.<br />
Instead, the necessary functionality takes the form of building blocks (which are often<br />
identical with familiar design patterns) on a higher level of abstraction. This makes it<br />
possible to use the blueprint in a heterogeneous development environment with profitable<br />
results.</P><br />
<P>An <B>architecture blueprint</B> is based on widely-used, tried-and-tested techniques,<br />
components and patterns, which are grouped into a suitable structure to meet the<br />
requirements of the target domain.</P><br />
<P>The concepts, the functionality, and the building blocks to be implemented are described<br />
in an abstract form in blueprints. These are then replaced or fine-tuned by productspecific<br />
building blocks in the implementation project. Therefore, the Trivadis Integration<br />
Architecture Blueprint has been deliberately designed to be independent of individual<br />
vendors, products, and technologies. It includes integration scenarios and proposals that<br />
apply to specific problems, and can be used as aids during the project implementation<br />
process. The standardized view of the integration domain and the standardized means of<br />
representation enable strategies, concepts, solutions, and products to be compared with<br />
one another more easily in evaluations of architectures.</P><br />
<P>The specifications of the blueprint act as guidelines. Differences between this model and<br />
reality may well occur when the blueprint is implemented in a specific project. Individual<br />
building blocks and the relationships between them may not be needed, or may be<br />
grouped together. For example, the <B>adapter</B> and <B>mapper</B> building blocks may be joined<br />
together to form one component in implementation processes or products.</P><br />
<H1>Structuring the integration blueprint</H1><br />
<P>The following diagram is an overview of the Trivadis Integration Architecture Blueprint.<br />
It makes a distinction between the <B>application and information view</B> and the<br />
<B>integration view</B>.</P><br />
<P><CENTER><IMG SRC="images/2010/10/Blueprint/1.jpg"/></CENTER></P><br />
<H1>Insertt image 1049EN_03_01.png</H1><br />
<P>The <B>application and information view</B> consists of external systems, which are to be<br />
connected together by an integration solution. These are source or target entities in the<br />
information flow of an integration solution. Generally one physical system can also take<br />
on both roles. The building blocks belonging to the view, and the view itself, must be<br />
regarded as external to the integration system that is being described and, therefore, not<br />
the subject of the integration blueprint. The external systems can be divided into three<br />
main categories:</P><br />
<UL><br />
<LI><B>Transactional information storage:</B> This includes classic relational<br />
database management systems (RDBMS) and messaging systems (queues,<br />
topics). The focus is on <B>data integration</B>.</LI><br />
<LI><B>Non-transactional information storage:</B> This primarily file-based systems<br />
and non-relational data stores (NoSQL) with a focus on <B>data integration</B>.</LI><br />
<LI><B>Applications:</B> Applications include transactional or non-transactional<br />
systems that are being integrated (ERP—Enterprise Resource Planning,<br />
CMS—Content Management System, and so on) and can be accessed<br />
through a standardized API (web service, RMI/IIOP, DCOM, and so on).<br />
The focus is on <B>application</B> and <B>process integration</B>.</LI><br />
</UL><br />
<P>The integration view lies at the heart of the integration blueprint and is divided (on the<br />
basis of the principle of <B>divide and conquer</B>) into the following levels:</P><br />
<UL><br />
<LI><B>Transport level:</B> The transport level encapsulates the technical details of<br />
communication protocols and formats for the external systems. It contains:</LI><br />
	<UL><br />
	<LI><B>Communication layer:</B> The communication layer is part of the<br />
transport level, and is responsible for transporting information.<br />
This layer links the integration solution with external systems,<br />
and represents a type of gateway to the infrastructure at an<br />
architectural level. It consists of transport protocols and formats.</LI><br />
</UL><br />
<LI><B>Integration domain level:</B> The integration domain level covers the classic<br />
areas of integration, including typical elements of the integration domain,<br />
such as adapters, routers, and filters. It is divided into:</LI><br />
	<UL><br />
	<LI><B>Collection/distribution layer:</B> This layer is responsible for<br />
connecting components. It is completely separate from the main<br />
part of the integration domain (mediation). The building blocks<br />
in this layer connect the mediation layer above with the<br />
communication layer below. The layer is responsible for<br />
encapsulating external protocols and their technical details from<br />
the integration application, and transforming external technical<br />
formats into familiar internal technical formats.</LI><br />
<LI><B>Mediation layer:</B> This layer is responsible for forwarding<br />
information. Its main task is to ensure the reliable forwarding of<br />
information to business components in the process layer, or<br />
directly to output channels that are assigned to the<br />
collection/distribution layer, and that distribute data to the target<br />
systems. This is the most important functionality of the<br />
integration domain. In more complex scenarios, the information<br />
forwarding process can be enhanced by information<br />
transformation, filtering, and so on.</LI><br />
</UL><br />
<LI><B>Application level:</B> The application level encapsulates the integration<br />
management and process logic. It is an optional level and contains:</LI><br />
	<UL><br />
	<LI><B>Process layer:</B> The process layer is part of the application level,<br />
and is responsible for orchestrating component and service calls.<br />
It manages the integration processes by controlling the building<br />
blocks in the mediation layer (if they cannot act autonomously).</LI><br />
</UL><br />
</UL><br />
<P>The integration view contains additional functionality that cannot be assigned to any of<br />
the levels and layers referred to above. This functionality consists of so-called<br />
cross-cutting concerns that can be used by building blocks from several other layers.<br />
Cross-cutting concerns include:</P><br />
<UL><br />
<LI><B>Assembly/deployment:</B> Contains configurations (often declarative or<br />
scripted) of the components and services. For example, this is where the<br />
versioning of Open Service Gateway initiative (OSGi) services is specified.</LI><br />
<LI><B>Transaction:</B> Provides the transaction infrastructure used by the building<br />
blocks in the integration domain.</LI><br />
<LI><B>Security/management:</B> This is the security and management infrastructure<br />
used by the building blocks in the integration domain. It includes, for<br />
example, libraries with security functionality, <B>JMX</B> agents and similar<br />
entities.</LI><br />
<LI><B>Monitoring, BAM, QoS:</B> These components are used for monitoring<br />
operations. This includes ensuring compliance with the defined <B>Service<br />
Level Agreements (SLA)</B> and <B>Quality of Service (QoS). Business Activity<br />
Monitoring (BAM)</B> products can be used for monitoring purposes.</LI><br />
<LI><B>Governance:</B> These components and artifacts form the basis for SLAs and<br />
QoS. The artifacts include business regulations, for example. In addition, this<br />
is where responsibilities, functional and non-functional requirements, and<br />
accounting rules for the services/capacities used are defined.</LI><br />
</UL></p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2010/10/service-oriented-architecture-an-integration-blueprint/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Developing a Web Service with CXF</title>
		<link>http://www.javabeat.net/2010/07/developing-a-web-service-with-cxf/</link>
		<comments>http://www.javabeat.net/2010/07/developing-a-web-service-with-cxf/#comments</comments>
		<pubDate>Fri, 23 Jul 2010 23:55:33 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Webservices]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=1815</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Apache CXF Web Service Development Apache CXF is an open source services framework that makes web service development easy, simplified, and standard based. CXF provides many features such as frontend programming, support for different transports and data bindings, support for different protocols, and other advanced concepts like Features and Invokers. It also provides a programming [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><H1><CENTER>Apache CXF Web Service Development</CENTER></H1><br />
<P>Apache CXF is an open source services framework that makes web service development<br />
easy, simplified, and standard based. CXF provides many features such as frontend<br />
programming, support for different transports and data bindings, support for different<br />
protocols, and other advanced concepts like Features and Invokers. It also provides a<br />
programming model to build and deploy RESTful services.</P><br />
<P>The focus of the book is to provide readers with comprehensive details on how to use the<br />
overview of CXF features and architecture. Each feature is explained in a separate<br />
chapter, each of which covers well defined practical illustrations using real world<br />
examples. This helps developers to easily understand the CXF API. Each chapter<br />
provides hands on examples and provides step-by-step instructions to develop, deploy,<br />
and execute the code.</P><br />
<H1>What This Book Covers</H1><br />
<P>The book is about the CXF service development framework. The book covers two of the<br />
most widely used approaches, for web services development, SOAP and REST. Each<br />
chapter in the book provides hands on examples, where we look in detail at how to use<br />
the various CXF features in detail to develop web services in a step-by-step fashion</P><br />
<P>Chapter 1: <I>Getting Familiar with CXF</I> revisits web service concepts and provides an<br />
introduction to CXF framework and its usage, and prepares the CXF environment for the<br />
following chapters. By the end of this chapter the reader will be able to understand the<br />
core concepts of CXF.</P><br />
<P>Chapter 2: <I>Developing a Web Service with CXF</I> focuses on getting the reader quickly<br />
started with the CXF framework by developing a simple web service and running it under<br />
the Tomcat container.</P><br />
<P>By the end of this chapter the reader will be able to develop a simple web service<br />
using CXF.</P><br />
<P>Chapter 3: <I>Working with CXF Frontends</I> illustrates the use of different frontends, like<br />
JAX-WS and CXF simple fronted API, and shows how to apply code-first and contractfirst<br />
development approaches for developing web services. We will look at how to create<br />
dynamic web service clients, the use of web service context, and how to work directly<br />
with XML messages using CXF Provide and Dispatch implementation.</P><br />
<P>By the end of this chapter the reader will be able to apply different frontends to develop a<br />
web service.</P><br />
<P>Chapter 4: <I>Learning about Service Transports</I> explains basic transport protocols for a<br />
service and shows you how to configure HTTP, HTTP(s), JMS, and Local protocol for<br />
web services communication. You will get introduced to the concept of HTTP conduit,<br />
which enables the client program to apply policies or properties to HTTP and HTTPs<br />
protocols, and how to generate a crypto key and a key store for HTTPs based service<br />
communication. You will learn how to use JMS protocol for web services<br />
communication and how to facilitate web services message exchange using CXF Local<br />
service transport.</P><br />
<P>By the end of this chapter the reader will be able develop services with<br />
different transports</P><br />
<P>Chapter 5: <I>Implementing Advanced Features</I> will explain advanced concepts using CXF<br />
Features, Interceptors, and Invokers, and how to integrate these concepts in existing<br />
applications.</P><br />
<P>By the end of this chapter the reader will be able develop services with features like<br />
Interceptors and Invokers</P><br />
<P>Chapter 6: <I>Developing RESTful Services with CXF</I> explains the concept of REST<br />
demonstrates additional features for developing enterprise RESTful services. We will<br />
look at how to design, develop, and unit test the RESTful Service by taking a real world<br />
example using CXF JAX-RS implementation.</P><br />
<P>By the end of this chapter the reader will be able to design, develop, and unit test the<br />
RESTful service</P><br />
<P>Chapter 7: <I>Deploying RESTful Services with CXF</I> will explain how to deploy<br />
REST services in a container like Tomcat using Spring configuration, and how to<br />
test out the various operations exposed by the RESTFul application using CXF RESTful<br />
client APiusing a web service development tool. We will look at how to enable<br />
exception handling, JSON message support, and logging support for RESTful<br />
applications using CXF framework.</P><br />
<P>By the end of this chapter the reader would be able utilize various CXF features for<br />
developing RESTful services and how to leverage Spring configuration for deploying<br />
RESTful service in the tomcat container.</P><br />
<P>Chapter 8: <I>Working with CXF Tools</I> will explain some of the commonly used CXF<br />
tools that assist us in web services development. We will look at how to invoke a real<br />
world .NET service over the internet using a Java client and JavaScript, create web<br />
service implementation from WSDL files, generate WSDL files from web service<br />
implementation, and validate the WSDL file for compliance.</P><br />
<P>By the end of this chapter the reader will be able to use different CXF tools to<br />
develop a service.</P><br />
<P><I>Appendix A</I> deals with how to set up the CXF environment, provides details on how the<br />
source code for each chapter is organized, and shows how to run the source code<br />
examples using the ANT tool and Maven Tool.</P><br />
<P><I>Appendix B</I> provides an explanation of the basics of the Spring framework and IoC<br />
concepts, along with an end-to-end example which utilizes Spring IoC concepts.</P><br />
<P>By the end of this Appendix chapter the reader will have a good understanding of Spring<br />
capabilities used in the context of CXF web services development in this book.</P><br />
<H1><CENTER>Developing a Web Service with CXF</CENTER></H1><br />
<P>The first chapter provided an introduction to web services and CXF framework. We<br />
looked at the features supported by the CXF framework and how to set up the CXF<br />
environment. This chapter will focus on programming web service with CXF. CXF<br />
provides a robust programming model that offers simple and convenient APIs for<br />
web service development. The chapter will focus on illustrating a simple web service<br />
development using CXF and Spring-based configurations. The chapter will also talk<br />
about the architecture of CXF.</P><br />
<P>Before we examine CXF-based web service development, we will review the example<br />
application that will be illustrated throughout the book. The example application<br />
will be called <B>Order Processing Application</B>. The book will demonstrate the same<br />
application to communicate different concepts and features of CXF so that the reader<br />
can have a better understanding of CXF as a whole. This chapter will focus on the<br />
following topics:</P><br />
<UL><br />
<LI>Overview of a sample Order Processing Application</LI><br />
<LI>CXF-based web service development with Spring</LI><br />
<LI>Insight into CXF architecture</LI><br />
</UL><br />
<H1>The Order Processing Application</H1><br />
<P>The objective of the Order Processing Application is to process a customer order.<br />
The order process functionality will generate the customer order, thereby making<br />
the order valid and approved. A typical scenario will be a customer making an<br />
order request to buy a particular item. The purchase department will receive the<br />
order request from the customer and prepare a formal purchase order. The purchase<br />
order will hold the details of the customer, the name of the item to be purchased,<br />
the quantity, and the price. Once the order is prepared, it will be sent to the<br />
Order Processing department for the necessary approval. If the order is valid and<br />
approved, then the department will generate the unique order ID and send it back to<br />
the Purchase department. The Purchase department will communicate the order ID<br />
back to the customer.</P><br />
<P><CENTER><IMG SRC="images/2010/07/Apache-cfx/1.jpg"/></CENTER></P><br />
<P>For simplicity, we will look at the following use cases:</P><br />
<UL><br />
<LI>Prepare an order</LI><br />
<LI>Process the order</LI><br />
</UL><br />
<P>The client application will prepare an order and send it to the server application<br />
through a business method call. The server application will contain a web service<br />
that will process the order and generate a unique order ID. The generation of the<br />
unique order ID will signify order approval.</P><br />
<P><PRE><CODE><br />
	In real world applications a unique order ID is always accompanied by<br />
	the date the order was approved. However, in this example we chose to<br />
	keep it simple by only generating order ID.<br />
</CODE></PRE></P><br />
<H1>Developing a service</H1><br />
<P>Let&#8217;s look specifically at how to create an Order Processing Web Service and then<br />
register it as a Spring bean using a JAX-WS frontend.</P><br />
<P><PRE><CODE><br />
	In Chapter 3 you will learn about the JAX-WS frontend. The chapter<br />
	will also cover a brief discussion on JAX-WS. The Sun-based JAX-WS<br />
	specification can be found at the following URL:</p>
<p>http://jcp.org/aboutJava/communityprocess/final/</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>	jsr224/index.html<br />
</CODE></PRE></P><br />
<P>JAX-WS frontend offers two ways of developing a web service—Code-first and<br />
Contract-first. We will use the <I>Code-first</I> approach, that is, we will first create a Java<br />
class and convert this into a web service component. The first set of tasks will be to<br />
create server-side components.</P><br />
<P><PRE><CODE><br />
	In web service terminology, Code-first is termed as the Bottoms Up<br />
	approach, and Contract-first is referred to as the Top Down approach.<br />
</CODE></PRE></P><br />
<P>To achieve this, we typically perform the following steps:</P><br />
<UL><br />
<LI>Create a <B>Service Endpoint Interface (SEI)</B> and define a business method<br />
to be used with the web service.</LI><br />
<LI>Create the implementation class and annotate it as a web service.</LI><br />
<LI> Create beans.xml and define the service class as a Spring bean using a<br />
JAX-WS frontend.</LI><br />
</UL></p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2010/07/developing-a-web-service-with-cxf/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>RESTful Java Web Services</title>
		<link>http://www.javabeat.net/2009/12/restful-java-web-services/</link>
		<comments>http://www.javabeat.net/2009/12/restful-java-web-services/#comments</comments>
		<pubDate>Tue, 08 Dec 2009 00:39:02 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Book Review]]></category>
		<category><![CDATA[RESTFul WebServices]]></category>
		<category><![CDATA[RESTful WebServices]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=1964</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>RESTful Java Web ServicesThis article is sample chapter for the book RESTful Java Web Services. If you&#8217;re already familiar with REST theory, but are new to RESTful Java web services, and want to use the Java technology stack together with Java RESTful frameworks to create robust web services, this is the book for you. This book is [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><center><strong>RESTful Java Web Services</strong></center>This article is sample chapter for the book <a href="http://web.archive.org/web/20100611224545/http://www.packtpub.com/restful-java-web-services/book" target="_blank">RESTful Java Web Services.</a> If you&#8217;re already familiar with <strong>REST</strong> theory, but are new to <strong>RESTful Java web services</strong>, and want to use the Java technology stack together with <strong>Java RESTful</strong> frameworks to create robust web services, this is the book for you.</p>
<p>This book is a guide for developing <strong>RESTful web services</strong> using Java and the most popular RESTful Java frameworks available today. This book covers the theory of REST, practical coding examples for RESTful clients, a practical outline of the <strong>RESTful</strong> design, and a complete implementation of a non-trivial web service using the frameworks Jersey&#8217;s JAX-RS, Restlet&#8217;s Lightweight REST, JBoss&#8217;s JAX-RS RESTEasy, and Struts 2 with the REST plugin.</p>
<p>We cover each framework in detail so you can compare their strengths and weaknesses. This coverage will also provide you with enough knowledge to begin developing your own web services after the first reading. What&#8217;s more, all the source code is included for<br />
you to study and modify. Finally, we discuss performance issues faced by web service developers and cover practical solutions for securing your web services.</p>
<h2>What This Book Covers</h2>
<p>Chapter 1, <i>RESTful Architectures</i>, introduces you to the REST software architectural style and discusses the constraints, main components, and abstractions that make a software system RESTful. It also elaborates on the details of HTTP requests and responses between clients and servers, and the use of RESTful web services in the context of Service-Oriented Architectures (SOA).</p>
<p>Chapter 2, <i>Accessing RESTful Services—Part 1</i>, teaches you to code four different RESTful Java clients that connect and consume RESTful web services, using the messaging API provided by Twitter.</p>
<p>Chapter 3, <i>Accessing RESTful Services—Part 2</i>, shows you how to develop a mashup application that uses RESTful web services that connect to Google, Yahoo!, Twitter, and TextWise&#8217;s SemanticHacker API. It also covers in detail what it takes to consume JSON<br />
objects using JavaScript.</p>
<p>Chapter 4, <i>RESTful Web Services Design</i>, demonstrates how to design a micro-blogging web service (similar to Twitter), where users create accounts and then post entries. It also outlines a set of steps that can be used to design any software system that needs to be<br />
deployed as a RESTful web service.</p>
<p>Chapter 5, <i>Jersey: JAX-RS</i>, implements the micro-blogging web service specified in Chapter 4 using Jersey, the reference implementation of Sun&#8217;s Java API for RESTful Web Services.</p>
<p>Chapter 6, <i>The Restlet Framework</i>, implements the micro-blogging web service specified in Chapter 4 using the Restlet framework, using two of its latest versions, 1.1 and 2.0.</p>
<p>Chapter 7, <i>RESTEasy: JAX-RS</i>, implements the micro-blogging web service specified in Chapter 4 using JBoss&#8217;s RESTEasy framework.</p>
<p>Chapter 8, <i>Struts 2 and the REST Plugin</i>, implements the micro-blogging web service specified in Chapter 4 using Struts 2 framework (version 2.1.6) together with the REST plugin. This chapter covers configuration of Struts 2 and the REST plugin, mapping of URIs to Struts 2 action classes, and handling of HTTP requests using the REST plugin.</p>
<p>Chapter 9, <i>Restlet Clients and Servers</i>, extends coverage of the Restlet framework. This chapter looks at the client connector library and the standalone server library.</p>
<p>Chapter 10, <i>Security and Performance</i>, explores how to secure web services using HTTP Basic Authentication, and covers the OAuth authentication protocol. This chapter also covers the topics of availability and scalability and how they relate to implementing high<br />
performing web services.</p>
<p><center></p>
<h2><span style="text-decoration: underline;"><span style="color: #000080; text-decoration: underline;">RESTful Web Services Design</span></span></h2>
<p></center>The RESTful development process follows traditional development paradigms. However, with RESTful web services, we need to analyze the resource requirements first, design the representation for our resources second, identify the URIs third, and, lastly, worry about implementation technologies.</p>
<p>Throughout this book we&#8217;ve talked about creating web services that are noun dependent as opposed to verb dependent. In this chapter we&#8217;ll look at what that means in terms of the design process. For this, we&#8217;ll design a blogging application, but we&#8217;ll leave the implementation for later chapters. Our sample application is a micro-blogging web service (similar to Twitter), where users create accounts and then post entries.</p>
<p>Finally, while designing our application, we&#8217;ll define a set of steps that can be applied to designing any software system that needs to be deployed as a RESTful web service.</p>
<h2>Designing a RESTful web service</h2>
<p>Designing RESTful web services is not different from designing traditional web applications. We still have business requirements, we still have users who want to do things with data, and we still have hardware constraints and software architectures to deal with. The main difference, however, is that we look at the requirements to tease out resources and forget about specific actions to be taken on these resources.</p>
<p>We can think of RESTful web service design as being similar to Object Oriented Design (OOD). In OOD, we try to identify objects from the data we want to represent together with the actions that an object can have. But the similarities end at the data structure definition, because with RESTful web services we already have specific calls that are part of the protocol itself.The underlying RESTful web service design principles can be summarized in the following four steps:</p>
<ol>
<li><b>Requirements gathering—</b>this step is similar to traditional software requirement gathering practices.</li>
<li><b>Resource identification—</b>this step is similar to OOD where we identify objects, but we don&#8217;t worry about messaging between objects.</li>
<li><b>Resource representation definition—</b>because we exchange representation between clients and servers, we should define what kind of representation we need to use. Typically, we use XML, but JSON has gained popularity. That&#8217;s not to say that we can&#8217;t use any other form of resource representation—on the contrary, we could use XHTML or any other form of binary representation, though we let the requirements guide our choices.</li>
<li><b>URI definition—</b>with resources in place, we need to define the API, which consists of URIs for clients and servers to exchange resources&#8217; representations.</li>
</ol>
<p>This design process is not static. These are iterative steps that gravitate around resources. Let&#8217;s say that during the <i>URI definition</i> step we discover that one of the URI&#8217;s responses is not covered in one of the resources we have identified. Then we go back to define a suitable resource. In most cases, however, we find that the resources that we already have cover most of our needs, and we just have to combine existing resources into a meta-resource to take care of the new requirement.</p>
<h2>Requirements of sample web service</h2>
<p>The RESTful web service we design in this chapter is a social networking web application similar to Twitter.</p>
<p>Throughout this book, we follow an OOD process mixed with an agile philosophy for designing and coding our applications. This means that we create just enough documentation to be useful, but not so much that we spend an inordinate amount of time deciphering it during our implementation phase.</p>
<p>As with any application, we begin by listing the main business requirements, for which we have the following use cases (these are the main functions of our application):</p>
<ul>
<li>A web user creates an account with a username and a password (creating an account means that the user is now registered).</li>
</ul>
<ul>
<li>Registered users post blog entries to their accounts. We limit messages to 140 characters.</li>
</ul>
<ul>
<li>Registered and non-registered users view all blog entries.</li>
</ul>
<ul>
<li>Registered and non-registered users view user profiles.</li>
</ul>
<ul>
<li>Registered users update their user profiles, for example, users update their password.</li>
</ul>
<ul>
<li>Registered and non-registered users search for terms in all blog entries.</li>
</ul>
<p>However simple this example may be, social networking sites work on these same principles: users sign up for accounts to post personal updates or information. Our intention here, though, is not to fully replicate Twitter or to fully create a social networking application. What we are trying to outline is a set of requirements that will test our understanding of RESTful web services design and implementation.</p>
<pre class="brush: java; title: ; notranslate">	The core value of social networking sites lies in the ability to connect
	to multiple users who connect with us, and the value is derived from
	what the connections mean within the community, because of the
	tendency of users following people with similar interests. For example,
	the connections between users create targeted distribution networks.</pre>
<p>The connections between users create random graphs in the <i>graph theory</i> sense, where nodes are users and edges are connections between users. This is what is referred to as the <i>social graph</i>.</p>
<h2>Resource identification</h2>
<p>Out of the use cases listed above, we now need to define the service&#8217;s resources. From reading the requirements we see that we need users and messages. Users appear in two ways: a single user and a list of users. Additionally, users have the ability to post blog entries in the form of messages of no more than 140 characters. This means that we need resources for a single message and a list of messages. In sum, we identify the following resources:</p>
<ol>
<li>User</li>
<li>List of users</li>
<li>Message</li>
<li>List of messages</li>
</ol>
<h2>Representation definition</h2>
<p>As we discussed in our introduction to RESTful web services, a representation is a temporal mapping of a resource at the time of a request. Furthermore, a representation is transmitted between clients and servers over HTTP. Because of HTTP&#8217;s fl exibility, any binary stream can be transferred. Nevertheless, we don&#8217;t recommend choosing just any type of binary representation that requires special code or libraries to consume. We recommend using primarily XML and JSON structures, remembering, of course, that the requirements of the problem we&#8217;re solving dictate what representation types we must provide.</p>
<p>A well-designed RESTful web service needs to provide multiple resource representations. We can&#8217;t assume that only web browsers will be accessing our public APIs or that only the one type of client we identified in our <i>requirement gathering</i> process will use our services.</p>
<p><strong>What are the options available, then?</strong></p>
<p>Again, arriving at the ideal representation format is a matter of the design process. We need to take into account what the service is doing and what clients will be using the resources for. The safest representation format is therefore XML. This is what web services are known for: transferring XML streams over web transport protocols. More important, most programming languages already have libraries available to parse XML streams.</p>
<p>Finally, we need to account for linkability of representations. Linkability of representation means that the web services provide for resource discoverability, such that resources link to other resources (what&#8217;s currently being referred to as <b>HATEOS or Hypermedia As The Engine Of State transfer)</b>. For example, our URI for a list of users returns a structure of users with each element in the list having a direct URI to each element in the service (a link to a user).</p>
<h2>XML representations</h2>
<p>From our analysis, we identified two types of resources: users and messages. As part of the heuristics we outlined earlier, we need to define what our representation will look like. The following representations are the structures that we will have to implement when we actually code the web service.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<h3>Users</h3>
<p>We first define a user representation as follows:</p>
<pre class="brush: java; title: ; notranslate">
&lt;code&gt;&lt;user&gt;
		&lt;username&gt;&lt;/username&gt;
		&lt;password&gt;&lt;/password&gt;
		&lt;link&gt;&lt;/link&gt;
	&lt;/user&gt;&lt;/code&gt;
</pre>
<p>As part of a user resource, we store only a username and a password. The username is unique in the context of our system and is used to uniquely identify each user. The link element, which points back to the web service, is either assigned when the resource is created or a representation is built for transport (for our sample service, we let the backend create the link).</p>
<p>We now define a list of users as follows:</p>
<pre class="brush: java; title: ; notranslate">	&lt;users&gt;
		&lt;count&gt;&lt;/count&gt;
		&lt;link&gt;&lt;/link&gt;
		&lt;user&gt;
			&lt;username&gt;&lt;/username&gt;
			&lt;password&gt;&lt;/password&gt;
			&lt;link&gt;&lt;/link&gt;
		&lt;/user&gt;
		...
		&lt;user&gt;
			&lt;username&gt;&lt;/username&gt;
			&lt;password&gt;&lt;/password&gt;
			&lt;link&gt;&lt;/link&gt;
		&lt;/user&gt;
	&lt;/users&gt;</pre>
<p>This XML structure declares a list of users stored in an XML element . We use ellipses or &#8230; to show that we can have more than one user in the list.</p>
<pre class="brush: java; title: ; notranslate">	We can see here the linkability concept at play: with a list of users
	we can drill down to individual users using the link element's value.</pre>
<h3>Messages</h3>
<p>We first define a single blog entry or message as follows:</p>
<pre class="brush: java; title: ; notranslate">	&lt;message&gt;
		&lt;messageID&gt;&lt;/messageID&gt;
		&lt;content&gt;&lt;/content&gt;
		&lt;link&gt;&lt;/link&gt;
		&lt;user&gt;
			&lt;username&gt;&lt;/username&gt;
			&lt;password&gt;&lt;/password&gt;
			&lt;link&gt;&lt;/link&gt;
		&lt;/user&gt;
	&lt;/message&gt;</pre>
<p>A message needs a message id, the body of the message (the content element), and the user who posted the message. Note that depending on what we are doing with the message, we don&#8217;t pass all the resource&#8217;s information back and forth. For example, when we are creating a message at the client layer, we don&#8217;t know what the value for messageID is. Therefore, we still need to pass the message structure to the service, but our web service will know that any messageID value needs to be ignored, because, in our case, it will be created by the storage layer.</p>
<p>Finally, we define a list of messages as follows:</p>
<pre class="brush: java; title: ; notranslate">	&lt;messages&gt;
		&lt;count&gt;&lt;/count&gt;
		&lt;link&gt;&lt;/link&gt;
		&lt;message&gt;
			&lt;messageID&gt;&lt;/messageID&gt;
			&lt;content&gt;&lt;/content&gt;
			&lt;link&gt;&lt;/link&gt;
			&lt;user&gt;
				&lt;username&gt;&lt;/username&gt;
				&lt;password&gt;&lt;/password&gt;
				&lt;link&gt;&lt;/link&gt;
			&lt;/user&gt;
		&lt;/message&gt;
		...
		&lt;message&gt;
			&lt;messageID&gt;&lt;/messageID&gt;
			&lt;content&gt;&lt;/content&gt;
			&lt;link&gt;&lt;/link&gt;
			&lt;user&gt;
				&lt;username&gt;&lt;/username&gt;
				&lt;password&gt;&lt;/password&gt;
				&lt;link&gt;&lt;/link&gt;
			&lt;/user&gt;
		&lt;/message&gt;
	&lt;/messages&gt;</pre>
<p>This XML structure holds a collection of messages, and each message holds the user who posted the message.</p>
<pre class="brush: java; title: ; notranslate">	We use the XML representation type for input and output.
	Input in this case means that we send a resource representation
	to create and update the resources at the web service layer in the
	form of an XML object. Output means that a client requests an XML
	representation of a resource.</pre>
<h2>JSON representations</h2>
<p>We use the same key names for our JSON representation, and we still have only two types of resources: users and messages. Again, these structures are our specification of what we need to return for each request.</p>
<h3>Users</h3>
<p>We define a user representation as follows:</p>
<pre class="brush: java; title: ; notranslate">	{&quot;user&quot;:{&quot;username&quot;:&quot;john&quot;, &quot;password&quot;:&quot;password&quot;, &quot;link&quot;:&quot;/users/
	john&quot;}}</pre>
<p>And we define a list of users as follows (we use the &#8230; characters to show that there is more than one user in the array):</p>
<pre class="brush: java; title: ; notranslate">	{&quot;users-result&quot;:{&quot;count&quot;:&quot;6&quot;, &quot;users&quot;:[{&quot;username&quot;:&quot;john&quot;,
	&quot;password&quot;:&quot;password&quot;, &quot;link&quot;:&quot;/users/john&quot;}, ...,{&quot;username&quot;:&quot;jane&quot;,
	&quot;password&quot;:&quot;password&quot;, &quot;link&quot;:&quot;/users/jane&quot;}]}}</pre>
<p>The array for all users as a JSON structure, looks as follows:</p>
<pre class="brush: java; title: ; notranslate">	&quot;users&quot;:[{&quot;username&quot;:&quot;john&quot;, &quot;password&quot;:&quot;password&quot;, &quot;link&quot;:&quot;/users/
	john&quot;}, ...,{&quot;username&quot;:&quot;jane&quot;, &quot;password&quot;:&quot;password&quot;, &quot;link&quot;:&quot;/users/
	jane&quot;}]</pre>
<p>Once the JSON response has been evaluated with the JavaScript eval() function, similar to what we did in Chapters 2 and 3, we can then access any of the values in the structure. For example, if we need the user name of the first element on the array, we use users-result.users[0].username.</p>
<h3>Messages</h3>
<p>We now define a message representation as follows:</p>
<pre class="brush: java; title: ; notranslate">	{&quot;message&quot;:{&quot;messageID&quot;:&quot;some-id&quot;, &quot;content&quot;:&quot;some content&quot;,
	&quot;link&quot;:&quot;/messages/some-id&quot;, &quot;user&quot;:{&quot;user&quot;:{&quot;username&quot;:&quot;john&quot;,
	&quot;password&quot;:&quot;password&quot;, &quot;link&quot;:&quot;/users/john&quot;}}}</pre>
<p>And a list of messages as follows:</p>
<pre class="brush: java; title: ; notranslate">	{&quot;messages-result&quot;:{&quot;count&quot;:&quot;6&quot;, &quot;link&quot;:&quot;/messages&quot;,
	&quot;messages&quot;:[{&quot;messageID&quot;:&quot;some-id&quot;, &quot;content&quot;:&quot;some content&quot;,
	&quot;link&quot;:&quot;/messages/some-id&quot;, &quot;user&quot;:{&quot;username&quot;:&quot;john&quot;,
	&quot;password&quot;:&quot;password&quot;, &quot;link&quot;:&quot;/users/john&quot;}}, ...,{&quot;messageID&quot;:&quot;someid2&quot;,
	&quot;content&quot;:&quot;some content&quot;, &quot;link&quot;:&quot;/messages/some-id2&quot;,
	&quot;user&quot;:{&quot;username&quot;:&quot;jane&quot;, &quot;password&quot;:&quot;password&quot;, &quot;link&quot;:&quot;/users/
	jane&quot;}}]}}</pre>
<p>Each message element in the array has a user structure embedded as follows:</p>
<pre class="brush: java; title: ; notranslate">	{&quot;messageID&quot;:&quot;some-id&quot;, &quot;content&quot;:&quot;some content&quot;,
	&quot;user&quot;:{&quot;username&quot;:&quot;john&quot;, &quot;password&quot;:&quot;password&quot;, &quot;link&quot;:&quot;/users/
	john&quot;}}</pre>
<p>Once the JSON response has been evaluated with the JavaScript eval() function, we can then access the first element on the list with messages-result.messages[0]. content; if we want to get the user name of the user who posted the message, we access the value with messages-result.messages[0].user.username.</p>
<pre class="brush: java; title: ; notranslate">	Note that during implementation we'll use JSON representations only
	as response streams. This means that we won't use JSON structures to
	create or update resources at the web service layer. Although we could
	use XML and JSON to update resources at the service layer, we'll omit
	JSON for the sake of brevity.</pre>
<h2>URI definition</h2>
<p>The next step involves the definition of URIs. This is a crucial step, as the URIs define our API and it&#8217;s likely that we want to make our web service public.</p>
<p>We strive to make our APIs logical, hierarchical, and as permanent as we can. We must emphasize these three tenets, as we may have many developers depending on the services we make available. Therefore, a good API is one that doesn&#8217;t change too often and is unambiguous to use. Furthermore, the idea of RESTful APIs is that we maintain URI uniqueness and reliability of service. (For a complete discussion about this topic, see http://www.w3.org/Provider/Style/URI.)</p>
<p>The first thing we need is a web address. In our case, we assume that we&#8217;re using our development machine running on http://localhost:8080/.</p>
<pre class="brush: java; title: ; notranslate">	It's important to distinguish between a web service and a web application:
	we use web services to implement web applications, and web services
	can be, and are recommended to be, independent of web applications.
	What's more, web applications are meant to be consumed by humans,
	as opposed to web services that are intended for machine consumption.</pre>
<p>For example, a RESTful API could live under http://api. restfuljava.com/ and a web application using the API could ive under http://restfuljava.com/. Both the API and the web application should be running on independent hardware for performance reasons, but when we get to implement our sample service we run everything on the same server.</p>
<p>The nomenclature of RESTful URIs falls under the topic of URI templates and the following conventions are widely used. First, for items or identifiers that don&#8217;t change, we find the keyword to be part of the actual URI—for instance, we use users to be the URI for a list of all users. Second, we use keys or dynamic keywords to be enclosed in { and }. Applying these conventions, our URI list for users looks as follows:</p>
<ul>
<ul>
<li>http://localhost:8080/users—with the GET method, this URI returns a list of all users; with the POST method, we create a new user and the payload is a user&#8217;s XML representation; we don&#8217;t support the PUT method; finally, we don&#8217;t support the DELETE method for an entire list of users</li>
</ul>
</ul>
<ul>
<ul>
<li>http://localhost:8080/users/{username}—with the GET method, this URI returns a representation of a user with a unique identifier username; with the PUT method, it updates a user; and, with the DELETE method, it deletes a user.</li>
</ul>
</ul>
<p>And for messages, our URI list looks as follows:</p>
<ul>
<ul>
<li>http://localhost:8080/messages—with the GET method, this URI returns a list of all messages from all users; with the POST method, it creates a new message, with the message&#8217;s XML representation as the payload of the request</li>
</ul>
</ul>
<ul>
<ul>
<li>http://localhost:8080/messages/{messageID}—with the GET method, this URI returns a representation for a message with the unique identifier messageID; with the DELETE method, it deletes a message; and we don&#8217;t support the POST or PUT methods</li>
</ul>
</ul>
<ul>
<ul>
<li>http://localhost:8080/messages/users/{username}—with the GET method, this URI returns a list of all message for a user with identifier username; no POST, PUT, or DELETE methods are supported</li>
</ul>
</ul>
<pre class="brush: java; title: ; notranslate">	At the time of this writing, the URI Template specification is still under
	review. For more information, see http://tools.ietf.org/html/
	draft-gregorio-uritemplate-03.</pre>
<h2>Executing logic with RESTful URIs</h2>
<p>A question arises when designing RESTful web services that has to do with executing code at the server level. Specifically, how do we execute logic if we limit our client/server interactions to only four CRUD-like calls (POST, GET, PUT, and DELETE)? For this we need to introduce URIs that execute logic on the server,remembering that responses must be in the form of resource representations. In other<br />
words, we avoid any RPC style calls and concentrate on the resources only.</p>
<p>For our web service, we only offer the ability of searching for a term or a phrase in the blog entries. For example, any user can search for the term &#8220;programming&#8221; or&#8221; software development&#8221; using the following URI (note that the URI pattern is arbitrary and you can choose whatever makes sense for the service you are developing):</p>
<pre class="brush: java; title: ; notranslate">	http://localhost:8080/messages/search/{search_item}</pre>
<p>This URI returns a list of messages that contain the word or words search_item—this is strictly a GET method call and no POST, PUT, or DELETE method is supported.</p>
<h2>Using URIs to request representation types</h2>
<p>A RESTful web service is one that adheres to all the constraints we outlined in Chapter 1, <i>RESTful Architectures</i>. However, we have encountered APIs that don&#8217;t strictly adhere to every constraint. For example, requesting representation types via URIs is something we saw with Twitter&#8217;s API. We requested three different types of representations with the URI ttp://twitter.com/statuses/public_timeline. {xml, json, rss}.</p>
<p>We said that this is not technically a RESTful web service request, because we don&#8217;t use the communication protocol—HTTP headers—to tell the service what kind of representation to get. Even though this is not a RESTful web service, it still works. Nevertheless, the API may be open to interpretation. For example, what does it mean to send an HTTP GET request to the URI http://twitter.com/statuses/<br />
public_timeline.json with an HTTP <i>Accept</i> header value of application/xml? Do we get a JSON representation or an XML epresentation? A properly designed RESTful web service has to adhere to <i>all</i> REST constraints, and using the protocol to negotiate representations is part of being RESTful.</p>
<p>Creating a properly defined RESTful web service, however, ensures that there are no misunderstandings on how to use such services. For example, setting the HTTP method type to GET with an appropriate <i>Accept</i> header value makes it clear that we are requesting a resource of a specific type. In the end, you, as a developer or software architect, need to make a decision as to which style will benefit your users the most.</p>
<p>Using this representation request style is a design decision that facilitates—it can be argued—the writing of clients. For instance, the majority of public APIs are read only, so using a straight HTTP GET request with the type of representation embedded in the URI is easier than instantiating a full HTTP request and modifying the HTTP header <i>Accept</i> each time. Note that neither is hard to implement; however, with the former, we save a couple of lines of code at the client layer. Again, it&#8217;s a matter of choice.</p>
<pre class="brush: java; title: ; notranslate">	Our sample web service is a canonical application, thus we don't deviate
	from any of the constraints. This means that we use the HTTP protocol
	to request a preferred resource representation and not the URI style
	described in this section.</pre>
<h1>Summary</h1>
<p>As we&#8217;ve seen, the RESTful design process is resource centric. In addition, we have no arbitrary actions executing on the data—we have HTTP method calls that exchange representations using clearly defined URIs. The steps to arrive at a web service that adheres to all REST constraints are similar to traditional web application design. So we can still use all our traditional requirement <em id="__mceDel">gathering techniques, but tweak the process to account for proper design of usable </em><em id="__mceDel"><em id="__mceDel"><em id="__mceDel"><em id="__mceDel">URIs and consumable representations.</em></em></em></em></p>
<p>Now that we have our social networking web service specification defined together with a set of RESTful design principles, the next step is implementation. We have four different REST frameworks in the menu, so in the next chapter we begin with Jersey, which is the reference implementation of the Java API for RESTful Web Services Specification, more commonly known as JAX-RS.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2009/12/restful-java-web-services/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Building SOA-Based Composite Applications Using NetBeans IDE 6</title>
		<link>http://www.javabeat.net/2009/10/building-soa-based-composite-applications-using-netbeans-ide-6/</link>
		<comments>http://www.javabeat.net/2009/10/building-soa-based-composite-applications-using-netbeans-ide-6/#comments</comments>
		<pubDate>Thu, 08 Oct 2009 14:11:59 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[SOA]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=2006</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Building SOA-Based Composite Applications Using NetBeans IDE 6 Composite applications aid businesses by stitching together various componented business capabilities. In the current enterprise scenario, empowering business users to react quickly to the rapidly changing business environment is the top most priority. With the advent of composite applications the &#8216;reuse&#8217; paradigm has moved from the technical [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h1><center>Building SOA-Based Composite Applications Using NetBeans IDE 6</center></h1>
<p>Composite applications aid businesses by stitching together various<br />
componented business capabilities. In the current enterprise scenario,<br />
empowering business users to react quickly to the rapidly changing business<br />
environment is the top most priority. With the advent of composite applications<br />
the &#8216;reuse&#8217; paradigm has moved from the technical aspect to the business<br />
aspect. You no longer re-use a service but re-use a business process. Now,<br />
enterprises can define their own behaviors optimized for their businesses through<br />
metadata and flows. This business process composition has become<br />
increasingly important for constructing business logic.</p>
<p>The ability of composite applications to share components between them nullifies<br />
the distinction between actual applications. Business users should be able to<br />
move between the activities they need to do without any actual awareness that<br />
they are moving from one domain to another.</p>
<p>The composite application design enables your company to combine multiple<br />
heterogeneous technologies into a single application, bringing key application<br />
capability within reach of your business user. Enterprises creating richer<br />
composite applications by leveraging existing interoperable components increase<br />
the development organization&#8217;s ability to respond quickly and cost-effectively to<br />
emerging business requirements. While there are many vendors offering various<br />
graphical tools to create composite applications, this book will focus on<br />
OpenESB and NetBeans IDE for designing and building composite applications.</p>
<p>This book introduces basic SOA concepts and shows how you can use<br />
NetBeans and OpenESB tools to design and deploy a composite application.<br />
After introducing the SOA concepts, you are introduced to various NetBeans<br />
Editors and aids that you need to understand and work with to design a<br />
composite application. The last part of the book deals with a full fl edged<br />
incremental example on how you can build a complex composite application with<br />
necessary screen shots accompanied by the source code available on the<br />
website.</p>
<h1>What This Book Covers</h1>
<p><b><i>Chapter 1</i></b> introduces SOA and BPEL to the readers with simple examples and<br />
gives an overview of the JBI components and runtime required to build<br />
composite applications. This chapter also gives you an overview of the need for<br />
SOA-based applications in companies by depicting an example of an imaginary<br />
AirlinesAlliance system.</p>
<p><b><i>Chapter 2</i></b> shows you how you can quickly setup NetBeans IDE and other<br />
runtime environments including OpenESB runtime and BPEL engine. There are<br />
many software/tools mentioned in this chapter that you need to download and<br />
configure to get started building composite applications using NetBeans.</p>
<p><b><i>Chapter 3</i></b> provides an overview of Java Business Integration (JBI) and the<br />
Enterprise Service Bus (ESB). You will learn about JBI Service Engines and how<br />
they are supported within the NetBeans IDE.</p>
<p><b><i>Chapter 4</i></b> introduces JBI Binding Components and how they provide protocol<br />
independent communication between JBI components. You will also learn about<br />
the support that the NetBeans IDE provides for Binding Components.</p>
<p><b><i>Chapter 5</i></b> introduces the NetBeans BPEL Designer that comes bundled with the<br />
NetBeans IDE. You will also be introduced to the graphical tools/wizards and<br />
palettes available for creating BPEL files.</p>
<p><b><i>Chapter 6</i></b> provides an overview of WSDL and how WSDL documents are<br />
formed. You will learn about the use of WSDL in enterprise applications and the<br />
WSDL editor within the NetBeans IDE.</p>
<p><b><i>Chapter 7</i></b> covers the XML schema designer and shows how it aids rapid<br />
development and testing of XML schema documents.</p>
<p><b><i>Chapter 8</i></b> provides you an overview of the Intelligent Event Processor (IEP)<br />
module and the IEP Service Engine that can be acquired from the OpenESB<br />
software bundle. This chapter also shows the need for an event processing tool<br />
through simple composite application examples.</p>
<p><b><i>Chapter 9</i></b> provides details of fault handling within a BPEL process and shows<br />
how these can be managed within the NetBeans IDE by using graphical tools.</p>
<p><b><i>Chapter 10</i></b> shows you how you can build simple to complex composite<br />
applications and BPEL processes using the NetBeans IDE. The examples in this<br />
chapter are divided into several parts and the source code for all parts is<br />
available in the code bundle.</p>
<p><b><i>Chapter 11</i></b> gives you the overall picture of the composite application and the<br />
need for a composite application to deploy your BPEL processes. The composite<br />
application support provided in NetBeans IDE comes with a visual editor for<br />
adding and configuring WSDL ports and JBI modules.</p>
<h1><center>Service Engines</center></h1>
<p>In Chapter 1, we introduced the concept of SOA applications, and introduced<br />
BPEL processes and JBI applications. To gain a greater understanding of these<br />
concepts and to enable us to develop enterprise level SOA applications, we need to<br />
understand JBI in further depth, and how JBI components can be linked together.<br />
This chapter will introduce the JBI Service Engine and how it is supported within the<br />
NetBeans Enterprise Pack.</p>
<p>In this chapter, we will discuss the following topics:</p>
<ul>
<li>Need for Java Business Integration (JBI)</li>
<li>Enterprise Service Bus</li>
<li>Normalized Message Router</li>
<li>Introduction to Service Engines</li>
<li>NetBeans Support for Service Engines</li>
<li>BPEL Service Engine</li>
<li>Java EE Service Engine</li>
<li>SQL Service Engine</li>
<li>IEP Service Engine</li>
<li>XSLT Service Engine</li>
</ul>
<h1>Need for Java Business Integration (JBI)</h1>
<p>To have a good understanding of Service Engines (a specific type of JBI component),<br />
we need to first understand the reason for Java Business Integration.</p>
<p>In the business world, not all systems talk the same language. They use different<br />
protocols and different forms of communications. Legacy systems in particular can<br />
use proprietary protocols for external communication. The advent and acceptance of<br />
XML has been greatly beneficial in allowing systems to be easily integrated, but XML<br />
itself is not the complete solution.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>When some systems were first developed, they were not envisioned to be able<br />
to communicate with many other systems; they were developed with closed<br />
interfaces using closed protocols. This, of course, is fine for the system developer,<br />
but makes system integration very difficult. This closed and proprietary nature<br />
of enterprise systems makes integration between enterprise applications very<br />
difficult. To allow enterprise systems to effectively communicate between each other,<br />
system integrators would use vendor-supplied APIs and data formats or agree on<br />
common exchange mechanisms between their systems. This is fine for small short<br />
term integration, but quickly becomes unproductive as the number of enterprise<br />
applications to integrate gets larger. The following figure shows the problems with<br />
traditional integration.</p>
<p><center><img src="images/2009/10/NetBeans-IDE/1.GIF"/></center></p>
<p>As we can see in the figure, each third party system that we want to integrate with<br />
uses a different protocol. As a system integrator, we potentially have to learn new<br />
technologies and new APIs for each system we wish to integrate with. If there are<br />
only two or three systems to integrate with, this is not really too much of a problem.<br />
However, the more systems we wish to integrate with, the more proprietary code we<br />
have to learn and integration with other systems quickly becomes a large problem.</p>
<p>To try and overcome these problems, the Enterprise Application Integration (EAI)<br />
server was introduced. This concept has an integration server acting as a central<br />
hub. The EAI server traditionally has proprietary links to third party systems, so the<br />
application integrator only has to learn one API (the EAI server vendors). With this<br />
architecture however, there are still several drawbacks. The central hub can quickly<br />
become a bottleneck, and because of the <b>hub-and-spoke</b> architecture, any problems<br />
at the hub are rapidly manifested at all the clients.</p>
<h1>Enterprise Service Bus</h1>
<p>To help solve this problem, leading companies in the integration community<br />
(led by Sun Microsystems) proposed the Java Business Integration Specification<br />
Request (JSR 208) (Full details of the JSR can be found at http://jcp.org/en/jsr/<br />
detail?id=208). JSR 208 proposed a standard framework for business integration<br />
by providing a standard set of service provider interfaces (SPIs) to help alleviate the<br />
problems experienced with Enterprise Application Integration.</p>
<p>The standard framework described in JSR 208 allows pluggable components to be<br />
added into a standard architecture and provides a standard common mechanism for<br />
each of these components to communicate with each other based upon WSDL. The<br />
pluggable nature of the framework described by JSR 208 is depicted in the following<br />
figure. It shows us the concept of an Enterprise Service Bus and introduces us to the<br />
Service Engine (SE) component:</p>
<p><center><img src="images/2009/10/NetBeans-IDE/2.GIF"/></center></p>
<p>JSR 208 describes a service engine as a component, which provides business<br />
logic and transformation services to other components, as well as consuming<br />
such services. SEs can integrate Java-based applications (and other resources), or<br />
applications with available Java APIs.</p>
<p>
<pre><code>
	Service Engine is a component which provides (and consumes) business
	logic and transformation services to other components. There are
	various Service Engines available, such as the BPEL service engine
	for orchestrating business processes, or the Java EE service engine for
	consuming Java EE Web Services. We will discuss some of the more
	common Service Engines later in this chapter.
</code></pre>
</p>
<h1>The Normalized Message Router</h1>
<p>As we can see from the previous figure, SE&#8217;s don&#8217;t communicate directly with each<br />
other or with the clients, instead they communicate via the NMR. This is one of the<br />
key concepts of JBI, in that it promotes loose coupling of services.</p>
<p>So, what is NMR and what is its purpose? NMR is responsible for taking messages<br />
from clients and routing them to the appropriate Service Engines for processing.<br />
(This is not strictly true as there is another standard JBI component called the Binding<br />
Component responsible for receiving client messages. Binding Components are<br />
discussed in Chapter 4. Again, this further enhances the support for loose coupling<br />
within JBI, as Service Engines are decoupled from their transport infrastructure).</p>
<p>NMR is responsible for passing normalized (that is based upon WSDL) messages<br />
between JBI components. Messages typically consist of a payload and a message<br />
header which contains any other message data required for the Service Engine to<br />
understand and process the message (for example, security information). Again, we<br />
can see that this provides a loosely coupled model in which Service Engines have no<br />
prior knowledge of other Service Engines. This therefore allows the JBI architecture<br />
to be flexible, and allows different component vendors to develop standard<br />
based components.</p>
<p>
<pre><code>
	Normalized Message Router enables technology for allowing messages to
	be passed between loosely coupled services such as Service Engines.
</code></pre>
</p>
<p>The figure below gives an overview of the message routing between a client<br />
application and two service engines, in this case the EE and SQL service engines.</p>
<p><center><img src="images/2009/10/NetBeans-IDE/3.GIF"/></center></p>
<p>In this figure, a request is made from the client to the JBI Container. This request<br />
is passed via NMR to the EE Service Engine. The EE Service Engine then makes<br />
a request to the SQL Service Engine via NMR. The SQL Service Engine returns a<br />
message to the EE Service Engine again via NMR. Finally, the message is routed back<br />
to the client through NMR and JBI framework. The important concept here is that<br />
NMR is a message routing hub not only between clients and service engines, but also<br />
for intra-communication between different service engines.</p>
<p>The entire architecture we have discussed is typically referred to as an Enterprise<br />
Service Bus.</p>
<p>
<pre><code>
	<i>Enterprise Service Bus (ESB)</i> is a standard-based middleware architecture
	that allows pluggable components to communicate with each other via a
	messaging subsystem.
</code></pre>
</p>
<p>Now that we have a basic understanding of what a Service Engine is, how<br />
communication is made between application clients and Service Engines, and<br />
between Service Engines themselves, let&#8217;s take a look at what support the NetBeans<br />
IDE gives us for interacting with Service Engines.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2009/10/building-soa-based-composite-applications-using-netbeans-ide-6/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What is XPath?</title>
		<link>http://www.javabeat.net/2009/04/what-is-xpath/</link>
		<comments>http://www.javabeat.net/2009/04/what-is-xpath/#comments</comments>
		<pubDate>Fri, 03 Apr 2009 14:54:47 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=2225</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Processing XML documents with Oracle JDeveloper 11g While a number of books on XML are available, none covers XML support in Oracle JDeveloper. Welcome to Processing XML documents with Oracle JDeveloper 11g, a book that will teach you about using Oracle XML technologies in Oracle JDeveloper. XML is the standard medium of data exchange. Examples of data exchange using [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><strong>Processing XML documents with Oracle JDeveloper 11g</strong></p>
<p>While a number of books on XML are available, none covers XML support in Oracle JDeveloper. Welcome to <i>Processing XML documents with Oracle JDeveloper 11g</i>, a book that will teach you about using Oracle XML technologies in Oracle JDeveloper. XML is the standard medium of data exchange. Examples of data exchange using XML are web feeds, which include RSS feeds and Atom feeds, and XML messages in web services. Java is the language most commonly used to process XML.</p>
<p>Among the IDEs, Oracle JDeveloper has the most XML features. Some of the graphical XML features in JDeveloper are an XML editor to create an XML document, an XML schema editor to model an XML schema, and an XPath explorer to process XPath expressions. JDeveloper also provides built-in support for JAXB compilation. JDeveloper includes an integrated application server—the WebLogic Server—for running XML-based applications. Oracle <b>XML Developer Kit (XDK)</b> provides a set of components, tools, and utilities for developing XML-based applications. The XDK 11g libraries are included with Oracle JDeveloper 11g.</p>
<p>The objective of this book is to discuss XML development in Oracle JDeveloper. We shall use JDeveloper 11g, the latest version of JDeveloper. As developers commonly use an IDE for processing XML and developing XML applications, the book covers all aspects of XML development, which include:</p>
<ul>
<li>Creating an XML document</li>
<li>Validating an XML document with an XML schema</li>
<li>Transforming an XML document</li>
<li>Addressing elements/attributes in an XML document using XPath</li>
</ul>
<p>We shall use the Oracle XDK 11g for Java to develop XML applications. We shall also discuss Oracle XML Publisher and Oracle Berkeley DB XML. By the end of this book, you should know everything there is to know about XML and JDeveloper.</p>
<p><strong>What This Book Covers</strong></p>
<p><i>Chapter 1</i>: We discuss creating an XML document using Oracle&#8217;s <b>XML Developer Kit (XDK)</b> 11g in Oracle JDeveloper. We also discuss parsing an XML document using SAX and DOM Java APIs, which are also included in XDK 11g.</p>
<p><i>Chapter 2</i>: We create an XML schema in the XML schema editor of Oracle JDeveloper. An XML schema represents the structure of an XML document. Subsequently, we instantiate an XML document from the XML schema.</p>
<p><i>Chapter 3</i>: We discuss validating an XML document with an XML schema using the built-in feature to validate the schema and the XDK 11g schema validation APIs. We discuss three different APIs for schema validation: the XSDValidator, the SAX parser, and the DOM parser.</p>
<p><i>Chapter 4</i>: We discuss XPath, which is used to address nodes in an XML document. We use XPath in the XPath Search GUI tool in Oracle JDeveloper 11g. We also use the XPath Java API in XDK 11g.</p>
<p><i>Chapter 5</i>: We transform an XML document using the Transformation API for XML (TrAX), which is included in XDK 11g. We also discuss the XSLT extension functions.</p>
<p><i>Chapter 6</i>: We parse and transform XML using the JSTL XML tag library in JDeveloper 11g.</p>
<p><i>Chapter 7</i>: We load, save, and filter an XML document using the DOM 3.0 Load and Save APIs, which are provided in XDK 11g.</p>
<p><i>Chapter 8</i>: We construct and validate an XML document using the DOM 3.0 Validation API, which is also included in XDK 11g.</p>
<p><i>Chapter 2</i>: We discuss another built-in feature of JDeveloper 11g, the JAXB 2.0 compiler. We bind an XML schema to Java classes using the JAXB 2.0 compiler. Subsequently, we unmarshal an XML document and marshal an XML document using the compiled Java classes.</p>
<p><i>Chapter 10</i>: We compare XML documents using the XMLDiff Java API included in XDK 11g.</p>
<p><i>Chapter 11</i>: We convert an XML document to a PDF document using the Apache FOP Java API in JDeveloper.</p>
<p><i>Chapter 12</i>: We create an MS Excel spreadsheet from an XML document in JDeveloper using the Apache POI Java API.</p>
<p><i>Chapter 13</i>: We store an XML document in Oracle Berkeley DB XML, and subsequently query and update the XML document using both the Berkeley DB XML command shell and the Berkeley DB XML Java API. The Berkeley DB XML API is used in JDeveloper 11g.</p>
<p><i>Chapter 14</i>: We create PDF reports in JDeveloper 11g using the Oracle XML Publisher Java API. We also merge PDF documents. We also create an XML report from a database table using the Data Engine API.</p>
<h2 style="text-align: center;"><span style="text-decoration: underline;"><span style="color: #000080; text-decoration: underline;">What is XPath?</span></span></h2>
<p>As mentioned in the earlier chapters, XML documents can be used for the transfer of data. The data in an XML document may be retrieved either with the <b>JAXP (Java API for XML Processing)</b> DOM and SAX APIs, or with the JAXP XPath API. Addressing<br />
an XML document with XPath has the advantage that a single node may be selected directly without iterating over a node set. With SAX and DOM APIs, node lists have to be iterated over to access a particular node. Another advantage of navigating an XML document with XPath is that an attribute node may be selected directly. With DOM and SAX APIs, an element node has to be selected before an element attribute can be selected. In this chapter we shall discuss XPath support in JDeveloper.</p>
<h2>What is XPath?</h2>
<p>XPath is a language for addressing an XML document&#8217;s elements and attributes. As an example, say you receive an XML document that contains the details of a shipment and you want to retrieve the element/attribute values from the XML document. You don&#8217;t just want to list the values of all the nodes, but also want to output the values of specific elements or attributes. In such a case, you would use<br />
XPath to retrieve the values of those elements and attributes. XPath constructs a hierarchical structure of an XML document, a tree of nodes, which is the XPath data model. The XPath data model consists of seven node types. The different types of nodes in the XPath data model are discussed in the following table:</p>
<table border="1">
<tbody>
<tr>
<th>Node</th>
<th>Type Description</th>
</tr>
<tr>
<td>Root Node</td>
<td>The root node is the root of the DOM tree. The document element<br />
(the root element) is a child of the root node. The root node also<br />
has the processing instructions and comments as child nodes.</td>
</tr>
<tr>
<td>Element Node</td>
<td>This represents an element in an XML document. The character<br />
data, elements, processing instructions, and comments within an<br />
element are the child nodes of the element node.</td>
</tr>
<tr>
<td>Attribute Node</td>
<td>This represents an attribute other than the xmlns-prefixed<br />
attribute, which declares a namespace.</td>
</tr>
<tr>
<td>Text Node</td>
<td>The character data within an element is a text node. A text<br />
node has at least one character of data. A whitespace is also<br />
considered as a character of data. By default, the ignorable<br />
whitespace after the end of an element and before the start of the<br />
following element is also a text node. The ignorable whitespace<br />
can be excluded from the DOM tree built by parsing an XML<br />
document. This can be done by setting the whitespace-preserving<br />
mode to false with the setPreserveWhitespace(boolean<br />
flag) method.</td>
</tr>
<tr>
<td>Comment Node</td>
<td>This represents a comment in an XML document, except the<br />
comments within the DOCTYPE declaration.</td>
</tr>
<tr>
<td>Processing Instruction Node</td>
<td>This represents a processing instruction in an XML document<br />
except the processing instruction within the DOCTYPE<br />
declaration. The XML declaration is not considered as a<br />
processing instruction node.</td>
</tr>
<tr>
<td>Namespace Node</td>
<td>This represents a namespace mapping, which consists of a<br />
xmlns:-prefixed attribute such as xmlns:xsd=&#8221;http://www.<br />
w3.org/2001/XMLSchema&#8221;. A namespace node consists of a<br />
namespace prefix (xsd in the example) and a namespace URI<br />
(http://www.w3.org/2001/XMLSchema in the example).</td>
</tr>
</tbody>
</table>
<p>Specific nodes including element, attribute, and text nodes may be accessed with XPath. XPath supports nodes in a namespace. Nodes in XPath are selected with an XPath expression. An expression is evaluated to yield an object of one of the following four types: node set, Boolean, number, or string.</p>
<pre class="brush: java; title: ; notranslate">	For an introduction on XPath refer to the &lt;i&gt;W3C Recommendation for
	XPath&lt;/i&gt; (http://www.w3.org/TR/xpath). As a brief review,
	expression evaluation in XPath is performed with respect to a &lt;b&gt;context
	node&lt;/b&gt;. The most commonly used type of expression in XPath is a &lt;b&gt;location
	path&lt;/b&gt; . XPath defines two types of location paths: &lt;b&gt;relative location paths&lt;/b&gt;
	and &lt;b&gt;absolute location paths&lt;/b&gt;. A relative location path is defined with
	respect to a context node and consists of a sequence of one or more
	location steps separated by &quot;/&quot;. A &lt;b&gt;location step&lt;/b&gt; consists of an &lt;b&gt;axis&lt;/b&gt;, a
	&lt;b&gt;node test&lt;/b&gt;, and &lt;b&gt;predicates&lt;/b&gt;.
</pre>
<p>An example of a location step is:</p>
<pre class="brush: java; title: ; notranslate">	child::journal[position()=2]
</pre>
<p>In the example, the child axis contains the child nodes of the context node. Node test is the journal node set, and predicate is the second node in the journal node set. An absolute location path is defined with respect to the root node, and starts with &#8220;/&#8221;. The difference between a relative location path and an absolute location path is that a relative location path starts with a location step, and an absolute location path starts with &#8220;/&#8221;.</p>
<h2>XPath support in Oracle XDK 11g</h2>
<p>As we discussed in Chapter 1, Oracle XML Developer&#8217;s Kit 11g, which is included in JDeveloper, provides the DOMParser class to parse an XML document and construct a DOM structure of the XML document. An XMLDocument object represents the DOM structure of an XML document. An XMLDocument object may be retrieved from a DOMParser object after an XML document has been parsed. The XMLDocument class provides select methods to select nodes in an XML document with an XPath expression.</p>
<p>In this chapter we shall parse an example XML document with the DOMParser class, obtain an XMLDocument object for the XML document, and select nodes from the document with the XMLDocument class select methods. The different select methods in the XMLDocument class are discussed in the following table:</p>
<table border="1">
<tbody>
<tr>
<th>Method Name</th>
<th>Description</th>
</tr>
<tr>
<td>selectSingleNode(String<br />
XPathExpression)</td>
<td>Selects a single node that matches an XPath expression.<br />
If more than one node matches the specified<br />
expression, the first node is selected. Use this method<br />
if you want to select the first node that matches an<br />
XPath expression.</td>
</tr>
<tr>
<td>selectNodes(String<br />
XPathExpression)</td>
<td>Selects a node list of nodes that match a specified<br />
XPath expression. Use this method if you want to select<br />
a collection of similar nodes.</td>
</tr>
<tr>
<td>selectSingleNode(String<br />
XPathExpression,<br />
NSResolver resolver)</td>
<td>Selects a single namespace node that matches a<br />
specified XPath expression. Use this method if the XML<br />
document has nodes in namespaces and you want to<br />
select the first node that is in a namespace and matches<br />
an XPath expression.</td>
</tr>
<tr>
<td>selectNodes(String<br />
XPathExpression,<br />
NSResolver resolver)</td>
<td>Selects a node list of nodes that match a specified<br />
XPath expression. Use this method if you want to select<br />
a collection of similar nodes that are in a namespace.</td>
</tr>
</tbody>
</table>
<p>The example XML document that is parsed in this chapter has a namespace declaration mlns:journal=&#8221;http://www.xdk11g.com/xpath&#8221; for elements in the namespace with the prefix journal. For an introduction on namespaces in XML refer to the <i>W3C Recommendation on Namespaces in XML 1.0</i> (http://www.w3.org/ TR/REC-xml-names/). catalog.xml, the example XML document, is shown in the<br />
following listing:</p>
<pre class="brush: java; title: ; notranslate">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;catalog xmlns:journal=&quot;http://www.xdk11g.com/xpath&quot;
		title=&quot;Oracle Magazine&quot; publisher=&quot;Oracle Publishing&quot;&gt;
   &lt;journal:journal journal:date=&quot;November-December 2008&quot;&gt;
	  &lt;journal:article journal:section=&quot;ORACLE DEVELOPER&quot;&gt;
		 &lt;title&gt;Instant ODP.NET Deployment&lt;/title&gt;
		 &lt;author&gt;Mark A. Williams&lt;/author&gt;
	  &lt;/journal:article&gt;
	  &lt;journal:article journal:section=&quot;COMMENT&quot;&gt;
		 &lt;title&gt;Application Server Convergence&lt;/title&gt;
		 &lt;author&gt;David Baum&lt;/author&gt;
	  &lt;/journal:article&gt;
   &lt;/journal:journal&gt;
   &lt;journal date=&quot;March-April 2008&quot;&gt;
	  &lt;article section=&quot;TECHNOLOGY&quot;&gt;
		 &lt;title&gt;Oracle Database 11g Redux&lt;/title&gt;
		 &lt;author&gt;Tom Kyte&lt;/author&gt;
	  &lt;/article&gt;
	  &lt;article section=&quot;ORACLE DEVELOPER&quot;&gt;
		 &lt;title&gt;Declarative Data Filtering&lt;/title&gt;
		 &lt;author&gt;Steve Muench&lt;/author&gt;
	  &lt;/article&gt;
   &lt;/journal&gt;
&lt;/catalog&gt;
</pre>
<h2>Setting the environment</h2>
<p>Create an application (called XPath, for example) and a project (called XPath) in JDeveloper as explained in the earlier chapters. The XPath API will be demonstrated in a Java application. Therefore, create a Java class in the XPath project with <b>File|New</b>. In the <b>New Gallery</b> window select <b>Categories|General </b>and Items|Java Class. In the Create Java Class window, specify the class name<br />
(<b>XPathParser</b>, for example), the package name (<b>xpath</b> in the example application), and click on the <b>OK</b> button.</p>
<p>To develop an application with XPath, add the required libraries to the project classpath. Select the project node in <b>Application Navigator</b> and select <b>Tools|Project Properties</b>. In the <b>Project Properties</b> window, select the <b>Libraries and Classpath</b><br />
node. To add a library, select the <b>Add Library</b> button. Select the <b>Oracle XML Parser v2</b> library. Click on the <b>OK</b> button in the <b>Project Properties</b> window. We also need to add an XML document that is to be parsed and navigated with XPath.</p>
<p>To add an XML document, select <b>File|New</b>. In the <b>New Gallery</b> window, select <b>Categories|General|XML</b> and <b>Items|XML Document</b>. Click on the <b>OK</b> button. In the <b>Create XML File</b> window specify the file name catalog.xml in the <b>File Name </b>field, and click on the <b>OK</b> button. Copy the catalog.xml listing to the <b>catalog.xml </b>file in the <b>Application Navigator</b>. The directory structure of the XPath project is shown in the following illustration:</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-1.bmp"><img class="aligncenter size-full wp-image-6697" alt="xpath-1" src="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-1.bmp" /></a></p>
<h2>XPath search</h2>
<p>In this section, we shall select nodes from the example XML document, catalog.xml, with the <b>XPath Search</b> tool of JDeveloper 11g. The <b>XPath Search</b> tool consists of an <b>Expression</b> field for specifying an XPath expression. Specify an XPath expression and click on <b>OK</b> to select nodes matching the XPath expression. The <b>XPath Search</b> tool has the provision to search for nodes in a specific namespace. An XML namespace is a collection of element and attribute names that are identified by a URI reference. Namespaces are specified in an XML document using namespace declarations. A namespace declaration is an xmlns-prefixed attribute in an element<br />
that consists of a namespace prefix in the attribute name with the namespace URI as the attribute value.</p>
<p>If you want to select nodes in a specific namespace or nodes from different namespaces, first add the namespace <b>Prefix</b> and <b>URI</b> to the <b>XPath Search</b> tool using the <b>Add</b> button. Subsequently, include namespace prefixes in the XPath expression. The <b>XPath Search</b> tool is shown here:</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-2.bmp"><img class="aligncenter size-full wp-image-6698" alt="xpath-2" src="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-2.bmp" /></a></p>
<p>To navigate catalog.xml with XPath, select catalog.xml in the Application Navigator and select Search|XPath Search.</p>
<p style="text-align: center;"><a href="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-3.bmp"><img class="aligncenter  wp-image-6699" alt="xpath-3" src="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-3.bmp" width="466" height="291" /></a></p>
<p>In the following subsections, we shall select example nodes using absolute location paths and relative location paths. Use a relative location path if the XML document is large and a specific node is required. Also, use a relative path if the node from which subnodes are to be selected and the relative location path are known. Use an absolute location path if the XML document is small, or if the relative location path is not known. The objective is to use minimum XPath navigation. Use the minimum number nodes to navigate in order to select the required node.</p>
<h2>Selecting nodes with absolute location paths</h2>
<p>Nex t, we shall demonstrate with various examples of selecting nodes using XPath. As an example, select all the title elements in catalog.xml. Specify the XPath expression for selecting the title elements in the <b>Expression</b> field of the <b>Apply an XPath Expression on catalog.xml</b> window. The XPath expression to select all title elements is <b>/catalog/journal/article/title</b>. Click on the <b>OK</b> button to select the title elements.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-4.bmp"><img class="aligncenter size-full wp-image-6700" alt="xpath-4" src="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-4.bmp" /></a></p>
<p>The title elements get selected. Title elements from the journal:article elements in the journal namespace do not get selected because a namespace has not been applied to the XPath expression.</p>
<p style="text-align: center;"><a href="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-5.bmp"><img class="aligncenter  wp-image-6701" alt="xpath-5" src="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-5.bmp" width="374" height="215" /></a></p>
<p>As an other example, select the title element in the first article element using the XPath expression /<b>catalog/journal/article[1]/title</b>. We are not using namespaces yet. The XPath expression is specified in the <b>Expression</b> field.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p><a href="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-6.bmp"><img class="aligncenter size-full wp-image-6702" alt="xpath-6" src="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-6.bmp" /></a></p>
<p>The title of the first article element gets selected as shown in the JDeveloper output:</p>
<p style="text-align: center;"><a href="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-7.bmp"><img class="aligncenter  wp-image-6703" alt="xpath-7" src="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-7.bmp" width="376" height="230" /></a></p>
<p>Attribu te nodes may also be selected with XPath. Attributes are selected by using the &#8221;@&#8221; prefix. As an example, select the section attribute in the first article element in the journal element. The XPath expression for selecting the section attribute is<br />
<b>/catalog/journal/article[1]/@section</b> and is specified in the <b>Expression field</b>. Click on the <b>OK</b> button to select the section attribute.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-8.bmp"><img class="aligncenter size-full wp-image-6704" alt="xpath-8" src="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-8.bmp" /></a></p>
<p>The attr ibute section gets outputted in JDeveloper.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-9.bmp"><img class="aligncenter size-full wp-image-6705" alt="xpath-9" src="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-9.bmp" /></a></p>
<h2>Selecting nodes with relative location paths</h2>
<p>In the pr evious examples, an absolute location is used to select nodes. Next, we shall demonstrate selecting an element with a relative location path. As an example, select the title of the first article element in the journal element. The relative location path for selecting the title element is <b>child::catalog/journal/article[position()=1]/ title</b>. Specifying the axis as child and node test as catalog selects all the child nodes of the catalog node and is equivalent to an absolute location path that starts with /catalog. If the child nodes of the journal node were required to be selected, specify the node test as journal. Specify the XPath expression in the <b>Expression</b><br />
field and click on the <b>OK</b> button.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-10.bmp"><img class="aligncenter size-full wp-image-6706" alt="xpath-10" src="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-10.bmp" /></a></p>
<p>The title of the first article element in the journal element gets selected as shown here:</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-11.bmp"><img class="aligncenter size-full wp-image-6707" alt="xpath-11" src="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-11.bmp" /></a></p>
<h2>Selecting namespace nodes</h2>
<p>XPath Searc h also has the provision to select elements and attributes in a namespace.To illustrate, select all the title elements in the journal element (that is, in the journal namespace) using the XPath expression <b>/catalog/journal:journal/journal:<br />
article/title</b>. First, add the namespaces of the elements and attributes to be selected in the <b>Namespaces</b> text area. Prefix and URI of namespaces are added with the <b>Add</b> button. Specify the prefix in the <b>Prefix</b> column, and the URI in the <b>URI </b>column. Multiple namespace mappings may be added. XPath expressions that select namespace nodes are similar to no-namespace expressions, except that the namespace prefixes are included in the expressions. Elements in the default namespace, which does not have a namespace prefix, are also considered to be in a namespace. Click on the <b>OK</b> button to select the nodes with XPath.</p>
<p style="text-align: center;"><a href="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-12.bmp"><img class="aligncenter  wp-image-6708" alt="xpath-12" src="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-12.bmp" width="435" height="275" /></a></p>
<p>The title elements in the journal element (in the journal namespace) get selected and outputted in JDeveloper.</p>
<p>Attributes in a namespace may also be selected with <b>XPath Search</b>. As an example, select the section attributes in the journal namespace. Specify the XPath expression to select the section attributes in the <b>Expression</b> field and click on the <b>OK</b> button.</p>
<p>Section attributes in the journal namespace get selected.</p>
<h2>Selecting nodes with XPath API</h2>
<p>In the previous section, XML document nodes were selected automatically with the <b>XPath Search</b> tool in JDeveloper. In this section, we shall select nodes with the XPath API in the <b>XPathParser</b> class. JDeveloper XPath searches with the XPath Search tool are for the convenience of the developer as they find nodes faster than when looking through the XML file. The XPath searches, using the XPath API, actually let your application find nodes via XPath.</p>
<p>The XMLDocument class has select methods to select nodes with an XPath expression. A single node may be selected or a NodeList of nodes may be selected. Nodes declared in a namespace may also be selected. First, we need to import the oracle.xml.parser.v2 package that has the XMLDocument class and the parser class DOMParser, from which an XMLDocument may be obtained.</p>
<pre class="brush: java; title: ; notranslate">	import oracle.xml.parser.v2.*;
</pre>
<h2>Creating the DOM parser</h2>
<p>Next, we need t o parse an XML document and create a DOM structure for the XML document before being able to select nodes with XPath. Therefore, create a DOMParser using:</p>
<pre class="brush: java; title: ; notranslate">	DOMParser domParser=new DOMParser();</pre>
<p>The DOMParser class, which extends the XMLParser class, has overloaded the parse methods to parse an XML document from different input sources. An XML document may be parsed from InputSource, InputStream, Reader, String, or URL. In the example application XPathParser.java, we shall parse an example document from a FileReader.</p>
<p>Create a FileReader object from a File object and parse it with the parse(Reader) method as shown in the following listing:</p>
<pre class="brush: java; title: ; notranslate">	domParser.parse(new FileReader(xmlDocument));</pre>
<p>Variable xmlDocument is the File representation of the XML document catalog.xml. The class that provides XPath functionality is XMLDocument. Obtain an XMLDocument object from the DOMParser object with the getDocument() method.</p>
<pre class="brush: java; title: ; notranslate">	XMLDocument document=domParser.getDocument();</pre>
<h2>Method selectS ingleNode(String)</h2>
<p>The XMLDocument class method selectSingleNode(String) selects a single node specified by an XPath expression. If more than one nodes match the XPath expression, the first node that matches the XPath expression gets selected. As an example, select the title of the first article node with section attribute value ORACLE DEVELOPER. The title element is selected with the selectSingleNode(String) method as shown here:</p>
<pre class="brush: java; title: ; notranslate">	XMLNode titleNode=(XMLNode)document.selectSingleNode(&quot;/catalog/
	journal/article[@section='ORACLE DEVELOPER']/title&quot;);
</pre>
<p>The title element value may be selected by first selecting the text node in the title element node using the getFirstChild() method and subsequently selecting the text node value using the getNodeValue() method, as shown in the following listing:</p>
<pre class="brush: java; title: ; notranslate">	String title=titleNode.getFirstChild().getNodeValue();
</pre>
<p>As another example of the selectSingleNode(String) method, select the author of the article with the title Oracle Database 11g Redux, as shown here:</p>
<pre class="brush: java; title: ; notranslate">	XMLNode authorNode=(XMLNode)document.selectSingleNode(&quot;/catalog/
	journal/article[title= Oracle Database 11g Redux']/author&quot;);
</pre>
<p>The author element text value is outputted by first selecting the text node within the author element node using the getFirstChild() method and subsequently selecting the text node value using the getNodeValue() method, as shown here:</p>
<pre class="brush: java; title: ; notranslate">	String author=authorNode.getFirstChild().getNodeValue();
</pre>
<p>The XMLDocument class selectSingleNode(String) may also be used to select an attribute node. As an example, select the section attribute of the second article in the journal of date March-April 2008:</p>
<pre class="brush: java; title: ; notranslate">	XMLNode sectionNode=(XMLNode)document.selectSingleNode(&quot;/catalog/
	journal[@date=March-April 2008]/article[2]/@section&quot;);
</pre>
<p>The section node value may be selected with the getNodeValue() method:</p>
<pre class="brush: java; title: ; notranslate">	String section=sectionNode.getNodeValue();
</pre>
<p>Method selectNodes(String)</p>
<p>The XMLDocument class method selectNodes(String XPathExpression) selects all the nodes specified by an XPath expression. As an example, select all the title elements for the journal of date March-April 2008, as shown in the following listing:</p>
<pre class="brush: java; title: ; notranslate">	NodeList nodeList=document.selectNodes(&quot;/catalog/journal[@date='March-
	April 2008']/article/title&quot;);
</pre>
<p>The method selectNodes(String) returns a NodeList that may be iterated over to output title elements:</p>
<pre class="brush: java; title: ; notranslate">	for(int i=0; i&lt;nodeList.getLength(); i++){
	   titleNode=(XMLElement)nodeList.item(i);
	   title=titleNode.getFirstChild().getNodeValue();
	   System.out.println(title);
	}
</pre>
<p>The method selectNodes(String) may also be used to select attribute nodes. For example, select all the section attributes for the articles in the journal of date March-April 2008:</p>
<pre class="brush: java; title: ; notranslate">	NodeList
	nodeList=document.selectNodes(&quot;/catalog/journal[@date='March- April
	2008]/article/@section&quot;);
</pre>
<p>The NodeList of section nodes may be iterated over to output section node values as shown in the following listing:</p>
<pre class="brush: java; title: ; notranslate">	for(int i=0; i&lt;nodeList.getLength(); i++){
	   XMLNode sectionNode=(XMLNode)nodeList.item(i);
	   String section=sectionNode.getNodeValue();
	   System.out.println(section+&quot; &quot;);
	}
</pre>
<h2>Method selectSingleNode(String,NSResolver)</h2>
<p>The XMLDocument class method selectSingleNode(String XSLPattern, NSResolver resolver) selects a single node specified by an XPath expression. NSResolver is used to resolve any namespace prefixes that may occur in the XPath expression.</p>
<p>To select nodes in a namespace, create a class (for example, CustomNSResolver) that implements the NSResolver interface. In the implementation class, implement the NSResolver method resolveNamespacePrefix(String prefix) as shown in the following listing:</p>
<pre class="brush: java; title: ; notranslate">	class CustomNSResolver implements NSResolver{
	   public java.lang.String resolveNamespacePrefix(java.lang.String
	   prefix){
	      if(prefix.equals(&quot;journal&quot;)){
		 return new String(&quot;http://www.xdk11g.com/xpath&quot;);
	      }
	   }
	}
</pre>
<p>The resolveNamespacePrefix method accepts a prefix and returns a URI.Create an NSResolver object. Set the namespace prefix to resolve using the resolveNamespacePrefix method:</p>
<pre class="brush: java; title: ; notranslate">	CustomNSResolver resolver=new CustomNSResolver();
	resolver.resolveNamespacePrefix(&quot;journal&quot;);
</pre>
<p>In the example XML document, catalog.xml, one of the journal elements is in the journal namespace. As an example, select the section attribute in the journal namespace in the first article element (in journal namespace) in the journal element (in journal namespace). The section attribute value will be outputted with the getNodeValue() method, as shown in the following listing:</p>
<pre class="brush: java; title: ; notranslate">	XMLNode sectionNode= (XMLNode)document.selectSingleNode(&quot;/catalog/
	journal:journal/journal:article/@journal:section&quot;, resolver);
	section=sectionNode.getNodeValue();
</pre>
<p>As a contrast b etween the selectSingleNode method that takes an NSResolver and the selectSingleNode method that doesn&#8217;t, the method that doesn&#8217;t take an NSResolver does not select nodes in a namespace. On the other hand, the one thatdoes selects nodes in a namespace. If the method that does not take an NSResolver is invoked with an XPath expression containing namespace nodes, the following error is generated:</p>
<pre class="brush: java; title: ; notranslate">	XSLException Namespace prefix 'journal' used but not declared.
</pre>
<h2>Method selectNodes(String,NSResolver)</h2>
<p>The XMLDocument class method selectNodes(String XPathExpression, NSResolver resolver) selects all the namespace nodes resolved by an NSResolver that are specified in an XPath expression. NSResolver is used to resolve any prefixes that may occur in the XPath expression. For example, select all the title elements in journal (in journal namespace) of date (in journal namespace) November-December 2008, as shown in the following listing:</p>
<pre class="brush: java; title: ; notranslate">	NodeList nodeList=document.selectNodes(&quot;/catalog/journal:journal[@
	journal:date='November-December 2008']/journal:article/title&quot;,
	resolver );
</pre>
<p>The namespace prefix journal in the XPath expression is resolved with an NSResolver object. The NodeList returned by the selectNodes(String, NSResolver) method may be iterated over to output the title elements.</p>
<pre class="brush: java; title: ; notranslate">	for(int i=0; i&lt;nodeList.getLength(); i++){
	   titleNode=(XMLElement)nodeList.item(i);
	   title=titleNode.getFirstChild().getNodeValue();
	   System.out.println(title);
	}
</pre>
<h2>Running the Java application</h2>
<p>The Java progra m XPathParser.java is used to select nodes from the XML document catalog.xml. The Java application is listed with additional explanations about the application as follows:</p>
<ol>
<li>First, we import the required packages from XDK 11g.
<pre class="brush: java; title: ; notranslate">	import oracle.xml.parser.v2.*;
	import java.io.*;
	import org.xml.sax.SAXException;
	import org.w3c.dom.*;
</pre>
</li>
<li>Next, we add the XPathParser Java class declaration.
<pre class="brush: java; title: ; notranslate">	public class XPathParser{
</pre>
</li>
<li>We define the parseDocument method to parse an XML document with the DOMParser.</li>
</ol>
<pre class="brush: java; title: ; notranslate">	public void parseDocument(File xmlDocument){
	   try{
</pre>
<ul>
<li>Next, we create a DOMParser object and parse the XML document.
<pre class="brush: java; title: ; notranslate">	DOMParser domParser=new DOMParser();
	domParser.parse(new FileReader(xmlDocument));
	XMLDocument document=domParser.getDocument();
</pre>
</li>
<li>We specify the NSResolver object to resolve namespaces.
<pre class="brush: java; title: ; notranslate">	CustomResolver resolver=new CustomResolver();
	resolver.resolveNamespacePrefix(&quot;journal&quot;);
</pre>
</li>
<li>Next, we select nodes using the selectSingleNode(String) method.
<pre class="brush: java; title: ; notranslate">	XMLNodetitleNode=(XMLNode)document.selectSingleNode
	(&quot;/catalog/journal/article[@section=' ORACLE DEVELOPER']/title&quot;);
	String title=titleNode.getFirstChild().getNodeValue();
	System.out.println(&quot;Title of first Article in ORACLE DEVELOPER
	Section (with nodes not in any namespace) is &quot;+ title);
	XMLNode authorNode=(XMLNode)document.selectSingleNode(&quot;/catalog/
	journal/article[title= Oracle Database 11g Redux']/author&quot;);
	String author=authorNode.getFirstChild().getNodeValue();
	   System.out.println(&quot;Author of Title Oracle Database 11g Redux
	   is &quot;+ author);
	   XMLNode sectionNode=(XMLNode)document.selectSingleNode
	   (&quot;/catalog/journal[@date=March-April 2008']/article[2]
	   /@section&quot;);
	String section=sectionNode.getNodeValue();
	System.out. println(&quot;Section of 2nd Article in Journal of date
	March-April 2008 is &quot;+ section);
</pre>
</li>
<li>We select nodes using the selectNodes(String) method.
<pre class="brush: java; title: ; notranslate">	NodeList nodeList = document.selectNodes(&quot;/catalog/journal[@date=
	'March-April 2008']/article/title&quot;);
	System.out.println(&quot;Article Titles published in journal of March-
	April 2008 are: &quot;);
	for(int i=0; i&lt;nodeList.getLength(); i++){
	   titleNode=(XMLElement)nodeList.item(i);
	   title=titleNode.getFirstChild().getNodeValue();
	   System.out.println(title);
	}
	nodeList=document.selectNodes(&quot;/catalog/journal[@date='March-April
	2008']/article/@section&quot;);
	System.out.println(&quot;Articles in journal of March-April 2008 were
	published in Sections: &quot;);
	for(int i=0; i&lt;nodeList.getLength(); i++){
	   sectionNode=(XMLNode)nodeList.item(i);
	   section=sectionNode.getNodeValue();
	   System.out.println(section+&quot; &quot;);
	}
</pre>
</li>
<li>Next, we select nodes using the selectSingleNode(String,NSResolver) method.
<pre class="brush: java; title: ; notranslate">
	sectionNode=(XMLNode)document.selectSingleNode(&quot;/catalog/journal:
	journal/journal:article/@journal:section&quot;, resolver);
	section=sectionNode.getNodeValue();
	System.out.println(&quot;Section of first article in first journal
	(nodes being in journal namespace) is &quot;+section+&quot; &quot;);
	System.out.println(&quot;Titles for articles in journal of date
	November-December 2008 (journal, article, and date nodes being in
	journal namespace) are &quot;);
</pre>
</li>
<li>We also select nodes using the selectNodes(String,NSResolver) method.
<pre class="brush: java; title: ; notranslate">	nodeList=document.selectNodes(&quot;/catalog/journal:journal[@journal:
	date= 'November-December 2008']/journal:article/title&quot;,
	resolver );
	for(int i=0; i&lt;nodeList.getLength(); i++){
	   titleNode=(XMLElement)nodeList.item(i);
	   title=titleNode.getFirstChild().getNodeValue();
	   System.out.println(title);
	   }
	   }catch(IOException e){
	      System.err.println(&quot;IOException&quot;+e.getMessage());
	   }
	   catch(XMLDOMException e){
	      System.err.println(&quot;XMLDOMException&quot;+e.getMessage());
	   }
	   catch(XMLParseException e)
	      {System.err.println(&quot;XMLParseException&quot;+e.getMessage());
	   }
	   catch(XSLException e){
	      System.err.println(&quot;XSLException&quot;+e.getMessage());
	   }
	   catch(SAXException e){
	      System.err.println(&quot;SAXException&quot;+e.getMessage());
	   }
	}
</pre>
</li>
<li>We add the Java class that extends the NSResolver class.
<pre class="brush: java; title: ; notranslate">	class CustomResolver implements NSResolver{
	public java.lang.String
	resolveNamespacePrefix(java.lang.String prefix){
	if(prefix.equals(&quot;journal&quot;)){
	   return new &quot;http://www.xdk11g.com/xpath&quot;;
	}else
	   return null;
	   }
	}
</pre>
</li>
<li>Finally, we define the main method in which we create an instance of the
<pre class="brush: java; title: ; notranslate">	XPathParser class and invoke the parseDocument method.
	   public static void main(String[] argv){
	      XPathParser parser=new XPathParser();
	      parser.parseDocument(new File(&quot;catalog.xml&quot;));
	   }
	}
</pre>
</li>
</ul>
<p>To run the XPathParser.java application in JDeveloper, right-click on the <b>XPathParser.java</b> node in the <b>Application Navigator</b>, and select <b>Run</b>. The output from the XPathParser.java application is shown in the following illustration:</p>
<h2>Summary</h2>
<p>In this chapter you learned about XPath support in JDeveloper 11g. JDeveloper provides an <b>XPath Search</b> GUI tool to select nodes from an XML document using XPath. We selected nodes using absolute location paths and relative location paths, and also selected namespace nodes. We discussed the XDK&#8217;s XMLDocument class select methods to select elements and attributes in an XML document with XPath. The select methods may be used to select single nodes or collections of nodes. The select methods may also be used to select nodes in a namespace. In the next chapter, you will learn about <b>XSLT(Extensible Stylesheet Language Transformation)</b> support in JDeveloper.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2009/04/what-is-xpath/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>XML Schema Elements &#8211; Part2</title>
		<link>http://www.javabeat.net/2009/03/xml-schema-elements-part2/</link>
		<comments>http://www.javabeat.net/2009/03/xml-schema-elements-part2/#comments</comments>
		<pubDate>Wed, 25 Mar 2009 04:44:06 +0000</pubDate>
		<dc:creator>JavaBeat</dc:creator>
				<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=505</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Complex Elements Complex elements are those which contain other elements as children or these elements have attributes. Empty elements and elements containing only text are also considered complex. The following is an examples of complex element 1 2 3 4 5 6 &#60;employee grade=&#34;senior&#34;&#62; &#60;id&#62;745821&#60;/id&#62; &#60;empName&#62;Tim&#60;/empName&#62; &#60;salary&#62;35000&#60;/salary&#62; &#60;domain&#62;Insurance&#60;/domain&#62; &#60;/employee&#62; Define Complex Type in XML schema [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h3>Complex Elements</h3>
<p>Complex elements are those which contain other elements as children or these elements have attributes. Empty elements and elements containing only text are also considered complex. The following is an examples of complex element</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;employee grade=&quot;senior&quot;&gt;
	&lt;id&gt;745821&lt;/id&gt;
	&lt;empName&gt;Tim&lt;/empName&gt;
	&lt;salary&gt;35000&lt;/salary&gt;
	&lt;domain&gt;Insurance&lt;/domain&gt;
&lt;/employee&gt;</pre></td></tr></table></div>

<h4>Define Complex Type in XML schema</h4>
<p>Complex types can be defined in XML schema as demonstrated in this example:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;employee&quot;&gt;
    &lt;xs:complexType&gt;
      &lt;xs:sequence&gt;
	&lt;xs:element name=&quot;id&quot; type=&quot;xs:string&quot;/&gt;
	&lt;xs:element name=&quot;empName&quot; type=&quot;xs:string&quot;/&gt;
	&lt;xs:element name=&quot;salary&quot; type=&quot;xs:string&quot;/&gt;
	&lt;xs:element name=&quot;domain&quot; type=&quot;xs:string&quot;/&gt;
      &lt;/xs:sequence&gt;
    &lt;/xs:complexType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

<h3>Define empty elements</h3>
<p>Consider the following XML element:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;employee empId=&quot;157117&quot; /&gt;</pre></td></tr></table></div>

<p>This empty element can be defined in XML schema as follows:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;employee&quot;&gt;
  &lt;xs:complexType&gt;
    &lt;xs:attribute name=&quot;empId&quot; type=&quot;xs:positiveInteger&quot;/&gt;
  &lt;/xs:complexType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

<p>Here we can see that in the definition we dont define any child elements. We just define the attribute.</p>
<h4>Define text only elements</h4>
<p>Consider the following XML element:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;domain&gt;BFS&lt;/domain&gt;</pre></td></tr></table></div>

<p>The above element can be defined in XML schema as follows:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;domain&quot;&gt;
  &lt;xs:complexType&gt;
    &lt;xs:simpleContent&gt;
      &lt;xs:extension base=&quot;xs:string&quot; /&gt;
    &lt;/xs:simpleContent&gt;
  &lt;/xs:complexType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

<p>Here, we define that the content of the complex type is simple. In schema terms simple means plain text. The <b>xs:extension</b> is used to declare the type of the data.</p>
<h3>Define Mixed Content</h3>
<p>Sometimes an XML element can contain elements and text combined. Consider the following example:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;employeeInfo&gt;
The employee &lt;id&gt;134567&lt;/id&gt;
belongs to &lt;domain&gt;BFS&lt;/domain&gt;
and his salary is &lt;salary&gt;56430&lt;/salary&gt;
&lt;/employeeInfo&gt;</pre></td></tr></table></div>

<p>The above fragment can be defined in XML schema as follows:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;employeeInfo&quot;&gt;
  &lt;xs:complexType mixed=&quot;true&quot;&gt;
    &lt;xs:sequence&gt;
      &lt;xs:element name=&quot;id&quot; type=&quot;xs:positiveInteger&quot;/&gt;
      &lt;xs:element name=&quot;domain&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:element name=&quot;salary&quot; type=&quot;xs:positiveInteger&quot;/&gt;
    &lt;/xs:sequence&gt;
  &lt;/xs:complexType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

<p>In the defined XML schema we use the attribute <b>mixed</b> and set its value as true. This indicates that the XML element can contain other elements and simple text as it children</p>
<h2>XSD Indicators</h2>
<p>Using XSD Indicator a desicion can be made about how to use Complex types elements in a XML document. The indicators are basically divided into three groups :</p>
<ul>
<li>Order indicators</li>
<li>Occurrence indicators</li>
<li>Group indicators</li>
</ul>
<p>Let us know look at each of these categories.</p>
<h3>Order Indicators</h3>
<p>The order indicators define the ordering of the elements or the sequence in which the elements appear in the XML document. This group of indicators has three types of indicators :</p>
<ul>
<li>All</li>
<li>Choice</li>
<li>Sequence</li>
</ul>
<p><u>All</u></p>
<p>Using the <b>All</b> indicator allows the child elements to appear in any order. However, it sets a restriction that each child must appear only once. Lets look at an example :</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;employee&quot;&gt;
  &lt;xs:complexType&gt;
    &lt;xs:all&gt;
      &lt;xs:element name=&quot;empId&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:element name=&quot;name&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:element name=&quot;salary&quot; type=&quot;xs:integer&quot;/&gt;
      &lt;xs:element name=&quot;domain&quot; type=&quot;xs:string&quot;/&gt;
    &lt;/xs:all&gt;
  &lt;/xs:complexType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

<p><u>Choice</u></p>
<p>The <b>Choice</b> indicators specifies that out of all the child elements one can appear. Lets look at an example:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;employee&quot;&gt;
  &lt;xs:complexType&gt;
    &lt;xs:choice&gt;
      &lt;xs:element name=&quot;manager&quot; type=&quot;manager&quot;/&gt;
      &lt;xs:element name=&quot;member&quot; type=&quot;member&quot;/&gt;
    &lt;/xs:choice&gt;
  &lt;/xs:complexType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

<p><u>Sequence</u></p>
<p>This indicator specfies that the child elements should follow the specified order :</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;employee&quot;&gt;
  &lt;xs:complexType&gt;
    &lt;xs:sequence&gt;
      &lt;xs:element name=&quot;empId&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:element name=&quot;name&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:element name=&quot;salary&quot; type=&quot;xs:integer&quot;/&gt;
      &lt;xs:element name=&quot;domain&quot; type=&quot;xs:string&quot;/&gt;
    &lt;/xs:sequence&gt;
  &lt;/xs:complexType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

<h3>Occurrence Indicators</h3>
<p>The occurrence indiactor defines the number of times an element can appear. This group has two differetn types:</p>
<ul>
<li>maxOccurs</li>
<li>minOccurs</li>
</ul>
<p><u>maxOccurs</u></p>
<p>The <b>maxOccurs</b> element sets an upper limit on the number of times an element can upper. Lets looks at an example:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;employee&quot;&gt;
  &lt;xs:complexType&gt;
    &lt;xs:sequence&gt;
      &lt;xs:element name=&quot;empId&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:element name=&quot;name&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:element name=&quot;salary&quot; type=&quot;xs:integer&quot;/&gt;
      &lt;xs:element name=&quot;domain&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:element name=&quot;project&quot; type=&quot;xs:string&quot; maxOccurs=&quot;10&quot;/&gt;
    &lt;/xs:sequence&gt;
  &lt;/xs:complexType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

<p><u>minOccurs</u></p>
<p>The <b>minOccurs</b> element sets the lower imit on the number of times an element can upper. Lets looks at an example:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;employee&quot;&gt;
  &lt;xs:complexType&gt;
    &lt;xs:sequence&gt;
      &lt;xs:element name=&quot;empId&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:element name=&quot;name&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:element name=&quot;salary&quot; type=&quot;xs:integer&quot;/&gt;
      &lt;xs:element name=&quot;domain&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:element name=&quot;project&quot; type=&quot;xs:string&quot; maxOccurs=&quot;10&quot; minOccurs=&quot;0&quot;/&gt;
    &lt;/xs:sequence&gt;
  &lt;/xs:complexType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

<h3>Group Indicators</h3>
<p>Group indicators allow us to define a group of elements</p>
<ul>
<li>Group name</li>
<li>attributeGroup name</li>
</ul>
<p><u>Group Name</u></p>
<p>The group indicator is used to define a group of elements. Once defined the group can be referenced in other places within the XML schema. Lets look at an example :</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:group name=&quot;projectGroup&quot;&gt;
  &lt;xs:sequence&gt;
    &lt;xs:element name=&quot;projectname&quot; type=&quot;xs:string&quot;/&gt;
    &lt;xs:element name=&quot;technology&quot; type=&quot;xs:string&quot;/&gt;
  &lt;/xs:sequence&gt;
&lt;/xs:group&gt;</pre></td></tr></table></div>

<p>In the above example we define a group named <b>projectGroup</b>. Now we will see how to refer this group in other places :</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;employee&quot;&gt;
  &lt;xs:complexType&gt;
    &lt;xs:sequence&gt;
      &lt;xs:element name=&quot;empId&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:element name=&quot;name&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:element name=&quot;salary&quot; type=&quot;xs:integer&quot;/&gt;
      &lt;xs:element name=&quot;domain&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:group ref=&quot;projectGroup&quot;/&gt;
    &lt;/xs:sequence&gt;
  &lt;/xs:complexType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

<p>After making a reference to the <b>projectGroup</b> the employee element gets a total of six child elements:<br />
<b>empId, name, salary, domain, projectname, technology</b></p>
<p>.</p>
<p><u>Attribute Groups</u></p>
<p>The attribute group is used to group together a set of attributes. Once defined the group can be referenced in other elements to define the attributes for a element. Lets look at an example :</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:attributeGroup name=&quot;empAttrGroup&quot;&gt;
    &lt;xs:attribute name=&quot;designation&quot; type=&quot;xs:string&quot;/&gt;
&lt;/xs:attributeGroup&gt;
&nbsp;
&lt;xs:complexType name=&quot;employee&quot;&gt;
    &lt;xs:attributeGroup ref=&quot;empAttrGroup&quot;/&gt;
&lt;/xs:complexType&gt;</pre></td></tr></table></div>

<p><u>The <any> Element</u></p>
<p>With the use of the <b>any</b> element an XML schema can can extend another XML schema. Lets look at an example :</p>
<p><b>Filename : employee.xsd</b></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;employee&quot;&gt;
  &lt;xs:complexType&gt;
    &lt;xs:sequence&gt;
      &lt;xs:element name=&quot;empId&quot; type=&quot;xs:positiveinteger&quot;/&gt;
      &lt;xs:element name=&quot;name&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:element name=&quot;salary&quot; type=&quot;xs:positiveinteger&quot;/&gt;
      &lt;xs:element name=&quot;domain&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:any minOccurs=&quot;0&quot;/&gt;
    &lt;/xs:sequence&gt;
  &lt;/xs:complexType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

<p>Filename : children.xsd</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;project&quot;&gt;
  &lt;xs:complexType&gt;
    &lt;xs:sequence&gt;
      &lt;xs:element name=&quot;projectName&quot; type=&quot;xs:string&quot; /&gt;
      &lt;xs:element name=&quot;technologyUsed&quot; type=&quot;xs:string&quot; /&gt;
    &lt;/xs:sequence&gt;
  &lt;/xs:complexType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

<p>The XML file can use components from both the files:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;employee&gt;
	&lt;empId&gt;143233&lt;/empId&gt;
	&lt;name&gt;John&lt;/name&gt;
	&lt;salary&gt;34500&lt;/salary&gt;
	&lt;domain&gt;Insurance&lt;/domain&gt;
	&lt;project&gt;
		&lt;projectName&gt;ISD&lt;/projectName&gt;
		&lt;technologyUsed&gt;.NET&lt;/technologyUsed&gt;
	&lt;/project&gt;
&lt;/employee&gt;</pre></td></tr></table></div>

<h2>XSD Data Types</h2>
<p><b>String</b></p>
<p>The string data type is used to store characters and strings. For e.g:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">	&lt;table border=&quot;1&quot;&gt;
	&lt;tr&gt;
		&lt;td&gt;XML Schema&lt;/td&gt;
		&lt;td&gt;&lt;xs:element name=&quot;name&quot; type=&quot;xs:string&quot;/&gt;&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td&gt;XML&lt;/td&gt;
		&lt;td&gt;&lt;name&gt;John&lt;/name&gt;&lt;/td&gt;
	&lt;/tr&gt;
	&lt;/table&gt;</pre></td></tr></table></div>

<p><b>Date</b></p>
<p>The date type represents a date. The date represented by using the date datatype is specified in the following format : <b>YYYY-MM-DD</b>.<br />
For e.g:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;table border=&quot;1&quot;&gt;
&lt;tr&gt;
	&lt;td&gt;XML Schema&lt;/td&gt;
	&lt;td&gt;&lt;xs:element name=&quot;joiningDate&quot; type=&quot;xs:date&quot;/&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
	&lt;td&gt;XML&lt;/td&gt;
	&lt;td&gt;&lt;joiningDate&gt;2007-03-27&lt;/joiningDate&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;</pre></td></tr></table></div>

<p><b>Numeric</b></p>
<p>The numeric data types are of two types:</p>
<ul>
<li>Decimal</li>
<p>The decimal data type is used to represent decimal numbers. For e.g:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;table border=&quot;1&quot;&gt;
&lt;tr&gt;
	&lt;td&gt;XML Schema&lt;/td&gt;
	&lt;td&gt;&lt;xs:element name=&quot;price&quot; type=&quot;xs:decimal&quot;/&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
	&lt;td&gt;XML&lt;/td&gt;
	&lt;td&gt;&lt;price&gt;678.50&lt;/price&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;</pre></td></tr></table></div>

<li>Integer</li>
<p>The integer data type is used to represent integers. For e.g:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;table border=&quot;1&quot;&gt;
&lt;tr&gt;
	&lt;td&gt;XML Schema&lt;/td&gt;
	&lt;td&gt;&lt;xs:element name=&quot;salary&quot; type=&quot;xs:integer&quot;/&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
	&lt;td&gt;XML&lt;/td&gt;
	&lt;td&gt;&lt;salary&gt;678.50&lt;/salary&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;</pre></td></tr></table></div>

</ul>
<p><b>Other Datatypes</b></p>
<ul>
<li>Boolean</li>
<p>The boolean datatype represents the value true or false.E.g:</p>
<table border="1">
<tr>
<td>XML Schema</td>
<td><xs:attribute name="terminated" type="xs:boolean"/></td>
</tr>
<tr>
<td>XML</td>
<td><employee terminated="false">John</employee></td>
</tr>
</table>
</ul>
<p>[Note: If one wants to test these examples then you should have a suitable XML editor. By simply copying the files in your system and executing them in the browser wont produce the expected output.]</p>
<h3>XML Reference</h3>
<ul>
<li><a href="http://www.javabeat.net/tips/186-xml-schema-elements.html">XML Schema Elements</a></li>
<li><a href="http://www.javabeat.net/tips/185-xforms.html">XForms</a></li>
<li><a href="http://www.javabeat.net/tips/184-creating-xslt-documents.html">Creating XSLT documents</a></li>
<li><a href="http://www.javabeat.net/tips/183-how-to-use-xlink-and-xpointer.html">How to use XLink and XPointer?</a></li>
<li><a href="http://www.javabeat.net/tips/182-how-to-query-xml-using-xpath.html">How to Query XML using XPath</a></li>
</ul>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2009/03/xml-schema-elements-part2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>XML Schema Elements</title>
		<link>http://www.javabeat.net/2009/03/xml-schema-elements/</link>
		<comments>http://www.javabeat.net/2009/03/xml-schema-elements/#comments</comments>
		<pubDate>Sat, 21 Mar 2009 04:43:29 +0000</pubDate>
		<dc:creator>JavaBeat</dc:creator>
				<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=503</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>XML schema is a language for describing the contents and structure of a XML document. It basically creates a blue print of the actual XML document by describing everything about the elements which can appear in the document. By creating a XML schema we make the XML document conform to the rules defined in the [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>
XML schema is a language for describing the contents and structure of a XML document. It basically creates a blue print of the actual XML document by describing everything about the elements which can appear in the document. By creating a XML schema we make the XML document conform to the rules defined in the XML schema. It essentially says that the XML document cant break the rules defined in the XML schema document.
</p>
<p>
Lets create a sample XML schema document <i>empSchema.xsd</i>:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot; ?&gt;
&lt;xs:schema xmlns:xs=&quot;http://www.w3.org/2001/XMLSchema&quot;&gt;
&lt;xs:element name=&quot;employee&quot;&gt;
    &lt;xs:complexType&gt;
      &lt;xs:sequence&gt;
	&lt;xs:element name=&quot;id&quot; type=&quot;xs:string&quot;/&gt;
	&lt;xs:element name=&quot;empName&quot; type=&quot;xs:string&quot;/&gt;
	&lt;xs:element name=&quot;salary&quot; type=&quot;xs:string&quot;/&gt;
	&lt;xs:element name=&quot;domain&quot; type=&quot;xs:string&quot;/&gt;
      &lt;/xs:sequence&gt;
    &lt;/xs:complexType&gt;
&lt;/xs:element&gt;
&lt;/xs:schema&gt;</pre></td></tr></table></div>

<p>Lets create a XML document <i>employee.xml</i>:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;employee
xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xsi:noNamespaceSchemaLocation=&quot;empSchema.xsd&quot;&gt;
	&lt;id&gt;745821&lt;/id&gt;
	&lt;empName&gt;Tim&lt;/empName&gt;
	&lt;salary&gt;35000&lt;/salary&gt;
	&lt;domain&gt;Insurance&lt;/domain&gt;
&lt;/employee&gt;</pre></td></tr></table></div>

<p>In the XML document above we see that the document is referring to a XSD document[xsi:noNamespaceSchemaLocation="empSchema.xsd"]. XSD is nothing but a file which defines XML schema.<br />
I will explain the details of the XML schema document as we go along. The above example is just supposed to give you a feel of what an XML schema looks like and how to refer to the XSD from a XML file.
</p>
<p><h2>XML Schema Elements</h2>
<h3>schema</h3>
<p>Every XML schema starts with <b><schema></b> element as the root. The attribute <b>xmlns:xs=&#8221;http://www.w3.org/2001/XMLSchema&#8221;</b> says that the elements in the XML document belong to the <b>&#8220;http://www.w3.org/2001/XMLSchema&#8221;</b> namespace  and each of the elements that belong to this namespace should be prefixed with the <b>xs</b>.
</p>
<p><h2>Simple Type</h2>
<p>A simple type element cannot contain any other elements or attributes. It can contain only text data.  For E.g:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;table&gt;
&lt;tr&gt;
&lt;td&gt;Syntax:&lt;/td&gt;
&lt;td&gt;&lt;xs:element name=&quot;element-name&quot; type=&quot;data-type&quot;/&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;XML Schema:&lt;/td&gt;
&lt;td&gt;&lt;xs:element name=&quot;empName&quot; type=&quot;xs:string&quot;/&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;XML:&lt;/td&gt;
&lt;td&gt;&lt;empName&gt;Daniel&lt;/empName&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;</pre></td></tr></table></div>

<p>The allowed datatypes in XML schema are :</p>
<table border="1" style="background-color:#EFEFEF">
<tr>
<td>xs:string</td>
</tr>
<tr>
<td>xs:decimal</td>
</tr>
<tr>
<td>xs:integer</td>
</tr>
<tr>
<td>xs:boolean</td>
</tr>
<tr>
<td>xs:date</td>
</tr>
<tr>
<td>xs:time</td>
</tr>
</table>
<h3>Attributes</h3>
<p>An attribute provides additional information about the element. Simple types cannot have attributes. However the attribute itself are of type simple. Let us now look at the syntax and an example of how to define attributes in XML Schema:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;table&gt;
&lt;tr&gt;
&lt;td&gt;Syntax:&lt;/td&gt;
&lt;td&gt;&lt;xs:attribute name=&quot;attribute-name&quot; type=&quot;data-type&quot;/&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;XML Schema:&lt;/td&gt;
&lt;td&gt;&lt;xs:attribute name=&quot;grade&quot; type=&quot;xs:string&quot;/&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;XML:&lt;/td&gt;
&lt;td&gt;&lt;employee grade=&quot;senior&quot;&gt;Daniel&lt;/employee&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;</pre></td></tr></table></div>

</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<h3>Content Restrictions</h3>
<p>
When an element or an attribute is defined with a particular data type, it essentially means that the element or attribute cant be assigned a value which is of some other type. In XML schema we can define custom restrictions on elements. Such restrictions are called <b>facets</b>. </p>
<ul>
<li><b>Value restrictions</b></li>
<p>
Using value restrictions the XML schema places a restriction that the value of the element should be between a allowed range.In the following example element a restriction is placed on the salary element that its value cannot be less that zero and more than 85000.<br />
In case it happens then the XML document will not validate:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;salary&quot;&gt;
	&lt;xs:simpleType&gt;
		&lt;xs:restriction base=&quot;xs:integer&quot;&gt;
			&lt;xs:minInclusive value=&quot;0&quot;/&gt;
			&lt;xs:maxInclusive value=&quot;85000&quot;/&gt;
		&lt;/xs:restriction&gt;
	&lt;/xs:simpleType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

<li><b>Restriction on a set</b></li>
<p>
In set restriction the value of an element should be set from only an allowed set of values. In the following example the value of the domain element is limited to a certain set of values:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;domain&quot;&gt;
	&lt;xs:simpleType&gt;
		&lt;xs:restriction base=&quot;xs:string&quot;&gt;
			&lt;xs:enumeration value=&quot;BFS&quot;/&gt;
			&lt;xs:enumeration value=&quot;Insurance&quot;/&gt;
			&lt;xs:enumeration value=&quot;Manlog&quot;/&gt;
			&lt;xs:enumeration value=&quot;Life Sciences&quot;/&gt;
		 &lt;/xs:restriction&gt;
	&lt;/xs:simpleType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

<li><b>Restriction on a series</b></li>
<p>In such type of restriction we can use any valid regular expression syntax to define the restrictions. In the following example we define a restriction that the number should be between 0 and 9.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;number&quot;&gt;
	&lt;xs:simpleType&gt;
		&lt;xs:restriction base=&quot;xs:string&quot;&gt;
			&lt;xs:pattern value=&quot;[0-9]&quot;/&gt;
		&lt;/xs:restriction&gt;
	&lt;/xs:simpleType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

<li><b>Restriction on a whitespace characters</b></li>
<p>These restrictions define how the whitespace characters are handled in the XML document. The restriction can be placed using the following syntax:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:whiteSpace value=&quot;preserve&quot;/&gt;
or
&lt;xs:whiteSpace value=&quot;replace&quot;/&gt;</pre></td></tr></table></div>

<p>The attribute value <b>preserve</b> says that the whitespace characters will not be removed by the XML processor. The attribute value <b>replace</b> says that the following characters will be replaced by spaces :<br />
line feeds, tabs, spaces, and carriage returns. Lets looks at an example now :</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;feedback&quot;/&gt;
	&lt;xs:simpleType&gt;
		&lt;xs:restriction base=&quot;xs:string&quot;/&gt;
			&lt;xs:whiteSpace value=&quot;preserve&quot;/&gt;
		&lt;/xs:restriction/&gt;
	&lt;/xs:simpleType/&gt;
&lt;/xs:element/&gt;</pre></td></tr></table></div>

<li><b>Restriction on the length</b></li>
<p>
This places a restriction on the allowed numbers of characters. The following example places a restriction that the employee id cannot be more than 6 characters</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;empId&quot;&gt;
&lt;xs:simpleType&gt;
	&lt;xs:restriction base=&quot;xs:integer&quot;&gt;
		&lt;xs:length value=&quot;6&quot;/&gt;
	&lt;/xs:restriction&gt;
&lt;/xs:simpleType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

</ul>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2009/03/xml-schema-elements/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
