KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > wsif > util > WSIFUtils


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.util;
59
60 import java.io.IOException JavaDoc;
61 import java.io.Reader JavaDoc;
62 import java.io.StringReader JavaDoc;
63 import java.io.Writer JavaDoc;
64 import java.lang.reflect.Method JavaDoc;
65 import java.net.MalformedURLException JavaDoc;
66 import java.net.URL JavaDoc;
67 import java.security.AccessController JavaDoc;
68 import java.security.PrivilegedAction JavaDoc;
69 import java.util.ArrayList JavaDoc;
70 import java.util.HashMap JavaDoc;
71 import java.util.Iterator JavaDoc;
72 import java.util.List JavaDoc;
73 import java.util.Map JavaDoc;
74 import java.util.Set JavaDoc;
75 import java.util.StringTokenizer JavaDoc;
76
77 import javax.wsdl.Binding;
78 import javax.wsdl.BindingOperation;
79 import javax.wsdl.Definition;
80 import javax.wsdl.Import;
81 import javax.wsdl.Message;
82 import javax.wsdl.Operation;
83 import javax.wsdl.Part;
84 import javax.wsdl.PortType;
85 import javax.wsdl.Service;
86 import javax.wsdl.WSDLException;
87 import javax.wsdl.extensions.ExtensibilityElement;
88 import javax.wsdl.extensions.ExtensionRegistry;
89 import javax.wsdl.factory.WSDLFactory;
90 import javax.wsdl.xml.WSDLReader;
91 import javax.wsdl.xml.WSDLWriter;
92 import javax.xml.namespace.QName JavaDoc;
93
94 import org.apache.wsif.WSIFConstants;
95 import org.apache.wsif.WSIFException;
96 import org.apache.wsif.WSIFService;
97 import org.apache.wsif.base.WSIFServiceImpl;
98 import org.apache.wsif.compiler.schema.tools.Schema2Java;
99 import org.apache.wsif.format.WSIFFormatHandler;
100 import org.apache.wsif.logging.MessageLogger;
101 import org.apache.wsif.logging.Trc;
102 import org.apache.wsif.schema.ComplexType;
103 import org.apache.wsif.schema.ElementType;
104 import org.apache.wsif.schema.Parser;
105 import org.apache.wsif.schema.SequenceElement;
106 import org.apache.wsif.wsdl.WSIFWSDLLocatorImpl;
107 import org.apache.wsif.wsdl.extensions.format.TypeMapping;
108 import org.w3c.dom.Document JavaDoc;
109 import org.w3c.dom.Element JavaDoc;
110 import org.xml.sax.InputSource JavaDoc;
111
112 import com.ibm.wsdl.Constants;
113 import com.ibm.wsdl.PartImpl;
114
115 /**
116  * This class provides utilities for WSIF runtime and generated stubs.
117  *
118  * @author Alekander Slominski
119  * @author Matthew J. Duftler
120  * @author Sanjiva Weerawarana
121  * @author Owen Burroughs <owenb@apache.org>
122  * @author Ant Elder <antelder@apache.org>
123  * @author Jeremy Hughes <hughesj@apache.org>
124  * @author Mark Whitlock <whitlock@apache.org>
125  * @author Piotr Przybylski
126  */

127 public class WSIFUtils {
128     private static Class JavaDoc initContextClass;
129     private static final String JavaDoc SLASH = "/";
130     private static final String JavaDoc DOT = ".";
131     private static final String JavaDoc FORMAT_HANDLER = "FormatHandler";
132     private static final String JavaDoc ELEMENT_FORMAT_HANDLER = "ElementFormatHandler";
133     private static final String JavaDoc PHYSICALREP = "physicalrep/";
134     private static final String JavaDoc FORMATBINDING = "formatbinding/";
135     private static final String JavaDoc XMLSEPARATORS =
136         "\u002D\u002E\u003A\u00B7\u0387\u06DD\u06DE\u30FB";
137     private static final String JavaDoc XMLSEPARATORS_NODOT =
138         "\u002D\u003A\u00B7\u0387\u06DD\u06DE";
139     private static final String JavaDoc UNDERSCORE = "_";
140     private static final String JavaDoc WWW = "www";
141     private static final String JavaDoc lookupPrefix = "java:comp/env/";
142     private static final String JavaDoc emptyString = "";
143     
144     private static Boolean JavaDoc providersInitialized = new Boolean JavaDoc(false);
145     private static Boolean JavaDoc simpleTypesMapCreated = new Boolean JavaDoc(false);
146     private static HashMap JavaDoc simpleTypesMap = new HashMap JavaDoc();
147     private static HashMap JavaDoc keywordMap = null;
148     
149     /**
150      * This checks whether JNDI classes are available at runtime.
151      * If the return value is true, then generated stubs should
152      * invoke lookupFactoryFromJNDI to get the WSIFService.
153      * If not, then there's no need to do so.
154      */

155     public static boolean isJNDIAvailable() {
156         Trc.entry(null);
157         initContextClass =
158             (Class JavaDoc) AccessController.doPrivileged(new PrivilegedAction JavaDoc() {
159             public Object JavaDoc run() {
160                 try {
161                     return Class.forName(
162                         "javax.naming.InitialContext",
163                         true,
164                         Thread.currentThread().getContextClassLoader());
165                 } catch (Throwable JavaDoc ignored) {
166                     Trc.ignoredException(ignored);
167                 }
168                 return null;
169             }
170         });
171
172         boolean b = true;
173         if (initContextClass == null)
174             b = false;
175         Trc.exit(b);
176         return b;
177     }
178
179     /**
180      * Given the service and portType identification, return a factory
181      * that can produce WSIFPorts for that service/portType combination.
182      */

183     public static WSIFService lookupFactoryFromJNDI(
184         String JavaDoc serviceNS,
185         String JavaDoc serviceName,
186         String JavaDoc portTypeNS,
187         String JavaDoc portTypeName)
188         throws WSIFException {
189         Trc.entry(null, serviceNS, serviceName, portTypeNS, portTypeName);
190         if (serviceNS == null)
191             throw new IllegalArgumentException JavaDoc("service namespace can not be null");
192         if (serviceName == null)
193             throw new IllegalArgumentException JavaDoc("service name can not be null");
194         if (portTypeNS == null)
195             throw new IllegalArgumentException JavaDoc("port type namespace can not be null");
196         if (portTypeName == null)
197             throw new IllegalArgumentException JavaDoc("port type name can not be null");
198
199         WSIFService ws = null;
200         try {
201             if (initContextClass == null) {
202                 initContextClass =
203                     Class.forName(
204                         "javax.naming.InitialContext",
205                         true,
206                         WSIFUtils.class.getClassLoader());
207             }
208             Object JavaDoc ic = initContextClass.newInstance();
209             Class JavaDoc[] lookupSig = new Class JavaDoc[] { String JavaDoc.class };
210             Object JavaDoc[] lookupArgs =
211                 new String JavaDoc[] {
212                     serviceNS
213                         + "::"
214                         + serviceName
215                         + "::"
216                         + portTypeNS
217                         + "::"
218                         + portTypeName };
219             Method JavaDoc m = initContextClass.getMethod("lookup", lookupSig);
220             ws = (WSIFService) m.invoke(ic, lookupArgs);
221         } catch (Exception JavaDoc e) {
222             Trc.exception(e);
223             throw new WSIFException(
224                 "Exception while looking up JNDI factory: " + e.getMessage(),
225                 e);
226         }
227         Trc.exit(ws);
228         return ws;
229     }
230
231     public static Service selectService(
232         Definition def,
233         String JavaDoc serviceNS,
234         String JavaDoc serviceName)
235         throws WSIFException {
236         Trc.entry(null, def, serviceNS, serviceName);
237         Map JavaDoc services = getAllItems(def, "Service");
238         QName JavaDoc serviceQName =
239             ((serviceNS != null && serviceName != null)
240                 ? new QName JavaDoc(serviceNS, serviceName)
241                 : null);
242         Service service =
243             (Service) getNamedItem(services, serviceQName, "Service");
244
245         Trc.exit(service);
246         return service;
247     }
248
249     public static PortType selectPortType(
250         Definition def,
251         String JavaDoc portTypeNS,
252         String JavaDoc portTypeName)
253         throws WSIFException {
254         Trc.entry(null, def, portTypeNS, portTypeName);
255         Map JavaDoc portTypes = getAllItems(def, "PortType");
256         QName JavaDoc portTypeQName =
257             ((portTypeNS != null && portTypeName != null)
258                 ? new QName JavaDoc(portTypeNS, portTypeName)
259                 : null);
260         PortType portType =
261             (PortType) getNamedItem(portTypes, portTypeQName, "PortType");
262
263         Trc.exit(portType);
264         return portType;
265     }
266
267     public static void addDefinedItems(
268         Map JavaDoc fromItems,
269         String JavaDoc itemType,
270         Map JavaDoc toItems) {
271         Trc.entry(null, fromItems, itemType, toItems);
272
273         if (fromItems != null) {
274             Iterator JavaDoc entryIterator = fromItems.entrySet().iterator();
275
276             if (itemType.equals("Message")) {
277                 while (entryIterator.hasNext()) {
278                     Map.Entry JavaDoc entry = (Map.Entry JavaDoc) entryIterator.next();
279                     Message message = (Message) entry.getValue();
280
281                     if (!message.isUndefined()) {
282                         toItems.put(entry.getKey(), message);
283                     }
284                 }
285             } else if (itemType.equals("Operation")) {
286                 while (entryIterator.hasNext()) {
287                     Map.Entry JavaDoc entry = (Map.Entry JavaDoc) entryIterator.next();
288                     Operation operation = (Operation) entry.getValue();
289
290                     if (!operation.isUndefined()) {
291                         toItems.put(entry.getKey(), operation);
292                     }
293                 }
294             } else if (itemType.equals("PortType")) {
295                 while (entryIterator.hasNext()) {
296                     Map.Entry JavaDoc entry = (Map.Entry JavaDoc) entryIterator.next();
297                     PortType portType = (PortType) entry.getValue();
298
299                     if (!portType.isUndefined()) {
300                         toItems.put(entry.getKey(), portType);
301                     }
302                 }
303             } else if (itemType.equals("Binding")) {
304                 while (entryIterator.hasNext()) {
305                     Map.Entry JavaDoc entry = (Map.Entry JavaDoc) entryIterator.next();
306                     Binding binding = (Binding) entry.getValue();
307
308                     if (!binding.isUndefined()) {
309                         toItems.put(entry.getKey(), binding);
310                     }
311                 }
312             } else if (itemType.equals("Service")) {
313                 while (entryIterator.hasNext()) {
314                     Map.Entry JavaDoc entry = (Map.Entry JavaDoc) entryIterator.next();
315                     Service service = (Service) entry.getValue();
316
317                     toItems.put(entry.getKey(), service);
318                 }
319             }
320         }
321         Trc.exit();
322     }
323
324     private static void getAllItems(
325         Definition def,
326         String JavaDoc itemType,
327         Map JavaDoc toItems) {
328         Trc.entry(null, def, itemType, toItems);
329         Map JavaDoc items = null;
330
331         if (itemType.equals("PortType")) {
332             items = def.getPortTypes();
333         } else if (itemType.equals("Service")) {
334             items = def.getServices();
335         } else {
336             throw new IllegalArgumentException JavaDoc(
337                 "Don't know how to find all " + itemType + "s.");
338         }
339
340         addDefinedItems(items, itemType, toItems);
341
342         Map JavaDoc imports = def.getImports();
343
344         if (imports != null) {
345             Iterator JavaDoc valueIterator = imports.values().iterator();
346
347             while (valueIterator.hasNext()) {
348                 List JavaDoc importList = (List JavaDoc) valueIterator.next();
349
350                 if (importList != null) {
351                     Iterator JavaDoc importIterator = importList.iterator();
352
353                     while (importIterator.hasNext()) {
354                         Import tempImport = (Import) importIterator.next();
355
356                         if (tempImport != null) {
357                             Definition importedDef = tempImport.getDefinition();
358
359                             if (importedDef != null) {
360                                 getAllItems(importedDef, itemType, toItems);
361                             }
362                         }
363                     }
364                 }
365             }
366         }
367         Trc.exit();
368     }
369
370     public static Map JavaDoc getAllItems(Definition def, String JavaDoc itemType) {
371         Trc.entry(null, def, itemType);
372         Map JavaDoc ret = new HashMap JavaDoc();
373
374         getAllItems(def, itemType, ret);
375
376         Trc.exit(ret);
377         return ret;
378     }
379
380     public static Object JavaDoc getNamedItem(Map JavaDoc items, QName JavaDoc qname, String JavaDoc itemType)
381         throws WSIFException {
382         Trc.entry(null, items, qname, itemType);
383         if (qname != null) {
384             Object JavaDoc item = items.get(qname);
385
386             if (item != null) {
387                 Trc.exit(item);
388                 return item;
389             } else {
390                 throw new WSIFException(
391                     itemType
392                         + " '"
393                         + qname
394                         + "' not found. Choices are: "
395                         + getCommaListFromQNameMap(items));
396             }
397         } else {
398             int size = items.size();
399
400             if (size == 1) {
401                 Iterator JavaDoc valueIterator = items.values().iterator();
402
403                 Object JavaDoc o = valueIterator.next();
404                 Trc.exit(o);
405                 return o;
406             } else if (size == 0) {
407                 throw new WSIFException(
408                     "WSDL document contains no " + itemType + "s.");
409             } else {
410                 throw new WSIFException(
411                     "Please specify a "
412                         + itemType
413                         + ". Choices are: "
414                         + getCommaListFromQNameMap(items));
415             }
416         }
417     }
418
419     private static String JavaDoc getCommaListFromQNameMap(Map JavaDoc qnameMap) {
420         StringBuffer JavaDoc strBuf = new StringBuffer JavaDoc("{");
421         Set JavaDoc keySet = qnameMap.keySet();
422         Iterator JavaDoc keyIterator = keySet.iterator();
423         int index = 0;
424
425         while (keyIterator.hasNext()) {
426             QName JavaDoc key = (QName JavaDoc) keyIterator.next();
427
428             strBuf.append((index > 0 ? ", " : "") + key);
429             index++;
430         }
431
432         strBuf.append("}");
433
434         return strBuf.toString();
435     }
436
437     /**
438      * Read WSDL - it is different from standard readWSDL method as it is
439      * using extensibility elements that were registered for dynamic port
440      * factory.
441      */

442     public static Definition readWSDL(String JavaDoc contextURL, String JavaDoc wsdlLoc)
443         throws WSDLException {
444         Trc.entry(null, contextURL, wsdlLoc);
445
446         initializeProviders();
447
448         WSDLFactory factory = WSDLFactory.newInstance(
449             WSIFConstants.WSIF_WSDLFACTORY);
450         WSDLReader wsdlReader = factory.newWSDLReader();
451         wsdlReader.setFeature(Constants.FEATURE_VERBOSE, false);
452         try {
453             Definition def = wsdlReader.readWSDL(contextURL, wsdlLoc);
454             Trc.exitExpandWsdl(def);
455             return def;
456         } catch (WSDLException e) {
457             Trc.exception(e);
458             MessageLogger.log("WSIF.0002E", wsdlLoc);
459             throw e;
460         }
461     }
462
463     /**
464      * Read WSDL - it is different from standard readWSDL method as it is
465      * using extensibility elements that were registered for dynamic port
466      * factory. It also uses the accompanying class loader to load imported WSDL
467      * resources.
468      */

469     public static Definition readWSDL(
470         URL JavaDoc documentBase,
471         Reader JavaDoc reader,
472         ClassLoader JavaDoc cl)
473         throws WSDLException {
474         String JavaDoc base = (documentBase == null) ? null : documentBase.toString();
475         return readWSDL(base, reader, cl);
476     }
477
478     /**
479      * Read WSDL - it is different from standard readWSDL method as it is
480      * using extensibility elements that were registered for dynamic port
481      * factory. It also uses the accompanying class loader to load imported WSDL
482      * resources.
483      */

484     public static Definition readWSDL(
485         String JavaDoc documentBase,
486         Reader JavaDoc reader,
487         ClassLoader JavaDoc cl)
488         throws WSDLException {
489         Trc.entry(null, documentBase, reader, cl);
490
491         initializeProviders();
492
493         WSDLFactory factory = WSDLFactory.newInstance(
494             WSIFConstants.WSIF_WSDLFACTORY);
495         WSDLReader wsdlReader = factory.newWSDLReader();
496         wsdlReader.setFeature(Constants.FEATURE_VERBOSE, false);
497         WSIFWSDLLocatorImpl lo = null;
498         try {
499             lo = new WSIFWSDLLocatorImpl(documentBase, reader, cl);
500             Definition def = wsdlReader.readWSDL(lo);
501             Trc.exitExpandWsdl(def);
502             return def;
503         } catch (WSDLException e) {
504             Trc.exception(e);
505             MessageLogger.log("WSIF.0002E", documentBase);
506             throw e;
507         } finally {
508             try {
509                 if (lo != null) lo.close();
510             } catch (IOException JavaDoc ioe) {
511                 //ignore
512
Trc.ignoredException(ioe);
513             }
514         }
515     }
516
517     /**
518      * Read WSDL - it is different from standard readWSDL method as it is
519      * using extensibility elements that were registered for dynamic port
520      * factory. It also uses the accompanying class loader to load imported WSDL
521      * resources.
522      */

523     public static Definition readWSDL(
524         URL JavaDoc contextURL,
525         String JavaDoc wsdlLoc,
526         ClassLoader JavaDoc cl)
527         throws WSDLException {
528         Trc.entry(null, contextURL, wsdlLoc, cl);
529
530         initializeProviders();
531
532         WSDLFactory factory = WSDLFactory.newInstance(
533             WSIFConstants.WSIF_WSDLFACTORY);
534         WSDLReader wsdlReader = factory.newWSDLReader();
535         wsdlReader.setFeature(Constants.FEATURE_VERBOSE, false);
536         WSIFWSDLLocatorImpl lo = null;
537
538         try {
539             String JavaDoc url = (contextURL == null) ? null : contextURL.toString();
540             lo = new WSIFWSDLLocatorImpl(url, wsdlLoc, cl);
541             Definition def = wsdlReader.readWSDL(lo);
542             Trc.exitExpandWsdl(def);
543             return def;
544         } catch (WSDLException e) {
545             Trc.exception(e);
546             MessageLogger.log("WSIF.0002E", wsdlLoc);
547             throw e;
548         } finally {
549             try {
550                 if (lo != null) lo.close();
551             } catch (IOException JavaDoc ioe) {
552                 //ignore
553
Trc.ignoredException(ioe);
554             }
555         }
556     }
557
558     /**
559      * Read WSDL - it is different from standard readWSDL method as it is
560      * using extensibility elements that were registered for dynamic port
561      * factory.
562      */

563     public static Definition readWSDL(String JavaDoc contextURL, Reader JavaDoc reader)
564         throws WSDLException {
565         Trc.entry(null, contextURL, reader);
566
567         initializeProviders();
568
569         WSDLFactory factory = WSDLFactory.newInstance(
570             WSIFConstants.WSIF_WSDLFACTORY);
571         WSDLReader wsdlReader = factory.newWSDLReader();
572         wsdlReader.setFeature(Constants.FEATURE_VERBOSE, false);
573         Definition def =
574             wsdlReader.readWSDL(contextURL, new InputSource JavaDoc(reader));
575         Trc.exitExpandWsdl(def);
576         return def;
577     }
578
579     /**
580      * Read WSDL - it is different from standard readWSDL method as it is
581      * using extensibility elements that were registered for dynamic port
582      * factory.
583      */

584     public static Definition readWSDL(String JavaDoc contextURL, Document JavaDoc wsdlDocument)
585         throws WSDLException {
586         Trc.entry(null, contextURL, wsdlDocument);
587
588         initializeProviders();
589
590         WSDLFactory factory = WSDLFactory.newInstance(
591             WSIFConstants.WSIF_WSDLFACTORY);
592         WSDLReader wsdlReader = factory.newWSDLReader();
593         wsdlReader.setFeature(Constants.FEATURE_VERBOSE, false);
594         Definition def = wsdlReader.readWSDL(contextURL, wsdlDocument);
595
596         Trc.exitExpandWsdl(def);
597         return def;
598     }
599
600     /**
601      * Read WSDL - it is different from standard readWSDL method as it is
602      * using extensibility elements that were registered for dynamic port
603      * factory.
604      */

605     public static Definition readWSDL(
606         String JavaDoc contextURL,
607         Element wsdlServicesElement)
608         throws WSDLException {
609         Trc.entry(null, contextURL, wsdlServicesElement);
610
611         initializeProviders();
612
613         WSDLFactory factory = WSDLFactory.newInstance(
614             WSIFConstants.WSIF_WSDLFACTORY);
615         WSDLReader wsdlReader = factory.newWSDLReader();
616         wsdlReader.setFeature(Constants.FEATURE_VERBOSE, false);
617         Definition def = wsdlReader.readWSDL(contextURL, wsdlServicesElement);
618
619         Trc.exitExpandWsdl(def);
620         return def;
621     }
622
623     /**
624      * Write WSDL - it is different from standard writeWSDL method as it is
625      * using extensibility elements that were registered for dynamic port
626      * factory.
627      */

628     public static void writeWSDL(Definition def, Writer JavaDoc sink)
629         throws WSDLException {
630         Trc.entry(null, def, sink);
631
632         WSDLFactory factory = WSDLFactory.newInstance(
633             WSIFConstants.WSIF_WSDLFACTORY);
634         WSDLWriter wsdlWriter = factory.newWSDLWriter();
635         wsdlWriter.writeWSDL(def, sink);
636
637         Trc.exit();
638     }
639
640     public static Definition getDefinitionFromLocation(
641         String JavaDoc contextURL,
642         String JavaDoc location)
643         throws WSIFException {
644         Trc.entry(null, contextURL, location);
645
646         if (location == null) {
647             throw new WSIFException("WSDL location must not be null.");
648         }
649
650         Definition def = null;
651         try {
652             def = WSIFUtils.readWSDL(contextURL, location);
653         } catch (WSDLException e) {
654             Trc.exception(e);
655             throw new WSIFException("Problem reading WSDL document.", e);
656         }
657         Trc.exitExpandWsdl(def);
658         return def;
659     }
660
661     public static Definition getDefinitionFromContent(
662         String JavaDoc contextURL,
663         String JavaDoc content)
664         throws WSIFException {
665         Trc.entry(null, contextURL, content);
666         if (content == null) {
667             throw new WSIFException("WSDL content must not be null.");
668         }
669
670         Definition def = null;
671         try {
672             def = WSIFUtils.readWSDL(contextURL, new StringReader JavaDoc(content));
673         } catch (WSDLException e) {
674             Trc.exception(e);
675             throw new WSIFException("Problem reading WSDL document.", e);
676         }
677         Trc.exitExpandWsdl(def);
678         return def;
679     }
680
681     /**
682      * Initialize the WSIF providers. Each provider initializes its WSDL
683      * extension registries. This has no effect if AutoLoad providers has
684      * been turned off on WSIFServiceImpl ... in that case it is the
685      * responsibility of the application to initialize providers.
686      */

687     public static void initializeProviders() {
688         synchronized (providersInitialized) {
689             if (!providersInitialized.booleanValue()) {
690                 WSIFPluggableProviders.getProvider("/");
691                 providersInitialized = new Boolean JavaDoc(true);
692             }
693         }
694     }
695
696     /**
697      * Create a map of all schema simple types and there Java equivalents.
698      */

699     public static void createSimpleTypesMap() {
700         synchronized (simpleTypesMapCreated) {
701             if (!simpleTypesMapCreated.booleanValue()) {
702                 new Schema2Java(
703                     WSIFConstants.NS_URI_1999_SCHEMA_XSD).getRegistry(
704                     simpleTypesMap);
705                 new Schema2Java(
706                     WSIFConstants.NS_URI_2000_SCHEMA_XSD).getRegistry(
707                     simpleTypesMap);
708                 new Schema2Java(
709                     WSIFConstants.NS_URI_2001_SCHEMA_XSD).getRegistry(
710                     simpleTypesMap);
711                 simpleTypesMapCreated = new Boolean JavaDoc(true);
712             }
713         }
714     }
715
716     /**
717      * Get a map of all schema simple types and there Java equivalents.
718      * @return The map of simple types
719      */

720     public static Map JavaDoc getSimpleTypesMap() {
721         if (!simpleTypesMapCreated.booleanValue()) {
722             createSimpleTypesMap();
723         }
724         return simpleTypesMap;
725     }
726
727     // the following code copied from JCAUtils
728
public static WSIFFormatHandler getFormatHandler(
729         Part part,
730         Definition definition,
731         javax.wsdl.Binding binding)
732         throws
733             java.lang.InstantiationException JavaDoc,
734             java.lang.IllegalAccessException JavaDoc,
735             java.lang.ClassNotFoundException JavaDoc {
736         Trc.entry(null, part, definition, binding);
737         WSIFFormatHandler formatHandler = null;
738         javax.xml.namespace.QName JavaDoc partTypeQName = part.getTypeName();
739         if (partTypeQName == null)
740             partTypeQName = part.getElementName();
741         if (partTypeQName == null)
742             throw new ClassNotFoundException JavaDoc(part.getName());
743
744         String JavaDoc typePackageName =
745             getPackageNameFromNamespaceURI(partTypeQName.getNamespaceURI());
746         String JavaDoc formatHandlerName = typePackageName;
747
748         String JavaDoc bindingShortName =
749             getPackageNameFromXMLName(
750                 definition.getPrefix(getBindingNamespace(binding)));
751         if (bindingShortName != null)
752             formatHandlerName = formatHandlerName + DOT + bindingShortName;
753
754         if (getFormatStylePackage(binding) != null)
755             formatHandlerName =
756                 formatHandlerName + DOT + getFormatStylePackage(binding);
757
758         String JavaDoc formatHandlerShortName =
759             formatHandlerName
760                 + DOT
761                 + getJavaClassNameFromXMLName(partTypeQName.getLocalPart());
762
763         try {
764             ClassLoader JavaDoc cl = Thread.currentThread().getContextClassLoader();
765             formatHandler =
766                 (WSIFFormatHandler) cl
767                     .loadClass(formatHandlerShortName + FORMAT_HANDLER)
768                     .newInstance();
769         } catch (ClassNotFoundException JavaDoc exn1) {
770             Trc.ignoredException(exn1);
771             try {
772                 ClassLoader JavaDoc cl = Thread.currentThread().getContextClassLoader();
773                 formatHandler =
774                     (WSIFFormatHandler) cl
775                         .loadClass(
776                             formatHandlerShortName + ELEMENT_FORMAT_HANDLER)
777                         .newInstance();
778             } catch (ClassNotFoundException JavaDoc exn2) {
779                 Trc.ignoredException(exn2);
780                 try {
781                     formatHandler =
782                         (WSIFFormatHandler) Class
783                             .forName(formatHandlerShortName + FORMAT_HANDLER)
784                             .newInstance();
785                 } catch (ClassNotFoundException JavaDoc exn3) {
786                     Trc.ignoredException(exn3);
787                     //try {
788
formatHandler =
789                         (WSIFFormatHandler) Class
790                             .forName(
791                                 formatHandlerShortName
792                                     + ELEMENT_FORMAT_HANDLER)
793                             .newInstance();
794                     //}
795
//catch (ClassNotFoundException exn4) {
796
// throw new ClassNotFoundException(JCAResource.get("IWAA0101E", formatHandlerName));
797
//}
798
}
799             }
800         }
801         //catch (Throwable exn3) {
802
//throw new ClassNotFoundException(JCAResource.get("IWAA0102E", formatHandlerName, exn3.getLocalizedMessage()));
803
//}
804
if (formatHandler == null)
805             //throw new ClassNotFoundException(JCAResource.get("IWAA0101E", formatHandlerName));
806
throw new ClassNotFoundException JavaDoc(formatHandlerName);
807         else {
808             Trc.exit(formatHandler);
809             return formatHandler;
810         }
811     }
812
813     public static String JavaDoc getPackageNameFromNamespaceURI(String JavaDoc namespaceURI) {
814         Trc.entry(null, namespaceURI);
815         // Get the segments in the namespace URI
816
List JavaDoc segments = getNamespaceURISegments(namespaceURI);
817
818         StringBuffer JavaDoc packageNameBuffer = new StringBuffer JavaDoc();
819         for (int i = 0; i < segments.size(); i++) {
820             String JavaDoc name;
821
822             // The first segment is the host name
823
if (i == 0) {
824
825                 // Turn segment into a valid package segment name
826
name = getPackageNameFromXMLName((String JavaDoc) segments.get(i));
827
828                 // Reverse its components
829
StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(name, ".");
830                 List JavaDoc host = new ArrayList JavaDoc();
831                 for (; tokenizer.hasMoreTokens();) {
832                     String JavaDoc nextT = tokenizer.nextToken();
833                     host.add(0, nextT);
834                 }
835                 StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
836                 for (Iterator JavaDoc hi = host.iterator(); hi.hasNext();) {
837                     if (buffer.length() != 0)
838                         buffer.append('.');
839                     String JavaDoc nextSegment = (String JavaDoc) hi.next();
840                     if (!Character
841                         .isJavaIdentifierStart(nextSegment.toCharArray()[0]))
842                         nextSegment = UNDERSCORE + nextSegment;
843                     if (isJavaKeyword(nextSegment))
844                         nextSegment = UNDERSCORE + nextSegment;
845                     buffer.append(nextSegment);
846                 }
847                 name = buffer.toString();
848             } else {
849
850                 // Turn segment into a valid java name
851
name = getJavaNameFromXMLName((String JavaDoc) segments.get(i));
852
853             }
854
855             // Concatenate segments, separated by '.'
856
if (name.length() == 0)
857                 continue;
858             if (packageNameBuffer.length() != 0)
859                 packageNameBuffer.append('.');
860             packageNameBuffer.append(name);
861         }
862         Trc.exit(packageNameBuffer.toString());
863         return packageNameBuffer.toString();
864     }
865
866     public static String JavaDoc getJavaNameFromXMLName(
867         String JavaDoc xmlName,
868         String JavaDoc delims) {
869         Trc.entry(null, xmlName, delims);
870         StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(xmlName, delims);
871         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
872         while (tokenizer.hasMoreTokens()) {
873             buffer.append(tokenizer.nextToken());
874         }
875         String JavaDoc result = buffer.toString();
876         if (!Character.isJavaIdentifierStart(result.toCharArray()[0]))
877             result = UNDERSCORE + result;
878         if (isJavaKeyword(result))
879             result = UNDERSCORE + result;
880         Trc.exit(result);
881         return result;
882     }
883
884     public static String JavaDoc getJavaNameFromXMLName(String JavaDoc xmlName) {
885         Trc.entry(null, xmlName);
886         String JavaDoc s = getJavaNameFromXMLName(xmlName, XMLSEPARATORS);
887         Trc.exit(s);
888         return s;
889     }
890
891     public static String JavaDoc getPackageNameFromXMLName(String JavaDoc xmlName) {
892         Trc.entry(null, xmlName);
893
894         // Tokenize, don't consider '.' as a delimiter here
895
String JavaDoc name = getJavaNameFromXMLName(xmlName, XMLSEPARATORS_NODOT);
896
897         // Tokenize using delimiter '.' and add the tokens separated by '.'
898
// This is to ensure that we have no heading/trailing/dup '.' in the string
899
StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(name, DOT);
900         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
901         for (; tokenizer.hasMoreTokens();) {
902             if (buffer.length() != 0)
903                 buffer.append('.');
904             // -->
905
String JavaDoc nextSegment = (String JavaDoc) tokenizer.nextToken();
906             if (!Character.isJavaIdentifierStart(nextSegment.toCharArray()[0]))
907                 nextSegment = UNDERSCORE + nextSegment;
908             if (isJavaKeyword(nextSegment))
909                 nextSegment = UNDERSCORE + nextSegment;
910             buffer.append(nextSegment);
911
912             // buffer.append(tokenizer.nextToken());
913
// <--
914
}
915         Trc.exit(buffer.toString());
916         return buffer.toString();
917     }
918
919     private static List JavaDoc getNamespaceURISegments(String JavaDoc namespaceURI) {
920         Trc.entry(null, namespaceURI);
921
922         // Tokenize
923
List JavaDoc segments = new ArrayList JavaDoc();
924         StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(namespaceURI, ":/");
925         while (tokenizer.hasMoreTokens()) {
926             segments.add(tokenizer.nextToken());
927         }
928
929         // Remove protocol
930
if (!segments.isEmpty()) {
931             try {
932                 URL JavaDoc url = new URL JavaDoc(namespaceURI);
933                 if (segments.get(0).equals(url.getProtocol()))
934                     segments.remove(0);
935             } catch (MalformedURLException JavaDoc exn) {
936                 Trc.ignoredException(exn);
937             }
938         }
939         Trc.exit(segments);
940         return segments;
941     }
942
943     private static String JavaDoc getBindingNamespace(Binding bindingModel) {
944         Trc.entry(null, bindingModel);
945         Iterator JavaDoc iterator = bindingModel.getExtensibilityElements().iterator();
946         String JavaDoc returnNamespace = null;
947         while (iterator.hasNext()) {
948             ExtensibilityElement ee = (ExtensibilityElement) iterator.next();
949             if (returnNamespace == null) {
950                 String JavaDoc namespace = ee.getElementType().getNamespaceURI();
951                 if (!namespace.endsWith(PHYSICALREP)
952                     && !namespace.endsWith(FORMATBINDING)) {
953                     returnNamespace = namespace;
954                 }
955             }
956         }
957         Trc.exit(returnNamespace);
958         return returnNamespace;
959     }
960
961     public static String JavaDoc getFormatStylePackage(Binding bindingModel) {
962         Trc.entry(null, bindingModel);
963
964         Iterator JavaDoc iterator = bindingModel.getExtensibilityElements().iterator();
965         String JavaDoc formatPackageName = null;
966         while (iterator.hasNext()) {
967             ExtensibilityElement ee = (ExtensibilityElement) iterator.next();
968             if (ee instanceof TypeMapping) {
969                 TypeMapping typeMapping = (TypeMapping) ee;
970                 formatPackageName = typeMapping.getEncoding();
971                 if (typeMapping.getStyle() != null)
972                     formatPackageName += typeMapping.getStyle();
973             }
974             if (formatPackageName != null)
975                 break;
976         }
977         String JavaDoc s = null;
978         if (formatPackageName != null) {
979             // return getJavaNameFromXMLName(formatPackageName);
980
s = getPackageNameFromXMLName(formatPackageName);
981         } else {
982             s = formatPackageName;
983         }
984         Trc.exit(s);
985         return s;
986     }
987
988     public static String JavaDoc getFormatHandlerName(
989         Part part,
990         Definition definition,
991         Binding binding)
992         throws
993             java.lang.InstantiationException JavaDoc,
994             java.lang.IllegalAccessException JavaDoc,
995             java.lang.ClassNotFoundException JavaDoc {
996         Trc.entry(null, part, definition, binding);
997
998         javax.xml.namespace.QName JavaDoc partTypeQName = part.getTypeName();
999         if (partTypeQName == null)
1000            partTypeQName = part.getElementName();
1001        if (partTypeQName == null)
1002            throw new ClassNotFoundException JavaDoc(part.getName());
1003
1004        String JavaDoc typePackageName =
1005            getPackageNameFromNamespaceURI(partTypeQName.getNamespaceURI());
1006        String JavaDoc formatHandlerName = typePackageName;
1007
1008        String JavaDoc bindingShortName =
1009            getPackageNameFromXMLName(
1010                definition.getPrefix(getBindingNamespace(binding)));
1011        if (bindingShortName != null)
1012            formatHandlerName = formatHandlerName + DOT + bindingShortName;
1013
1014        if (getFormatStylePackage(binding) != null)
1015            formatHandlerName =
1016                formatHandlerName + DOT + getFormatStylePackage(binding);
1017
1018        formatHandlerName =
1019            formatHandlerName
1020                + DOT
1021                + getJavaClassNameFromXMLName(partTypeQName.getLocalPart())
1022                + FORMAT_HANDLER;
1023
1024        Trc.exit(formatHandlerName);
1025        return formatHandlerName;
1026    }
1027
1028    public static String JavaDoc getJavaClassNameFromXMLName(String JavaDoc xmlName) {
1029        Trc.entry(null, xmlName);
1030        String JavaDoc s = getJavaClassNameFromXMLName(xmlName, XMLSEPARATORS);
1031        Trc.exit(s);
1032        return s;
1033    }
1034
1035    public static String JavaDoc getJavaClassNameFromXMLName(
1036        String JavaDoc xmlName,
1037        String JavaDoc delims) {
1038        Trc.entry(null, xmlName, delims);
1039        StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(xmlName, delims);
1040        StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
1041        while (tokenizer.hasMoreTokens()) {
1042            String JavaDoc nextSegment = (String JavaDoc) tokenizer.nextToken();
1043            if (nextSegment.length() > 0) {
1044                nextSegment =
1045                    Character.toUpperCase((nextSegment.toCharArray())[0])
1046                        + nextSegment.substring(1);
1047            }
1048            buffer.append(nextSegment);
1049        }
1050        String JavaDoc result = buffer.toString();
1051        if (!Character.isJavaIdentifierStart(result.toCharArray()[0]))
1052            result = UNDERSCORE + result;
1053        Trc.exit(result);
1054        if (isJavaKeyword(result))
1055            return UNDERSCORE + result;
1056        else
1057            return result;
1058    }
1059
1060    public static String JavaDoc getXSDNamespaceFromPackageName(String JavaDoc packageName) {
1061    
1062        String JavaDoc result = "";
1063        StringTokenizer JavaDoc tokenizer = new java.util.StringTokenizer JavaDoc(packageName, ".");
1064        while (tokenizer.hasMoreTokens()) {
1065            String JavaDoc nextT = tokenizer.nextToken();
1066            result = nextT + "." + result;
1067        }
1068        if (result.endsWith("."))
1069            return "http://" + result.substring(0, result.length() - 1) + "/";
1070        return "http://" + result + "/";
1071    }
1072
1073   /**
1074    * Get a binding operation for a portType operation.
1075    *
1076    * @param binding the WSLD binding the operation will choosen from
1077    * @param portTypeOp the portType operation the binding operation
1078    * must match
1079    * @return the BindingOperation
1080    */

1081   public static BindingOperation getBindingOperation(
1082      Binding binding,
1083      Operation portTypeOp) throws WSIFException {
1084
1085      Trc.entry(null, binding, portTypeOp);
1086      BindingOperation bop;
1087      if ( portTypeOp == null ) {
1088        bop = null;
1089      } else {
1090        bop = getBindingOperation(
1091           binding,
1092           portTypeOp.getName(),
1093           portTypeOp.getInput()==null ? null : portTypeOp.getInput().getName(),
1094           portTypeOp.getOutput()==null ? null : portTypeOp.getOutput().getName() );
1095      }
1096      Trc.exit(bop);
1097      return bop;
1098   }
1099
1100   /**
1101    * Get a binding operation for a portType operation.
1102    *
1103    * @param binding the WSLD binding the operation will choosen from
1104    * @param opName the portType operation name of the wanted operation
1105    * @param inName the portType operation input name
1106    * @param outName the portType operation outpur name
1107    * @return the BindingOperation
1108    */

1109   public static BindingOperation getBindingOperation(
1110      Binding binding,
1111      String JavaDoc opName,
1112      String JavaDoc inName,
1113      String JavaDoc outName) throws WSIFException {
1114
1115      Trc.entry(null, binding, opName, inName, outName);
1116      BindingOperation op = null;
1117      if (binding != null && opName != null) {
1118         ArrayList JavaDoc matchingOps = new ArrayList JavaDoc();
1119         List JavaDoc bops = binding.getBindingOperations();
1120         if (bops != null) {
1121            for (Iterator JavaDoc i = bops.iterator(); i.hasNext();) {
1122               BindingOperation bop = (BindingOperation) i.next();
1123               if ( opName.equalsIgnoreCase(bop.getName()) ) {
1124                  matchingOps.add(bop);
1125               }
1126            }
1127            if (matchingOps.size() == 1) {
1128               op = (BindingOperation) matchingOps.get(0);
1129            } else if (matchingOps.size() > 1) {
1130               op = chooseBindingOperation(matchingOps, inName, outName);
1131            }
1132         }
1133      }
1134      Trc.exit(op);
1135      return op;
1136   }
1137
1138   private static BindingOperation chooseBindingOperation(
1139      ArrayList JavaDoc bindingOps,
1140      String JavaDoc inName,
1141      String JavaDoc outName) throws WSIFException {
1142        
1143      BindingOperation choosenOp = null;
1144      for (Iterator JavaDoc i = bindingOps.iterator(); i.hasNext(); ) {
1145         BindingOperation bop = (BindingOperation) i.next();
1146         String JavaDoc binName = (bop.getBindingInput() == null) ?
1147            null :
1148            bop.getBindingInput().getName();
1149         String JavaDoc boutName = (bop.getBindingOutput() == null) ?
1150            null :
1151            bop.getBindingOutput().getName();
1152         if ((inName == null) ? binName == null : inName.equalsIgnoreCase(binName)) {
1153            if ((outName == null)
1154               ? boutName == null
1155               : outName.equalsIgnoreCase(boutName)) {
1156               if ( choosenOp == null ) {
1157                  choosenOp = bop;
1158               } else {
1159                  throw new WSIFException(
1160                     "duplicate operation in binding: " +
1161                     bop.getName() +
1162                     ":" + inName +
1163                     ":" + outName );
1164               }
1165            }
1166         }
1167      }
1168      return choosenOp;
1169   }
1170
1171    private static boolean isJavaKeyword(String JavaDoc identifier) {
1172        if (keywordMap == null) {
1173            Object JavaDoc value = new Object JavaDoc();
1174            keywordMap = new HashMap JavaDoc();
1175            keywordMap.put("abstract", value);
1176            keywordMap.put("default", value);
1177            keywordMap.put("if", value);
1178            keywordMap.put("private", value);
1179            keywordMap.put("this", value);
1180            keywordMap.put("boolean", value);
1181            keywordMap.put("do", value);
1182            keywordMap.put("implements", value);
1183            keywordMap.put("protected", value);
1184            keywordMap.put("throw", value);
1185            keywordMap.put("break", value);
1186            keywordMap.put("double", value);
1187            keywordMap.put("import", value);
1188            keywordMap.put("public", value);
1189            keywordMap.put("throws", value);
1190            keywordMap.put("byte", value);
1191            keywordMap.put("else", value);
1192            keywordMap.put("instanceof", value);
1193            keywordMap.put("return", value);
1194            keywordMap.put("transient", value);
1195            keywordMap.put("case", value);
1196            keywordMap.put("extends", value);
1197            keywordMap.put("int", value);
1198            keywordMap.put("short", value);
1199            keywordMap.put("try", value);
1200            keywordMap.put("catch", value);
1201            keywordMap.put("final", value);
1202            keywordMap.put("interface", value);
1203            keywordMap.put("static", value);
1204            keywordMap.put("void", value);
1205            keywordMap.put("char", value);
1206            keywordMap.put("finally", value);
1207            keywordMap.put("long", value);
1208            keywordMap.put("strictfp", value);
1209            keywordMap.put("volatile", value);
1210            keywordMap.put("class", value);
1211            keywordMap.put("float", value);
1212            keywordMap.put("native", value);
1213            keywordMap.put("super", value);
1214            keywordMap.put("while", value);
1215            keywordMap.put("const", value);
1216            keywordMap.put("for", value);
1217            keywordMap.put("new", value);
1218            keywordMap.put("switch", value);
1219            keywordMap.put("continue", value);
1220            keywordMap.put("goto", value);
1221            keywordMap.put("package", value);
1222            keywordMap.put("synchronized", value);
1223            keywordMap.put("null", value);
1224            keywordMap.put("true", value);
1225            keywordMap.put("false", value);
1226            keywordMap.put("assert", value);
1227        }
1228        return keywordMap.containsKey(identifier);
1229
1230        // abstract default if private this
1231
// boolean do implements protected throw
1232
// break double import public throws
1233
// byte else instanceof return transient
1234
// case extends int short try
1235
// catch final interface static void
1236
// char finally long strictfp volatile
1237
// class float native super while
1238
// const for new switch
1239
// continue goto package synchronized
1240
// null true false assert
1241
}
1242
1243    /**
1244     * Compares two strings taking acount of a wildcard.
1245     * The first string is compared to the second string taking
1246     * account of a wildcard character in the first string. For
1247     * example, wildcardCompare( "*.ibm.com", "hursley.ibm.com", '*')
1248     * would return true.
1249     */

1250    public static boolean wildcardCompare(String JavaDoc s1, String JavaDoc s2, char wild) {
1251        if (s1 == null) {
1252            return false;
1253        }
1254        String JavaDoc w = wild + "";
1255        return cmp(new StringTokenizer JavaDoc(s1, w, true), s2, w);
1256    }
1257    
1258    private static boolean cmp(StringTokenizer JavaDoc st, String JavaDoc s, String JavaDoc wild) {
1259        if ( s == null || s.equals( "" ) ) {
1260            return !st.hasMoreTokens();
1261        }
1262        if ( st.hasMoreTokens() ) {
1263           String JavaDoc s2 = st.nextToken();
1264           if ( wild.equals( s2 ) ) {
1265              if ( !st.hasMoreTokens() ) {
1266                 return true; // a trailing wildcard matches anything
1267
}
1268              s2 = st.nextToken();
1269              if ( s.equals( s2 ) ) {
1270                 return false; // wildcard must be at least 1 character
1271
}
1272           }
1273           int i = s.indexOf( s2 );
1274           if ( i < 0 ) {
1275              return false; // prefix not in s
1276
}
1277           i += s2.length();
1278           if ( i < s.length() ) {
1279              return cmp( st, s.substring( i ), wild );
1280           } else {
1281              return cmp( st, "", wild );
1282           }
1283        }
1284        return false; // no more tokens but still some s
1285
}
1286    
1287    /**
1288     * Tests if this is wrapped document literal stype operation.
1289     * An operation is wrapped if:
1290     * - there is only one input or output message part
1291     * and that part is an element not a type
1292     * (MIME means there can be many parts, so all this
1293     * can check is that there is only one element part)
1294     * - the message name is the same as the operation name
1295     * (for a response the operation name is appened with "Response")
1296     */

1297    public static boolean isWrappedDocLiteral(List JavaDoc parts, String JavaDoc operationName) {
1298        boolean wrapped = !(parts==null);
1299        Part elementPart = null;
1300        for (int i = 0; wrapped && i < parts.size(); i++) {
1301            Part p = (Part) parts.get(i);
1302            if (p.getElementName() != null) {
1303                if (elementPart == null) {
1304                    elementPart = p;
1305                    String JavaDoc pName = p.getElementName().getLocalPart();
1306                    if (!operationName.equals(pName)) {
1307                       wrapped = false;
1308                    }
1309                } else {
1310                    wrapped = false;
1311                }
1312            }
1313        }
1314        return wrapped;
1315    }
1316
1317    /**
1318     * Gets the wrapped Part if this is wrapped document literal
1319     * stype operation. An operation is wrapped if:
1320     * - there is only one input or output message part
1321     * and that part is an element not a type
1322     * (MIME means there can be many parts, so all this
1323     * can check is that there is only one element part)
1324     * - the message name is the same as the operation name
1325     * (for a response the operation name is appened with "Response")
1326     */

1327    public static Part getWrappedDocLiteralPart(List JavaDoc parts, String JavaDoc operationName) {
1328        boolean wrapped = !(parts==null);
1329        Part elementPart = null;
1330        for (int i = 0; wrapped && i < parts.size(); i++) {
1331            Part p = (Part) parts.get(i);
1332            if (p.getElementName() != null) {
1333                if (elementPart == null) {
1334                    elementPart = p;
1335                    String JavaDoc pName = p.getElementName().getLocalPart();
1336                    if (!operationName.equals(pName)) {
1337                       wrapped = false;
1338                    }
1339                } else {
1340                    wrapped = false;
1341                }
1342            }
1343        }
1344        if (!wrapped) {
1345            elementPart = null;
1346        }
1347        return elementPart;
1348    }
1349
1350    /**
1351     * Unwraps a wrapped DocLit style part.
1352     */

1353    public static List JavaDoc unWrapPart(Part p, Definition def) throws WSIFException {
1354
1355        ArrayList JavaDoc l = new ArrayList JavaDoc();
1356        Parser.getAllSchemaTypes(def, l, null);
1357        if (l == null || l.size()<1) {
1358            throw new WSIFException("no schema elements found");
1359        }
1360
1361        QName JavaDoc partQN = p.getElementName();
1362        if (partQN == null) {
1363            throw new WSIFException("part has no QName");
1364        }
1365        
1366        ElementType et = null;
1367        for (int i=0; i<l.size() && et==null; i++ ){
1368            Object JavaDoc o = l.get(i);
1369            if ( o instanceof ElementType ) {
1370                QName JavaDoc etQN = ((ElementType)o).getTypeName();
1371                if ( partQN.equals(etQN) ){
1372                    et = (ElementType)o;
1373                }
1374            }
1375        }
1376        if (et == null) {
1377            throw new WSIFException("no ElementType found for part: " + p);
1378        }
1379
1380        List JavaDoc children = et.getChildren();
1381        if (children == null || l.size()<1) {
1382            throw new WSIFException("no ComplexType children on elementType: " + et);
1383        }
1384        
1385        ComplexType ct = (ComplexType) children.get(0);
1386        SequenceElement[] se = ct.getSequenceElements();
1387        if (se == null) {
1388            throw new WSIFException("no sequence elements found on: " + ct);
1389        }
1390        
1391        ArrayList JavaDoc unWrappedParts = new ArrayList JavaDoc();
1392        for (int i=0; i< se.length; i++) {
1393           PartImpl np = new PartImpl();
1394           QName JavaDoc type = se[i].getTypeName();
1395           if (type==null) {
1396              throw new WSIFException("sequence element has no type name: " + se[i]);
1397           }
1398           np.setName(type.getLocalPart());
1399           np.setElementName(se[i].getElementType());
1400           unWrappedParts.add(np);
1401        }
1402
1403        return unWrappedParts;
1404    }
1405    
1406    /**
1407     * Gets the WSIF WSDL Extensions Registry
1408     * This calls initializeProviders to ensure all providers
1409     * have registered any custom WSDL extensions.
1410     * @return ExtensionRegistry the WSIF ExtensionRegistry
1411     */

1412    public static ExtensionRegistry getExtensionRegistry() {
1413        Trc.entry(null);
1414        initializeProviders();
1415        ExtensionRegistry er = WSIFServiceImpl.getCompositeExtensionRegistry();
1416        Trc.exit(er);
1417        return er;
1418    }
1419
1420}
Popular Tags