What is a Web Service - Described with WSDL. SOAP Web Service with Spring-WS

How WSDL 1.1 Defines Web Services, and How to Create Java Models for Verifying and Transforming WSDL Documents

Content Series:

About this series of articles

Web services are an important feature of Java ™ technology in enterprise computing. In this article series, XML and Web services consultant Denis Sosnovskiy discusses the basic structures and technologies that are valuable to Java developers using Web services. Follow the articles in the series to keep abreast of the latest developments in this area and know how to apply them in your own projects.

Web services for enterprise applications rely heavily on the use of service definitions. Service definitions describe the basic agreement between a service provider and any potential customer, detailing the types of functions provided by the service and the messages within each function. Providers and consumers are free to choose how they implement their exchange objects, insofar as the actual messages they send match the service definition. Using a service definition to describe how XML messages are exchanged is what differentiates Web services from earlier distributed programming technologies.

Various methods have been proposed for defining Web services, but WSDL 1.1 remains the most widely used approach. WSDL 1.1 has some drawbacks, including an overly complex structure that makes it difficult to read for the uninitiated. It also suffers from a lack of an authoritative formal definition, which has led to consistent “refinements” that fill in some of the gaps in the original specification document. As a result, Web services stacks try to handle WSDL 1.1 documents as flexibly as possible. This flexibility can add to the confusion in understanding WSDL 1.1, as developers see a wide variety of WSDL structures without any indication of which approach is preferred.

In this article, we'll show you how to parse WSDL 1.1 documents and walk you through the first parts of a Java model for validating WSDL documents and converting them to standard form.

Parsing WSDL 1.1

Namespaces used

This article uses:

  • the wsdl prefix to represent the WSDL 1.1 namespace http://schemas.xmlsoap.org/wsdl/;
  • the soap prefix for the http://schemas.xmlsoap.org/wsdl/soap/ namespace used by the WSDL 1.1 SOAP 1.1 extension
  • the xs prefix for the http://www.w3.org/2001/XMLSchema namespace used for XML Schema definitions.

WSDL Revision 1.1, published in early 2001, is technically superseded by the W3C WSDL 2.0 Guidelines, published in 2007. WSDL 2.0 offers a clearer structure than WSDL 1.1, along with more flexibility. But WSDL 2.0 suffers from a chicken and egg problem: WSDL 2.0 is not widely used because it is not widely supported, and because it is not widely used, there is little incentive for Web service stack developers to support it. Despite all its flaws, WSDL 1.1 is good enough for most purposes.

The original WSDL 1.1 specification was inaccurate in terms of the number of features used. Because the focus of WSDL was on SOAP service definitions, it also included support for SOAP features (such as rpc encoding) that were later deprecated. The Web Services Interoperability Organization (WS-I) addressed these issues in the Baseline Profile (BP), which provides best practices for Web services using SOAP and WSDL. BP 1.0 was approved in 2004 and BP 1.1 was released in 2006. This article focuses on WSDL 1.1 based on the WS-I BP guidelines and does not touch upon de facto legacy features such as rpc encoding for SOAP.

The structure of XML documents is assumed to be defined by XML schema definitions. The original WSDL 1.1 specification included a schema description, but the schema does not match the textual descriptions in several respects. This was later fixed in a modified version of the schema, but the WSDL 1.1 document was not edited to reflect this change. The BP WS-I team then decided to make even more changes to the WSDL schema and created what is being hailed as a best practice guide to this slippery schema. Documents written for one version of the schema are generally not compatible with other versions (despite using the same namespace), but fortunately, most Web services tools basically ignore the schema and accept anything that looks like reasonable. (See links to many WSDL schemas in the section).

Even the WS-I BP version of the WSDL 1.1 schema is not very helpful in ensuring compliance with the WSDL 1.1 document specification. The diagram does not reflect all the limitations of BP WS-I, especially with regard to component ordering. In addition, XML Schema is unable to handle many types of easily set constraints in documents (such as alternate attributes or required additional elements from a separate schema). Therefore, validating a WSDL 1.1 document against the WSDL 1.1 specification (as amended by BP WS-I) involves much more than just performing XML schema validation. We'll come back to this topic in this article. But first, let's look at the structure of WSDL 1.1 service descriptions.

Description components

WSDL 1.1 docs use a fixed root element with a convenient name ... Within this root element in the WSDL 1.1 namespace, one "passive" child element (just a link to individual WSDL 1.1 documents) and five "active" child elements (which actually make up the service description) are defined:

  • refers to a separate WSDL 1.1 document with descriptions to be included in this document;
  • defines the XML types or elements used for messaging;
  • defines the actual message in terms of types or XML elements;
  • defines an abstract set of operations performed by the service;
  • defines the actual implementation using specific protocols and formats;
  • defines a service as a whole, usually including one or more elements with access information for elements .

There is also an element which can be used for documentation purposes as the first child as well as the first child of any of the above.

