Building a web service endpoint in Java

Ok, so what is a web service?

I provide an overview of what Web Services (WS) are in this post, An introduction to Web Services. Give it a read and pop back here Smile

Seriously, Java? The most insecure software platform ever?

Yes, Java. The platform agnostic software environment that is taught in a lot of University CS courses and has had a consistently high spot in the tiobe programming language popularity chart (Currently #2, with only .2% less market than the number one, C).

Its also worth bearing in mind that the security issues that have plagued Java in recent months are usually related to the use of a web plug in. This plug in causes issues as Java is a powerful, fully featured platform which when combined with a web plugin introduces a large number of attack vectors. From a Desktop/Server application perspective Java is quite safe and in many ways safer than native code due to its Bytecode interpreting sandboxed process virtual machine.

Which Web Service technology will be used here?

In this example SOAP based web services will be used to provide a quick example. For large production systems you may prefer to look at JSON (Message format) and REST (communication strategy) based WS.  This example will be built using Netbeans.

Plug-in and communicate

What??? I’m quite I read a lot so I’m plugged in but I‘m a stereotypical Socially Awkward Penguin, I don’t like the talky talk. Not fair!!!

Not that type of plugged in and communicate, to develop WS in Java we need to install a  development plugin. To do this go to the Tools –> Plugins menu.

image

In the plugin interface go to Available plugins and install the Java web and EE option. After installation restart Netbeans.

image

Once the  WS support is enabled a hosting server is needed, this can be specified or isntaleld from the Tools-> Servers menu. Click Add Server

image

Next choose a server, I have chosen the Glassfish server below.

image

If you have the installed already you may specify the path or download the server. To download tick the agreement then select Download Now. Then go through the Installation process. Follow the screen shots below

image

image

image

image

Now that your environment is ready you can now create a project.

Time to make a project.

Create a New ‘Web Application’ Project as shown below.

image

image

Yes, I am aware I forgot the ‘l’, I have another Example Application in the same folder and am a little lazy.

image

image

Do not click any of these frameworks as they are not needed for this tutorial.

image

Codey Time!

Under web services click New –> Web Service and then specify customization.

image

image

image

You should now be presented with a source file which contains some boiler plate code. To this code a small math operation should be added. image

The code in question will go into a class called MathFun and will calculate the Pearson product-movement coefficient.  A walkthrough of calculating this is shown here. This code accepts 2 arrays containing Doubles and returns a double as a reply.

image

Once the code has been added to a class it can then be called by the service endpoint code by specifying a @WebMethod.

This code follows this form.

   1: private MathFun mathFun = new MathFun();

   2:  

   3: @WebMethod(operationName = "CalculatePearson")

   4: public Double CalculatePearson(Double  a1[], Double  a2[]) {

   5:     return mathFun.CalcPearsonCorrelation(a1,a2);

   6: }

image

Once the code is complete and tested it is then possible to test the web service with a useful Open Source tool called SoapUI.

image

And we are done!!

Yes, it is that easy to set up a WS. The next step involves consuming it from a device/web browser. This is simple enough as most development environments support SOAP.

An introduction to Web Services

No matter what you say I wont appreciate spiders

While spiders are useful housing companions for people who would like to see a reduction in insect numbers in their residence this isn’t the type of web services that I am referring to.

So is this a post about forcing genetic abnormalities on people to create a team of spider-men types to clean the windows of skyscrapers\help pick up litter with their extraordinary abilities?

Although those types of dangerous mutations may initially seem to be offer advantages I doubt inducing them would be a reasonable solution to the age old dirty skyscraper windows problem.

Web services offer a method of presenting functionality offered by a service to software\consumers in a platform agnostic manner using web based messaging protocols.

What exactly do you mean by “web”, should they not be called internet services?

No, internet based communications an undefined approach to inter system interoperability but generally these do not have to offer a shared standard way for these components to communicate. For example UDP video game client A may not have any facility to communicate with a meaningful manner with TCP based game server B.

I thought the web and the internet were the same thing, what’s so special about “web” technologies?

The internet is the channel that web communication takes place over and facilitates many different diverse and potentially (likely) in-operable communications mechanisms examples of these mechanisms include:

Web communications take place over a much more defined\rigid\compatible set of web derived specifications which basically include

  • Use of a standard internet protocol – e.g. TCP
  • Application level communication using a common protocol – e.g. HTTP\REST
  • Messages and responses formatted in a standard manner  – SOAP\JSON etc

Put simply there are many approaches to networked communication and using web based technology provides a lingua franca for offering and consuming services.

So that explains the web part, what do you mean by services?

A service in this context offers some facility that may be consumed by clients which may be entities like web browsers, mobile apps, server programs and desktop software.

One such service could be getting realtime data from a information source (e.g. stock prices from an exchange) or providing some data processing service  e.g using an heavy iron server than can factor primes more quickly than a home machine.

Essentially web services allow hosting of some modular function(s) in a self contained system and providing a mechanism for interaction, a lot of mobile apps rely on this sort of service.

 

Overview of web service interaction

image

 

As the above diagram shows a web service consumer interacting with a web service.

The server HTTP component listens for and responds requests sent by the HTTP client, these request are formatted in (typically) a mutual message format as generated/understood by the Message Parser/Packer which then generates/extracts parameters/responses and passes them to the consumer/function logic.

In simple terms the whole purpose of using web service technologies is to pass parameters to functions and receive responses over a network using http communications

 

A SOAP Example

Lets imagine that there is a web service offered at www.example.org which communicates using the XML-based SOAP message format, this service at example.org offers a function called GetStockPrice which takes one parameter StockName.

POST /Stock HTTP/1.1
Host: www.example.org

Content-Type: application/soap+xml; charset=utf-8
Content-Length: 223

<?xml version=”1.0″?>
<soap:Envelope
xmlns:soap=”http://www.w3.org/2001/12/soap-envelope”
soap:encodingStyle=”http://www.w3.org/2001/12/soap-encoding”>
<soap:Header>
</soap:Header>
<soap:Body xmlns:m=”http://www.example.org/stock”>
<m:GetStockPrice>
<m:StockName>IBM</m:StockName>
</m:GetStockPrice>
</soap:Body>
</soap:Envelope>

This message is sent via a HTTP 1.1 post to the /Stock path of www.example.com with a content type of soap+xml in Unicode format.

The above message is colour coded to indicate the parts that are germane to  each stage of processing, this coding is keyed as following.

HTTP Message – The entire body sent and received by the Client/Server
Message Body – The XML + SOAP which is generated and processed by the Parser/Generator
Desired Information – Consumed and generated by the Service/Consumer logic

When this message is sent to an appropriate service is it processed and passed to a specified function (<m:GetStockPrice>) with the parameters specified by (<m:StockName>IBM</m:StockName> ).

The following is an example of such a function called GetStockPrice where the StockName variable would contain IBM.

public int GetStockPrice(String StockName){

return hashMap.Get(StockName);

}

This service would then reply with the following message assuming there was no error, remember to provide error feedback and handling

HTTP/1.1 200 OK
Content-Type: application/soap+xml; charset=utf-8
Content-Length: nnn
<?xml version=”1.0″?>
<soap:Envelope
xmlns:soap=”http://www.w3.org/2001/12/soap-envelope”
soap:encodingStyle=”http://www.w3.org/2001/12/soap-encoding”>
<soap:Header>
</soap:Header>
<soap:Body xmlns:m=”http://www.example.org/stock”>
<m:GetStockPriceResponse>
<m:Price>34.5</m:Price>
</m:GetStockPriceResponse>
</soap:Body>
</soap:Envelope>

 

As you can see from this response the price for IBM stock is 34.5, this message is received  and then parsed by the client and the useful information is extracted from it and  used by the the consumer.

In summary web services allow a relatively firewall friendly communications mechanism as most L7 firewalls allow HTTP traffic using fairly platform agnostic approach to messaging (most platforms have support for HTTP).