Monday, July 29, 2013

Java WebServices Tutorial Part 08 - Ways of Writing WebServices in Java

Hi , Again we are discussing here  how to write a webservice, i told you in the previous post that they are many ways you can the write the webservice it's all depends upon what kind of webservice you want.

Well we can write a simple java class with some business method and make that class as webservice that's what we have seen previously http://ayazroomy-java.blogspot.in/2013/07/writing-simple-webservice-using-eclipse.html .There we wrote a class and let eclipse to do all the stuffs such as creating wsdl with XML schemas and deployment in the server and other stuffs.

Now as i told you there are many ways to write a Webservice, Mention below are the approaches to write a webservice.

1. Bottom Up Approach
2. Top Down Approach

1. Bottom Up Approach:
The Bottom Up  approach we have seen already in the post writing simple webservice with eclipse. and In the next  part  we will see how to write a webservice using  Bottom Up Approach with JAX-WS API Provided by J2EE  .

The Bottom Up Approach can be define as :

Step1: Write a Java Class with Business Methods.
Step2: Generate wsdl and XML Schemas from the Java Class.
Step3: Deploy the Class as a  Service once it is converted to webservice standard.

Step2 & Step3 can be done using tools and IDE such as Eclipse,NetBeans etc.

2. Top Down Approach:
The Top Down approach is little complicated.

Step1: Create the XSD or binding required for the WSDL.
Step2: Create the WSDL .
Step3: Generate the Java Class source and Binding Classes from the XSD and WSDL.
Step4 : Write your Business Logic in the Generated Classes so called Skeleton class.
Step5 : Deploy the Service.

Here Step1 & Step 2 are created based upon contract and policies such as government ,Banking,Insurance companies provides based upon that it is created.

To make the Step1 and Step2 to be successful one should be knowing clearly about the WSDL and XML Schema's and there namespace,policy ,WS-Standards,WS-Policy,WS-Security and all.

Step 3 is some what easier then Step1 & Step 2 the Java classes can be created using tools such as Axis2 or by using ID's as Eclipse,NetBeans etc.

Step4 and Step5 they have to done manually by the developer.

Both these approaches have advantages and disadvantages.

Advantages:

-  Top Down Approach:

Can achieve better performance

Integrity of the WSDL is assured

Useful for long running business critical service development

- Bottom Up Approach:

Easy to use. Simple and less time consuming

No need of in-depth knowledge on WSDL. Useful at development stage

Can be used to make Web services out of legacy systems.

Disadvantages:

- Top Down Approach:

Complex than Code First

Need a better understanding on WSDL

- Bottom Up Approach:
Less performance 

Can't guarantee the integrity of the WSDL


So it all depends upon  what kind of business you are dealing with and what kind of service approach you want.I hate to say it but if you are going to create a webservice based upon the Top Down approach which need XML Schema and WSDL knowledge you can use the .NET WCF Blue Plug in which comes with Visual Studio 2010. It doesn't mean that you cannot create webservice with this approach in Java ,Yes we can do that Eclipse and NetBeans provides the facilities , but this WCF Blue gives you to create WSDL and XSD on fly.If you know .NET you can use this.

So coming to Our Topic i don't want to confuse more , i like to split the types of Web-services and  how can we write them

1.SOAP :

In Java SOAP style webservice can  be created using:

- JAX-WS API provided by J2EE . 
- Using Simple Java class  using eclipse
- Using  Axis2 frame work (which has lot of stuff we will discuss in details about Axis2 in later part).
- Using Spring framework

2. REST :

In Java  REST Style webservice can be created using :

- JAX-RS API Provided by J2EE.
- Using Jersey framework.
- Using Spring framework.

These are all some of the mostly used mechanisms to create webservice , there are lot of other ways also we can do that but this is sufficient to create any webservice .

In the next tutorial we will see how to create JAX-WS Style webservice with Bottom Up Approach.

Thanks for reading....


<<Previous                   Next>>                      Index>>

---------------------------------------------------------------------------------





Technology Blogs
blogs

Sunday, July 28, 2013

A Swing Application to Store and Retrive an image from MYSQL


Hi , Today we are going to see how to store an image in MySQL and how to retrieve the image and display it to the user using Swing.

So First we need MySQL Data base if you don't have you can download it from oracle website.

So this is the table we are going to create:

Table : image

create table image
( id varchar(20),
image longblob);

I have created this table under the schema name "test" in MySQL ,So from the code i will be accessing  test schema for referring this table.

So we have two fields here one is id another one is image as type long blob which can store an image up to the size of 1 MB i guess.More then that will thrown an Exception.

Now ,we need to write our Java code to connect to this table and to store this image along with image file.

We also need Mysql-connector.jar .So download this jar and add it to the class path.

Code :

import java.awt.Toolkit;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.sql.*;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
public class StoreImage extends javax.swing.JFrame {
Connection connection=null;
PreparedStatement ps=null;
ResultSet rs=null;
String filePath=null;

public StoreImage() {

initComponents();
initConnection();
setSize(600,500);
}

public void retriveImage()
{
try
{
String val=jTextField1.getText();
if(val.length()>0)
{
ps=connection.prepareStatement("select * from image where id=?");
ps.setObject(1, val);
rs=ps.executeQuery();
byte b[] = null;
while(rs.next())
{
b= rs.getBytes(2);
}

jLabel6.setIcon(new ImageIcon (Toolkit.getDefaultToolkit().createImage(b)));


}else
{
JOptionPane.showMessageDialog(this,"Please enter ID..." );
}


}catch(Exception e)
{

}
}

//1048576 Size limit allowed for Image storage in MySQL.
public void storeImage()
{
try
{

JFileChooser chooser=new JFileChooser(new File("E:\\"));
 
chooser.setMultiSelectionEnabled(false);
chooser.setVisible(true);

chooser.showOpenDialog(this);

File file=chooser.getSelectedFile();
if(file!=null){filePath=file.getPath();}
if(filePath!=null){
jLabel5.setText("File:"+" "+filePath);
jLabel6.setIcon(new ImageIcon(filePath));
}


if(filePath!=null && check())
{
ps=connection.prepareStatement("insert into image values(?,?)");
FileInputStream fileInputStream=new FileInputStream(filePath);
byte b[]=new byte[fileInputStream.available()];
fileInputStream.read(b);
fileInputStream.close();
ps.setObject(1, jTextField1.getText());
ps.setBytes(2, b);
int val=ps.executeUpdate();
if(val>=1)JOptionPane.showMessageDialog(this, "Succesfully Stored...");
else
JOptionPane.showMessageDialog(this, "Error in storage...");

}
else
{
JOptionPane.showMessageDialog(this,"Please select an Image of type .jpeg/gif/jpg...");
}

}catch(Exception e)
{

JOptionPane.showMessageDialog(this, e.getMessage());
e.printStackTrace();
}
}

public void initConnection()
{
try
{

Class.forName("com.mysql.jdbc.Driver");
connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","ayaz");
System.out.println("Connection Established Succcesfully...");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this, e.getMessage());
}
}

 
private void initComponents() {

jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jLabel6 = new javax.swing.JLabel();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(null);

jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel1.setText("Store/Retive Image From MySQL");
getContentPane().add(jLabel1);
jLabel1.setBounds(90, 30, 220, 14);

jLabel2.setText("ID :");
getContentPane().add(jLabel2);
jLabel2.setBounds(60, 90, 18, 14);

jLabel3.setText("Select an Image :");
getContentPane().add(jLabel3);
jLabel3.setBounds(40, 130, 100, 14);

jButton1.setText("Browse");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
getContentPane().add(jButton1);
jButton1.setBounds(150, 123, 100, 30);

jButton3.setText("Show");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
getContentPane().add(jButton3);
jButton3.setBounds(130, 213, 80, 30);
getContentPane().add(jTextField1);
jTextField1.setBounds(150, 80, 90, 20);

jLabel5.setForeground(new java.awt.Color(255, 0, 0));
getContentPane().add(jLabel5);
jLabel5.setBounds(40, 170, 240, 30);

jScrollPane1.setViewportView(jLabel6);

getContentPane().add(jScrollPane1);
jScrollPane1.setBounds(330, 70, 210, 160);

pack();
  } 

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
  storeImage(); 
}

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
retriveImage();
}