A complete description of a service usually requires at least one element of each of these types, with the exception of , but it is not necessary that they are all in the same document. To build a complete WSDL description from multiple documents, you can use , which allows you to subdivide descriptions for the needs of the organization. For example, the first three description elements ( , and ) together constitute a complete description of the service interface (possibly defined by the architecture group), so it makes sense to keep them separate from implementation-oriented elements and ... All major Web services stacks support splitting descriptions into multiple WSDL documents.

Listing 1 shows an example of a WSDL service description split into two WSDL documents, so the interface description components are in the BookServerInterface.wsdl file and the implementation components in the BookServerImpl.wsdl file. Listing 1 shows BookServerInterface.wsdl.

Listing 1. BookServerInterface.wsdl
Book service interface definition. ... ... Book service implementation. This creates an initial library of books when the class is loaded, then supports method calls to access the library information (including adding new books). Get the book with a particular ISBN. ... Add a new book.

Listing 2 shows BookServerImpl.wsdl. Element first imports the description of the BookServerInterface.wsdl interface.

Listing 2. BookServerImpl.wsdl
Definition of actual book service implementation. ...

In addition to the definitions of elements (and attributes) in the WSDL 1.1 namespace, WSDL 1.1 also defines additional elements. They are intended to fill in specific cells in WSDL 1.1 service descriptions to convey additional information required for a specific type of service. The only additional WSDL 1.1 elements that are still widely used are the bindings for SOAP 1.1 (these are presented in, in the elements and ), which were defined in the original WSDL 1.1 specification, and for SOAP 1.2, defined in a separate specification in 2006.

Component details

Element contains all XML definitions used for messages as one or more elements ... (WSDL allows alternatives to XML Schema for these definitions, but most stacks only support XML Schemas.) If necessary, the elements can use or to include other schemas external to WSDL (and also refer to separate schemas within the same WSDL).

Since one element can contain any number of schema definitions, there is no reason to use more than one element in a WSDL document ... Into element is at the top of BookServerInterface.wsdl.

Besides and , all top-level components of the WSDL document are assigned separate names using the required name attribute. When using targetNamespace attribute on root element document (which is usually best), the names of these components are defined in that target namespace. This means that when defining a name, it is sufficient to assign the simple, or "local" part of the name, but references to that component must qualify the name with a namespace prefix or with a default namespace. Figure 1 shows the most important relationships between WSDL components, with solid lines representing links by full name and dashed lines by name used to identify without qualifying the namespace.

Figure 1. Relationships between WSDL Components

Messages represented by elements are located in the core of WSDL service descriptions. The elements are descriptions of XML data transferred between a customer and a service provider. Each element contains zero or more (usually one) children ... Each part element requires its own name attribute (unique within ) and one of the element or type attributes that reference the XML data schema definition. Multiple items shown in, after item in BookServerInterface.wsdl.

The elements define the abstract interface of the service in terms of messages sent to and received from the service. The elements contain any number of children ... Each child requires its own name attribute (BP WS-I requires it to be unique within ), and it contains one or more child elements that describe the messages used by the operation. Child elements are of three types, corresponding to different uses:

  • : data sent by the customer to the service provider as input for an operation;
  • : data returned to the customer by the service provider as a result of the operation;
  • : Data returned to the customer by the service provider when an error occurs during processing.

WSDL 1.1 defines several patterns of interaction between customer and service provider, represented by different sequences of children and but not all models are well defined enough to be implemented. BP WS-I allows only two models: request-response operations, where for should , and one-way operations containing only ... In the case of operations of the request-response type (by far the most common type) behind elements and any number of elements can follow .

Each element , or refers to the description of the message through the required message attribute. This is a namespace qualified reference, so it usually requires a prefix to be added. Examples can be seen in: for example, when an element used in the description of the getBook operation. (The tns prefix serves as the definition of the root element with the same URI namespace as the targetNamespace attribute.)

IN many respects can be thought of as the logical equivalent of a Java interface, so that the elements are equivalent to methods, elements - method parameters, elements - the results of the methods, and the elements - checked exceptions. These mappings are used when generating Java code from WSDL, as with most tools that generate WSDL from existing Java code.

Comparing SOAP 1.1 and 1.2

SOAP 1.1 has been widely used for Web services since the specification was published in 2000. SOAP 1.2 was developed with wider industry support through the W3C and published as an official W3C standard in 2007. SOAP 1.2 is better documented and cleaner than SOAP 1.1, with some of the ugly aspects of 1.1 being surgically removed. Despite this refined structure, there is little practical difference between the two for most Web services. Probably the most significant feature of SOAP 1.2 is that it is the only officially supported way to leverage the extended SOAP attachment support for XML binary Optimized Packaging (XOP) and SOAP Message Transmission Optimization Mechanism (MTOM). In a loop Java Web Services I've used SOAP 1.1 so far because some older stacks don't support SOAP 1.2, but for developing new Web services 1.2 is probably the best choice.

The elements represent an instance of an abstract interface defined which is visible at the beginning of BookServerImpl.wsdl. The type attribute contains the fully qualified name of the port type implemented in the binding.

Child elements contain details on how to implement the port type. Child elements from WSDL namespace correspond to elements and should use the same name value - but not refined references as in the case ... this relationship is shown by dashed lines at the level ... The same relationship by name applies to children as well / / elements ... Despite this reuse of the same element names, the content of these elements differs significantly when they are child elements. , not an element .

WSDL defined extensions come into play in ... Child element used in a SOAP service definition (the only service type allowed by the WS-I BP, although WSDL 1.1 also allows HTTP bindings). This item uses the required transport attribute to define the mode of transport used by the binding. (HTTP, as you can see from the value of http://schemas.xmlsoap.org/soap/http in, is the only choice allowed by WS-I VR.) The optional style attribute allows you to choose between rpc and document styles to represent XML data ( the most common value for document matches messages using schema definition elements rather than type).

Inside each child element element element can be used to specify a SOAPAction value to identify requests to invoke this operation (and potentially also to override the document or rpc style selection specified by the , although BP WS-I prohibits such use). Each child / / contains another optional element, which is always an element (indicating that the message data is passed in the body of the SOAP message - data and even errors can be passed in SOAP headers as well, although I do not recommend this) for or , or its equivalent used with .

The final component of the WSDL service description is the element which consists of a group of elements ... Each element associates an access address with ... The access address is contained in the nested optional element .

Working with WSDL

Not surprisingly, with all the schema and rule variations for WSDL 1.1 documents, many documents do not follow the BP WS-I best practices. The support by all Web services stacks of many best practice deviations has helped perpetuate the use of outdated or misconstructed constructs, leading to the spread of bad practice throughout the industry. And I'm definitely not immune to this infection - by looking at the WSDL documents I've provided as code examples for this series, I was surprised to find that none of them are completely correct.

So when I decided to write this article, I thought it would be good to include a tool with which you can validate WSDL documents for best practices. It would seem that this is only one step away from converting WSDL documents into the correct form, provided that the original WSDL is free of errors. But the work turned out to be much more than I originally planned, and I will include full information about this model in the next two articles of this series.

Many different models have been built for working with WSDL documents in Java, including the widely used Web Services Description Language for the Java Toolkit (WSDL4J), which is the JSR 110 reference implementation (see section). None of these models match what I was going to do, due to the twofold setting of the problem: first, reading WSDL documents in any semi-reasonable form and reporting errors and deviations from best practices, and secondly, writing error-free WSDLs. documents reformatted into a form that complies with practical recommendations. WSDL4J, for example, does not preserve the order of input elements so that ordering problems can be reported, and it does not process schema definitions so it cannot be used directly to check references from elements. ... So I had to choose between a more realistic setting of the problem and writing my own model. Naturally, I decided to write my own model.

WSDL Model

Validation and verification

In this article, I use the term verification to denote validation of a WSDL document, because the alternative term is validation, commonly used for XML documents, means validating documents against a schema definition.

I have previously partially implemented the WSDL model for use with JiBX data binding as part of a JiBX / WS project. This model is for output only and includes a relatively small number of classes that in some cases combine data from nested WSDL XML structure elements ( combined with one child , , and inside combined with element or etc.). This compact class structure made it easier to build a subset of the WSDL documents supported by the framework, but when I began to consider building a verification and restructuring tool based on this model, I realized that the model to support input of a possibly poorly structured WSDL should be closer to XML. representation.

Another option is to generate code from the WS-I BP schema for WSDL 1.1. Seeing this, I realized that simply using the generated classes would directly lead to confusion, as the schema includes redundant types as well as some awkward constructs that are used to represent various messaging models (some of which were then disallowed by the WS-I BP text) ...

So I ended up writing the classes by hand, although the result was pretty much the same as if I started with the code generated from the schema and just cut down on unnecessary duplication and complexity. The JiBX data binding maintains multiple bindings to the same classes, so I was able to create an input binding to handle the full range of options allowed by any version of WSDL 1.1, although configuring the output binding for WSDL output was only in a best practice form.

Listing 3 shows the portion of the Definitions class corresponding to the root element. .

Listing 3. The Definitions class (partially)
public class Definitions extends ElementBase (/ ** Lists child elements in expected order. * / static enum AddState (invalid, imports, types, message, portType, binding, service); / ** List of allowed attribute names. * / public static final StringArray s_allowedAttributes \u003d new StringArray (new String ("name", "targetNamespace")); / ** Validate the context used. * / Private ValidationContext m_validationContext; / ** Current state (used to check the order in which * / / ** children are added). * / private AddState m_state; / ** The name of this definition. * / private String m_name; / ** Target namespace WSDL. * / private String m_targetNamespace; / ** List of all imported children. * / private List m_imports \u003d new ArrayList (); / ** List of all types of children. * / private List m_types \u003d new ArrayList (); / ** List of all messages of child elements. * / private List m_messages \u003d new ArrayList (); / ** List of all child portType elements. * / private List M_portTypes \u003d new ArrayList (); / ** List of all child bindings. * / private List m_bindings \u003d new ArrayList (); / ** List of all child services. * / private List m_services \u003d new ArrayList m_nameMessageMap \u003d new HashMap (); / ** Mapping a qualified name to a port type in this definition. * / private Map m_namePortTypeMap \u003d new HashMap (); / ** Mapping a qualified name to a message in this definition. * / private Map m_nameBindingMap \u003d new HashMap (); / ** Mapping a qualified name to a service in this definition. * / private Map m_nameServiceMap \u003d new HashMap (); ... / ** * Checking transition states between different types of children. * If the items are not in the expected order, * the first item out of the expected order is flagged for the report. * @param state new add state * @param comp element component * / private void checkAdd (AddState state, ElementBase comp) (if (m_state! \u003d state) (if (m_state \u003d\u003d null || (m_state! \u003d AddState.invalid && state.ordinal ()\u003e m_state.ordinal ())) (// switch to another type of child elements m_state \u003d state;) else if (state.ordinal ()< m_state.ordinal()) { // отчет о дочерних элементах вне ожидаемого порядка m_validationContext.addWarning ("Child element of wsdl:definitions out of order", comp); m_state = AddState.invalid; } } } ... /** * Добавление немаршаллизированного дочернего элемента wsdl:message. * Здесь же сообщение индексируется по имени для доступа с целью валидации. * * @param child */ public void addMessage(Message child) { checkAdd(AddState.message, child); m_messages.add(child); addName(child.getName(), child, m_nameMessageMap); } ...

The organization of child data in shows how the model supports both generic input and output as best practice. Instead of a single list of children of all types, separate lists are used for each type. The JiBX input binding treats children as an unordered set, invoking the item-specific setter whenever the child is out of place. Instead of replacing any of the preceding values, the setter adds the instance to the typed list, as seen from the addMessage () setter used for child elements. ... Each setter also runs a state check to catch out-of-order items.

Additional attributes and elements are allowed in any of the WSDL elements (typically, all attributes or elements that do not use the WSDL 1.1 namespace). Examples of such additional elements are the WS-Policy configurations embedded in the WSDL documents from the previous articles in this series, as well as links to the actual policies. It is best for these additional elements to precede any child elements from the WSDL 1.1 namespace, and this is how they are handled in the output binding. Input binding handles additional elements and attributes using base class code from the WSDL element classes not shown in, and allows elements to follow in any order (generating a warning if they follow an element from the WSDL 1.1 namespace).

The model handles known elements using separate bindings for each additional namespace, each with its own set of classes. I will cover handling these additional elements in more detail in the next release. Java Web Services, where the source code will be presented in more detail.

Model verification

Some basic verification of the WSDL data is done as the non-marshalling objects corresponding to the elements are added to the tree structure of the WSDL document, as shown in the addMessage () code at the end. This code uses the checkAdd () method to check the order of the children, and the addName () method to check that a valid name is provided (the text matches the schema type NCName and the value is unique within the element type) and maps the name to an object. But this is only a check of the most basic information for a single element; additional verification code is required to verify other properties of each item and the relationships between items.

JiBX allows you to call custom extension handlers as part of the marshalling and unmarshalling process. The WSDL model uses one of these additional handlers, the post-set method, to execute the verification logic. The post-set method is called after the unmarshalling of the associated object is complete, so this is often a good way to perform type checks on objects. In the case of WSDL validation, the simplest approach is to perform all object verification from one post-set method for the root element ... This approach avoids the problem of directly referencing the components of the WSDL document when the components are not in the expected order.

Other additions

This article outlines the basics of the structure and use of WSDL and provides an introduction to the Java Data Model for WSDL to support the verification of WSDL documents and transform them into a best practice form.

The next article will continue this topic by looking at common issues when writing WS-Policy and WS-SecurityPolicy assertions. It also goes into more detail on the WSDL model and verification process, including extending the model to include WS-Policy / WS-SecurityPolicy assertions embedded in WSDL.

Once they gave me the task of starting the development of Web services and gave me a sample of the simplest project without any explanation. The project, of course, did not start. What is Spring and how it works, I also had no idea. I also could not find adequate articles on developing Web services using Spring, either in Russian or in English. I had to figure it out myself, it turned out to be not so scary.
And just recently, I decided to look at what new features have been added to Spring since then and update the old services, which, as a result, prompted me to write this article.

This article is a guide to developing a basic SOAP-based Web service using Spring-WS.

And so, we will write a simple service that accepts a username and sends a greeting and the current time on the server.

What do we need?
  • IDE. I am using Eclipse.
Preparation for work
Create a new Web application project. In Eclipse, this is: "File \u003d\u003e New \u003d\u003e Dynamic Web Project".
I named the project: HelloService.
Next, copy the libraries from Spring, XMLBean, wsdl4j, commons-logging to the project directory WEB-INF / lib.
If you want, you can add them to the server libraries, so as not to drag them around with every application.
Creating a WSDL schema
Essentially, a WSDL schema is intended to describe a service.
Of course, we will not create it manually. The schema will be generated automatically by Spring, but more on that later.
Defining input and output data
Input data:
  • String name.
Output:
  • String greeting;
  • Time is the current time.
Create a description of the input and output data
In the WEB-INF directory, create a HelloService.xsd file. This file will be needed to generate the WSDL schema and create the corresponding Java classes.
File text:

Attribute targetNamespace - used namespace. Those. all created objects will be located in the org.example.helloService package.
The elements ServiceRequest and ServiceResponse describe the input and output data (request / response), respectively.
Attributes minOccurs and maxOccurs determine the number of repetitions of a given component within one element. If these parameters are not specified, then by default they are considered equal to 1. For an optional component, you must specify minOccurs \u003d 0. With an unlimited number of components: maxOccurs \u003d unbounded.
You can read more about XML Schemas.
Create JavaBeans
Based on the created scheme, we will create Java classes. To do this, create a build.xml file:

Parameter WS_HOME should point to the directory where XMLBeans is located.
HelloService.xsd - path to the created scheme.
lib \\ helloservice.jar - the java library being created.

Next, run Ant-build (I hope you've already installed it).
In Eclipse, you can run it like this: RMB on the build.xml file \u003d\u003e Run As \u003d\u003e Ant Build.
If via the command line:
ant -buildfile build.xml
Well, we are waiting for the completion of the construction. After that, we can check the project directory WEB-INF \\ lib for the presence of the corresponding library (helloservice.jar).

Service implementation
Create an interface and service class
Service interface: HelloService.java:
package org.example; import java.util.Calendar; public interface HelloService (public String getHello (String name) throws Exception; public Calendar getCurrentTime ();)
Service implementation: HelloServiceImpl.java:
package org.example; import java.util.Calendar; import org.springframework.stereotype.Service; @Service public class HelloServiceImpl implements HelloService (public String getHello (String name) throws Exception (return "Hello," + name + "!";) Public Calendar getCurrentTime () (return Calendar.getInstance ();))
This code, I think, does not need any comments. The only thing that people who have not previously encountered Spring may raise questions is the @ Service annotation, but I'll talk about this a little later.
Endpoint
Endpoint is a class that will be responsible for processing incoming requests (a kind of entry point).

Create HelloServiceEndpoint.java file:
package org.example; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ws.server.endpoint.annotation.Endpoint; import org.springframework.ws.server.endpoint.annotation.PayloadRoot; import org.example.helloService.ServiceRequestDocument; import org.example.helloService.ServiceRequestDocument.ServiceRequest; import org.example.helloService.ServiceResponseDocument; import org.example.helloService.ServiceResponseDocument.ServiceResponse; @Endpoint public class HelloServiceEndpoint (private static final String namespaceUri \u003d "http://www.example.org/HelloService"; private HelloService helloService; @Autowired public void HelloService (HelloService helloService) (this.helloService \u003d helloService;) (@PayloadRoot localPart \u003d "ServiceRequest", namespace \u003d namespaceUri) public ServiceResponseDocument getService (ServiceRequestDocument request) throws Exception (ServiceRequestDocument reqDoc \u003d request; ServiceRequest req \u003d reqDoc.getServiceRequest (); ServiceResponseDocument \u003d respaDoc \u003d ServiceResponseDocument addNewServiceResponse (); String userName \u003d req.getName (); String helloMessage \u003d testNewService.getHello (userName); Calendar currentTime \u003d testNewService.getCurrentTime (); resp.setHello (helloMessage); resp.setCurrent); returnTime (currentTime) )
What has been done here?
annotation @Endpoint just determines that this class will process incoming requests.
namespaceUri - the same namespace that was specified when creating the xml schema.

Now let's go back a little and remember the annotation @ Service... If you do not go into details, so as not to overload the reader with unnecessary information, then this annotation tells Spring "to create an appropriate object. And the annotation @Autowired serves for injection (automatic substitution) of the corresponding object. Of course, when building simple applications, there is no point in using these annotations, but I decided not to exclude them all in this example.

Otherwise, again, everything should be clear. Note that ServiceRequest, ServiceResponse, etc. - these are just the classes that were created based on our xml-schema.

Spring service configuration
So the end is already approaching.
Create service-ws-servlet.xml file.

sws: annotation-driven - says exactly that annotations are used in this project.
AND context: component-scan indicates the package in which to search for annotations, while searching in subpackages as well.

The next two bins will always be unchanged. Their essence is to receive and transform a request from Xml into a Java object and then reverse the transformation.

sws: dynamic-wsdl responsible for the automatic generation of a WSDL document based on the generated Xml schema.
location indicates the path to the schema.
locationUri - the address (relative to the container) at which the WSDL scheme will be available.
In my case, WSDL is available at the following address:
localhost / HelloService / HelloService.wsdl

Deployment descriptor
And finally, the last thing.
Modify or create web.xml file in WEB-INF directory.
HelloService HelloService service-ws org.springframework.ws.transport.http.MessageDispatcherServlet transformWsdlLocations true service-ws /*
I will not describe this file, the majority should already know. For uncomplicated projects, it essentially shouldn't change. It is worth noting only that the servlet name (servlet-name) must match the name of the service's Spring configuration file. service-ws-servlet.xml.
Functional check
The very first sign of correct operation is the generated WSDL schema.
To check, just go to the address of this scheme (http: //localhost/HelloService/HelloService.wsdl) and see: the xml file should be displayed there. If nothing was displayed or what error appeared, we reread the entire article carefully and look for what we did wrong.

For further verification, we need soapUI (I have version 3.0.1).
Install and run it.
Create a new project: File \u003d\u003e New soapUI Project. In the Initial WSDL / WADL field, insert a link to the WSDL schema (http: //localhost/HelloService/HelloService.wsdl).
In the created project, open the required request.

In the Name field, drive in the name and click on the "Send request" button


As a result, we receive a response from the server with a greeting and the current time.


If something went wrong, then we reread this article again.

What's next?
Well, the next step is to write a client for this Web service. But this is already material for another article, which will probably be written later, if this material will interest someone.

The topic title is really a question, since I myself do not know what it is and for the first time I will try to work with it within the framework of this article. The only thing I can guarantee that the code below will work, but my phrases will only be assumptions and guesses about how I myself understand all this. So let's go ...

Introduction

We need to start with what the concept of web services was created for. By the time this concept appeared, technologies already existed in the world that allowed applications to interact at a distance, where one program could call some method in another program, which could be run on a computer located in another city or even a country. All of this is abbreviated as RPC (Remote Procedure Calling). Examples include CORBA technologies, and for Java - RMI (Remote Method Invoking). And everything seems to be good in them, especially in CORBA, tk. you can work with it in any programming language, but something was still missing. I believe that the disadvantage of CORBA is that it works through some of its own network protocols instead of simple HTTP, which will crawl through any firewall. The idea behind the web service was to create an RPC that would stick into HTTP packets. This is how the development of the standard began. What are the basic concepts of this standard:
  1. SOAP... Before calling a remote procedure, you need to describe this call in a SOAP XML file. SOAP is simply one of the many XML markups used in web services. Everything that we want to send somewhere via HTTP is first converted into an XML SOAP description, then put into an HTTP packet and sent to another computer on the network via TCP / IP.
  2. WSDL... There is a web service i.e. a program whose methods can be called remotely. But the standard requires that a description be attached to this program, which says that "yes, you are not mistaken - this is really a web service and you can call such and such methods from it." This description is represented by another XML file that has a different format, namely WSDL. Those. WSDL is just an XML file describing a web service and nothing else.
Why do you ask so briefly? Can't you get more details? Probably you can, but for this you have to turn to books such as Mashnin T. "Java Web Services". There, for the first 200 pages, there is a detailed description of each tag of the SOAP and WSDL standards. Should I do it? In my opinion, no, because all of this is created automatically in Java, and you only need to write the contents of the methods that are supposed to be called remotely. So, in Java there appeared such an API as JAX-RPC. If someone does not know when they say that Java has such and such an API, it means that there is a package with a set of classes that encapsulate the technology in question. JAX-RPC evolved from version to version for a long time and eventually evolved into JAX-WS. WS obviously stands for WebService and you might think that this is a simple renaming of RPC into a popular word these days. This is not the case, since Now web services have moved away from the original idea and allow you not only to call remote methods, but also to simply send document messages in SOAP format. Why this is needed, I do not know yet, the answer is unlikely to be "just in case, suddenly it will be needed." I myself would like to learn from more experienced comrades. And the last thing, then JAX-RS appeared for the so-called RESTful web services, but this is a topic for a separate article. This is where the introduction can be ended, since next we will learn to work with JAX-WS.

General approach

Web services always have a client and a server. The server is our web service and is sometimes called an endpoint (like the endpoint where SOAP messages from the client go). We need to do the following:
  1. Describe the interface of our web service
  2. Implement this interface
  3. Start our web service
  4. Write a client and call the required web service method remotely
You can start a web service in different ways: either you describe a class with a main method and start the web service directly as a server, or deploy it to a server like Tomcat or any other. In the second case, we do not start a new server ourselves and do not open another port on the computer, but simply tell the Tomcat servlet container that “we wrote the web service classes here, publish them, please, so that everyone who contacts you can our use the web service ". Regardless of the method of launching the web service, we will have the same client.

Server

Let's start IDEA and create a new project Create New Project... Let's enter a name HelloWebService and press the button Next, then the button Finish... In folder src create a package ru.javarush.ws... In this package, we will create the HelloWebService interface: package ru. javarush. ws; // these are annotations, i.e. a way to mark our classes and methods, // as related to web service technology import javax. jws. WebMethod; import javax. jws. WebService; import javax. jws. soap. SOAPBinding; // say that our interface will work as a web service @WebService // say that the web service will be used to call methods @SOAPBinding (style \u003d SOAPBinding. Style. RPC) public interface HelloWebService ( // we say that this method can be called remotely @WebMethod public String getHelloString (String name); ) In this code, the WebService and WebMethod classes are so-called annotations and do nothing but mark our interface and its method as a web service. The same is true for the SOAPBinding class. The only difference is that SOAPBinding is a parameter annotation. In this case, the style parameter is used with a value that says that the web service will work not through document messages, but as a classic RPC, i.e. to call the method. Let's implement the logic of our interface and create a HelloWebServiceImpl class in our package. By the way, I will note that the end of the class in Impl is a convention in Java, according to which the implementation of interfaces is so denoted (Impl - from the word implementation, i.e. implementation). This is not a requirement and you are free to name the class whatever you want, but the rules of good form require it: package ru. javarush. ws; // the same annotation as when describing the interface, import javax. jws. WebService; // but used here with endpointInterface parameter, // specifying the fully qualified class name of our web service interface @WebService (endpointInterface \u003d "ru.javarush.ws.HelloWebService") public class HelloWebServiceImpl implements HelloWebService (@Override public String getHelloString (String name) ( // just return a greeting return "Hello," + name + "!" ; )) Let's start our web service as an independent server, i.e. without the involvement of any Tomcat and application servers (this is a topic for a separate discussion). To do this, in the project structure in the folder src create a package ru.javarush.endpoint, and in it create a HelloWebServicePublisher class with a main method: package ru. javarush. endpoint; // class to start a web server with web services import javax. xml. ws. Endpoint; // class of our web service import ru. javarush. ws. HelloWebServiceImpl; public class HelloWebServicePublisher (public static void main (String... args) ( // start the web server on port 1986 // and at the address specified in the first argument, // start the web service passed in the second argument Endpoint. publish ( "http: // localhost: 1986 / wss / hello", new HelloWebServiceImpl ()); )) Now let's run this class by clicking Shift + F10... Nothing appears in the console, but the server is running. You can verify this by typing the line http: // localhost: 1986 / wss / hello? Wsdl in the browser. The page that opens, on the one hand, proves that a web server (http: //) has started on our computer (localhost) on port 1986, and, on the other hand, shows the WSDL description of our web service. If you stop the application, the description will become unavailable, like the web service itself, so we will not do this, but proceed to writing the client.

Client

In the project folder src create a package ru.javarush.client, and in it the HelloWebServiceClient class with the main method: package ru. javarush. client; // needed to get wsdl description and through it // reach the web service itself import java. net. URL; // such an execution will occur when working with a URL object import java. net. MalformedURLException; // classes to parse xml with wsdl description // and reach the service tag in it import javax. xml. namespace. QName; import javax. xml. ws. Service; // interface of our web service (we need more) import ru. javarush. ws. HelloWebService; public class HelloWebServiceClient (public static void main (String args) throws MalformedURLException ( // create a link to wsdl description Url url \u003d new url ( "http: // localhost: 1986 / wss / hello? wsdl") ; // We look at the parameters of the next constructor in the very first tag of the WSDL description - definitions // look at the 1st argument in the targetNamespace attribute // see the 2nd argument in the name attribute QName qname \u003d new QName ("http://ws.javarush.ru/", "HelloWebServiceImplService"); // Now we can reach the service tag in the wsdl description, Service service \u003d Service. create (url, qname); // and then up to the nested port tag, so that // get a link to a web service object remote from us HelloWebService hello \u003d service. getPort (HelloWebService. class); // Hooray! Now you can call the remote method System. out. println (hello. getHelloString ("CodeGym")); )) I gave maximum comments on the code in the listing. I have nothing to add, so we run (Shift + F10). We should see the text in the console: Hello, CodeGym! If you didn't see it, you probably forgot to start the web service.

Conclusion

In this topic, a brief excursion into web services was presented. Again, a lot of what I've written is my guesswork as to how it works, and therefore shouldn't be trusted too much. I would be grateful if knowledgeable people would correct me, because then I will learn something. UPD.

Page 2 of 3

Describing with WSDL

SOAP works very well if you know everything about the Web service. However, this is not always the case. The Web Services Description Language (WSDL) is used to describe the interface for accessing a Web service. This standard was jointly developed by IBM, Microsoft and webMethods. The three companies each had their own approach to developing a standard for describing Web services: IBM created NASSL, Microsoft developed SCL, and webMethods came up with WIDL.

The result of their collaboration was version 1.1 of the WSDL language. Regarding the W3C, it should be noted that, as with SOAP, the W3C, based on version 1.1, developed version WSDL 1.2, which is now a W3C recommendation. The WSDL for a Web service contains all the information required to use the service, including the available methods and their parameters. This information is contained in the following five elements:

  • - Supported protocols.
  • - Web service messages (request, response).
  • All available methods.
  • - Service URI.
  • - used data types.

All this information is stored in the root element of the WSDL description. The listing below shows an example of a WSDL description for a Web service.

WSDL Web Service Description

Yeah ... you can't figure it out without a glass, but this is one of the simplest (!) WSDL files. Unfortunately, one of the drawbacks of the SOAP extension for PHP 5 is that, unlike other SOAP implementations, it doesn't automatically generate WSDL descriptions (at least not yet). Surely this flaw will be fixed in future versions of PHP.

By the way!

You can use alternative SOAP implementations in PHP to automatically generate WSDL descriptions:

Searching the Directory with UDDI

Now that we know how to get information about a Web service and how to request it, we need to learn how to find such a service. For this purpose, there is something akin to the Yellow Pages, namely, the Universal Business Registries (UBRs) - Web services directories.

There are several such registries, including those of IBM, Microsoft, NTT-Com, and SAP. These registries synchronize their data, so you can use any of them. The current version of the UDDI standard is UDDI 3.0, although most implementations use version 2. The developers of this standard include such giants as HP, Intel, Microsoft and Sun.

To interact with UBR, there is two types of APIs: Inquiry API and Publish API... Interface Inquiry API is for request services in UBR registries, and the interface Publish API allows developers to register their services... It looks like filling the contents of the registries with spam is only a matter of time :)

By the way!

There are test registries designed to test service registrations before placing them in "real" registries.

This is what the Web service request looks like:

sortByNameAsc sortByDateDesc % guid%

In the example above, you can see that the UDDI request is encapsulated in a SOAP message, so it looks pretty familiar. The response to the request is also the SOAP document shown below:

Web Services Guided Tour Sample Web services for Guided Tourbook Guided Tour StockQuote Service

Installation

Installing the SOAP extension for PHP5 is fairly easy. On Windows, this module is located in the ext subdirectory of the PHP installation directory. To use it, add the following line to php.ini file: extension \u003d php_soap.dll For this module to work, it is required, which is included in PHP 5 by default, at least in the Windows version.

XSD: XML Schema definition.

XML: Extensible Markup Language.

WSDL: Web Services Definition Language.

I'm not going to answer technically. I am directing this explanation towards newbies.

It is not easy to communicate between two different applications that are being developed using two different technologies. For example, a company in Chicago might develop a web application using Java, and another company in New York might develop an application in C #, and when the two companies decide to exchange information, then XML will appear in the picture. It helps to store and transport data between two different applications that are developed using different technologies. Note. This is not limited to a programming language, please investigate the transport of information between two different applications.

XSD is a schema definition. By that I mean it tells users to design their XML in such a schema. Please see below image and watch closely with the "load-on-startup" element and its type which is an integer. In the XSD image, you can see that it is for an integer value for "load-on-startup" and hence when the user created his XML, he passed the int value to that particular element. Recall that XSD is a schema and style, whereas XML is a form for communicating with another application or system. You need to see the XSD and create XML that way, otherwise it won't communicate with another application or system that was developed using a different technology. The Chicago company provides an XSD template for the Texas company to write or generate its XML in this XSD format. If the Texas company has failed to adhere to those rules or schemes mentioned in the XSD, then it is impossible to expect correct information from the Chicago company. After the above story, there is so much more that the hobbyist or newbie needs to know while coding some things like I said above. If you really want to know what comes next, then it's best to sit with the senior software engineers who actually developed the web services. Next comes the WSDL, please follow the images and try to figure out where the WSDL will fit.

*************** \u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d Below is a partial XML image \u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d ********* *** ***

*************** \u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d Below is a partial XSD image \u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d ********* *** ***

*************** \u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d Below is a partial image of WSDL \u003d\u003d\u003d\u003d\u003d\u003d\u003d *********** **

I had to create a sample WSDL for a web service called Book. Note that this is XSD, but you must name it WSDL (Web Services Definition Language) because it is very specific to web services. Below WSDL (or in other words XSD) is generated for Book.java class and it created SOAP service. How the SOAP web service was created is a different topic. A Java class needs to be written, and before proceeding to create it as a web service, the user needs to make sure the Axis2 API is installed and Tomcat to host the web service in place.

As a service provider (one who allows others (customers) to access information or data from their systems) actually gives the customer (those who need to use the information or data of the service provider) full access to the data through the web service, neither one company on earth is not ready to share its database with outsiders. Like my company, I decided to provide some product information via web services, so we had to create an XSD template and hand over some of our clients who want to work with us. They have to write code to make full use of the given XSD and make Web Service calls to retrieve data from the servicer and transform the data returned to their suitable request, and then display or publish the data or product information on their website. A simple example is the flight booking FLIGHT. The airline will allow third parties to use the flight details on its website to sell tickets. But then again there is a lot more, just by not allowing a third party airline ticket agency to sell tickets, there will be synchronization and security in place. If there is no synchronization, then the probability is 100% more than one customer can buy the same ticket from different sources.

I hope the experts will contribute to my answer. It is very difficult for a beginner or newbie to understand XML, XSD, and then work with web services.

Did you like the article? To share with friends: