Platform for distributed applications based on Web Service basics Summary

sponsored links
One, Web Service's profile
1, What is Web Service
Web services is to build interoperable distributed applications of the new platform.
Web service platform is a standard that defines how applications to achieve interoperability in the Web. You can use any language you like in any platform you like to write Web service, as long as we can through standard Web service to query and access those services.
Web service platform needs a protocol to achieve the creation of distributed applications. Any platform has its own data representation and types of systems. To achieve interoperability, Web service platform must provide a standard type system for communication between different platforms, programming languages and component models of different types of systems.
Based Web Services platform is XML + HTTP.
HTTP protocol is the most common Internet protocols.
XML provides a platform for different languages and programming languages.
Web services platform is a simple interoperable messaging framework. It still lacks many other important issues such as security and routing features. However, once SOAP becomes more advanced, these issues will be solved.
Web services is expected to make the application easier communication.
★ Web services to enhance the Web application to another level through the use of Web services, your application can function or message to the world.
Web services use XML to encoding and decoding data, and by using the SOAP protocol to transfer from the open data.
Through Web services, your accounting department Win 2k server with IT suppliers to connect to UNIX servers.
★ Web services applications, there are two types of reusable application components that have some features are often different applications used. So why again and again to develop them?
Web services application components can be provided as a service, such as currency converter, weather forecast or even a language translator and more.
Ideal situation, each application component is only one of the best version, so anyone can use it in their applications.
Connect the existing software for different applications by providing a way to link their data, Web services help solve interoperability problems.
By using Web services, you can in different applications and platforms to exchange data.
★ Web Services has two basic elements.
They are: SOAP and WSDL
(1) What is SOAP?
 SOAP Simple Object Access Protocol refers to  SOAP is a communication protocol  SOAP for communication between applications  SOAP is a format for sending messages  SOAP is designed to communicate via the Internet  SOAP is platform independent  SOAP independent XML-based language  SOAP
 SOAP is simple and can be extended to allow you to bypass the firewall  SOAP  SOAP as the development of W3C standards
(2) What is WSDL?
WSDL is used to describe the XML-based Web Services and how to access Web Services of the language.
 WSDL means Web Service Description Language  WSDL using the XML written  WSDL is an XML document  WSDL for describing Web services  WSDL Web services can also be used to locate is not W3C standards  WSDL
