Soap purification wired protocol (4): Simplified customer Program

Source: Internet
Author: User
Java 2 platform version 1.3 is a Java image API (reflection
API) adds an extremely practical extension: Dynamic proxy class. A dynamic proxy class is a class that implements a series of interfaces specified during runtime. This proxy can make
. In other words, you can directly call any method of any interface on the proxy object-of course, you must first set the necessary type (casting ). Therefore, we can use a dynamic proxy class to connect a group
Create a type-safe proxy object without having to generate a proxy in advance like using a compile-time tool (for more detailed descriptions of dynamic proxy classes, see the reference resources at the end of this Article ).

Next, I will introduce a framework based on dynamic proxy classes. This framework makes creation of SOAP (Simple Object Access Protocol) client programs easier and more intuitive. Soap is a data encoding method using XML.
. In the second and third parts of this series of articles, when constructing the soap service, we found that the developer of the customer program had to do a lot of work that was not previously required. To help recall, you can take a look
The soap service code in the second article looks at how insignificant the soap code of the service program is when compared with the client program code. Display of simple soap services created in the previous articles in this series
. The developer of the service program has few additional code to write, but the developer of the customer program has a lot of extra work to do. This article
The classes described will minimize these extra work.

1. Introduction to the soap proxy class
First, I want to explain what the customer program will look like if it uses the framework created in this article:

Package hello;
Import soapproxy .*;
Public class client
{
Public static void main (string [] ARGs)
{
Try
{
Class [] interfaces = new class [] {hello. hello. Class };
Hello = (Hello) (proxy. newinstance ("urn: Hello", interfaces ));

// Call the sayhelloto Method
// This sayhelloto method requires a string parameter
System. Out. println (hello. sayhelloto ("John "));

// Call the sayhelloto Method
// This sayhelloto method requires a name JavaBean Parameter
Name thename = new name ();
Thename. setname ("Mala ");
System. Out. println (hello. sayhelloto (thename ));
}
Catch (exception E)
{
E. printstacktrace ();
}
}
}

Perhaps out of my personal interests, I think the above Customer Code is better than the customer code in the second and third articles. If you cannot understand the above Code, it is normal, but I think you will understand it by the end of this article.

To understand the client program code, you must have a deep understanding of soap.
Proxy class, which is in the soapproxy package and can be found in proxy. Java (see the reference resources at the end of this Article ). The proxy class has a private constructor, which means
The proxy instance cannot be created outside the proxy; the only way to create a proxy instance is through the static newinstance () method. The newinstance () method has
Two parameters: the Object ID of the soap service and an array containing the names of the interfaces to be implemented by the proxy. The object ID is simple, but what are the names of these interfaces? Where can I get these connections?
Port name? Developers of the soap service directly heap all methods on the service that can be called by the client program to obtain an interface. It's quite simple, isn't it?

Now we define an interface for the helloworld service. In the second article, the final version of this service includes two overloaded versions of the sayhelloto () method: the parameter of one version is
And the parameter of another version is a name JavaBean. These two methods can constitute an interface called HELLO, as shown below:

Package hello;
Public interface hello
{
Public String sayhelloto (string name );
Public String sayhelloto (name );
}

The service developer decides the number of interfaces to be created and the name of these interfaces. For example, you can create two interfaces for the helloworld service. Each interface contains a method. Generally,
You should avoid creating interfaces with more than seven methods. In addition, note that only the methods that seem necessary to be put together are organized using one interface. For example, if the helloworld service has
The customized saybyeto () method for sending a good-bye message to the caller. It may be wise to design two independent interfaces: one interface is used for the sayhelloto () method and the other
The saybyeto () method.

Now we have an interface for defining the contract between the helloworld service and the customer program. The following shows the newinstance () method. As before
The newinstance () method to create a new instance of the proxy class. The newinstance () method can create a new instance because it belongs to the proxy class and can access the private
Some constructors. The newinstance () method calls the initialize () method for the newly created instance. Initialize () is worth noting, because dynamic proxy is
Create and return here. The initialize () code is as follows:

Private object initialize (class [] interfaces)
{
Return (Java. Lang. Reflect. Proxy. newproxyinstance (getclass (). getclassloader ()
, Interfaces, this ));
}

Note the application of the newproxyinstance () method. The only way to create a dynamic proxy instance is to call this class (that is, the Java. Lang. Reflect. proxy class)
Static newproxyinstance () method. The Java. Lang. Reflect. proxy class provides static methods for creating dynamic proxy classes, and
The superclass of the dynamic proxy class created by these methods. In other words, it is not only a factory that creates a dynamic proxy class, but also a dynamic proxy class! Therefore, in our example, the soap proxy is not
Dynamic proxy; on the contrary, this dynamic proxy is actually an instance of the Java. Lang. Reflect. proxy class returned by the newproxyinstance static method. Slave
Later in this article, we can see that this dynamic proxy actually completes all its work through the invoke () method implemented by the soap proxy. How can this dynamic proxy establish contact with the soap proxy?
What about it? Because a reference to the soap proxy is passed to the newproxyinstance () method. This may sound confusing now, but if you analyze the invoke () side
Method.

The first parameter of the Java. Lang. Reflect. proxy class constructor is a Class Loader instance, and the second parameter is the array of interfaces that need to be dynamically implemented (it is transmitted by the Client Program)
For the newinstance () array), the third parameter is an implementation of the Java. Lang. Reflect. invocationhandler interface class.
Example. Because soap
The proxy class implements the invocationhandler interface, so the third parameter is the proxy instance itself (that is, this ). The invocationhandler interface has
Method (). When the dynamically implemented interface of the dynamic proxy is called, the Java Runtime Environment calls the invoke () method. Therefore, for example, when a client program calls a dynamic proxy
When the sayhelloto () method of the hello interface is used, the Java Runtime Environment calls the invoke () method of the soap proxy.

You may have discovered that the newinstance () method of the soap proxy does not return the instance of the soap proxy; instead, it returns the dynamic Proxy just created by newinsance (), while
The dynamic proxy dynamically implements the array of interfaces passed in by the customer program. The client program can set the returned dynamic proxy to any interface type passed in to newinstance () and call
The methods defined by interfaces are the same as those implemented by dynamic proxies.

.
.
Try
{
Class [] interfaces = new class [] {hello. hello. Class };
Hello = (Hello) (proxy. newinstance ("urn: Hello", interfaces ));
// Call the sayhelloto method with the string parameter
System. Out. println (hello. sayhelloto ("John "));
// Call the sayhelloto method whose parameter is name JavaBean
Name thename = new name ();
Thename. setname ("Mala ");
System. Out. println (hello. sayhelloto (thename ));
}
.
.

In the preceding code, the invoke () method is called twice and executed once each time the sayhelloto () method is called. Now let's take a look at the invoke () method. In short
In the second article, the work of the invoke () method is exactly what each customer program must do manually, including setting a call object with appropriate call parameters and customizing the call parameters.
Required type ing. Because the invoke () method in the soap proxy undertakes all these tasks, the client program releases this burden.

Among the three parameters received by the invoke () method, we are only interested in the next two parameters. The second parameter, that is, the method object, provides the name of the called method. Remember, the name of the called Method
Corresponds to a known method exported by the soap service. The service object ID is passed as a parameter to the newinstance () method, so the invoke () method already has this object ID.
The invoke () method uses this information to set the call object as follows:

Call call = new call ();
Call. settargetobjecturi (URN );
Call. setmethodname (M. getname ());
Call. setencodingstyleuri (constants. ns_uri_soap_enc );

Now you need to set parameters for remote service calls. To this end, we need to use the third parameter of the invoke () method: to input a parameter array of the called method on the dynamic proxy. The parameter with the index 0 in the array
Number is the leftmost parameter in a method call. The parameter with index 1 is the second parameter of the method, and so on. For example, if the client program calls sayhelloto (string
Name) method, then the parameter array is an array containing a string. The invoke () method processes every element of the array and creates a vector composed of parameter objects.
(Vector) (as the customer program in the second article does ):

Java. util. Vector Params = new java. util. vector ();
For (INT I = 0; I & lt; args. length; I ++)
{
If (issimple (ARGs [I]) | issimplearray (ARGs [I])
{
Params. Add (new parameter (_ paramname + (I + 1 ),
ARGs [I]. getclass (), argS [I], null ));
}
Else if (isvector (ARGs [I])
{
Addmapping (Java. util. Vector) ARGs [I]);
Params. Add (New
Parameter (_ paramname + (I + 1), argS [I]. getclass (), argS [I], null ));
}
// If the element of this array does not belong to the Java Basic Data Type
// Assume this is an array of JavaBean.
Else if (isarray (ARGs [I])
{
If (SMR = NULL)
SMR = new soapmappingregistry ();
If (beanser = NULL)
Beanser = new beanserializer ();

Arrayserializer arrayser = new arrayserializer ();
SMR. maptypes (constants. ns_uri_soap_enc,
Null, null, beanser, beanser );
SMR. maptypes (constants. ns_uri_soap_enc,
Null, argS [I]. getclass (), arrayser, arrayser );
Params. Add (new parameter (_ paramname + (I + 1 ),
ARGs [I]. getclass (), argS [I], null ));
}
// Assume this is a bean
Else
{
If (SMR = NULL)
SMR = new soapmappingregistry ();
If (beanser = NULL)
Beanser = new beanserializer ();
String qnamepart = ARGs [I]. getclass (). getname ();
SMR. maptypes (constants. ns_uri_soap_enc,
New QNAME (urn, qnamepart), argS [I]. getclass (), beanser,
Beanser );
Params. Add (new parameter (_ paramname + (I + 1), argS [I]. getclass (), argS [I], null ));
}
}

The invoke () method uses many private auxiliary methods, such as using issimple () to determine the parameter type. If the parameter is a JavaBean or an array, then the program
You must set a custom soap ing registration item and use the setsoapmappingregistry () method to set the call object (see Article 2 ).
The soap proxy assumes that when a JavaBean occurs, all the an ans used by the soap service map as follows: namespace
Set URI to object ID, local
Set part to the complete Class Name of JavaBean. We deployed the helloworld service according to this requirement, so there is no problem.

The rest of the invoke () method is quite simple: Set the call object parameters, set the custom soap ing registration items (if necessary), issue the call, and receive the return values of the method call. As follows:

If (Params. Size ()! = 0)
Call. setparams (Params );
If (SMR! = NULL)
Call. setsoapmappingregistry (SMR );
// Send a call
Response resp = call. Invoke (serverurl ,"");
If (! Resp. generatedfault ())
{
Parameter ret = resp. getreturnvalue ();
Return (Ret. getvalue ());
}
Else
{
Fault fault = resp. getfault ();
Throw new
Soapexception (fault. getfaultcode (), fault. getfaultstring ());
}

Ii. helloworld Service
The complete code of the helloworld service is as follows. Do you feel familiar?

Package hello;
Public class helloserver
{
Public String sayhelloto (string name)
{
System. Out. println ("sayhelloto (string name )");
Return "hello" + name + ", how are you doing? ";
}
Public String sayhelloto (name thename)
{
System. Out. println ("sayhelloto (name thename )");
Return "hello" + thename. getname () + ", how are you doing? ";
}
}

Recall that name is a simple JavaBean with the following code:

Package hello;

Public Class Name
{
Private string name;
Public String getname ()
{
Return name;
}
Public void setname (string name)
{
This. Name = Name;
}
}

In fact, the service code here is exactly the same as the service program code in the second article. For service developers, the only task added is to create a Java interface. The method for deploying the service is also discussed in the second article.
The discussion is exactly the same, so I will not introduce it here. In the same way, the methods for compiling and running client programs are the same as described in the second article. Why are there so many similarities? Because we create
The created proxy is a non-plug-in framework that does not modify or interfere with the internal work of any Apache SOAP component-either the client or the server.

Iii. Other Instructions
The soap proxy discussed in this article (which can be downloaded later) supports the following parameter types:

(1) The following basic java data types and their corresponding object forms.

Boolean, Boolean,
Double, double,
Float, float,
Long, long,
Int, integer,
Short, short,
Byte, byte

Note: The Server Always receives basic data types.

(2) Any JavaBean

Note:

  • This JavaBean cannot contain other JavaBean.
  • If an array or vector contains types other than string or 1 to list data types, the JavaBean cannot contain such arrays or vectors.

    (3) The following classes: String, Vector

    Note:

  • A vector can contain all types and strings listed in 1 and 2.
  • The server receives a vector as an array of objects.

    (4) array. The array element can be all types and strings listed in 1 and 2 (except as noted above ).

    ■ Conclusion
    In the series composed of the four articles, I not only introduced the basic knowledge of soap, but also introduced an excellent IMPLEMENTATION OF THE SOAP 1.1 Standard: Apache
    Soap. In this article, I provide a framework based on dynamic proxy classes, which greatly simplifies the work of client program developers who use Apache SOAP.

    I deeply feel that soap has a bright future. There are at least two reasons for me to think that: first, soap is based on some open standards, such as XML. This makes
    Microsoft and anti-Microsoft enterprises all widely accept soap. This is undoubtedly a great news for developers. Second, soap is becoming another
    Many standard foundations, such as UDDI (Universal Description, discovery, and
    Integration ). Many people think that web services represent the next generation of Web application development, and soap and UDDI are key components of Web Services.

    ■ Reference resources

  • Download the complete code of this article: javaandsoap4_code.zip
  • W3C soap 1.1 specifications:
  • Http://www.w3.org/TR/SOAP/
  • For more information about dynamic proxy classes:
  • Http://java.sun.com/j2se/1.3/docs/guide/reflection/proxy.html
  • For more information about the IBM soap project:
  • Http://www.alphaworks.ibm.com/tech/soap4j
  • Download Apache SOAP:
  • Http://xml.apache.org/dist/soap/
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.