How to create ZK Client for Web Service on NetBeans.

Before create Web Service Client,we must create Web Service.
Web Service and Web Service Client was very dificult to create.
Metro is the solution for this.
Metro™ is a high-performance, extensible, easy-to-use web service stack.
You can use it for every type of web service from simple to reliable, secured,
and transacted web services that interoperate with .NET services.
Metro bundles stable versions of JAX-WS RI and WSIT.




1. Web Service made by Metro

2. ZK Web Service Client

Steps to follow:

1. Create Web Service using Metro.

  1.Create Project

createProject

     createProject

 

    CreateProject

  2.Create classes
    package model
          CafeItem, CafeTableModel
    package service
          CafeCatalog 

    model package

      CafeItem class

 

package model;

import java.io.Serializable;
import java.math.BigDecimal;

public class CafeItem implements Serializable {

private static long serialVersionUID = 1L;


private Integer id;
private String name;
private String price;
private String image;

public CafeItem() {
}

/**
* @return the id
*/
public Integer getId() {
return id;
}

/**
* @param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}

/**
* @return the name
*/
public String getName() {
return name;
}

/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}

/**
* @return the price
*/
public String getPrice() {
return price;
}

/**
* @param price the price to set
*/
public void setPrice(String price) {
this.price = price;
}

/**
* @return the image
*/
public String getImage() {
return image;
}

/**
* @param image the image to set
*/
public void setImage(String image) {
this.image = image;
}

  


  CafeTableModel class

package model;

import javax.swing.table.AbstractTableModel;

/**
* @author Teodor Danciu (teodord@users.sourceforge.net)
* @version $Id: CustomTableModel.java 2692 2009-03-24 17:17:32Z teodord $
*/
public class CafeTableModel extends AbstractTableModel
{

/**
*
*/
private String[] columnNames = {"name", "id", "price", "image"};

/**
*
*/
private Object[][] data =
{
{"typica", new Integer(0), "5.12", "http://localhost:8080/CafeService/images/typica.png"},
{"sumatra", new Integer(1), "4.25", "http://localhost:8080/CafeService/images/sumatra.png"},
{"moca", new Integer(2), "4.25", "http://localhost:8080/CafeService/images/moca.png"},
{"kilimanjaro", new Integer(3), "5.65", "http://localhost:8080/CafeService/images/kilimanjaro.png"},
{"blue_mountain", new Integer(4), "5.65", "http://localhost:8080/CafeService/images/blue_mountain.png"},
{"kona", new Integer(5), "4.55", "http://localhost:8080/CafeService/images/kona.png"},
{"java", new Integer(6), "10.55", "http://localhost:8080/CafeService/images/java.png"},
{"columbia", new Integer(7), "4.55", "http://localhost:8080/CafeService/images/columbia.png"},
{"kenya", new Integer(8), "5.12", "http://localhost:8080/CafeService/images/kenya.png"},
{"geisya", new Integer(9), "6.65", "http://localhost:8080/CafeService/images/geisya.png"},
{"blend", new Integer(10), "5.25", "http://localhost:8080/CafeService/images/blend.png"},
};

/**
*
*/
public CafeTableModel()
{
}

/**
*
*/
public int getColumnCount()
{
return this.columnNames.length;
}

/**
*
*/
public String getColumnName(int columnIndex)
{
return this.columnNames[columnIndex];
}

/**
*
*/
public String[] getColumnNames()
{
return this.columnNames;
}

/**
*
*/
public int getRowCount()
{
return this.data.length;
}

/**
*
*/
public Object getValueAt(int rowIndex, int columnIndex)
{
return this.data[rowIndex][columnIndex];
}

public CafeItem getCafeItem(int rowIndex){
CafeItem item = new CafeItem();
item.setId((Integer)this.data[rowIndex][1]);
item.setName((String)this.data[rowIndex][0]);
item.setPrice((String)this.data[rowIndex][2]);
Object image = this.data[rowIndex][3];
item.setImage((String)image);
// item.setImage((String)this.data[rowIndex][3]);
return item;
}

}


    service package

      CafeCatalog class

/*
* Catalog.java
*
*/
package service;

import model.CafeItem;
import model.CafeTableModel;
import java.util.ArrayList;
import java.util.List;
import javax.jws.WebService;