2, What is JWS
JWS (Java Web Service) is a Java application platform specifically for the development of Web services, systems and service-oriented system of products, its latest version is 2.0, Java EE 5 and Java SE 6 is to provide support for JWS 2.0.
In the JWS 2.0, Java defines a set of new standards, JMS itself contains a number of tools, such as JAX-WS 2.0, JAXB 2.0, JAXP 1.4, SAAJ 1.3, and WS-Metadata and so on.
Service-oriented systems often by multiple sub-functions of different independent components, through their mutual cooperation between the good, the demand can be complex. Service-oriented system, the characteristics and requirements of the independent formation of the interface between the public, the public interface for exchanging data with good definition. Due to data communication between units, which have well-defined interfaces to other components must be identified and properly understood in order to achieve collaboration.
After defining the public interface, there are specific data exchange that both sides need to follow a common data exchange standards, the data exchange standard known as protocols. Between components in a separate communication, requires a series of strict rules of data communication standards to the format and rules.
The emergence of Web Service to solve the above problem, the use of WSDL definition of a unified interface formats, SOAP message with a unified input / output parameters of a unified format. SOAP messages can be passed from a variety of ways, for example, through HTTP, SMTP, and JMS protocol transmission. To HTTP, for example, in the service use client, WSDL interface definition can be obtained by HTTP-GET request, while the SOAP response message and reply to messages transmitted through the HTTP-POST request can be achieved. In this way, WSDL and SOAP-based message mechanism to meet the service-oriented application development needs.
Web Service platform architecture consists of three parts: the serialization and deserialization subsystem, call subsystem and release subsystem. The three subsystems are not subject to specific restrictions on language, platform and framework are not subject to the restrictions, regardless of language or Java. NET language, regardless of platform or Axis JWS to develop web services, will involve three basic functions module.
(1) serialization and deserialization
Java objects in JMS will be transformed into an XML element of a process called serialization. Instead an XML element into a corresponding Java
The process object is called deserialization. Serialization and deserialization process depends on the Java classes and XML-Scheme mapping between, JWS independent serialization and deserialization to be responsible for completion of the mapping subsystem and transformation.
In the web service client, the serialization process parameters into the xml node, and then packaged into Soap request message, sent to the server-side web service endpoint. Return values, the deserialization process is initiated, it will return value from the SOAP message is specified in the xml nodes removed, and then convert it to customers Duanxiang corresponding Java object.
Transformation rule is defined in the JWS annotations by JAXB to complete. The new version of JAXB simplifies the description of binding rules, which allows rules to directly write notes in the form of Java classes.
For example:
@ Entity
@ Name ("hotel")
@ XmlAccessorType (XmlAccessType.PUBLIC_MEMBER)
@ XmlType (name = "", propOrder = (
"Id",
"Img",
"Name",
"Address",
"City",
"State",
"Zip",
"Country",
"Price",
"IpAddress"
))
@ XmlRootElement (name = "Hotel")
public class Hotel implements Serializable
(
private Long id;
private String img;
private String name;
private String address;
private String city;
private String state;
private String zip;
private String country;
private BigDecimal price;
private String ipAddress = "192.168.1.112";

@ Id @ GeneratedValue
public Long getId ()
(
return id;
)
public void setId (Long id)
(
this.id = id;
)

@ Length (max = 50)
@ NotNull
public String getImg () (
return img;
)

public void setImg (String img) (
this.img = img;
)

@ Length (max = 50) @ NotNull
public String getName ()
(
return name;
)
public void setName (String name)
(
this.name = name;
)

@ Length (max = 100) @ NotNull
public String getAddress ()
(
return address;
)
public void setAddress (String address)
(
this.address = address;
)

@ Length (max = 40) @ NotNull
public String getCity ()
(
return city;
)
public void setCity (String city)
(
this.city = city;
)

@ Length (min = 4, max = 6) @ NotNull
public String getZip ()
(
return zip;
)
public void setZip (String zip)
(
this.zip = zip;
)

@ Length (min = 2, max = 10) @ NotNull
public String getState ()
(
return state;
)
public void setState (String state)
(
this.state = state;
)

@ Length (min = 2, max = 40) @ NotNull
public String getCountry ()
(
return country;
)
public void setCountry (String country)
(
this.country = country;
)

@ Column (precision = 6, scale = 2)
public BigDecimal getPrice ()
(
return price;
)
public void setPrice (BigDecimal price)
(
this.price = price;
)
@ Transient
public String getIpAddress () (
return ipAddress;
)
public void setIpAddress (String ipAddress) (
this.ipAddress = ipAddress;
)
@ Override
public String toString ()
(
return "Hotel (" + name + "," + address + "," + city + "," + zip + ")";
)
)
(2) the process of service invocation
In service-oriented distributed system, the general framework of the traditional client-server in the Client as a client service consumers, as the server-side service providers.
According to current web service standards, a service is called, in the service delivery end of the process roughly as follows:
① accepted and pre-SOAP request message, such as efficacy, processing SOAP message header.
② to get the message from the message interface and want to call the specific operation.
③ using web services support, find specific implementation object and calls the object's interface. This object can be a different language. JWS supports the mapping from WSDL to Java, you can find it through the WSDL corresponding to the Java service endpoint implementation class.
④ The serialization deserialization process tool, the SOAP request message out in the service request parameters passed to the target object in step 3 the corresponding function.
⑤ target Java object to perform the appropriate action, the results of the calculation to return the object.
⑥ sequence using the sequence of process tools, according to the definition in the wsdl will be the result of step 5 sequence of objects into XML elements, and packages to the SOAP response message.
⑦ to Step 6 of the SOAP response message back to the service call side.
By contrast, in the service using the client's call is as follows:
① First, create a service endpoint interface object SEI (Service Endpoint Interface), the Web service client will normally have completed SEI corresponding factory class to instantiate the object. In the JWS, SEI object is generally achieved by a Java agent.
② SEI call one of the client package via web service interface.
③ sequence by sequence process tools, according to the definition of WSDL, the client calls the parameters of the interface elements into XML, then the element in the SOAP request message in the package.
④ In the synchronous mode, after the issue of the SOAP request message, the client will wait for SOAP response message; asynchronous mode, the client follow-up to the code sequence, until received by listeners in the SOAP request message.
⑤ Analysis obtained from the server SOAP response message, use the tools in sequence during deserialization, the SOAP response message data into a client object, the object's value is called the service return value.
(3) web publishing service
The JMS example, web services, the main function of distribution system
① The URL to be released in the form of public WEB service WSDL files and SOAP request message and the Java binding target classes.
② release JAVA object file (such as Java Object files, WAR files, JAR files and associated configuration files, etc.).
③ configuration serialization and deserialization subsystem.
④ web service endpoint listener configuration and pre-process SOAP messages.
Second, web service development and call several ways (1) model development with EJB Container Web Service, use the wsimport tool to generate auxiliary class call.
Examples are as follows (example application for the EJB container Jboss, all of the code is based on the JBoss Seam framework to write):
① service provider side <service-side code>:
Service provider side of the task is to expose a web service for external use, in this case the web service platform offered by @ java.jws.WebService JavaEE annotations to achieve.
The following code path is pre-survey on the VSS folder SOA \ web service \ EJB container model development using Web Service, use the wsimport tool to generate auxiliary class called \ tele \ book \ src \ org \ jboss \ seam \ example \ booking \ ws \ impl, with the EJB container model development Web Service, use the wsimport tool to generate auxiliary class called folder contains two folders: local, tele. tele folder decentralized service provider side of the project and lay the EAR package. decentralization of services to local consumers in the folder end of the project and lay the EAR package.
package org.jboss.seam.example.booking.ws.impl;
import static org.jboss.seam.ScopeType.SESSION;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.jws.WebService;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.jboss.seam.annotations.Out;
import org.jboss.seam.example.booking.Hotel;
import org.jboss.seam.example.booking.User;
import org.jboss.seam.example.booking.ws.HotelObject;

@ Stateless
/ ** Example is the use of two JBoss application server, the code is the service provider side code, so use the @ Remote annotation, and remote interface. . * /
@ Remote (HotelObject.class)
@ WebService
public class HotelObjectImpl implements HotelObject (
@ PersistenceContext
private EntityManager em;

public List <Hotel> getHotelObject (String hotelName) (
List <Hotel> results = em.createQuery ("select h from Hotel h where h.name like" + "'%" + hotelName +"%'")
. GetResultList ();
if (results.size ()> 0) (
return results;
)
return null;
)

public String updateHotelObject (Hotel h) (
try (
System.out.println (h);
System.out.println (h.getName ());
em.merge (h);
) Catch (Exception e) (
e.printStackTrace ();
return "error";
)
return "success";
)
)
The above class inherits an interface, interface class path is: VSS folder on the preliminary survey SOA \ web service \ EJB container model development using Web Service, use the wsimport tool to generate auxiliary class called \ tele \ book \ src \ org \ jboss \ seam \ example \ booking \ ws.
package org.jboss.seam.example.booking.ws;

import java.util.List;
import org.jboss.seam.example.booking.Hotel;

public interface HotelObject (
public List <Hotel> getHotelObject (String hotelName);
public String updateHotelObject (Hotel h);
)
@ WebService annotation named above is a Web Service. Open the Ant file, perform desploy business. After deployment, JBoss management platform through the deployment of view just Web Service, enter http://localhost:8080/jbossws/ view into the JBoss Web Service interface, you can see View a list of deployed services link, click View a list of deployed services link, you can view the Web Service has released the URL address, click the address to view the generated WSDL to the text.
This is the service provider side of the main code, first with the annotation defines a web service, the web service provides two methods, the two methods can receive parameters from a remote pass them. Services consumed by the above URL address to access the service.
(2) the consumer-side service "Using server-side code>
To call the web service, we can be a lot of ways, one of them is through wsimport tool (in the JDK1.6, Sun has been to provide users with the wsimport tool) to generate helper class to call the web service.
Web Service in the VSS folder on a file called jaxws-ri package which contains the wsimport tool, in this case the helper class is generated with it directly. Use the wsimport tool to generate helper classes, we must first open a dos environment where wsimport tools directory, such as local path wsimport tool:

Dos wsimport tool to open the path where the.

Wsimport path in the input the following:
wsimport.bat-keep-d .. / build / classes / client http://192.168.1.106:8080/WsHelloWorld/HelloWorldBean?wsdl
Including .. / build / classes / client helper class that generates the path of storage, http://192.168.1.106:8080/WsHelloWorld/HelloWorldBean?wsdl said to call the web service WSDL text of the address, which said the service 192.168.1.106 providing end of IP address.
Generated helper class as shown below:

Java class to generate the auxiliary copy to our project and then instantiate an object of the generated helper class, by calling the object method of service providers <that getHotelObjec ()>, to retrieve the qualifying records.
VSS is located on the class path as follows;
SOA \ Web Servic \ EJB container model development using Web Service, use the wsimport tool to generate auxiliary class called \ local \ book \ src \ org \ jboss \ seam \ example \ booking
package org.jboss.seam.example.booking;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Factory;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.datamodel.DataModel;
import org.jboss.seam.annotations.security.Restrict;
import org.jboss.seam.example.booking.ws.impl.Hotel;
import org.jboss.seam.example.booking.ws.impl.HotelObjectImpl;
import org.jboss.seam.example.booking.ws.impl.HotelObjectImplService;

@ Stateful
@ Name ("teledataHotelSearch")
@ Scope (ScopeType.SESSION)
@ Restrict ("# (identity.loggedIn)")
public class TeledateHotelSearchingAction implements TeledateHotelSearching
(
@ PersistenceContext
private EntityManager em;

private String searchString;

@ DataModel
private List <Hotel> telehotels;

public void find ()
(
queryHotels ();
)

private void queryHotels () (
/ ** Helper class to instantiate the object generated by the object to call remote web service. * /
HotelObjectImplService service;
try
(
service = new HotelObjectImplService ();
HotelObjectImpl hotelObjectImpl = service.getHotelObjectImplPort ();
List <Hotel> result = hotelObjectImpl.getHotelObject (this.getSearchString ());
System.out.println (result.size ());
if (result.size ()> 0) (
telehotels = result;
) Else (
telehotels = null;
)
) Catch (Exception e) (
e.printStackTrace ();
)
)
public String getSearchString ()
(
return searchString;
)

public void setSearchString (String searchString)
(
this.searchString = searchString;
)

@ Remove
public void destroy () ()

@ Override
public void cancel () (
/ / TODO Auto-generated method stub

)
)
There is also a class is modified to save the service provider (ie a remote Web Service) to return the Hotel object, you must call the service provider object preservation method Hotel <that updateHotelObject ()>.
package org.jboss.seam.example.booking;

import static javax.persistence.PersistenceContextType.EXTENDED;

import java.util.Calendar;

import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.jboss.seam.annotations.Begin;
import org.jboss.seam.annotations.End;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.security.Restrict;
import org.jboss.seam.core.Events;
import org.jboss.seam.example.booking.ws.impl.HotelObjectImpl;
import org.jboss.seam.example.booking.ws.impl.HotelObjectImplService;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.log.Log;

@ Stateful
@ Name ("saveTeteDataHotel")
@ Restrict ("# (identity.loggedIn)")
public class SaveTeteDataHotelAction implements SaveTeteDataHotel
(

@ Begin
public void seveHotel (Hotel hotel)
(
HotelObjectImplService service;
try
(
service = new HotelObjectImplService ();
HotelObjectImpl hotelObjectImpl = service.getHotelObjectImplPort ();
String result = hotelObjectImpl.updateHotelObject (this.conversionHotel (hotel));
System.out.println (result);
) Catch (Exception e) (
e.printStackTrace ();
)
)

public org.jboss.seam.example.booking.ws.impl.Hotel conversionHotel (Hotel hotel) (
org.jboss.seam.example.booking.ws.impl.Hotel h = new org.jboss.seam.example.booking.ws.impl.Hotel ();
h.setAddress (hotel.getAddress ());
h.setCity (hotel.getCity ());
h.setCountry (hotel.getCountry ());
h.setId (hotel.getId ());
h.setImg (hotel.getImg ());
h.setName (hotel.getName ());
h.setPrice (hotel.getPrice ());
h.setState (hotel.getState ());
h.setZip (hotel.getZip ());
return h;
)

@ End
public void cancel () ()

@ Remove
public void destroy () ()
)
Class above is worth noting that the service consumer in the Hotel object can not be directly used to hold, must be converted into the generated class auxiliary class org.jboss.seam.example.booking.ws.impl.Hotel in order to save the above conversionHotel (Hotel hotel) method is to carry out the conversion.
Above is the kind of web service to use a few important points, through the above steps to access remote web services published, and complete the process please refer to Vss on the Dome project.
(2) the use of dynamically generated SAAJ SOAP Message Access Protocol service provider side of the web service.
The first way is to use wsimpot tools to generate helper classes to implement the service provider side of the web service access, particularly due to the formation of auxiliary classes and more, and inflexible. Here we introduced the use of dynamically generated SAAJ SOAP message protocol to access the service provider side of the web service.
① service provider side code in the VSS on the class:
EHR \ SOA \ SOA (V1.2) \ Request endpoint (192.168.1.112) \ booking \ src \ org \ jboss \ seam \ example \ booking \ ws \ impl under
package org.jboss.seam.example.booking.ws.impl;
import static org.jboss.seam.ScopeType.SESSION;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.jboss.seam.annotations.Out;
import org.jboss.seam.example.booking.Hotel;
import org.jboss.seam.example.booking.User;
import org.jboss.seam.example.booking.ws.HotelObject;

@ Stateless
@ Remote (HotelObject.class)
@ WebService (name = "HotelObject", targetNamespace = "http://tower/ehr_DEV")
public class HotelObjectImpl implements HotelObject (
@ PersistenceContext
private EntityManager em;
@ WebResult (name = "Hotel")
public List <Hotel> getHotelObject (String hotelName) (
List <Hotel> results = em.createQuery ("select h from Hotel h where h.name like" + "'%" + hotelName +"%'")
. GetResultList ();
if (results.size ()> 0) (
return results;
)
return null;
)

public String updateHotelObject (Hotel h) (
try (
System.out.println (h);
System.out.println (h.getName ());
em.merge (h);
) Catch (Exception e) (
e.printStackTrace ();
return "error";
)
return "success";
)
)
The web service provides two methods, getHotelObject (String hotelName) method receives the remote's arguments through the parameters of the Hotel to find qualified object; updateHotelObject (Hotel h) method to save the modified object.
② service the caller-side code in the VSS on the class:
EHR \ SOA \ SOA (V1.2) \ Request endpoint (192.168.1.112) \ booking \ src \ org \ jboss \ seam \ example \ booking \ soa \ esb \ impl of this example uses the Jboss ESB, in fact, end of service call First send the request to Jboss ESB server, Jboss ESB Server also defines a number of web services, to accept these requests, receives the request message, further processing of the message or forward the message directly to the news provider to the real end.
The following code shows how the service consumer side ESB server to call the service provider side services.
package org.jboss.seam.example.booking.soa.esb.impl;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;

import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.soap.SOAPMessage;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.datamodel.DataModel;
import org.jboss.seam.annotations.security.Restrict;
import org.jboss.seam.example.booking.Hotel;
import org.jboss.seam.example.booking.commom.collectionbinder.ListHotel;
import org.jboss.seam.example.booking.commom.esb.BuildSoapMessage;
import org.jboss.seam.example.booking.commom.esb.SendSoapMessageToEsb;
import org.jboss.seam.example.booking.commom.esb.impl.BuildSoapMessageImpl;
import org.jboss.seam.example.booking.commom.esb.impl.SendSoapMessageToEsbImpl;
import org.jboss.seam.example.booking.commom.formattransform.TransformMessageFormat;
import org.jboss.seam.example.booking.commom.formattransform.TransformString;
import org.jboss.seam.example.booking.commom.formattransform.impl.TransformMessageFormatImpl;
import org.jboss.seam.example.booking.commom.formattransform.impl.TransformStringImpl;
import org.jboss.seam.example.booking.soa.esb.TeledateHotelSearching;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

@ Stateful
@ Name ("teledataHotelSearch")
@ Scope (ScopeType.SESSION)
@ Restrict ("# (identity.loggedIn)")
public class TeledateHotelSearchingImpl implements TeledateHotelSearching
(
@ PersistenceContext
private EntityManager em;

private String searchString;

@ DataModel
private List <Hotel> telehotels;

public void find ()
(
getHotelObject (this.getSearchString ());
)

public void getHotelObject (String searchString) (
try (
BuildSoapMessage bsm = new BuildSoapMessageImpl ();
SOAPMessage sm = bsm.getMessage ("sayGoodbye", "http://webservice_producer/goodbyeworld", searchString);
TransformMessageFormat tmf = new TransformMessageFormatImpl ();
String stringSOAPMessage = tmf.transformToString (sm);
SendSoapMessageToEsb smtEsb = new SendSoapMessageToEsbImpl ();
Object o = smtEsb.sendMessageToJBRListener ("http", "8765", stringSOAPMessage);

System.out.println ("wo de ma ya !!!"+ o.toString ());

TransformString tfs = new TransformStringImpl ();
Document doc = tfs.transformStringToDocument (o.toString ());
NodeList nodeList = doc.getElementsByTagName ("ListHotel");
Element element = (Element) nodeList.item (0);
String returnContent = element.getTextContent ();
if (returnContent.length ()> 0) (
String returnContentAnd = "<ListHotel>" + returnContent + "</ ListHotel>";
InputStream inputStream = new ByteArrayInputStream (returnContentAnd.getBytes ());
JAXBContext context = JAXBContext.newInstance (ListHotel.class);
try (
Unmarshaller um = context.createUnmarshaller ();
ListHotel hl = (ListHotel) um.unmarshal (inputStream);
System.out.println ("I'm King!" + Hl.getElements ());
telehotels = hl.getElements ();
) Catch (JAXBException e) (
e.printStackTrace ();
)
) Else (
telehotels = null;
)
) Catch (Exception e) (
e.printStackTrace ();
telehotels = null;
) Catch (Throwable e) (
e.printStackTrace ();
)

)

public String getSearchString ()
(
return searchString;
)

public void setSearchString (String searchString)
(
this.searchString = searchString;
)

@ Remove
public void destroy () ()

@ Override
public void cancel () (
searchString = "";
telehotels = null;
)
)
In getHotelObject (String searchString) method, the first class offered by BuildSoapMessage getMessage () method to generate the SOAP message to send. (Calling code is as follows:)
BuildSoapMessage bsm = new BuildSoapMessageImpl ();
SOAPMessage sm = bsm.getMessage ("sayGoodbye", "http://webservice_producer/goodbyeworld", searchString);
BuildSoapMessage class and code as follows:
Vss on the class path in the following:
SOA (V1.2) \ Request endpoint (192.168.1.112) \ booking \ src \ org \ jboss \ seam \ example \ booking \ commom \ esb \ impl
package org.jboss.seam.example.booking.commom.esb.impl;

import java.util.HashMap;
import java.util.Map;

import javax.xml.soap.MessageFactory;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;

import org.jboss.seam.example.booking.commom.esb.BuildSoapMessage;

public class BuildSoapMessageImpl implements BuildSoapMessage (

public static final SOAPConnection getSOAPConnection () (
SOAPConnectionFactory soapConnFactory;
SOAPConnection connection;
try (
soapConnFactory = SOAPConnectionFactory.newInstance ();
connection = soapConnFactory.createConnection ();
return connection;
) Catch (UnsupportedOperationException e) (
e.printStackTrace ();
return null;
) Catch (SOAPException e) (
e.printStackTrace ();
return null;
)
)

public static final SOAPMessage getSOAPMessage () (
MessageFactory messageFactory;
SOAPMessage message;
try (
messageFactory = MessageFactory.newInstance ();
message = messageFactory.createMessage ();
return message;
) Catch (SOAPException e) (
e.printStackTrace ();
return null;
)
)

public Name getName (String param) (
SOAPFactory soapFactory;
try (
soapFactory = SOAPFactory.newInstance ();
Name name = soapFactory.createName (param); / / "arg0"
return name;
) Catch (SOAPException e) (
e.printStackTrace ();
return null;
)
)

public SOAPElement getBodyElement (SOAPMessage message, String param1, String param2, String param3) (
SOAPPart soapPart = message.getSOAPPart ();
SOAPEnvelope envelope;
SOAPBody body;
SOAPElement bodyElement;
try (
envelope = soapPart.getEnvelope ();
body = envelope.getBody ();
bodyElement = body.addChildElement (envelope.createName (param1, / / "sayHello",
param1, / / "ns1",
param1 ));//" http://webservice_consumer1/helloworld "));
bodyElement.setEncodingStyle (SOAPConstants.URI_NS_SOAP_ENCODING);
return bodyElement;
) Catch (SOAPException e) (
e.printStackTrace ();
return null;
)
)

public SOAPElement addTextNode (SOAPMessage message, String param1, String param2, String param3) (
SOAPPart soapPart = message.getSOAPPart ();
SOAPEnvelope envelope;
SOAPBody body;
SOAPElement bodyElement;
try (
envelope = soapPart.getEnvelope ();
body = envelope.getBody ();
bodyElement = body.addChildElement (envelope.createName (param1, / / "sayHello",
param1, / / "ns1",
param1 ));//" http://webservice_consumer1/helloworld "));
bodyElement.setEncodingStyle (SOAPConstants.URI_NS_SOAP_ENCODING);
return bodyElement;
) Catch (SOAPException e) (
e.printStackTrace ();
return null;
)
)

public SOAPMessage getMessage (String methodName, String targetNamespace, String messageContext) throws SOAPException, Exception (

/ / Send parameters need to create a Name
SOAPFactory soapFactory = SOAPFactory.newInstance ();
/ / Next, create the actual message
MessageFactory messageFactory = MessageFactory.newInstance ();
SOAPMessage message = messageFactory.createMessage ();
/ / Get a SOAPPart object
SOAPPart soapPart = message.getSOAPPart ();
SOAPEnvelope envelope = soapPart.getEnvelope ();
SOAPBody body = envelope.getBody ();
/ / Create the main element and namespace
SOAPElement bodyElement =
body.addChildElement (envelope.createName (methodName,
"Tower",
targetNamespace));
bodyElement.setEncodingStyle (SOAPConstants.URI_NS_SOAP_ENCODING);

/ / Create a new Name object to send parameters
Name name = soapFactory.createName ("message");
SOAPElement symbol = bodyElement.addChildElement (name);
symbol.addTextNode (messageContext);
message.saveChanges ();
return message;
)

public SOAPMessage getMessage (String methodName, String targetNamespace, HashMap <String,String> hm) throws SOAPException, Exception (
/ / Send parameters need to create a Name
SOAPFactory soapFactory = SOAPFactory.newInstance ();
/ / Next, create the actual message
MessageFactory messageFactory = MessageFactory.newInstance ();
SOAPMessage message = messageFactory.createMessage ();
/ / Get a SOAPPart object
SOAPPart soapPart = message.getSOAPPart ();
SOAPEnvelope envelope = soapPart.getEnvelope ();
SOAPBody body = envelope.getBody ();
/ / Create the main element and namespace
SOAPElement bodyElement =
body.addChildElement (envelope.createName (methodName,
"Ns1",
targetNamespace));
bodyElement.setEncodingStyle (SOAPConstants.URI_NS_SOAP_ENCODING);

/ / Create a new Name object to send parameters
Name name = soapFactory.createName ("arg0");
SOAPElement symbol = bodyElement.addChildElement (name);
for (Map.Entry <String, String> m: hm.entrySet ()) (
System.out.println ("HashMap" + m.getKey () + ":" + m.getValue ());
Name symbolName = soapFactory.createName (m.getKey ());
SOAPElement symbolNameSOAPElemen = symbol.addChildElement (symbolName);
symbolNameSOAPElemen.addTextNode (m.getValue ());
)
message.saveChanges ();
return message;

)

)
In this case, Jboss esb web services provided by the server only accepts parameters of type String, so make soap message format conversion. The consumption side in the service code calls the following format conversion method:
TransformMessageFormat tmf = new TransformMessageFormatImpl ();
String stringSOAPMessage = tmf.transformToString (sm);
Format conversion classes and methods are as follows:
The class path:
SOA (V1.2) \ Request endpoint (192.168.1.112) \ booking \ src \ org \ jboss \ seam \ example \ booking \ commom \ formattransform \ impl

package org.jboss.seam.example.booking.commom.formattransform.impl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;

import org.jboss.internal.soa.esb.util.StreamUtils;
import org.jboss.seam.example.booking.commom.formattransform.TransformMessageFormat;

public class TransformMessageFormatImpl implements TransformMessageFormat (

public String transformToString (SOAPMessage sm) throws SOAPException, IOException (
ByteArrayOutputStream s = new ByteArrayOutputStream ();
sm.writeTo (s);
byte [] buf = s.toByteArray ();
ByteArrayInputStream bin = new ByteArrayInputStream (buf);
String msg = new String (StreamUtils.readStream (bin));
return msg;
)

)
Soap the converted message to the Jboss ESB Server, the service consumer side of the call procedure code is as follows:
SendSoapMessageToEsb smtEsb = new SendSoapMessageToEsbImpl ();
Object o = smtEsb.sendMessageToJBRListener ("http", "8765", stringSOAPMessage);
Send a message to the Jboss ESB server classes and methods are as follows:
On the class path in the VSS are as follows:
SOA (V1.2) \ Request endpoint (192.168.1.112) \ booking \ src \ org \ jboss \ seam \ example \ booking \ commom \ esb \ impl

package org.jboss.seam.example.booking.commom.esb.impl;

import org.jboss.remoting.Client;
import org.jboss.remoting.InvokerLocator;
import org.jboss.seam.example.booking.commom.esb.SendSoapMessageToEsb;

public class SendSoapMessageToEsbImpl implements SendSoapMessageToEsb (

public static String ESBSERVICEIP = "192.168.1.101";
public Object sendMessageToJBRListener (String protocol, String port, String message) throws Throwable (
String locatorURI = protocol + "://"+ ESBSERVICEIP + ":" + port;
InvokerLocator locator = new InvokerLocator (locatorURI);
Client remotingClient = null;
try (
remotingClient = new Client (locator);
remotingClient.connect ();
Object response = remotingClient.invoke (message);
return response;
) Finally (
if (remotingClient! = null) (
remotingClient.disconnect ();
)
)
)

)
public static String ESBSERVICEIP = "192.168.1.101"; the IP address of that server's IP address Jboss ESB.
String locatorURI = protocol + "://"+ ESBSERVICEIP + ":" + port; this line of code makes up access Jboss ESB Web services to publish the URL address.
We then look at calling side code, from the Jboss ESB's return value (in fact, Jboss ESB Server's Web services, and through the forwarding call service provider side of the Web services to get the return value, the service provider side of the return value of the first of the value of the transfer Back to the Jboss ESB Server, Jboss ESB server then the value returned to the service call side.) is a Object object Object object we need to convert this application in our real object (such as the example ListHotel object), this conversion I Use the JAXB standard, this standard is mainly used for. xml and system conversion between Java objects, because the return value is the SOAP message is. xml form, with over JAXB standard can be easily converted into java class we want (such as ListHotel), in the call-side code is as follows:
TransformString tfs = new TransformStringImpl ();
Document doc = tfs.transformStringToDocument (o.toString ());
NodeList nodeList = doc.getElementsByTagName ("ListHotel");
Element element = (Element) nodeList.item (0);
String returnContent = element.getTextContent ();
if (returnContent.length ()> 0) (
String returnContentAnd = "<ListHotel>" + returnContent + "</ ListHotel>";
InputStream inputStream = new ByteArrayInputStream (returnContentAnd.getBytes ());
JAXBContext context = JAXBContext.newInstance (ListHotel.class);
try (
Unmarshaller um = context.createUnmarshaller ();
ListHotel hl = (ListHotel) um.unmarshal (inputStream);
System.out.println ("I'm King!" + Hl.getElements ());
telehotels = hl.getElements ();
) Catch (JAXBException e) (
e.printStackTrace ();
)
) Else (
telehotels = null;
)
) Catch (Exception e) (
e.printStackTrace ();
telehotels = null;
) Catch (Throwable e) (
e.printStackTrace ();
)

Jboss ESB server from the first through the return value of the conversion, to convert it to Document Type, the code is as follows:
TransformString tfs = new TransformStringImpl ();
Document doc = tfs.transformStringToDocument (o.toString ());
Conversion classes and methods are as follows:
On the class path in the VSS are as follows:
SOA (V1.2) \ Request endpoint (192.168.1.112) \ booking \ src \ org \ jboss \ seam \ example \ booking \ commom \ formattransform \ impl
package org.jboss.seam.example.booking.commom.formattransform.impl;

import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.jboss.seam.example.booking.commom.formattransform.TransformString;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class TransformStringImpl implements TransformString (

public Document transformStringToDocument (String s) (
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance ();
DocumentBuilder builder;
try (
builder = factory.newDocumentBuilder ();
Document doc = builder.parse (new InputSource (new StringReader (s)));
return doc;
) Catch (ParserConfigurationException e) (
e.printStackTrace ();
) Catch (SAXException e) (
e.printStackTrace ();
) Catch (IOException e) (
e.printStackTrace ();
)
return null;
)

public String [] getObjectArrayByESBReturnContent (String s) (
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance ();
DocumentBuilder builder;
try (
builder = factory.newDocumentBuilder ();
Document doc = builder.parse (new InputSource (new StringReader (s)));
NodeList nodeList = doc.getElementsByTagName ("return");
Element element = (Element) nodeList.item (0);
String returnContent = element.getTextContent ();
if (returnContent.length ()> 0) (
String [] getObjectContest = returnContent.split ("</ O>");
return getObjectContest;
) Else (
return null;
)
) Catch (ParserConfigurationException e) (
e.printStackTrace ();
) Catch (SAXException e) (
e.printStackTrace ();
) Catch (IOException e) (
e.printStackTrace ();
)
return null;
)

public String [] getPropertyArrayByStringObject (String returnContent) (
if (returnContent.length ()> 0) (
String [] getObjectContest = returnContent.split ("</ A & V>");
return getObjectContest;
) Else (
return null;
)
)
)
Document object after conversion to be about the interception and re-assembled into a form suitable for JAXB XML conversion, the process is as follows:
NodeList nodeList = doc.getElementsByTagName ("ListHotel");
Element element = (Element) nodeList.item (0);
String returnContent = element.getTextContent ();
String returnContentAnd = "<ListHotel>" + returnContent + "</ ListHotel>";
InputStream inputStream = new ByteArrayInputStream (returnContentAnd.getBytes ());
The return value is converted to first convert the InputStream object InputStream object to meet the conversion of this form, and can be converted.
To use JAXB specification for such conversion, to a two-step:
① marked with the @ XmlRootElement annotation Java class to be converted.
Java classes are as follows:
VSS on the Java class path is:
SOA (V1.2) \ Request endpoint (192.168.1.112) \ booking \ src \ org \ jboss \ seam \ example \ booking \ commom \ collectionbinder
package org.jboss.seam.example.booking.commom.collectionbinder;

import java.util.List;

import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement;

import org.jboss.seam.example.booking.Hotel;
@ XmlRootElement (name = "ListHotel")
public class ListHotel (
private List <Hotel> hotel;

public ListHotel () (
)

public ListHotel (List <Hotel> hotel) (
this.hotel = hotel;
)

@ XmlElementRef
public List <Hotel> getElements () (
return hotel;
)

public void setElements (List <Hotel> hotel) (
this.hotel = hotel;
)

)
② grouping mechanisms provided by JAXB, the Java object is converted to xml character. Code:
JAXBContext context = JAXBContext.newInstance (ListHotel.class);
try (
Unmarshaller um = context.createUnmarshaller ();
ListHotel hl = (ListHotel) um.unmarshal (inputStream);
System.out.println ("I'm King!" + Hl.getElements ());
telehotels = hl.getElements ();
) Catch (JAXBException e) (
e.printStackTrace ();
)
That is all I use SAAJ implementation details of Web Service development process, the role of the document is only a reference to flexibility in this way to climb other information, serious thought.
This example involves the JBoss ESB Server, I do not have a detailed description, I will discuss in detail the next document in the part. A good understanding of the instance to refer to the documentation of my Jboss ESB and Vss on the relevant code.
These are by Jboss ESB server as middleware forwarding messages from the message consumer end to end messages using the process, SOA (V1.2) works under this folder also includes a service consumer-side direct access service provider side instance. Namely:
On the class path in the VSS:
SOA (V1.2) \ Request endpoint (192.168.1.112) \ booking \ src \ org \ jboss \ seam \ example \ booking \ soa \ esb \ impl

package org.jboss.seam.example.booking.soa.esb.impl;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;

import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;

import org.jboss.seam.annotations.Begin;
import org.jboss.seam.annotations.End;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.security.Restrict;
import org.jboss.seam.example.booking.Hotel;
import org.jboss.seam.example.booking.commom.esb.BuildSoapMessage;
import org.jboss.seam.example.booking.commom.esb.SendSoapMessage;
import org.jboss.seam.example.booking.commom.esb.impl.BuildSoapMessageImpl;
import org.jboss.seam.example.booking.commom.esb.impl.SendSoapMessageImpl;
import org.jboss.seam.example.booking.commom.formattransform.TransformMethodName;
import org.jboss.seam.example.booking.commom.formattransform.impl.TransformMethodNameImpl;
import org.jboss.seam.example.booking.soa.esb.TeteDataHotelSave;

@ Stateful
@ Name ("saveTeteDataHotel")
@ Restrict ("# (identity.loggedIn)")
public class TeteDataHotelSaveImpl implements TeteDataHotelSave
(
@ In (required = false)
@ Out (required = false)
private Hotel hotel;

@ Begin
public void selectHotel (Hotel selectedHotel)
(
/ / Hotel h = new Hotel ();
hotel = selectedHotel;
)

public void seveHotel (Hotel hotel)
(
String ipAddress = hotel.getIpAddress ();
System.out.println ("yuexiangcheng, test !!!!!========"+ ipAddress);
TransformMethodName tmn = new TransformMethodNameImpl ();
Field [] f = hotel.getClass (). GetDeclaredFields ();
HashMap <String,String> hm = new HashMap ();
for (int i = 0; i <f.length; i + +) (
try (
String attributeName = f [i]. GetName ();
System.out.println ("attributeNameattributeNameattributeNameattributeNameattributeNameattributeName" + attributeName);
String motherName = tmn.getGetMethodByAttribute (attributeName);
Method method = hotel.getClass (). GetDeclaredMethod (motherName, null);
String attributeValue = method.invoke (hotel, null). ToString ();
System.out.println ("attributeValueattributeValueattributeValueattributeValueattributeValueattributeValue" + attributeValue);
hm.put (attributeName, attributeValue);
) Catch (SecurityException e) (
e.printStackTrace ();
) Catch (NoSuchMethodException e) (
e.printStackTrace ();
) Catch (IllegalArgumentException e) (
e.printStackTrace ();
) Catch (IllegalAccessException e) (
e.printStackTrace ();
) Catch (InvocationTargetException e) (
e.printStackTrace ();
)
)
BuildSoapMessage bsm = new BuildSoapMessageImpl ();
SendSoapMessage ssm = new SendSoapMessageImpl ();
try (
SOAPMessage sm = bsm.getMessage ("updateHotelObject", "http://tower/ehr_DEV", hm);
SOAPMessage result = ssm.send (sm, "http://" + ipAddress + ": 8080/jboss-seam-booking-jboss-seam-booking/HotelObjectImpl");
TransformerFactory transformerFactory =
TransformerFactory.newInstance ();
Transformer transformer =
transformerFactory.newTransformer ();
Source sourceContent = result.getSOAPPart (). GetContent ();
StreamResult resultPrint = new StreamResult (System.out);
transformer.transform (sourceContent, resultPrint);
System.out.println ();
) Catch (SOAPException e) (
/ / TODO automatically generated catch block
e.printStackTrace ();
) Catch (Exception e) (
/ / TODO automatically generated catch block
e.printStackTrace ();
)

)

@ End
public void cancel () ()

@ Remove
public void destroy () ()
)
Service consumer side of the process is modified to retrieve from the service provider side to the data, and to amend its service provider and then to keep to the side. Specific cases of the process and check on the small, please study the code on the VSS. Note that this example uses JAXB unmarshal function.

Web Service that I realize the above two methods, because the capacity is limited, so badly written, for reference only. We want to help, thank you.
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of Platform for distributed applications based on Web Service basics Summary

  • ubuntu under the rails how to connect sqlserver?

    Rails to connect SQL SERVER is a more complicated matter. Since different platforms are different methods of treatment. Take linux for a different release version has a different treatment methods. Record ubuntu here under the rails to connect sqlser ...

  • javascript performance optimization

    Would like to sum up a long time about javascript performance optimization some things, usually also have the attention of the collection of information in this regard. Del.icio.us put in the collection of random things turned out, only surprised to find

  • Let Ruby On Rails into the Embedded Development

    In the embedded Linux development, and C are a pair of golden partner, almost to occupy the vast majority of the domestic market and become the mainstream model of embedded development. At present, for some equipment to do configuration interface, many of

  • ROR troubled long Axis2 web service calls to be initially resolved

    Problem: ROR how Axis2 call the web service Currently experiencing this problem, Google and Baidu found at numerous times, both at home and abroad have seen virtually no valuable information, the only help is a call ROR about. Net Services article (http:

  • Using Ruby on Rails and Action Web Service to create Web Services

    Action Web Service module will be at Ruby on Rails implementation of Web services. Action Web Service will create the SOAP and XML-RPC Web Service Protocol server-side support. You can use the Declaration and the Action Web Service released the API. ...

  • Buffalo has PHPRPC and those differences

    zhou7707 wrote Asked about Comet support on how to? Chen Jinzhou of Buffalo and has those differences ? 1, PHPRPC with Buffalo positioning different, Buffalo only positioning in a Javascript to Java's remote procedure call. PHPRPC not only suppor ...

  • Ruby will replace Java? I think not so soon

    I have heard a lot of such talk: Ruby On Rails (RoR) cool easy enough to prepare one In Web Application speed 10 times faster than Java, and it has some Java features not superior. By To, Ruby will replace Java to become the next generation of programming

  • Pring Beanfactory at the jsp, servlet, web.xml and other configuration

    Keywords: spring beanfactory Spring in the web application called the Beanfactory 1) Configure web.xml Java code <? xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE web-app PUBLIC "- / / Sun Microsystems, Inc. / / ...

  • RoR explained

    ROR is Ruby on Rails. Ruby is a well-known has been very good dynamic language It's dynamic language. Simple and easy. Dynamic languages are interpreted, but the performance may make a discount, but not absolute, because the application is complex, th

  • Servlet brief introduction

    Servlet brief introduction: Servlet is a small application server Are used to complete the B / S architecture, the client requests the response to treatment Platform independence, performance, able to run thread Servlet API for Servlet provides the s ...

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries