KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > wsif > base > WSIFServiceImpl


1 /*
2  * The Apache Software License, Version 1.1
3  *
4  *
5  * Copyright (c) 2002 The Apache Software Foundation. All rights
6  * reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  * notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  * notice, this list of conditions and the following disclaimer in
17  * the documentation and/or other materials provided with the
18  * distribution.
19  *
20  * 3. The end-user documentation included with the redistribution,
21  * if any, must include the following acknowledgment:
22  * "This product includes software developed by the
23  * Apache Software Foundation (http://www.apache.org/)."
24  * Alternately, this acknowledgment may appear in the software itself,
25  * if and wherever such third-party acknowledgments normally appear.
26  *
27  * 4. The names "WSIF" and "Apache Software Foundation" must
28  * not be used to endorse or promote products derived from this
29  * software without prior written permission. For written
30  * permission, please contact apache@apache.org.
31  *
32  * 5. Products derived from this software may not be called "Apache",
33  * nor may "Apache" appear in their name, without prior written
34  * permission of the Apache Software Foundation.
35  *
36  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
37  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
38  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
39  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
40  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
42  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
43  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
44  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
45  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
46  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47  * SUCH DAMAGE.
48  * ====================================================================
49  *
50  * This software consists of voluntary contributions made by many
51  * individuals on behalf of the Apache Software Foundation and was
52  * originally based on software copyright (c) 2001, 2002, International
53  * Business Machines, Inc., http://www.apache.org. For more
54  * information on the Apache Software Foundation, please see
55  * <http://www.apache.org/>.
56  */

57
58 package org.apache.wsif.base;
59
60 import java.util.ArrayList JavaDoc;
61 import java.util.HashMap JavaDoc;
62 import java.util.Hashtable JavaDoc;
63 import java.util.Iterator JavaDoc;
64 import java.util.List JavaDoc;
65 import java.util.Map JavaDoc;
66
67 import javax.wsdl.Binding;
68 import javax.wsdl.Definition;
69 import javax.wsdl.Input;
70 import javax.wsdl.Message;
71 import javax.wsdl.Operation;
72 import javax.wsdl.OperationType;
73 import javax.wsdl.Output;
74 import javax.wsdl.Port;
75 import javax.wsdl.PortType;
76 import javax.wsdl.Service;
77 import javax.wsdl.WSDLException;
78 import javax.wsdl.extensions.ExtensibilityElement;
79 import javax.wsdl.extensions.ExtensionRegistry;
80 import javax.wsdl.extensions.UnknownExtensibilityElement;
81 import javax.xml.namespace.QName JavaDoc;
82
83 import org.apache.wsif.WSIFConstants;
84 import org.apache.wsif.WSIFException;
85 import org.apache.wsif.WSIFMessage;
86 import org.apache.wsif.WSIFPort;
87 import org.apache.wsif.WSIFService;
88 import org.apache.wsif.compiler.schema.tools.Schema2Java;
89 import org.apache.wsif.compiler.util.TypeMapping;
90 import org.apache.wsif.compiler.util.Utils;
91 import org.apache.wsif.logging.MessageLogger;
92 import org.apache.wsif.logging.Trc;
93 import org.apache.wsif.providers.WSIFDynamicTypeMap;
94 import org.apache.wsif.spi.WSIFProvider;
95 import org.apache.wsif.util.WSIFPluggableProviders;
96 import org.apache.wsif.util.WSIFUtils;
97 import org.w3c.dom.Element JavaDoc;
98
99 import com.ibm.wsdl.util.xml.QNameUtils;
100
101
102 /**
103  * An entry point to dynamic WSDL invocations.
104  *
105  * @author Alekander Slominski
106  * @author Sanjiva Weerawarana
107  * @author Owen Burroughs <owenb@apache.org>
108  * @author Ant Elder <antelder@apache.org>
109  * @author Jeremy Hughes <hughesj@apache.org>
110  * @author Mark Whitlock <whitlock@apache.org>
111  */

112 public class WSIFServiceImpl implements WSIFService {
113     private static PrivateCompositeExtensionRegistry providersExtRegs =
114         new PrivateCompositeExtensionRegistry();
115     private Definition def = null;
116     private Service service;
117     private PortType portType;
118     private Port[] myPortsArr;
119     private Map JavaDoc myPortsMap;
120     private WSIFDynamicTypeMap typeMap = new WSIFDynamicTypeMap();
121     private boolean typeMapInitialised = false;
122     private String JavaDoc preferredPort = null;
123     private Map JavaDoc typeReg = null;
124     private Port chosenPort = null;
125     private WSIFMessage context;
126
127     /**
128      * Create a WSIF service instance from WSDL document URL.
129      * <br> If serviceName or serviceNS is null,
130      * then WSDL document must have exactly one service in it.
131      * <br> If portTypeName or portTypeNS is null,
132      * then WSDL document must have exactly one portType in it
133      * and all ports of the selected service must
134      * implement the same portType.
135      * <br>NOTE:
136      * The equivalent {@link org.apache.wsif.WSIFServiceFactory}.getService method
137      * should be used to create a WSIFService.
138      */

139     WSIFServiceImpl(
140         String JavaDoc wsdlLoc,
141         String JavaDoc serviceNS,
142         String JavaDoc serviceName,
143         String JavaDoc portTypeNS,
144         String JavaDoc portTypeName)
145         throws WSIFException {
146         Trc.entry(this, wsdlLoc, serviceNS, serviceName, portTypeNS, portTypeName);
147
148         // load WSDL defintion
149
Definition def = null;
150         try {
151             def = WSIFUtils.readWSDL(null, wsdlLoc);
152             checkWSDL(def);
153         } catch (WSDLException ex) {
154             Trc.exception(ex);
155             throw new WSIFException("could not load " + wsdlLoc, ex);
156         }
157
158         // select WSDL service if given name
159
Service service = WSIFUtils.selectService(def, serviceNS, serviceName);
160
161         // select WSDL portType if given name
162
PortType portType = WSIFUtils.selectPortType(def, portTypeNS, portTypeName);
163
164         init(def, service, portType);
165         if (Trc.ON)
166             Trc.exit(deep());
167     }
168
169     /**
170       * Create a WSIF service instance from WSDL document URL
171       * using a ClassLoader to find local resources.
172       * <br> If serviceName or serviceNS is null,
173       * then WSDL document must have exactly one service in it.
174       * <br> If portTypeName or portTypeNS is null,
175       * then WSDL document must have exactly one portType in it
176       * and all ports of the selected service must
177       * implement the same portType.
178       * <br>NOTE:
179       * The equivalent {@link org.apache.wsif.WSIFServiceFactory}.getService method
180       * should be used to create a WSIFService.
181       */

182     WSIFServiceImpl(
183         String JavaDoc wsdlLoc,
184         ClassLoader JavaDoc cl,
185         String JavaDoc serviceNS,
186         String JavaDoc serviceName,
187         String JavaDoc portTypeNS,
188         String JavaDoc portTypeName)
189         throws WSIFException {
190         Trc.entry(this, wsdlLoc, cl, serviceNS, serviceName, portTypeNS, portTypeName);
191
192         // load WSDL defintion
193
Definition def = null;
194         try {
195             def = WSIFUtils.readWSDL(null, wsdlLoc, cl);
196             checkWSDL(def);
197         } catch (WSDLException ex) {
198             Trc.exception(ex);
199             throw new WSIFException("could not load " + wsdlLoc, ex);
200         }
201
202         // select WSDL service if given name
203
Service service = WSIFUtils.selectService(def, serviceNS, serviceName);
204
205         // select WSDL portType if given name
206
PortType portType = WSIFUtils.selectPortType(def, portTypeNS, portTypeName);
207
208         init(def, service, portType);
209         if (Trc.ON)
210             Trc.exit(deep());
211     }
212
213     /**
214       * Create a WSIF service instance
215       * <br>NOTE:
216       * The equivalent {@link org.apache.wsif.WSIFServiceFactory}.getService method
217       * should be used to create a WSIFService.
218       */

219     WSIFServiceImpl(Definition def) throws WSIFException {
220         this(def, null);
221     }
222
223     /**
224       * Create a WSIF service instance
225       * <br>NOTE:
226       * The equivalent {@link org.apache.wsif.WSIFServiceFactory}.getService method
227       * should be used to create a WSIFService.
228       */

229     WSIFServiceImpl(Definition def, Service service) throws WSIFException {
230         this(def, service, null);
231     }
232
233     /**
234       * Create a WSIF service instance
235       * <br>NOTE:
236       * The equivalent {@link org.apache.wsif.WSIFServiceFactory}.getService method
237       * should be used to create a WSIFService.
238       */

239     WSIFServiceImpl(Definition def, Service service, PortType portType)
240         throws WSIFException {
241         Trc.entry(this, def, service, portType);
242
243         init(def, service, portType);
244         if (Trc.ON)
245             Trc.exit(deep());
246     }
247
248     /**
249       * Create a WSIF service instance
250       * <br>NOTE:
251       * The equivalent {@link org.apache.wsif.WSIFServiceFactory}.getService method
252       * should be used to create a WSIFService.
253       */

254     WSIFServiceImpl(Definition def, String JavaDoc serviceNS, String JavaDoc serviceName)
255         throws WSIFException {
256         Trc.entry(this, def, serviceNS, serviceName);
257
258         // select WSDL service if given by name or only one
259
Service service = WSIFUtils.selectService(def, serviceNS, serviceName);
260         init(def, service, null);
261         if (Trc.ON)
262             Trc.exit(deep());
263     }
264
265     /**
266       * Create a WSIF service instance
267       * <br>NOTE:
268       * The equivalent {@link org.apache.wsif.WSIFServiceFactory}.getService method
269       * should be used to create a WSIFService.
270       */

271     WSIFServiceImpl(
272         Definition def,
273         String JavaDoc serviceNS,
274         String JavaDoc serviceName,
275         String JavaDoc portTypeNS,
276         String JavaDoc portTypeName)
277         throws WSIFException {
278         Trc.entry(this, def, serviceNS, serviceName, portTypeNS, portTypeName);
279
280         checkWSDLForWSIF(def);
281
282         // select WSDL service if given by name or only one
283
Service service = WSIFUtils.selectService(def, serviceNS, serviceName);
284
285         // select WSDL portType if given by name or only one portType
286
PortType portType = WSIFUtils.selectPortType(def, portTypeNS, portTypeName);
287
288         init(def, service, portType);
289         if (Trc.ON)
290             Trc.exit(deep());
291     }
292
293     /**
294       * Create a WSIF service instance from another instance. This constructor
295       * is used by the caching mechanism in WSIFServiceFactoryImpl
296       */

297     WSIFServiceImpl(WSIFServiceImpl wsi)
298         throws WSIFException {
299         Trc.entry(this, wsi);
300         copyInitializedService(wsi);
301         if (Trc.ON)
302             Trc.exit(deep());
303     }
304
305     /**
306      * Copy the "read-only" parts of an initialized WSIFServiceImpl
307      */

308     private void copyInitializedService(WSIFServiceImpl svc) {
309         this.def = svc.def;
310         this.service = svc.service;
311         this.portType = svc.portType;
312         this.myPortsArr = new Port[svc.myPortsArr.length];
313         System.arraycopy(svc.myPortsArr, 0, this.myPortsArr, 0, svc.myPortsArr.length);
314         this.myPortsMap = (Map JavaDoc) ((Hashtable JavaDoc) svc.myPortsMap).clone();
315         this.typeMap = svc.typeMap.copy();
316     }
317
318     /**
319      * Set the preferred port
320      * @param portName The name of the port to use
321      */

322     public void setPreferredPort(String JavaDoc portName) throws WSIFException {
323         Trc.entry(this, portName);
324
325         if (portName == null) {
326             throw new WSIFException("Preferred port name cannot be null");
327         }
328         PortType pt = getPortTypeFromPortName(portName);
329         if (pt.getQName().equals(this.portType.getQName())) {
330             this.preferredPort = portName;
331         } else {
332             throw new WSIFException(
333                 "Preferred port "
334                     + portName
335                     + "is not available for the port type "
336                     + this.portType.getQName());
337         }
338         Trc.exit();
339     }
340
341     /**
342      * Create a PortType object from the name of a port
343      * @param portName The name of the port
344      * @return A PortType corresponding to the port type used by the
345      * specified port
346      */

347     private PortType getPortTypeFromPortName(String JavaDoc portName)
348         throws WSIFException {
349         if (portName == null) {
350             throw new WSIFException("Unable to find port type from a null port name");
351         }
352         Port port = (Port) service.getPort(portName);
353         if (port == null) {
354             throw new WSIFException(
355                 "Port '" + portName + "' cannot be found in the service");
356         }
357         Binding binding = port.getBinding();
358         if (binding == null) {
359             throw new WSIFException("No binding found for port '" + portName + "'");
360         }
361         PortType pt = binding.getPortType();
362         if (pt == null) {
363             throw new WSIFException(
364                 "No port type found for binding '" + binding.getQName() + "'");
365         }
366         checkPortTypeInformation(def, pt);
367         return pt;
368     }
369
370     /**
371      * Get the names of the available ports
372      * @return Iterator for list of available port names.
373      */

374     public Iterator JavaDoc getAvailablePortNames() throws WSIFException {
375         Trc.entry(this);
376         Iterator JavaDoc it = null;
377         try {
378             it = this.myPortsMap.keySet().iterator();
379         } catch (NullPointerException JavaDoc ne) {
380             Trc.exception(ne);
381             it = null;
382         }
383         Trc.exit();
384         return it;
385     }
386
387     /**
388      * Create dynamic port instance from WSDL model defnition and port.
389      */

390     private WSIFPort createDynamicWSIFPort(
391         Definition def,
392         Service service,
393         Port port)
394         throws WSIFException {
395         checkWSDLForWSIF(def);
396         List JavaDoc bindingExList = port.getBinding().getExtensibilityElements();
397         ExtensibilityElement bindingFirstEx =
398             (ExtensibilityElement) bindingExList.get(0);
399         String JavaDoc bindingNS = bindingFirstEx.getElementType().getNamespaceURI();
400         WSIFProvider provider = WSIFPluggableProviders.getProvider(bindingNS);
401         if (provider == null) {
402             throw new WSIFException(
403                 "could not find suitable provider for binding namespace '" + bindingNS + "'");
404         }
405         WSIFPort wsifPort =
406             provider.createDynamicWSIFPort(def, service, port, typeMap);
407         wsifPort.setContext(getContext());
408         return wsifPort;
409     }
410
411     public WSIFPort getPort() throws WSIFException {
412         Trc.entry(this);
413         WSIFPort wp = null;
414         if (preferredPort != null && myPortsMap.get(preferredPort) != null) {
415             wp = getPort(this.preferredPort);
416         } else {
417             if (preferredPort != null)
418                 MessageLogger.log("WSIF.0011I",preferredPort);
419             wp = getPort(null);
420         }
421         Trc.exit(wp);
422         return wp;
423     }
424
425     /**
426      * Return dynamic port instance selected by port name.
427      */

428     public WSIFPort getPort(String JavaDoc portName) throws WSIFException {
429         Trc.entry(this, portName);
430         Port port = null;
431
432         if (portName == null) {
433             // Get first available port
434
if (myPortsArr.length > 0) {
435                 port = myPortsArr[0];
436             }
437         } else {
438             port = (Port) myPortsMap.get(portName);
439         }
440         if (port == null) {
441             if (portName == null) {
442                 throw new WSIFException("Unable to find an available port");
443             } else {
444                 throw new WSIFException(
445                     "Port '"
446                         + portName
447                         + "' is not available and "
448                         + " no alternative can be found");
449             }
450         }
451
452         portName = port.getName();
453         WSIFPort portInstance = createDynamicWSIFPort(def, service, port);
454         if (portInstance == null) {
455             throw new WSIFException(
456                 "Provider was unable to create WSIFPort for port " + portName);
457         }
458         // Store the chosen port so that we can query which was is being used
459
chosenPort = port;
460
461         Trc.exit(portInstance);
462         return portInstance;
463     }
464
465     /**
466      * Add association between XML and Java type.
467      * @param xmlType The qualified xml name
468      * @param javaType The Java class
469      */

470     public void mapType(QName JavaDoc xmlType, Class JavaDoc javaType) throws WSIFException {
471         Trc.entry(this, xmlType, javaType);
472         typeMap.mapType(xmlType, javaType);
473         Trc.exit();
474     }
475
476     /**
477      * Add an association between XML and Java type.
478      * @param xmlType The qualified xml name
479      * @param javaType The Java class
480      * @param force flag to indicate if mapping should override an existing one
481      * for the same xmlType
482      */

483     private void mapType(QName JavaDoc xmlType, Class JavaDoc javaType, boolean force)
484         throws WSIFException {
485         Trc.entry(this, xmlType, javaType, new Boolean JavaDoc(force));
486         typeMap.mapType(xmlType, javaType, force);
487         Trc.exit();
488     }
489
490     /**
491      * Add an association between a namespace URI and and a Java package.
492      * @param namespace The namespace URI
493      * @param packageName The full package name
494      */

495     public void mapPackage(String JavaDoc namespace, String JavaDoc packageName)
496         throws WSIFException {
497         Trc.entry(namespace, packageName);
498         typeMap.mapPackage(namespace, packageName);
499         Trc.exit();
500     }
501
502     /**
503      * @deprecated this method is replaced by the getProvider
504      * method in the org.apache.util.WSIFPluggableProviders class
505      */

506     public static WSIFProvider getDynamicWSIFProvider(String JavaDoc namespaceURI) {
507         Trc.entry(null, namespaceURI);
508         WSIFProvider p =
509            WSIFPluggableProviders.getProvider( namespaceURI );
510         Trc.exit( p );
511         return p;
512     }
513
514     /**
515      * @deprecated this method is replaced by the overrideDefaultProvider
516      * method in the org.apache.util.WSIFPluggableProviders class
517      */

518     public static void setDynamicWSIFProvider(
519         String JavaDoc providerNamespaceURI,
520         WSIFProvider provider) {
521         Trc.entry(null, providerNamespaceURI, provider);
522
523         WSIFPluggableProviders.overrideDefaultProvider(
524            providerNamespaceURI, provider );
525
526         Trc.exit();
527     }
528
529     /**
530      * @deprecated this method is replaced by the setAutoLoadProviders
531      * method in the org.apache.util.WSIFPluggableProviders class
532      */

533     public static void setAutoLoadProviders(boolean b) {
534         Trc.entry(null, b);
535         WSIFPluggableProviders.setAutoLoadProviders( b );
536         Trc.exit();
537     }
538
539     /**
540      * Get the dynamic proxy that will implement the interface iface
541      * for the port portName.
542      */

543     public Object JavaDoc getStub(String JavaDoc portName, Class JavaDoc iface) throws WSIFException {
544         Trc.entry(this, portName, iface);
545
546         // Initialise the type mappings here (not in the constructor) so that
547
// other products which use non-standard WSDL in their complexTypes
548
// that WSIF wouldn't understand, can use the DynamicInvoker
549
// successfully. Using the DynamicInvoker means we would never come
550
// through this code and so never try to parse the complexTypes.
551
// Obviously if the user wants to use dynamic proxies then we have to
552
// parse the complex types.
553
if (!typeMapInitialised) {
554             initialiseTypeMappings();
555             typeMapInitialised = true;
556         }
557
558         // if the port is not available, force the expection now rather
559
// rather than go through the rest of this method
560
WSIFPort wsifPort = getPort(portName);
561
562         // If we've got to this line then the port must be available
563
PortType pt = getPortTypeFromPortName(portName);
564
565         // If the user has already created a proxy for this interface before
566
// but is now asking for a proxy for the same interface but a different
567
// portName, we should cache the proxy here and just call
568
// clientProxy.setPort() instead.
569
WSIFClientProxy clientProxy =
570             WSIFClientProxy.newInstance(
571                 iface,
572                 def,
573                 service.getQName().getNamespaceURI(),
574                 service.getQName().getLocalPart(),
575                 portType.getQName().getNamespaceURI(),
576                 portType.getQName().getLocalPart(),
577                 typeMap);
578
579         clientProxy.setPort(wsifPort);
580         Object JavaDoc proxy = clientProxy.getProxy();
581
582         // Tracing the proxy causes a hang!
583
Trc.exit();
584         return proxy;
585     }
586
587     /**
588      * Get the dynamic proxy that will implement the interface iface
589      */

590     public Object JavaDoc getStub(Class JavaDoc iface) throws WSIFException {
591         Trc.entry(this, iface);
592
593         // Initialise the type mappings here (not in the constructor) so that
594
// other products which use non-standard WSDL in their complexTypes
595
// that WSIF wouldn't understand, can use the DynamicInvoker
596
// successfully. Using the DynamicInvoker means we would never come
597
// through this code and so never try to parse the complexTypes.
598
// Obviously if the user wants to use dynamic proxies then we have to
599
// parse the complex types.
600
if (!typeMapInitialised) {
601             initialiseTypeMappings();
602             typeMapInitialised = true;
603         }
604
605         // if the port is not available, force the expection now rather
606
// rather than go through the rest of this method
607
WSIFPort wsifPort = getPort();
608
609         // Chosen port has been stored so use it to find portType
610
String JavaDoc portName = chosenPort.getName();
611         PortType pt = getPortTypeFromPortName(portName);
612
613         // If the user has already created a proxy for this interface before
614
// but is now asking for a proxy for the same interface but a different
615
// portName, we should cache the proxy here and just call
616
// clientProxy.setPort() instead.
617
WSIFClientProxy clientProxy =
618             WSIFClientProxy.newInstance(
619                 iface,
620                 def,
621                 service.getQName().getNamespaceURI(),
622                 service.getQName().getLocalPart(),
623                 pt.getQName().getNamespaceURI(),
624                 pt.getQName().getLocalPart(),
625                 typeMap);
626
627         clientProxy.setPort(wsifPort);
628         Object JavaDoc proxy = clientProxy.getProxy();
629
630         // Tracing the proxy causes a hang!
631
Trc.exit();
632         return proxy;
633     }
634
635     /**
636      * Add new WSDL model extension registry that is shared by all
637      * dynamic WSIF providers.
638      */

639     public static void addExtensionRegistry(ExtensionRegistry reg) {
640         Trc.entry(null, reg);
641         providersExtRegs.addExtensionRegistry(reg);
642         Trc.exit();
643     }
644
645     /**
646      * Return extension registry that contains ALL declared extensions.
647      * This is special registry that does not allow to register serializers
648      * but only to add new extension registreis through
649      * addExtensionRegistry method.
650      *
651      * @see #addExtensionRegistry
652      */

653     public static ExtensionRegistry getCompositeExtensionRegistry() {
654         Trc.entry(null);
655         Trc.exit(providersExtRegs);
656         return providersExtRegs;
657     }
658
659     private void init(Definition def, Service service, PortType portType)
660         throws WSIFException {
661         if (def == null)
662             throw new IllegalArgumentException JavaDoc("WSDL definition can not be null");
663         checkWSDLForWSIF(def);
664
665         if (service == null) {
666             Map JavaDoc services = WSIFUtils.getAllItems(def, "Service");
667
668             service = (Service) WSIFUtils.getNamedItem(services, null, "Service");
669         }
670
671         if (portType == null) {
672             // if all ports have the same portType --> use it
673
Map JavaDoc ports = service.getPorts();
674             if (ports.size() == 0) {
675                 throw new WSIFException(
676                     "WSDL must contain at least one port in " + service.getQName());
677             }
678
679             for (Iterator JavaDoc i = ports.values().iterator(); i.hasNext();) {
680                 Port port = (Port) i.next();
681                 if (portType == null) {
682                     portType = port.getBinding().getPortType();
683                 } else {
684                     PortType pt = port.getBinding().getPortType();
685                     if (!pt.getQName().equals(portType.getQName())) {
686                         throw new WSIFException(
687                             "when no port type was specified all ports "
688                                 + "must have the same port type in WSDL service "
689                                 + service.getQName());
690                     }
691                 }
692             }
693             if (portType == null) {
694                 throw new IllegalArgumentException JavaDoc(
695                     "WSDL more than one portType in service " + service);
696
697             }
698         }
699         this.def = def;
700         this.service = service;
701         this.portType = portType;
702
703         // checkPortTypeIsRPC(Definition def, PortType portType) has been replaced by
704
// checkPortTypeInformation(Definition def, PortType portType) since "Input Only"
705
// operations are supported.
706
checkPortTypeInformation(def, portType);
707
708         // get all ports from service that has given portType
709

710         Map JavaDoc ports = service.getPorts();
711         // check that service has at least one port ...
712
if (ports.size() == 0) {
713             throw new WSIFException(
714                 "WSDL must contain at least one port in " + service.getQName());
715         }
716
717         myPortsMap = new Hashtable JavaDoc();
718         for (Iterator JavaDoc i = ports.values().iterator(); i.hasNext();) {
719             Port port = (Port) i.next();
720
721             Binding binding = port.getBinding();
722             if (binding == null)
723                 continue; // Ignore this error for the moment
724

725             try {
726                 // Ignore port if provider is not available for supporting it
727
List JavaDoc bindingExList = port.getBinding().getExtensibilityElements();
728                 ExtensibilityElement bindingFirstEx =
729                     (ExtensibilityElement) bindingExList.get(0);
730                 String JavaDoc bindingNS = bindingFirstEx.getElementType().getNamespaceURI();
731                 String JavaDoc addressNS = bindingNS;
732                 try {
733                     List JavaDoc addressExList = port.getExtensibilityElements();
734                     ExtensibilityElement addressFirstEx =
735                         (ExtensibilityElement) addressExList.get(0);
736                     addressNS = addressFirstEx.getElementType().getNamespaceURI();
737                 } catch (NullPointerException JavaDoc npe) {
738                     Trc.ignoredException(npe);
739                     // ignore
740
} catch (ArrayIndexOutOfBoundsException JavaDoc aie) {
741                     Trc.ignoredException(aie);
742                     // Extensibility element 0 does not exist
743
// Allow address namespace to be the same as binding
744
}
745                 // Check for a provider that supports the
746
if (WSIFPluggableProviders.isProviderAvailable(bindingNS, addressNS) ) {
747                    // check if port has the same port type
748
if (binding.getPortType().getQName().equals(portType.getQName())) {
749                       String JavaDoc portName = port.getName();
750                       myPortsMap.put(portName, port);
751                    }
752                 }
753             } catch (NullPointerException JavaDoc e) {
754                 Trc.ignoredException(e);
755                 // Binding or extensibility element or QName was null
756
// any of which means something's not right with
757
// the port so don't include it.
758
} catch (ArrayIndexOutOfBoundsException JavaDoc aie) {
759                 Trc.ignoredException(aie);
760                 // Extensibility element 0 does not exist
761
}
762         }
763         int size = myPortsMap.size();
764         myPortsArr = new Port[size];
765         int count = 0;
766         for (Iterator JavaDoc i = myPortsMap.values().iterator(); i.hasNext();) {
767             // NOTE: there is no order in ports (it is hash function dependent...)
768
Port port = (Port) i.next();
769             myPortsArr[count++] = port;
770         }
771
772         // Provide the WSIDDynamicTypeMap with a list of all of the custom
773
// types in the wsdl
774
typeMap.setAllTypes(getAllCustomTypes());
775     }
776
777     /**
778      * Get a list of all the custom complexTypes and simpleTypes in the wsdl
779      */

780     private ArrayList JavaDoc getAllCustomTypes() {
781         ArrayList JavaDoc types = new ArrayList JavaDoc();
782         Iterator JavaDoc typeMappingIterator = getDefaultTypeMappings();
783         if (typeMappingIterator != null) {
784             while (typeMappingIterator.hasNext()) {
785                 TypeMapping tm = (TypeMapping) typeMappingIterator.next();
786                 if (tm != null) {
787                     String JavaDoc namespaceURI = tm.elementType.getNamespaceURI();
788                     if (!namespaceURI.equals(WSIFConstants.NS_URI_1999_SCHEMA_XSD)
789                         && !namespaceURI.equals(WSIFConstants.NS_URI_2000_SCHEMA_XSD)
790                         && !namespaceURI.equals(WSIFConstants.NS_URI_2001_SCHEMA_XSD)) {
791                         QName JavaDoc element = tm.elementType;
792                         if (element != null) {
793                             types.add(element);
794                         }
795                     }
796                 }
797             }
798         }
799         return types;
800     }
801
802     /**
803      * Get a list of all the default mappings for complexTypes and simpleTypes
804      * in the wsdl
805      */

806     private Iterator JavaDoc getDefaultTypeMappings() {
807         if (typeReg != null) {
808             return typeReg.values().iterator();
809         }
810         typeReg = new HashMap JavaDoc();
811         List JavaDoc typesElList = Utils.getAllTypesElements(def);
812         if (typesElList.size() > 0) {
813             String JavaDoc schemaURI1999 = WSIFConstants.NS_URI_1999_SCHEMA_XSD;
814             Schema2Java s2j1999 = new Schema2Java(schemaURI1999);
815             QName JavaDoc qElemSchema1999 = new QName JavaDoc(schemaURI1999, "schema");
816             String JavaDoc schemaURI2000 = WSIFConstants.NS_URI_2000_SCHEMA_XSD;
817             Schema2Java s2j2000 = new Schema2Java(schemaURI2000);
818             QName JavaDoc qElemSchema2000 = new QName JavaDoc(schemaURI2000, "schema");
819             String JavaDoc schemaURI2001 = WSIFConstants.NS_URI_2001_SCHEMA_XSD;
820             Schema2Java s2j2001 = new Schema2Java(schemaURI2001);
821             QName JavaDoc qElemSchema2001 = new QName JavaDoc(schemaURI2001, "schema");
822
823             Iterator JavaDoc typesElIterator = typesElList.iterator();
824             while (typesElIterator.hasNext()) {
825                 UnknownExtensibilityElement unknExEl =
826                     (UnknownExtensibilityElement) typesElIterator.next();
827                 Element schemaEl = unknExEl.getElement();
828                 try {
829                     if (QNameUtils.matches(qElemSchema1999, schemaEl)
830                         || QNameUtils.matches(qElemSchema2000, schemaEl)
831                         || QNameUtils.matches(qElemSchema2001, schemaEl)) {
832                         //Hashtable typeReg = new Hashtable();
833
if (QNameUtils.matches(qElemSchema1999, schemaEl))
834                             s2j1999.createJavaMapping(schemaEl, typeReg);
835                         else if (QNameUtils.matches(qElemSchema2000, schemaEl))
836                             s2j2000.createJavaMapping(schemaEl, typeReg);
837                         else
838                             s2j2001.createJavaMapping(schemaEl, typeReg);
839                     }
840                 } catch (Exception JavaDoc e) {
841                     Trc.ignoredException(e);
842                     //ignored
843
}
844             }
845         }
846         return typeReg.values().iterator();
847     }
848
849     /**
850      * Initialize default mappings between custom complex types and simple types and
851      * Java classes.
852      */

853     private void initialiseTypeMappings() throws WSIFException {
854         Iterator JavaDoc typeMappingIterator = getDefaultTypeMappings();
855         if (typeMappingIterator != null) {
856             while (typeMappingIterator.hasNext()) {
857                 TypeMapping tm = (TypeMapping) typeMappingIterator.next();
858
859                 if (tm.elementType != null && tm.elementType.getNamespaceURI() != null) {
860                     String JavaDoc namespaceURI = tm.elementType.getNamespaceURI();
861                     if (namespaceURI != null
862                         && !namespaceURI.equals(WSIFConstants.NS_URI_1999_SCHEMA_XSD)
863                         && !namespaceURI.equals(WSIFConstants.NS_URI_2000_SCHEMA_XSD)
864                         && !namespaceURI.equals(WSIFConstants.NS_URI_2001_SCHEMA_XSD)
865                         && !namespaceURI.equals(WSIFConstants.NS_URI_SOAP_ENC)
866                         && tm.javaType != null) {
867                         String JavaDoc packageName = Utils.getPackageName(tm.javaType);
868                         if (packageName != null && !packageName.equals("")) {
869                             packageName += ".";
870                         }
871                         String JavaDoc className = packageName + Utils.getClassName(tm.javaType);
872                         Class JavaDoc clazz = null;
873
874                         try {
875                             clazz =
876                                 Class.forName(className, true, Thread.currentThread().getContextClassLoader());
877                         } catch (ClassNotFoundException JavaDoc e) {
878                             // Ignore error - mapping will not be added
879
Trc.ignoredException(e);
880                         }
881                         // Create a new mapping but don't override one that already exists for this element type
882
if (clazz != null) {
883                             mapType(tm.elementType, clazz, false);
884                         }
885                     }
886                 }
887             } // end while
888
}
889     }
890
891     /**
892      * Check PortType information is consistent. This method can be updated when
893      * new operation types are supported.
894      */

895     private void checkPortTypeInformation(Definition def, PortType portType)
896         throws WSIFException {
897         List JavaDoc operationList = portType.getOperations();
898
899         // process each operation to create dynamic operation instance
900
for (Iterator JavaDoc i = operationList.iterator(); i.hasNext();) {
901             Operation op = (Operation) i.next();
902             String JavaDoc name = op.getName();
903             if (op.isUndefined()) {
904                 throw new WSIFException("operation " + name + " is undefined!");
905             }
906             OperationType opType = op.getStyle();
907             if (opType == null) {
908                 throw new WSIFException("operation " + name + " has no type!");
909             }
910             if (opType.equals(OperationType.REQUEST_RESPONSE)) {
911                 Input input = op.getInput();
912                 Output output = op.getOutput();
913                 if (input == null) {
914                     throw new WSIFException("missing input message for operation " + name);
915                 }
916                 if (output == null) {
917                     throw new WSIFException("missing output message for operation " + name);
918                 }
919             } else if (opType.equals(OperationType.ONE_WAY)) {
920                 Input input = op.getInput();
921                 if (input == null) {
922                     throw new WSIFException("missing input message for operation " + name);
923                 }
924             } else {
925                 // Log message
926
MessageLogger.log(
927                     "WSIF.0004E",
928                     opType,
929                     portType.getQName().getLocalPart());
930
931                 // End message
932
throw new WSIFException(
933                     "operation type "
934                         + opType
935                         + " is not supported in port instance for "
936                         + portType.getQName());
937             }
938         }
939     }
940
941     private void checkWSDLForWSIF(Definition def) throws WSIFException {
942         try {
943             checkWSDL(def);
944         } catch (WSDLException ex) {
945             Trc.exception(ex);
946             throw new WSIFException("invalid WSDL defintion " + def.getQName(), ex);
947         }
948     }
949
950     /**
951      * Check WSDL defintion to make sure it does not contain undefined
952      * elements (typical case is referncing not defined portType).
953      * <p><b>NOTE:</b> check is done only for curent document and not
954      * recursively for imported ones (they may be invalid but this
955      * port factory may not need them...).
956      */

957     private void checkWSDL(Definition def) throws WSDLException {
958         for (Iterator JavaDoc i = def.getMessages().values().iterator(); i.hasNext();) {
959             Message v = (Message) i.next();
960             if (v.isUndefined()) {
961                 throw new WSDLException(
962                     WSDLException.INVALID_WSDL,
963                     "referencing undefined message " + v);
964             }
965         }
966         for (Iterator JavaDoc i = def.getPortTypes().values().iterator(); i.hasNext();) {
967             PortType v = (PortType) i.next();
968             if (v.isUndefined()) {
969                 throw new WSDLException(
970                     WSDLException.INVALID_WSDL,
971                     "referencing undefined portType " + v);
972             }
973         }
974         for (Iterator JavaDoc i = def.getBindings().values().iterator(); i.hasNext();) {
975             Binding v = (Binding) i.next();
976             if (v.isUndefined()) {
977                 throw new WSDLException(
978                     WSDLException.INVALID_WSDL,
979                     "referencing undefined binding " + v);
980             }
981         }
982     }
983
984     /**
985     * Get the Definition object representing the wsdl document
986     * @return The Definition object
987     */

988     public Definition getDefinition() {
989         Trc.entry(this);
990         Trc.exit(def);
991         return def;
992     }
993
994     /**
995      * Gets the context information for this WSIFService.
996      * @return context
997      */

998     public WSIFMessage getContext() throws WSIFException {
999         Trc.entry(this);
1000        WSIFMessage contextCopy;
1001        if (this.context == null) {
1002            contextCopy = new WSIFDefaultMessage();
1003        } else {
1004            try {
1005                contextCopy = (WSIFMessage) this.context.clone();
1006            } catch (CloneNotSupportedException JavaDoc e) {
1007                throw new WSIFException(
1008                    "CloneNotSupportedException cloning context", e);
1009            }
1010        }
1011        Trc.exit(contextCopy);
1012        return contextCopy;
1013    }
1014
1015    /**
1016     * Sets the context information for this WSIFService.
1017     * @param WSIFMessage the new context information
1018     */

1019    public void setContext(WSIFMessage context) {
1020        Trc.entry(this, context);
1021        if (context == null) {
1022            throw new IllegalArgumentException JavaDoc("context must not be null");
1023        }
1024        this.context = context;
1025        Trc.exit();
1026    }
1027
1028    public String JavaDoc deep() {
1029        String JavaDoc buff = "";
1030        try {
1031            buff = new String JavaDoc(this.toString());
1032            buff += "\nprovidersExtRegs:"
1033                + (providersExtRegs == null ? "null" : providersExtRegs.toString());
1034            buff += "\ndef:" + Trc.brief(def);
1035            buff += "\nservice:" + Trc.brief(service);
1036            buff += "\nportType:" + Trc.brief(portType);
1037            buff += "\nmyPortsArr:" + (myPortsArr == null ? "null" : myPortsArr.toString());
1038            buff += "\nmyPortsMap:" + Trc.brief(myPortsMap);
1039            buff += "\ntypeMap:" + (typeMap == null ? "null" : typeMap.toString());
1040            buff += "\ntypeMapInitialised:" + typeMapInitialised;
1041            buff += "\npreferredPort:" + (preferredPort == null ? "null" : preferredPort);
1042            buff += "\nchosenPort:" + Trc.brief(chosenPort);
1043            buff += "\ncontext:" + context;
1044        } catch (Exception JavaDoc e) {
1045            Trc.exceptionInTrace(e);
1046        }
1047        return buff;
1048    }
1049}
1050
1051
Popular Tags