@WebService
public class CafeCatalog {

CafeTableModel datasource = new CafeTableModel();
int maxitem = datasource.getRowCount();
/**
* Creates a new instance of Catalog
*/
public CafeCatalog() {
}

public List<CafeItem> getItems(int firstItem, int batchSize) {
List<CafeItem> list = new ArrayList();
int items = 0;
if (maxitem < (firstItem + batchSize )) {
items = maxitem;
}else{
items = firstItem + batchSize ;
}

for(int i = firstItem;i < items ; i++ ){
CafeItem item = new CafeItem();
item = datasource.getCafeItem(i);
list.add(item);
}
return list;

}

public CafeItem getItem(int id){
CafeItem item = null;
item = datasource.getCafeItem(id);
return item;
}

public int getItemCount() {
return maxitem;
}

public double purchase(int id, int quantom){
CafeItem item = datasource.getCafeItem(id);
String sPrice = item.getPrice();
double price = Double.parseDouble(sPrice);
return price * quantom;
}
}


}

please notice at the top of class,Java annotation @WebService is attached.

@WebService
public class CafeCatalog {

  3.Create Web Service

     Right click the CafegService node in the Projects window. Select Clean and Build.
     then Web Service is built. 

webService

  4.Deploying and Testing the Web Service

When you deploy a web service to a web container, the NetBeans IDE lets you test the web service to see if it functions as you expect. The Tester application, provided by GlassFish, is integrated into NetBeans for this purpose

Right-click the project and choose Run.WebService

The IDE starts the application server, builds the application, and the browser opens.
In the Glassfish output window you should see that the CafeService has been deployed:

wsgen successful
DPL5306:Servlet Web Web Service Endpoint[CafeCatalog] listening at address[http://p551sh-stera:8080/CafeService/CafeCatalogService]
deployed with moduleid = CafeService

Under the Web Services node, right-click the CafeService node that represents your web service, and choose Test Web Service.

W

The IDE opens the tester page, similar to below, in your browser:

CafeCatalogService Web Service Tester


This form will allow you to test your web service implementation(WSDL File )
To invoke an operation,fill the method parameter(s) input boxes and click on the button labeled the method name.
操作を呼び出すには、メソッドパラメータの入力ボックスに入力し、メソッド名が表示されているボタンをクリックします。

Methods:

public abstract service.CafeItem service.CafeCatalog.getItem(int)
( )

public abstract java.util.List service.CafeCatalog.getItems(int,int)
( , )

public abstract int service.CafeCatalog.getItemCount()
()

public abstract double service.CafeCatalog.purchase(int,int)
( , )

 

Click on the WSDL File link to see the WSDL for the CafeService.

<?xml version="1.0" encoding="UTF-8"?>
<!-- Published by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.1.3.1-hudson-749-SNAPSHOT. -->
<!-- Generated by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.1.3.1-hudson-749-SNAPSHOT. -->
<definitions xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://service/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://service/" name="CafeCatalogService">
<types>
<xsd:schema>
<xsd:import namespace="http://service/" schemaLocation="http://localhost:8080/CafeService/CafeCatalogService?xsd=1"/>
</xsd:schema>
</types>
<message name="getItem">
<part name="parameters" element="tns:getItem"/>
</message>
<message name="getItemResponse">
<part name="parameters" element="tns:getItemResponse"/>
</message>
<message name="getItems">
<part name="parameters" element="tns:getItems"/>
</message>
<message name="getItemsResponse">
<part name="parameters" element="tns:getItemsResponse"/>
</message>
<message name="getItemCount">
<part name="parameters" element="tns:getItemCount"/>
</message>
<message name="getItemCountResponse">
<part name="parameters" element="tns:getItemCountResponse"/>
</message>
<message name="purchase">
<part name="parameters" element="tns:purchase"/>
</message>
<message name="purchaseResponse">
<part name="parameters" element="tns:purchaseResponse"/>
</message>
<portType name="CafeCatalog">
<operation name="getItem">
<input message="tns:getItem"/>
<output message="tns:getItemResponse"/>
</operation>
<operation name="getItems">
<input message="tns:getItems"/>
<output message="tns:getItemsResponse"/>
</operation>
<operation name="getItemCount">
<input message="tns:getItemCount"/>
<output message="tns:getItemCountResponse"/>
</operation>
<operation name="purchase">
<input message="tns:purchase"/>
<output message="tns:purchaseResponse"/>
</operation>
</portType>
<binding name="CafeCatalogPortBinding" type="tns:CafeCatalog">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
<operation name="getItem">
<soap:operation soapAction=""/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
<operation name="getItems">
<soap:operation soapAction=""/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
<operation name="getItemCount">
<soap:operation soapAction=""/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
<operation name="purchase">
<soap:operation soapAction=""/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
</binding>
<service name="CafeCatalogService">
<port name="CafeCatalogPort" binding="tns:CafeCatalogPortBinding">
<soap:address location="http://localhost:8080/CafeService/CafeCatalogService"/>
</port>
</service>
</definitions>

Type the  numbers 3, 3 in the tester page getItems method.

getItems Method invocation



Method parameter(s)

Type Value
int 3
int 3

Method returned

java.util.List : "[service.CafeItem@e8e3b0, service.CafeItem@1bc72c0, service.CafeItem@111a76c]"

SOAP Request


<?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
    <S:Header/>
    <S:Body>
        <ns2:getItems xmlns:ns2="http://service/">
            <arg0>3</arg0>
            <arg1>3</arg1>
        </ns2:getItems>
    </S:Body>
</S:Envelope>

SOAP Response


<?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
    <S:Body>
        <ns2:getItemsResponse xmlns:ns2="http://service/">
            <return>
                <id>4</id>
                <image>http://localhost:8080/CafeService/images/kilimanjaro.png</image>
                <name>kilimanjaro</name>
                <price>5.65</price>
            </return>
            <return>
                <id>5</id>
                <image>http://localhost:8080/CafeService/images/blue_mountain.png</image>
                <name>blue_mountain</name>
                <price>5.65</price>
            </return>
            <return>
                <id>6</id>
                <image>http://localhost:8080/CafeService/images/kona.png</image>
                <name>kona</name>
                <price>4.55</price>
            </return>
        </ns2:getItemsResponse>
    </S:Body>
</S:Envelope>

 

2. Create ZK Web Service Client..

  1.Create Project

createProject

     createProject

 

  2.Add a reference to the Web Service that we built in the previous exercise.
   Right-click on the CafeServiceClient project in the Projects navigator and select New > Web Service Client...


we

init:
wsimport-init:
Created dir: C:\ANetBeans6.7\jax-ws\CafeServiceClient\build\generated-sources\jax-ws
wsimport-client-CafeCatalogService:
Created dir: C:\ANetBeans6.7\jax-ws\CafeServiceClient\build\generated\jax-wsCache\CafeCatalogService
command line: wsimport -d C:\ANetBeans6.7\jax-ws\CafeServiceClient\build\generated\jax-wsCache\CafeCatalogService -extension -Xnocompile -keep -s C:\ANetBeans6.7\jax-ws\CafeServiceClient\build\generated\jax-wsCache\CafeCatalogService -catalog C:\ANetBeans6.7\jax-ws\CafeServiceClient\catalog.xml -verbose C:\ANetBeans6.7\jax-ws\CafeServiceClient/src/conf/xml-resources/web-service-references/CafeCatalogService/wsdl/localhost_8080/CafeService/CafeCatalogService.wsdl -wsdllocation http://localhost:8080/CafeService/CafeCatalogService?wsdl
parsing WSDL...

generating code...

service\CafeCatalog.java
service\CafeCatalogService.java
service\CafeItem.java
service\GetItem.java
service\GetItemCount.java
service\GetItemCountResponse.java
service\GetItemResponse.java
service\GetItems.java
service\GetItemsResponse.java
service\ObjectFactory.java
service\Purchase.java
service\PurchaseResponse.java
service\package-info.java
Copying 13 files to C:\ANetBeans6.7\jax-ws\CafeServiceClient\build\generated-sources\jax-ws
BUILD SUCCESSFUL (total time: 2 seconds)

wer

 

  3.We add uncomplete class to the Source Packages.
    Then fix this uncomple source code using NetBeans.
   

service.client package

ItemController class

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package service.client;

import java.util.List;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import service.CafeCatalogService;
import service.CafeItem;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.Intbox;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;

/**
*
* @author training1
*/
public class ItemController extends GenericForwardComposer {

// CafeCatalogService service = new service.CafeCatalogService();
// @WebServiceRef(wsdlLocation = "http://localhost:8080/CafeService/CafeCatalogService?wsdl")
private CafeCatalogService service= new service.CafeCatalogService();

public ItemController(){
}
private CafeItem item;
// private AbstractTableModel model = null;
// private CafeTableModel model = null;
private int batchSize = 10;
private int index = 0;
private int firstItem = 0;
private CafeItem selectedItem = new CafeItem();
protected Listbox list;
protected ListModelList listModelList;

@Override
public void doAfterCompose(Component window) throws Exception{
super.doAfterCompose(window);
listModelList = new ListModelList();
List<CafeItem> cafeitems = getAllItems();
listModelList.addAll(cafeitems);
final Listbox list = (Listbox) window.getFellow("listbox");
final Intbox intbox = (Intbox) window.getFellow("Coffee_id");
list.addEventListener("onSelect", new EventListener(){
public void onEvent(Event e)
throws Exception{
int index = list.getSelectedIndex();
selectedItem = (CafeItem) listModelList.get(index);
String sintvalue = selectedItem.getId().toString();
intbox.setValue(Integer.parseInt(sintvalue));

}

});
}

/**
* @return the item
*/
public CafeItem getItem() {
return item;
}

// /**
// * @return the model
// */
// public AbstractTableModel getModel() {
// return model;
// }
//
/**
* @return the batchSize
*/
public int getBatchSize() {
return batchSize;
}

/**
* @return the index
*/
public int getIndex() {
return index;
}

/**
* @return the firstItem
*/
public int getFirstItem() {
return firstItem;
}

public int getLastItem() {
int size = getItemCount();
return firstItem + batchSize > size ? size : firstItem + batchSize;
}

public List<CafeItem> getItems() {
return getNextItems();
// if (model == null || index != firstItem) {
// model = getNextItems();
// }
// return this.model;
}

public List<CafeItem> getNextItems() {

// try { // Call Web Service Operation
// service.CafeCatalogService service = new service.CafeCatalogService();
service.CafeCatalog port = service.getCafeCatalogPort();
// TODO initialize WS operation arguments here
int arg0 = this.firstItem;
int arg1 = this.batchSize;
// TODO process result here
java.util.List<service.CafeItem> result = port.getItems(arg0, arg1);
return result;
// System.out.println("Result = "+result);
// } catch (Exception ex) {
// // TODO handle custom exceptions here
// }

}

public List<CafeItem> getAllItems() {

// try { // Call Web Service Operation
// service.CafeCatalogService service = new service.CafeCatalogService();
service.CafeCatalog port = service.getCafeCatalogPort();
// TODO initialize WS operation arguments here
int arg0 = 0;
int arg1 = 100;
// TODO process result here
java.util.List
<service.CafeItem> result = port.getItems(arg0, arg1);
return result;
// System.out.println("Result = "+result);
// } catch (Exception ex) {
// // TODO handle custom exceptions here
// }

}

public CafeItem getItem(int id) {

// try { // Call Web Service Operation
// service.CafeCatalogService service = new service.CafeCatalogService();
service.CafeCatalog port = service.getCafeCatalogPort();
// TODO initialize WS operation arguments here
int arg0 = id;
// TODO process result here
service.CafeItem result = port.getItem(arg0);
return result;
// System.out.println("Result = "+result);
// } catch (Exception ex) {
// // TODO handle custom exceptions here
// }
}

public double purchase(int id, int quantom){

// try { // Call Web Service Operation
// service.CafeCatalogService service = new service.CafeCatalogService();
service.CafeCatalog port = service.getCafeCatalogPort();
// TODO initialize WS operation arguments here
int arg0 = id;
int arg1 = quantom;
// TODO process result here
double result = port.purchase(arg0, arg1);
return result;
// System.out.println("Result = "+result);
// } catch (Exception ex) {
// // TODO handle custom exceptions here
// }

}
/**
* @return the selecteItem
*/
public CafeItem getSelectedItem() {
return selectedItem;
}

/**
* @param selecteItem the selecteItem to set
*/
public void setSelectedItem(CafeItem selecteItem) {
this.selectedItem = selecteItem;
}
}


cr

Remove the line

 throw new UnsupportedOperationException("Not yet implemented");
from the newly created method.

cr

The method getItemCount() that you created in the previous step still needs to invoke the Web Service and return a result.
In the NetBeans Project navigator, expand the node Web Service References. Expand the contained CafeCatalogService and CafeCatalogPort nodes until you see the list of operations that this Web Service is offering.

With the mouse Drag the operation getItemCount() from the Projects navigator Window into the class ItemController.java in the Java editor window. Drop the operation inside the previously created method getItemCount(). NetBeans will generate the necessary code to invoke the Web Service where you dropped the operation.

cr2

You need to modify the code to return the result from the getItemCount Web Service operation. Add the line

 return result;

to the end of the method and remove the encapsulating try/catch block.
Change the getItemCount() method  from private to public.
The completed method should now look like this:

crt

  4.Now we completed with source code of controller.
    Then we try to make View.
    We make View using ZK framekwork instad of JSP or JSF.


We place index.zul at the Root of Web Page.

index.zul

<?xml version="1.0" encoding="UTF-8"?>
<zk xmlns="http://www.zkoss.org/2005/zul">
<zscript>
import service.client.ItemController;
catalogs = new ItemController().getAllItems();
</zscript>
<window>
<listbox id="listbox" mold="paging" pageSize="3">
<listitem forEach="&#36;{catalogs}">
<listcell label="&#36;{each.id}"/>
<listcell label="&#36;{each.name}"/>
<listcell label="&#36;{each.price}"/>
<listcell label="&#36;{each.image}"/>
<listcell image="&#36;{each.image}"/>
</listitem>
</listbox>
</window>

</zk>


The View from the code above.

yv

We modify index.zul to index_1.zul.
This time looks more rich and added purchase Button.

index_1.zul

<?xml version="1.0" encoding="UTF-8"?>
<zk xmlns="http://www.zkoss.org/2005/zul"
xmlns:h="http://www.w3.org/1999/xhtml"
xmlns:zk="http://www.zkoss.org/2005/zk"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.zkoss.org/2005/zul http://www.zkoss.org/2005/zul/zul.xsd">
<zscript>
import service.client.ItemController;
catalogs = new ItemController().getAllItems();
</zscript>
<div align="center">
<window id = "main" title="Welcome to the Metro-ZK Coffee shop" border="normal" width="800px"
apply="service.client.ItemController" >
<div align="left" style="margin-left:30pt;margin-top:10pt; margin-bottom:10pt">
<groupbox>
<caption label="Purchases"/>
Coffee_ID:
<intbox id="Coffee_id" cols="2" value="@{service.client.ItemController.selectedItem.id}" />
Coffee_Quantom:
<intbox id="Coffee_quantom" cols="2" />
<button label="Purchase" >
<attribute name="onClick">{
<!--import service.client.ItemController;-->
purchase = new ItemController().purchase(Coffee_id.getValue(),Coffee_quantom.getValue());
purchased.setValue(String.valueOf(purchase));
alert("Thank you");
}
</attribute>
</button>
<label value="Your fee is" />
<textbox id="purchased" />
<!--purchased.setValue(${purchase})-->
<!--<toolbarbutton label="Purchase" href="popup.zul"/>-->
</groupbox>
</div>
<listbox id="listbox" mold="paging" pageSize="3" selectedItem="@{service.client.ItemController.selectedItem}">
<listhead sizable="true">
<listheader align="center" label="ID" width="40px"/>
<listheader align="center" label="ProductName" width="120px"/>
<listheader align="center" label="Price" width="100px"/>
<listheader align="center" label="ImageURL" />
<listheader align="center" label="Image" />
<listheader align="center" label="Action" />
</listhead>
<listitem forEach="&#36;{catalogs}">
<listcell label="&#36;{each.id}"/>
<listcell label="&#36;{each.name}"/>
<listcell label="&#36;{each.price}"/>
<listcell label="&#36;{each.image}"/>
<listcell image="&#36;{each.image}"/>
<listcell label="Purchase this" >
<!-- <button label="Purchase this">
<attribute name="onClick">
</attribute>
</button>
-->
</listcell>
</listitem>
</listbox>
</window>
</div>

</zk>


The View from the code above.

yv2