public static void main(String args[]) {
   new StoreImage().setVisible(true);
}


// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField jTextField1;
// End of variables declaration

private boolean check() {
if(filePath!=null)
{
if(filePath.endsWith(".jpeg")||filePath.endsWith(".gif")||filePath.endsWith(".jpg")||filePath.endsWith(".JPEG")||filePath.endsWith(".GIF")||filePath.endsWith(".JPG"))
{
return true;
}
return false;
}
return false;
}
}


Result :




















<< Prev                               Index                  Next>>

-------------------------------------------------------------------------------------







Technology Blogs
blogs

Saturday, July 27, 2013

Creating a Simple EJB SessionBean Using NetBeans & GlassFish Server


Hi , Today we are going to see how to create a simple EJB Stateless Session Bean using NetBeans and then we are going to deploy it in GlassFish Server and finally we will test it.

We are not going to discuss what is EJB what is Session Bean and how we have to use it etc.

So we require the following :

1.NetBeans ID
2. GlassFish Server.

Generally NetBeans comes along with GlassFish Server .While downloading NetBeans you can select this Option so that NetBeans Installer will download along with GlassFish Server.

Install the NetBeans with GlassFish Server.Once it is done we are ready to Go.

In this tutorial i am using the NetBeans 7.3 Version along with GlassFish Server 3.1.2 Version.

Now open NetBeans ID.

Step 1:

- Select : File->New Project ->Java EE - > EJB Module and click the "Next" Button.

- Give Project a Suitable Name Here i am giving "MyApp" click the "Next" Button.

- Select the Server as "GlassFish" with the version You have installed . Here i am selecting "GlassFish Server 3.1.2"

-  Select the J2EE Version what ever you have installed. Currently it is J2EE 6. and click the "Finish" Button.

You will have the Project Directory Structure something like this:















Step 2:

- Create a New Package called test under the Source Package Folder.

-  Create a new interface called "Home".under test package and add the following code.

 - This is a Remote Interface this can access from anywhere,once it is deployed in the server.

package test;
import javax.ejb.Remote;

@Remote
public interface Home {
public String sayHello(String name);
   }

Step 3:

Create a SessionBean class which implements this Interface .

RightClick on test and create New --> JavaClass--> HomeImpl

package test;

import javax.ejb.Stateless;
@Stateless
public class HomeImpl implements Home{

@Override
public String sayHello(String name) {
return "Welcome to EJB"+" "+name;
}

}

Step 4:

Create a GlassFish Descriptor File by

Righ Click on the Project "MyApp" and then choose New -->Other-->GlassFish-->GlassFish Descriptor and then click the "Next" button and click the "Finish " Button.

 glassfish-ejb-jar.xml file will be created under the Configuration Files Folder.

Set the JNDI Name for the HomeImpl Bean by editing the file or by clicking the TAB "EJB" and giving jndi name as "abc". 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE glassfish-ejb-jar PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 EJB 3.1//EN" "http://glassfish.org/dtds/glassfish-ejb-jar_3_1-1.dtd">
<glassfish-ejb-jar>
<enterprise-beans>
<ejb>
<ejb-name>HomeImpl</ejb-name>
<jndi-name>abc</jndi-name>
<pass-by-reference>true</pass-by-reference>
</ejb>
</enterprise-beans>
</glassfish-ejb-jar>

Save the XML File.

Note : There can be only one glassfish-ejb-jar.xml file per EJB Module.

Step 5:

- Right click on the Project Node(MyApp)and select clean and Build.

- After clean and build again right click on the project node and select "Deploy".

For Both this Actions "BUILD SUCCESSFUL" Message will be displayed in the console output.Then every thing is fine and our EJB Session Bean  HomeImpl with JNDI Name "abc" is successfully Deployed.

Step 6:

RightClick on the Project Node (MyApp) and create new Class called "Main"

package test;

import java.util.Properties;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;


public class Main {

  public static void main(String arg[])throws Exception
{
Properties p=new Properties();
InitialContext c=new InitialContext();
Object l=c.lookup("abc");
Home r=(Home)l;
System.out.println(r.sayHello("Ayaz"));
}

}

Run this class to check our EJB is deployed Sucessfully . It will give the following result in the output console.
run:
Welcome to EJB Ayaz
BUILD SUCCESSFUL (total time: 14 seconds)


So far we have created a Stateless EJB Session Bean and deployed it in the Server and checked it through the same EJB Module , this will work since we are accessing from EJB Container locally from our EJB Module .

To access this bean remotely from another Java Component such as Web Application or Java Swing Application or Java Webservice we require the Jar files created from the "HomeImpl" Session Bean just now we created  & Server specific jars to load the Bean.

In my next Post on EJB we will see how to do this...


         Next >>                                          Index

--------------------------------------------------------------------------------------------------------



Technology Blogs
blogs

Friday, July 26, 2013

Java WebService Tutorial - Part 07 (Writing a simple webservice using eclipse and access it through SOAPUI )


Well, There are many ways to write a webservice, but it all depends upon the what kind of business logic and what kind of stuff your webservice wants to provide. They are two types of webservice available in the market as for now they are:

1.SOAP
2.REST

Here we will be creating SOAP based Web Service.What is SOAP and how it's work we have already seen,you can refer  links in our index page. As per REST we will see in later part of our tutorials.

In this section we will concentrating on writing a Java webservice based upon a  Java class  which has a business method from this class a webservice we are going to create ,which can be access by many for there needs.

We are going to follow the eclipse Bottom approach to create this webservice.

Bottom-Up-Approach : It is used to create a  webservice & WSDL from a Java class.

So before we begin we need the following

Requirements:

1. Eclipse IDE with J2EE Plugins or Eclipse Indigo J2EE Version [http://www.eclipse.org]

2.A Webserver or Application Server (Here i am   using Tomcat Webserver)


Once we are done with our first webservice. We will access it through SOAP UI.We have already discuss about SOAPUI functionality in previous tutorials you can refer from here :

http://ayazroomy-java.blogspot.in/2013/07/java-web-service-tutorial-with-soap-ui.html

Now, Once you have the Eclipse IDE , You should configure the Tomcat Server in the Eclipse by Adding the  Server in the Server TAB.So now we have the Server ready ....

Now create a new WebProject by :

Step 1:

File -> New -> Dynamic WebProject

Give a Name to the Project say : MyService and click the "Finish" Button.


























Step 2:

Create a Package called "com.test" under "src" folder of   "MyService" WebApplication.

Create a new Class called "Display" under "com.test" package.

Display class :

package com.test;

public class Display {

public String convert(String name)
{
return name.toUpperCase();
}

}

It is a straight forward simple class having a single business method which accepts a String and returns a String in Upper Case format.


Step 3:

Now, Right click on the Project "MyService"[Project Name] node and select the following :

New -> Other -> Webservices -> WebService : It will show a WebService Window

In this window we have couple of options:

1. Select the WebService Type as:  BottomUp Java Bean Service
2. Select the class you have created now here namely : "Display  By clicking on the Browse Button"

There are 3 Configuration links available in this window:

- ServerRuntime  : Select your server in this case we have use Tomcat
- Service Runtime :  Apache Axis - Default it will be selected
-Service Project  : Specify your Project name here "MyService"  and Click the Next Button >>



























Step 4:

Follow instructions in screen shot below. Click Next Button ...


























Step 5 :

After successful deployment the publishing window will appear.Now click the Finish Button














Now you can a wsdl namely Display.wsdl will be generated inside the wsdl folder under the WebContent Directory of the Project "MyService".

Display.wsdl :

<?xml version="1.0" encoding="UTF-8"?>
<wsdl:definitions targetNamespace="http://test.com" xmlns:apachesoap="http://xml.apache.org/xml-soap" xmlns:impl="http://test.com" xmlns:intf="http://test.com" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<!--WSDL created by Apache Axis version: 1.4
Built on Apr 22, 2006 (06:55:48 PDT)-->
<wsdl:types>
<schema elementFormDefault="qualified" targetNamespace="http://test.com" xmlns="http://www.w3.org/2001/XMLSchema">
<element name="convert">
<complexType>
<sequence>
<element name="name" type="xsd:string"/>
</sequence>
</complexType>
</element>
<element name="convertResponse">
<complexType>
<sequence>
<element name="convertReturn" type="xsd:string"/>
</sequence>
</complexType>
</element>
</schema>
</wsdl:types>

<wsdl:message name="convertRequest">

<wsdl:part element="impl:convert" name="parameters">

</wsdl:part>

</wsdl:message>

<wsdl:message name="convertResponse">

<wsdl:part element="impl:convertResponse" name="parameters">

</wsdl:part>

</wsdl:message>

<wsdl:portType name="Display">

<wsdl:operation name="convert">

<wsdl:input message="impl:convertRequest" name="convertRequest">

</wsdl:input>

<wsdl:output message="impl:convertResponse" name="convertResponse">

</wsdl:output>

</wsdl:operation>

</wsdl:portType>

<wsdl:binding name="DisplaySoapBinding" type="impl:Display">

<wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>

<wsdl:operation name="convert">

<wsdlsoap:operation soapAction=""/>

<wsdl:input name="convertRequest">

<wsdlsoap:body use="literal"/>

</wsdl:input>

<wsdl:output name="convertResponse">

<wsdlsoap:body use="literal"/>

</wsdl:output>

</wsdl:operation>

</wsdl:binding>

<wsdl:service name="DisplayService">

<wsdl:port binding="impl:DisplaySoapBinding" name="Display">

  <wsdlsoap:address location="http://localhost:8080/MyService/services/Display"/>

</wsdl:port>

</wsdl:service>

</wsdl:definitions>

Now in the browser if you type the URL :

http://localhost:8080/MyService/services . We can see list of Deployed Services in the Server.

Now, we have the service ready , now we can test this through SOAP UI.

Step 6:

 - Open SOAP UI.

-  Right Click on Project Node->New SoapUI Project --> Provide the WSDL Location Path .
 
-  In this case  http://localhost:8080/MyService/services/Display?wsdl

Open the Soap Request give some name in lower case in request XML and we can see the Response in Upper case for the given name.

















We can create stub for this Webservice by using wsimport tool please refer  http://ayazroomy-java.blogspot.in/2013/07/using-wsimport-tool-to-generate-client.html for creating Stub and client from WSDL.


<< Prev                             Next>>                        Index >>

-------------------------------------------------------------------------------




Technology Blogs
blogs

Thursday, July 25, 2013

Calling a JSP Page from Swing Using Http Library - [ sending & reciving data ]



Today we are going to see , how to call a jsp page which is running in the local server or remote server from swing application and how to sent values to the jsp page and retrieve the same and display to the user.

Requirements:

1. HttpClient Library - Download this library from the apache  site :

http://hc.apache.org/downloads.cgi

2. TomCat Server 

Any application server or web server is required , I have mentioned Tomcat here but you can use of your own.This is required to deploy a web application which contains some JSP Pages.

Once you download the http client library in the form of zip file ,extract the file it will have a folder called lib copy all the jars from lib folder and add it to your class path or if you are using Net beans ,eclipse or any other ID then paste it in your libraries folder.

Now , We need  to create a Web Application which have some jsp so that we can deploy the application and call this JSP from our swing application.I am using Netbeans ID to create a web application .

File -> New -> New Project - > Project Name : MyApp

Now i am going to  creating a JSP called  "http.jsp" in MyApp .   

http.jsp :

<%

int h=Integer.parseInt(request.getParameter("age"));
out.clearBuffer();

if(h>=18)
out.write("Eligible for Voting....");
else
out.write("Not eligible for Voting!!!!");

%>


In this JSP i have not followed any coding standard and enterprise approach for writing a JSP as JSP Document by moving the scriptlet in custom tags .

So this JSP will accept a Parameter called "age" and convert the age to an Integer and Prints the respective output based upon the conditions.Now deploy this application in to Tomcat and run this JSP by
passing age=some value in the URL otherwise it will give an Exception.

http://localhost:8083/ MyApp /http.jsp?age=17

Here i am referring my local host and my port you should refer your own port , other wise page not found error will occur.

Swing Code :

Now we are going to create a Simple Swing Application which will call this JSP and display the result .


package http;

import java.io.DataInputStream;
import javax.swing.JOptionPane;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class Connect extends javax.swing.JFrame {


public Connect() {
initComponents();
setSize(500,500);
}
void getData()
{
try
{

// Create a HttpClient
HttpClient client=new DefaultHttpClient();

// Set the value of TextField as a Parameter in the Request and made a call.
HttpGet get=new HttpGet("http://localhost:8083/scw/http.jsp?age="+jTextField1.getText());

// Get the Response
HttpResponse response=client.execute(get);

// Extract the Response
DataInputStream dataInputStream=new DataInputStream(response.getEntity().getContent());
jTextField2.setText("");
jTextField2.setText(dataInputStream.readLine());
dataInputStream.close();


}catch(Exception e){
JOptionPane.showMessageDialog(this, e.getMessage());}

}
 
private void initComponents() {

jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jTextField2 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(null);

jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel1.setText("Calling JSP From Swing");
getContentPane().add(jLabel1);
jLabel1.setBounds(100, 30, 140, 20);

jLabel2.setText("Age :");
getContentPane().add(jLabel2);
jLabel2.setBounds(46, 110, 40, 14);
getContentPane().add(jTextField1);
jTextField1.setBounds(100, 110, 140, 20);

jLabel3.setText("Result :");
getContentPane().add(jLabel3);
jLabel3.setBounds(44, 160, 50, 14);
getContentPane().add(jTextField2);
jTextField2.setBounds(100, 160, 170, 40);

jButton1.setText("Connect >>");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
getContentPane().add(jButton1);
jButton1.setBounds(260, 110, 110, 23);

pack();
  }

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
getData();
}

public static void main(String args[]) {
new Connect().setVisible(true);
}


// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
// End of variables declaration
}

Result :
























<< Prev                     Next>>                                               Index >>

-------------------------------------------------------------------------------------------- 




Technology Blogs
blogs

Java WebService Tutorial - Part 06 ( Using wsimport tool to generate Client and accessing a Webservice )


In this tutorial we will see how wsimport tool can be used to generate java classes from a wsdl and how we can access a webservice easily like normal java applications.

wsimport :

This tool is come along with the jdk.If you have install the JDK properly and your classpath or JAVA_HOME variable is set you can see the list of options provided by this command  by typing wsimport in the command prompt.

For generating Java classess from wsimport the syntax is :

wsimport  wsdl-location-path  -d -keep

The wsdl-location-path : Is the location of wsdl file existence.

-d : specify the directory where all the generated classes should be placed.

-keep : It will keep the java source code of generated classes in the respective directory mentioned.

-extension :allow vendor extension - functionality if not have been specified.

Ex:

wsimport  hello.wsdl   src  -keep

Now we will take the sample webservice of w3schools which has the follwing wsdl location:

http://www.w3schools.com/webservices/tempconvert.asmx?WSDL

Execute the command in DOS Prompt to generate classes from wsdl :

 C:\webservice> wsimport  http://www.w3schools.com/webservices/tempconvert.asmx?WSDL -extension   -keep
 


















After execution it will create a folder called org inside the webs service folder.

Now Create a Main class to access these webservice :

 Code:

import org.tempuri.*;

 public class Main {
   
    public static void main(String a[])
    {
        TempConvert convert=new TempConvert();
        System.out.println(convert.getTempConvertSoap().celsiusToFahrenheit("122"));
       
    }
}
   
Save these class inside "webservice" folder .Compile and run it you will see the output as "251.6" returning from web service.

Result :















<<Prev          Index            Next >>                 

 -------------------------------------------------------





Technology Blogs
blogs

Wednesday, July 24, 2013

Simple Swing Application to Store -Retrive Values from Embbeded Derby Database


Derby Database :

It is a light weight database comes along with java jdk.

It has two versions:

- Stand alone : It will be access only in the application which is using it . It will be embedded in to the  application and run in the JVM.

- Client/Server : It can access from outside as a server running separately. Multiple user can access it.

We are you to take the first One . embedded one . We are going to create the following table in DB from our java code and then we will insert data by using swing and displayed to the user in the textarea using swing components.

Table : data

create table data(name varchar(40), id varchar(40), age varchar(40), place varchar(40) )

For accessing Derby Embedded we need two jars:

- derby.jar
- derbytools.jar

This can be obtained from the lib folder of jdk installation directory.where you can find a folder called Sun it can be exists in the installation directory or in Program files .which have a folder called JavaDB/lib.From here you can obtain these jars and add these to your class path.

Code :

 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;


public class Home extends javax.swing.JFrame {

/* Driver for Embedded Derby Database */
String driver="org.apache.derby.jdbc.EmbeddedDriver";

/*Create Database with name derbyDB */
String connectionURL="jdbc:derby:derbyDB;create=true";
Connection c=null;
PreparedStatement preparedStatement=null;

public Home() {

initComponents();
setConnections();
setSize(800,500);

}

public void insert()
{
try
{
preparedStatement=c.prepareStatement("insert into data values(?,?,?,?)");
preparedStatement.setObject(1, jTextField1.getText());
preparedStatement.setObject(2, jTextField2.getText());
preparedStatement.setObject(3, jTextField3.getText());
preparedStatement.setObject(4, jTextField4.getText());
preparedStatement.executeUpdate();

preparedStatement=c.prepareStatement("select * from data");
ResultSet r= preparedStatement.executeQuery();
while(r.next())
{
jTextArea1.append("\nName:"+" "+r.getString(1)+"\n"+"Id:"+ " "+r.getString(2)+"\n"+"Age:"+" "+r.getString(3)+"\n"+"Place:"+" "+r.getString(4)+"\n"+"\n");


}

}catch(Exception e){
JOptionPane.showMessageDialog(this, e.getMessage());

}

}

public void setConnections()
{
try
{
Class.forName(driver).newInstance();
c= DriverManager.getConnection(connectionURL);
preparedStatement=c.prepareStatement("create table data(name varchar(40), id varchar(40), age varchar(40), place varchar(40) )");
preparedStatement.execute();

}
catch(Exception e){
JOptionPane.showMessageDialog(this, e.getMessage());
}
}


// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jTextField3 = new javax.swing.JTextField();
jTextField4 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jLabel5 = new javax.swing.JLabel();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(null);

jLabel1.setText("Name :");
getContentPane().add(jLabel1);
jLabel1.setBounds(30, 50, 80, 20);

jLabel2.setText("Id :");
getContentPane().add(jLabel2);
jLabel2.setBounds(30, 80, 60, 14);

jLabel3.setText("Age :");
getContentPane().add(jLabel3);
jLabel3.setBounds(26, 110, 50, 14);

jLabel4.setText("Place :");
getContentPane().add(jLabel4);
jLabel4.setBounds(20, 144, 60, 10);

jTextField1.setText(" ");
getContentPane().add(jTextField1);
jTextField1.setBounds(110, 50, 180, 20);

jTextField2.setText(" ");
getContentPane().add(jTextField2);
jTextField2.setBounds(110, 80, 180, 20);

jTextField3.setText(" ");
getContentPane().add(jTextField3);
jTextField3.setBounds(110, 110, 180, 20);

jTextField4.setText(" ");
getContentPane().add(jTextField4);
jTextField4.setBounds(110, 140, 180, 20);

jButton1.setText("Add");

/* Whenever button is pressed this action happens */

jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
getContentPane().add(jButton1);
jButton1.setBounds(90, 200, 170, 23);

jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);

getContentPane().add(jScrollPane1);
jScrollPane1.setBounds(340, 50, 190, 210);

jLabel5.setText("Values from Database :");
getContentPane().add(jLabel5);
jLabel5.setBounds(340, 30, 140, 14);

pack();
  } 


// call insert on clicking of Add button

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

insert();

}


public static void main(String args[]) {
new Home().setVisible(true);
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField jTextField4;
// End of variables declaration
}

Output:




Index                                                     Next >>


                               ------------------------------------------------




Technology Blogs
blogs

Java WebService Tutorial - Part 05 ( XSD )


In this tutorial  we will look in detail about XSD (XmlSchemaDefinition) in details now....

XSD : 

It is used in WSDL Document to define the data types of Method takes .Such as Input Parameters data types,Output Parameter data types,attribute types and return types.

It defines element that can appear in Document.

It defines attributes that can appear in the Document.

It defines the order of Child element and define no.of child elements.

It defines whether an elemnt is empty or can include text.
 
It defines default and fixed value for elements and attributes.

It can define in the WSDL itself or it can be refer externally by importing the XSD URL in the WSDL just like JavaScript and CSS.

It's an alternative to DTD's.More Powerful then DTD.(Document Type Definition)

Multiple Schema's can refer in one WSDL.Allows re-usability.Allow Namespace.

We can define our own dataype derived from the standard types.

Root Element of XSD :
  
<schema> : This is the root element of any XML Schema Document.It can contain attribute also.

 Syntax:
<? xml version="1.0" ? >
<xs:schema>
------
------
</xs:schema>

Ex:

<?xml version="1.0"?>

<xs:schema xmlns:"http://www.w3.org/2001/XMLSchema" targetNameSpace="http://www.ayaz.com" xmlns="http://www.ayaz.com" elementFromDefault="qualified">
...............
...............

</xs:schema>

Here xs:schema  xmlns follows the namespace define the w3 standards. targetNamspace schema defines the elements defines by this schema comes from ayaz.com.elementfromDefault specifies that every element should be namespace qualified.


Simple Example : (note.xml)
------------------------------------
<?xml version="1.0"?>
<note>
<from>Tom</from>
<to>Jack</to>
<heading>Remainders</heading>
<body> Dont'forget</body>
</note>

note.xsd :  Defines element for note.xml

<?xml version="1.0"?>
<xs:schema xmlns:"http://www.w3.org/2001/XMLSchema" targetNameSpace="http://www.ayaz.com" xmlns="http://www.ayaz.com" elementFromDefault="qualified">
.
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:String"/>
<xs:element name="from" type="xs:String/>
<xs:element name="heading" type="xs:String/>
<xs:element name="body" type="xs:String/>
 </xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

We will look on each of the element in detail in later part.So i have the xsd for my xml element now i can refer in my Document .

<?xml version="1.0"?>
< note xmlns="http://www.ayaz.com" xmlns=xsi="http://www.w3org.2001/XMLSchema-instance"
xsi:schemaLocation="http://www.ayaz.com/note.xsd">
<from>Tom</from>
<to>Jack</to>
<heading>Remainders</heading>
<body> Dont'forget</body>
</note>
Red color highlighted - tells the Schema validator that all elements used in this XML Document are declared in "http://www.ayaz.com"

Blue color highlighted - tells once you have the XML Schema instances we can use the SchemaLocation Attribute.

Brown Color highlighted - tells the namespace used for the xsd and it's location.

2. XSD Elements:

 XSD elements can be classified as "Single" and Complex" Element. 

a.Simple Element :

A Simple element does not have any attribute and other elements.

It can contain only Text.The Text can be of any type (String,boolean,Int)or it can be custom type define by the user.

We can also add restrictions such as limit the content or to match the specific pattern.

Synatx: 

<xs:element name="------ " type="------"/>

Ex: <xs:element name="firstname" type="xs:String"/>

Default & Fixed Value :

Default - This value is taken when there is no value is provided.
Fixed - This value is taken assigned automatically to the element and cannot assign other values.

Ex:
<xs:element name="firstname" type="xs:String" default="John "/>

<xs:element name="color" type="xs:String" fixed="red"/>


b. XSD Attributes:

Simple elements cannot have attributes. If an element is specified with attribute then it is considered ad complex type element.But a attribute always declared as   simple type.

Synatx :

<xs:attribute name="-----" type="----"/>

Ex:

<xs:attribute name="lang" type="xs:String" />

<lastname lang="en">Smith</lastname> -- Refering in XML Document.

Note: Default and fixed behave same way as the does for simple element.

Optional & required

Attribute can be specify as optional or required one.Attributes are optional by default to make the attribute declared as required we should declared by the "use" keyword.

<xs:attribute name="lang" type="xs:String"  use="required'/>

c. XSD Restrictions /Facets   :

<xs:restriction> is used to set restrcitions.

Restriction on Simple Element

Ex: To accept values between 0-120

<xs:element name="age">
  <xs:simpleType>
    <xs:restriction base="xs:integer">
      <xs:minInclusive value="0"/>
      <xs:maxInclusive value="120"/>
    </xs:restriction>
  </xs:simpleType>
</xs:element>


To set Restrictions on set of values use the enumeration

<xs:element name="car">
  <xs:simpleType>
    <xs:restriction base="xs:string">
      <xs:enumeration value="Audi"/>
      <xs:enumeration value="Golf"/>
      <xs:enumeration value="BMW"/>
    </xs:restriction>
  </xs:simpleType>
</xs:element>

Length Restriction

 <xs:element name="password">
  <xs:simpleType>
    <xs:restriction base="xs:string">
      <xs:length value="8"/>
    </xs:restriction>
  </xs:simpleType>
</xs:element>
 

Constraint          Description
enumeration Defines a list of acceptable values
fractionDigits Specifies the maximum number of decimal places allowed. Must be equal to or greater than zero
length Specifies the exact number of characters or list items allowed. Must be equal to or greater than zero
maxExclusive Specifies the upper bounds for numeric values (the value must be less than this value)
maxInclusive Specifies the upper bounds for numeric values (the value must be less than or equal to this value)
maxLength Specifies the maximum number of characters or list items allowed. Must be equal to or greater than zero
minExclusive Specifies the lower bounds for numeric values (the value must be greater than this value)
minInclusive Specifies the lower bounds for numeric values (the value must be greater than or equal to this value)
minLength Specifies the minimum number of characters or list items allowed. Must be equal to or greater than zero
pattern Defines the exact sequence of characters that are acceptable
totalDigits Specifies the exact number of digits allowed. Must be greater than zero
whiteSpace Specifies how white space (line feeds, tabs, spaces, and carriage returns) is handled

3. Complex XSD Elements :

A complex element is an XML element that contains other elements and/or attributes.
There are four kinds of complex elements:
  • empty elements
  • elements that contain only other elements
  • elements that contain only text
  • elements that contain both other elements and text.
empty element :

An empty complex element cannot have contents, only attributes.

An empty XML element

<product prodid="1345" /> 

 Ex:
<xs:element name="product">
  <xs:complexType>
    <xs:attribute name="prodid" type="xs:positiveInteger"/>
  </xs:complexType>
</xs:element> 

Element which have elements only :

An "elements-only" complex type contains an element that contains only other elements.

An XML element, "person", that contains only other elements:

<person>
  <firstname>John</firstname>
  <lastname>Smith</lastname>
</person>

You can define the "person" element in a schema, like this:
<xs:element name="person">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="firstname" type="xs:string"/>
      <xs:element name="lastname" type="xs:string"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>

Text- Only :

A complex text-only element can contain text and attributes.

This type contains only simple content (text and attributes), therefore we add a simpleContent element around the content. When using simple content, you must define an extension OR a restriction within the simpleContent element, like this:
<xs:element name="somename">
  <xs:complexType>
    <xs:simpleContent>
     
        ....
        ....
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
</xs:element>

OR

<xs:element name="somename">
  <xs:complexType>
    <xs:simpleContent>
     
        ....
        ....
      </xs:restriction>
    </xs:simpleContent>
  </xs:complexType>
</xs:element>

Mixed Complex Elements:
A mixed complex type element can contain attributes, elements, and text.

An XML element, "letter", that contains both text and other elements:
<letter>
  Dear Mr.<name>John Smith</name>.
  Your order <orderid>1032</orderid>
  will be shipped on 2001-07-13.
</letter>
The following schema  declares the "letter" element:

  <xs:complexType mixed="true">
    <xs:sequence>
      <xs:element name="name" type="xs:string"/>
      <xs:element name="orderid" type="xs:positiveInteger"/>
      <xs:element name="shipdate" type="xs:date"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>

4 . Indicators
There are seven indicators:
Order indicators:
  • All
  • Choice
  • Sequence
Occurrence indicators:
  • maxOccurs
  • minOccurs
Group indicators:
  • Group name
  • attributeGroup name

Mostly Used indicators are discussed below :

Sequence Indicator

The <sequence> indicator specifies that the child elements must appear in a specific order:
<xs:element name="person">
   <xs:complexType>
    <xs:sequence>
      <xs:element name="firstname" type="xs:string"/>
      <xs:element name="lastname" type="xs:string"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>

Occurence Indicator 

Occurrence indicators are used to define how often an element can occur.

maxOccurs Indicator
The <maxOccurs> indicator specifies the maximum number of times an element can occur:
<xs:element name="person">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="full_name" type="xs:string"/>
      <xs:element name="child_name" type="xs:string" maxOccurs="10"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>
The example above indicates that the "child_name" element can occur a minimum of one time (the default value for minOccurs is 1) and a maximum of ten times in the "person" element.

minOccurs Indicator 

 The <minOccurs> indicator specifies the minimum number of times an element can occur:
<xs:element name="person">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="full_name" type="xs:string"/>
      <xs:element name="child_name" type="xs:string"
      maxOccurs="10" minOccurs="0"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>
The example above indicates that the "child_name" element can occur a minimum of zero times and a maximum of ten times in the "person" element.

To allow an element to appear an unlimited number of times, use the maxOccurs="unbounded" statement


<<Prev                            Next >>                   Index

---------------------------------------------------------------------------------------------                                        

Please provide your comments...



Technology Blogs
blogs

Tuesday, July 23, 2013

Java Web Service Tutorial (WSDL & XSD ) - Part 04


WSDL :


WSDL stands for Web Services Description Language

WSDL is an XML based protocol for information exchange in decentralized and distributed environments.

WSDL is the standard format for describing a web service.

WSDL is an interface provided by the webservice publisher to the clients .Using this interface client can understands what are they type of operation the webservice is offering.

WSDL is declard as a  part of UDDI  while registering the webservice in UDDI.

WSDL Elements:

Three major elements of WSDL that can be defined separately and they are:

a.Types - It contains all the datatypes specification what type of values methods accepts.

b.Operations - Define the Methods provided by the Webservice and it's input parameters and it's result.

c.Binding - Contains the end point URL of  the webservice .

Apart from these WSDL also have other elements.

Definition: This element must be the root element of all WSDL documents. It defines the name of the web service, declares multiple namespaces used throughout the remainder of the document, and contains all the service elements described here.

Data types(xsd): the data types - in the form of XML schemas(xsd) or possibly some other mechanism - to be used in the messages. This can define inside the WSDL or can refer from external location.

Message: an abstract definition of the data, in the form of a message presented either as an entire document or as arguments to be mapped to a method invocation.

Operation: the abstract definition of the operation for a message, such as naming a method, message queue, or business process, that will accept and process the message

Port type : an abstract set of operations mapped to one or more end points, defining the collection of operations for a binding; the collection of operations, because it is abstract, can be mapped to multiple transports through various bindings.

Binding: the concrete protocol and data formats for the operations and messages defined for a particular port type.

Port: a combination of a binding and a network address, providing the target address of the service communication.

Service: a collection of related end points encompassing the service definitions in the file; the services map the binding to the port and include any extensibility definitions.

In addition to these major elements, the WSDL specification also defines the following utility elements:

Documentation: element is used to provide human-readable documentation and can be included inside any other WSDL element.

Import: element is used to import other WSDL documents or XML Schemas.

Ex:

<?xml version="1.0" encoding="utf-8"?>
<wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:tns="http://tempuri.org/" xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" targetNamespace="http://tempuri.org/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
<wsdl:types>
<s:schema elementFormDefault="qualified" targetNamespace="http://tempuri.org/">
<s:element name="FahrenheitToCelsius">
<s:complexType>
<s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="Fahrenheit" type="s:string" />
</s:sequence>
</s:complexType>
</s:element>
<s:element name="FahrenheitToCelsiusResponse">
<s:complexType>
<s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="FahrenheitToCelsiusResult" type="s:string" />
</s:sequence>
</s:complexType>
</s:element>
<s:element name="CelsiusToFahrenheit">
<s:complexType>
<s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="Celsius" type="s:string" />
</s:sequence>
</s:complexType>
</s:element>
<s:element name="CelsiusToFahrenheitResponse">
<s:complexType>
<s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="CelsiusToFahrenheitResult" type="s:string" />
</s:sequence>
</s:complexType>
</s:element>
<s:element name="string" nillable="true" type="s:string" />
</s:schema>
</wsdl:types>
<wsdl:message name="FahrenheitToCelsiusSoapIn">
<wsdl:part name="parameters" element="tns:FahrenheitToCelsius" />
</wsdl:message>
<wsdl:message name="FahrenheitToCelsiusSoapOut">
<wsdl:part name="parameters" element="tns:FahrenheitToCelsiusResponse" />
</wsdl:message>
<wsdl:message name="CelsiusToFahrenheitSoapIn">
<wsdl:part name="parameters" element="tns:CelsiusToFahrenheit" />
</wsdl:message>
<wsdl:message name="CelsiusToFahrenheitSoapOut">
<wsdl:part name="parameters" element="tns:CelsiusToFahrenheitResponse" />
</wsdl:message>
<wsdl:message name="FahrenheitToCelsiusHttpPostIn">
<wsdl:part name="Fahrenheit" type="s:string" />
</wsdl:message>
<wsdl:message name="FahrenheitToCelsiusHttpPostOut">
<wsdl:part name="Body" element="tns:string" />
</wsdl:message>
<wsdl:message name="CelsiusToFahrenheitHttpPostIn">
<wsdl:part name="Celsius" type="s:string" />
</wsdl:message>
<wsdl:message name="CelsiusToFahrenheitHttpPostOut">
<wsdl:part name="Body" element="tns:string" />
</wsdl:message>
<wsdl:portType name="TempConvertSoap">
<wsdl:operation name="FahrenheitToCelsius">
<wsdl:input message="tns:FahrenheitToCelsiusSoapIn" />
<wsdl:output message="tns:FahrenheitToCelsiusSoapOut" />
</wsdl:operation>
<wsdl:operation name="CelsiusToFahrenheit">
<wsdl:input message="tns:CelsiusToFahrenheitSoapIn" />
<wsdl:output message="tns:CelsiusToFahrenheitSoapOut" />
</wsdl:operation>
</wsdl:portType>
<wsdl:portType name="TempConvertHttpPost">
<wsdl:operation name="FahrenheitToCelsius">
<wsdl:input message="tns:FahrenheitToCelsiusHttpPostIn" />
<wsdl:output message="tns:FahrenheitToCelsiusHttpPostOut" />
</wsdl:operation>
<wsdl:operation name="CelsiusToFahrenheit">
<wsdl:input message="tns:CelsiusToFahrenheitHttpPostIn" />
<wsdl:output message="tns:CelsiusToFahrenheitHttpPostOut" />
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name="TempConvertSoap" type="tns:TempConvertSoap">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" />
<wsdl:operation name="FahrenheitToCelsius">
<soap:operation soapAction="http://tempuri.org/FahrenheitToCelsius" style="document" />
<wsdl:input>
<soap:body use="literal" />
</wsdl:input>
<wsdl:output>
<soap:body use="literal" />
</wsdl:output>
</wsdl:operation>
<wsdl:operation name="CelsiusToFahrenheit">
<soap:operation soapAction="http://tempuri.org/CelsiusToFahrenheit" style="document" />
<wsdl:input>
<soap:body use="literal" />
</wsdl:input>
<wsdl:output>
<soap:body use="literal" />
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:binding name="TempConvertSoap12" type="tns:TempConvertSoap">
<soap12:binding transport="http://schemas.xmlsoap.org/soap/http" />
<wsdl:operation name="FahrenheitToCelsius">
<soap12:operation soapAction="http://tempuri.org/FahrenheitToCelsius" style="document" />
<wsdl:input>
<soap12:body use="literal" />
</wsdl:input>
<wsdl:output>
<soap12:body use="literal" />
</wsdl:output>
</wsdl:operation>
<wsdl:operation name="CelsiusToFahrenheit">
<soap12:operation soapAction="http://tempuri.org/CelsiusToFahrenheit" style="document" />
<wsdl:input>
<soap12:body use="literal" />
</wsdl:input>
<wsdl:output>
<soap12:body use="literal" />
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:binding name="TempConvertHttpPost" type="tns:TempConvertHttpPost">
<http:binding verb="POST" />
<wsdl:operation name="FahrenheitToCelsius">
<http:operation location="/FahrenheitToCelsius" />
<wsdl:input>
<mime:content type="application/x-www-form-urlencoded" />
</wsdl:input>
<wsdl:output>
<mime:mimeXml part="Body" />
</wsdl:output>
</wsdl:operation>
<wsdl:operation name="CelsiusToFahrenheit">
<http:operation location="/CelsiusToFahrenheit" />
<wsdl:input>
<mime:content type="application/x-www-form-urlencoded" />
</wsdl:input>
<wsdl:output>
<mime:mimeXml part="Body" />
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="TempConvert">
<wsdl:port name="TempConvertSoap" binding="tns:TempConvertSoap">
<soap:address location="http://www.w3schools.com/webservices/tempconvert.asmx" />
</wsdl:port>
<wsdl:port name="TempConvertSoap12" binding="tns:TempConvertSoap12">
<soap12:address location="http://www.w3schools.com/webservices/tempconvert.asmx" />
</wsdl:port>
<wsdl:port name="TempConvertHttpPost" binding="tns:TempConvertHttpPost">
<http:address location="http://www.w3schools.com/webservices/tempconvert.asmx" />
</wsdl:port>
</wsdl:service>
</wsdl:definitions>

The following wsdl is obtained from the webservice TempConvert of w3schools.com
URL : http://www.w3schools.com/webservices/tempconvert.asmx?WSDL
Now,examine this WSDL closely.

wsdl definition- This contains lot of name space we don't need to care about this,these are all can be added/generated by tools. Generally a WSDL is generated by Tools.But we need to understand it content which help us to write the client code.

wsdl types : This contains the in-built xsd(Xml Schema Definition)for the types methods accept.We will discuss about XSD in detail in next part.

wsdl message : This contains the message name which can refer at various place for mention the types of input and output parameters for webservice methods.

wsdl operation : It contains the Methods provided by the webservice.

wsdl input/output : It contains the Methods inputs and output parameter name and it's type.Normally in big WSDL it being refer in external xsd's.

Other elements we actually no need to worry.Since once we obtained the WSDL ,next thing we have to do is generate java classes from it .It can done by tools.Once we obtained the java classes we can write the client code easily and  make a request to the webservice.

In the next part we will in detail about xsd, because it is important to understand what type of data a method accept. Please provide your comments.


 << Prev                                         Index                            Next >>


                     -------------------------------------------------------------------------------




Technology Blogs
blogs

Monday, July 22, 2013

Java Web Service Tutorial (With SOAP UI)- Part 03


  In the last part (02) we saw about SOAP elements, SOAP Specifications and  SOAP Faults.
  Now we will see SOAP encoding : 

 - Soap includes a built in set of rules for encoding Data types. 
 - These data types can be float,integers,String,Arrays etc
         
        They are two SOAP Data types :  
        1. Scalar 2. Compound


  1. Scalar : Scalar types contains only one value such as "Last Name","Price" etc.

  2.Compound : Compound Types contains multiple values such as "Purchase of orders" ,"List of Stock  Quotes."Compound types are further subdivided into arrays and structs. Arrays contain multiple values,  each of which is specified by an ordinal position. Structs also contain multiple values, but each element is    specified by an accessors name.

-  The encoding style for a SOAP message is set via the SOAP-ENV:encodingStyle attribute.
-  To use SOAP 1.1 encoding, use the value http://schemas.xmlsoap.org/soap/encoding/.
-  To use SOAP 1.2 encoding, use the value http://www.w3.org/2001/09/soap-encoding.

Ex: Scalar Type

<?xml version='1.0' encoding='UTF-8'?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://www.w3.org/2001/09/soap-envelope"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SOAP-ENV:Body>
<ns1:getPriceResponse
xmlns:ns1="urn:examples:priceservice"
SOAP-ENV:encodingStyle="http://www.w3.org/2001/09/soap-encoding">
<return xsi:type="xsd:double">54.99</return>

</ns1:getPriceResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

- The encoding Style Attribute is used to set the Encoding Style.
- Scalar types includes int,short,long,double,boolean,float,date,time etc.
- The SOAP specification provides several options for indicating the data type of a specific XML element.        The first option is to specify an xsi:type attribute for each element. The second option is to store data type      information within an external XML Schema or even within human-readable documentation.

Ex: Compound Type (Array)

Here is a sample SOAP response with an array of double values:

<?xml version='1.0' encoding='UTF-8'?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://www.w3.org/2001/09/soap-envelope"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SOAP-ENV:Body>
<ns1:getPriceListResponse
xmlns:ns1="urn:examples:pricelistservice"
SOAP-ENV:encodingStyle="http://www.w3.org/2001/09/soap-encoding">
<return
xmlns:ns2="http://www.w3.org/2001/09/soap-encoding"
xsi:type="ns2:Array" ns2:arrayType="xsd:double[2]">
<item xsi:type="xsd:double">54.99</item>
<item xsi:type="xsd:double">19.99</item>
</return>

</ns1:getPriceListResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Here , Array size is declared as 2, so two values has been send in the response for the Array.

Compound Type (Struct)

In contrast to arrays, structs contain multiple values, but each element is specified with a unique accessor element.
For example, consider an item within a product catalog. In this case, the struct might contain a product SKU, product name, description, and price. Here is how such a struct would be represented in a SOAP message:

<?xml version='1.0' encoding='UTF-8'?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://www.w3.org/2001/09/soap-envelope"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SOAP-ENV:Body>
<ns1:getProductResponse
xmlns:ns1="urn:examples:productservice"
SOAP-ENV:encodingStyle="http://www.w3.org/2001/09/soap-encoding">
<return xmlns:ns2="urn:examples" xsi:type="ns2:product">
<name xsi:type="xsd:string">Red Hat Linux</name>
<price xsi:type="xsd:double">54.99</price>
<description xsi:type="xsd:string">
Red Hat Linux Operating System
</description>
<SKU xsi:type="xsd:string">A358185</SKU>
</return>

</ns1:getProductResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Each element in a struct is specified with a unique accessor name.
For example, the message above includes four accessor elements: name , price , description , and SKU. Each element can have its own data type; for example, name is specified as a string , whereas price is specified as a double.

Literal Encoding:

We are not required to use the SOAP encoding style. In fact,occasionally you may want to ignore the SOAP encoding rules completely and embed an entire XML document (or just a portion of the document) directly into your SOAP message.

Doing so is referred to as literal XML encoding, and it requires that you specify a literal XML encoding style. Within Apache SOAP, the literal XML style is specified with the namespace http://xml.apache.org/xml-soap/literalxml.

For example, the following is a second option for encoding product information. Rather than encoding the product as a SOAP struct, the data is encoded as a literal XML document:

<?xml version='1.0' encoding='UTF-8'?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://www.w3.org/2001/09/soap-envelope"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SOAP-ENV:Body>
<ns1:getProductResponse
xmlns:ns1="urn:examples:XMLproductservice"
SOAP-ENV:encodingStyle=
"http://xml.apache.org/xml-soap/literalxml">

<return>
<product sku="A358185">
<name>Red Hat Linux</name>
<description>Red Hat Linux Operating System</description>
<price>54.99</price></product>
</return>

</ns1:getProductResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

So this ends the SOAP Part of Webservice, So far we have learnt about SOAP Specifications,SOAP   Messaging elements, SOAP Faults and SOAP Encoding.All these will help to understand the SOAP Request even without writing the code, and helps to write our own soap request and test it in the SOAP Tools. 

One of the major tool use for testing web service is "SoapUI". Now test a sample service withour SOAP knowledge in SOAP UI.For this we need to install SOAP UI Software.

Download SOAP UI from www.sopaui.com . It has "2" version pro version which is not a free ware and SOAP UI open source version which is a free ware ,You can download any one of these.

We are going to test the Sample Webservice provided by w3schools.com called "TempConversion" which has the below wsdl url .

WSDL URL :http://www.w3schools.com/webservices/tempconvert.asmx?WSDL

This service accepts accept Celsius as "String" and returns the Fahrenheit as "String".If you hit the following URL in browser an XML document will be open which is called as "WSDL" document .Dont worry if you dont understand we will discuss WSDL in our next post in detail.

After installation Open the SOAP UI :

1. Create New SoapUI Project by right clicking on the Project Node:

















2. Copy the WSDL URL and paste in the Initial WSDL/WADL Text Box , and the Project Name will automatically show up and click "ok" button.














3. Now Double click on the "Request Node" Inside the "CelciusTo Fahrenheit " Node.A request window will be open with default Soap Request.

















Request :

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
<soapenv:Header/>
<soapenv:Body>
<tem:CelsiusToFahrenheit>
<!--Optional:-->
<tem:Celsius>122</tem:Celsius> <!-- Change the "? " to 122 in the Request -->
</tem:CelsiusToFahrenheit>
</soapenv:Body>
</soapenv:Envelope>

Mention a String value in the Celsius Tag and click the Run Button , You can see the Response in the Right Side.












Response:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<CelsiusToFahrenheitResponse xmlns="http://tempuri.org/">
<CelsiusToFahrenheitResult>251.6</CelsiusToFahrenheitResult>
</CelsiusToFahrenheitResponse>
</soap:Body>
</soap:Envelope>

If we  see the Request we can see the Envelope,Header,Body with Method and Parameters is present which we discuss in earlier parts, So now we can easily understand any SOAP Request now.

In this way , we can test our web service without writing client code, In the next post we will discuss about WSDL and it's contents.

<< Previous                                 Index                                   Next>>                
                           
                          --------------------------------------------------------------------------------------

Please comment your thoughts...



Technology Blogs

blogs