KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > axis > wsdl > toJava > Utils


1 /*
2  * Copyright 2001-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.apache.axis.wsdl.toJava;
17
18 import org.apache.axis.Constants;
19 import org.apache.axis.components.logger.LogFactory;
20 import org.apache.axis.constants.Style;
21 import org.apache.axis.constants.Use;
22 import org.apache.axis.utils.JavaUtils;
23 import org.apache.axis.utils.Messages;
24 import org.apache.axis.wsdl.symbolTable.*;
25 import org.apache.commons.logging.Log;
26 import org.w3c.dom.Node JavaDoc;
27 import org.w3c.dom.NodeList JavaDoc;
28
29 import javax.wsdl.BindingInput;
30 import javax.wsdl.BindingOperation;
31 import javax.wsdl.Input;
32 import javax.wsdl.Message;
33 import javax.wsdl.Operation;
34 import javax.wsdl.Part;
35 import javax.wsdl.extensions.ExtensibilityElement;
36 import javax.wsdl.extensions.UnknownExtensibilityElement;
37 import javax.wsdl.extensions.mime.MIMEMultipartRelated;
38 import javax.wsdl.extensions.soap.SOAPBody;
39 import javax.wsdl.extensions.soap.SOAPOperation;
40 import javax.xml.namespace.QName JavaDoc;
41 import javax.xml.rpc.holders.BooleanHolder JavaDoc;
42 import java.io.File JavaDoc;
43 import java.io.IOException JavaDoc;
44 import java.net.MalformedURLException JavaDoc;
45 import java.net.URL JavaDoc;
46 import java.util.HashMap JavaDoc;
47 import java.util.Iterator JavaDoc;
48 import java.util.List JavaDoc;
49 import java.util.Map JavaDoc;
50 import java.util.StringTokenizer JavaDoc;
51 import java.util.Vector JavaDoc;
52
53 /**
54  * Class Utils
55  *
56  * @version %I%, %G%
57  */

58 public class Utils extends org.apache.axis.wsdl.symbolTable.Utils {
59
60     /** Field log */
61     protected static Log log = LogFactory.getLog(Utils.class.getName());
62
63     /**
64      * @see #holder(Parameter, Emitter)
65      */

66     public static String JavaDoc holder(TypeEntry type, Emitter emitter) {
67         Parameter arg = new Parameter();
68         // For other fields the default values will do.
69
arg.setType(type);
70         return holder(arg, emitter);
71     }
72     /**
73      * Given a type, return the Java mapping of that type's holder.
74      *
75      * @param p parameter whose holder class name we want to obtain.
76      * @param emitter the only {@link Emitter} object embodying the running
77      * instance of WSDL2Java.
78      * @return the name of the holder class for <tt>p</tt>.
79      */

80     public static String JavaDoc holder(Parameter p, Emitter emitter) {
81         String JavaDoc mimeType = (p.getMIMEInfo() == null)
82                 ? null
83                 : p.getMIMEInfo().getType();
84         String JavaDoc mimeDimensions = (mimeType == null)
85                 ? ""
86                 : p.getMIMEInfo().getDimensions();
87
88         // Add the holders that JAX-RPC forgot about - the MIME type holders.
89
if (mimeType != null) {
90             if (mimeType.equals("image/gif") || mimeType.equals("image/jpeg")) {
91                 return "org.apache.axis.holders.ImageHolder" + mimeDimensions;
92             } else if (mimeType.equals("text/plain")) {
93                 return "javax.xml.rpc.holders.StringHolder" + mimeDimensions;
94             } else if (mimeType.startsWith("multipart/")) {
95                 return "org.apache.axis.holders.MimeMultipartHolder"
96                         + mimeDimensions;
97             } else if (mimeType.startsWith("application/octetstream")
98                     || mimeType.startsWith("application/octet-stream")) {
99                 return "org.apache.axis.holders.OctetStreamHolder"
100                         + mimeDimensions;
101             } else if (mimeType.equals("text/xml")
102                     || mimeType.equals("application/xml")) {
103                 return "org.apache.axis.holders.SourceHolder" + mimeDimensions;
104             } else {
105                 return "org.apache.axis.holders.DataHandlerHolder"
106                         + mimeDimensions;
107             }
108         }
109
110         TypeEntry type = p.getType();
111         String JavaDoc typeValue = type.getName();
112         // For base types that are nillable and are mapped to primitives,
113
// need to switch to the corresponding wrapper types.
114
if (p.isOmittable()
115             && (type instanceof BaseType
116                  || type instanceof DefinedElement
117                      && type.getRefType() instanceof BaseType)) {
118             String JavaDoc wrapperTypeValue = (String JavaDoc) TYPES.get(typeValue);
119             typeValue = wrapperTypeValue == null ? typeValue
120                                                   : wrapperTypeValue;
121         }
122
123         // byte[] has a reserved holders
124
if (typeValue.equals("byte[]") && type.isBaseType()) {
125             return "javax.xml.rpc.holders.ByteArrayHolder";
126         }
127
128         // Anything else with [] gets its holder from the qname
129
else if (typeValue.endsWith("[]")) {
130             String JavaDoc name = emitter.getJavaName(type.getQName());
131             String JavaDoc packagePrefix = "";
132
133             // Make sure that holders for arrays of either primitive Java types
134
// or their wrappers are generated at a predictable location.
135
if ((type instanceof CollectionType)
136                     && (type.getRefType() instanceof BaseType)) {
137                 String JavaDoc uri = type.getRefType().getQName().getNamespaceURI();
138
139                 packagePrefix = emitter.getNamespaces().getCreate(uri, false);
140
141                 if (packagePrefix == null) {
142                     packagePrefix = "";
143                 } else {
144                     packagePrefix += '.';
145                 }
146             }
147
148             name = JavaUtils.replace(name, "java.lang.", "");
149
150             // This could be a special QName for a indexed property.
151
// If so, change the [] to Array.
152
name = JavaUtils.replace(name, "[]", "Array");
153             name = addPackageName(name, "holders");
154
155             return packagePrefix + name + "Holder";
156         }
157
158         // String also has a reserved holder
159
else if (typeValue.equals("String")) {
160             return "javax.xml.rpc.holders.StringHolder";
161         } else if (typeValue.equals("java.lang.String")) {
162             return "javax.xml.rpc.holders.StringHolder";
163         }
164
165         // Object also has a reserved holder
166
else if (typeValue.equals("Object")) {
167             return "javax.xml.rpc.holders.ObjectHolder";
168         } else if (typeValue.equals("java.lang.Object")) {
169             return "javax.xml.rpc.holders.ObjectHolder";
170         }
171
172         // Java primitive types have reserved holders
173
else if (typeValue.equals("int") || typeValue.equals("long")
174                 || typeValue.equals("short") || typeValue.equals("float")
175                 || typeValue.equals("double") || typeValue.equals("boolean")
176                 || typeValue.equals("byte")) {
177             return "javax.xml.rpc.holders." + capitalizeFirstChar(typeValue)
178                     + "Holder";
179         }
180
181         // Java language classes have reserved holders (with ClassHolder)
182
else if (typeValue.startsWith("java.lang.")) {
183             return "javax.xml.rpc.holders"
184                     + typeValue.substring(typeValue.lastIndexOf("."))
185                     + "WrapperHolder";
186         } else if (typeValue.indexOf(".") < 0) {
187             return "javax.xml.rpc.holders" + typeValue + "WrapperHolder";
188         }
189
190         // The classes have reserved holders because they
191
// represent schema/soap encoding primitives
192
else if (typeValue.equals("java.math.BigDecimal")) {
193             return "javax.xml.rpc.holders.BigDecimalHolder";
194         } else if (typeValue.equals("java.math.BigInteger")) {
195             return "javax.xml.rpc.holders.BigIntegerHolder";
196         } else if (typeValue.equals("java.util.Date")) {
197             return "org.apache.axis.holders.DateHolder";
198         } else if (typeValue.equals("java.util.Calendar")) {
199             return "javax.xml.rpc.holders.CalendarHolder";
200         } else if (typeValue.equals("javax.xml.namespace.QName")) {
201             return "javax.xml.rpc.holders.QNameHolder";
202         } else if (typeValue.equals("javax.activation.DataHandler")) {
203             return "org.apache.axis.holders.DataHandlerHolder";
204         }
205
206         // Check for Axis specific types and return their holders
207
else if (typeValue.startsWith("org.apache.axis.types.")) {
208             int i = typeValue.lastIndexOf('.');
209             String JavaDoc t = typeValue.substring(i + 1);
210
211             return "org.apache.axis.holders." + t + "Holder";
212         }
213
214         // For everything else add "holders" package and append
215
// holder to the class name.
216
else {
217             return addPackageName(typeValue, "holders") + "Holder";
218         }
219     } // holder
220

221     /**
222      * Add package to name
223      *
224      * @param className full name of the class.
225      * @param newPkg name of the package to append
226      * @return String name with package name added
227      */

228     public static String JavaDoc addPackageName(String JavaDoc className, String JavaDoc newPkg) {
229
230         int index = className.lastIndexOf(".");
231
232         if (index >= 0) {
233             return className.substring(0, index) + "." + newPkg
234                     + className.substring(index);
235         } else {
236             return newPkg + "." + className;
237         }
238     }
239
240     /**
241      * Given a fault message, return the fully qualified Java class name
242      * of the exception to be generated from this fault
243      *
244      * @param faultMessage The WSDL fault message
245      * @param symbolTable the current symbol table
246      * @return A Java class name for the fault
247      */

248     public static String JavaDoc getFullExceptionName(Message faultMessage,
249                                               SymbolTable symbolTable) {
250
251         MessageEntry me = symbolTable.getMessageEntry(faultMessage.getQName());
252
253         return (String JavaDoc) me.getDynamicVar(
254                 JavaGeneratorFactory.EXCEPTION_CLASS_NAME);
255     } // getFullExceptionName
256

257     /**
258      * Given a fault message, return the XML type of the exception data.
259      *
260      * @param faultMessage The WSDL fault message object
261      * @param symbolTable the current symbol table
262      * @return A QName for the XML type of the data
263      */

264     public static QName JavaDoc getFaultDataType(Message faultMessage,
265                                          SymbolTable symbolTable) {
266
267         MessageEntry me = symbolTable.getMessageEntry(faultMessage.getQName());
268
269         return (QName JavaDoc) me.getDynamicVar(
270                 JavaGeneratorFactory.EXCEPTION_DATA_TYPE);
271     } // getFaultDataType
272

273     /**
274      * Given a fault message, return TRUE if the fault is a complex type fault
275      *
276      * @param faultMessage The WSDL fault message object
277      * @param symbolTable the current symbol table
278      * @return A Java class name for the fault
279      */

280     public static boolean isFaultComplex(Message faultMessage,
281                                          SymbolTable symbolTable) {
282
283         MessageEntry me = symbolTable.getMessageEntry(faultMessage.getQName());
284         Boolean JavaDoc ret =
285                 (Boolean JavaDoc) me.getDynamicVar(JavaGeneratorFactory.COMPLEX_TYPE_FAULT);
286
287         if (ret != null) {
288             return ret.booleanValue();
289         } else {
290             return false;
291         }
292     } // isFaultComplex
293

294     /**
295      * If the specified node represents a supported JAX-RPC enumeration,
296      * a Vector is returned which contains the base type and the enumeration values.
297      * The first element in the vector is the base type (an TypeEntry).
298      * Subsequent elements are values (Strings).
299      * If this is not an enumeration, null is returned.
300      *
301      * @param node
302      * @param symbolTable
303      * @return
304      */

305     public static Vector JavaDoc getEnumerationBaseAndValues(Node JavaDoc node,
306                                                      SymbolTable symbolTable) {
307
308         if (node == null) {
309             return null;
310         }
311
312         // If the node kind is an element, dive into it.
313
QName JavaDoc nodeKind = Utils.getNodeQName(node);
314
315         if ((nodeKind != null) && nodeKind.getLocalPart().equals("element")
316                 && Constants.isSchemaXSD(nodeKind.getNamespaceURI())) {
317             NodeList JavaDoc children = node.getChildNodes();
318             Node JavaDoc simpleNode = null;
319
320             for (int j = 0; (j < children.getLength()) && (simpleNode == null);
321                  j++) {
322                 QName JavaDoc simpleKind = Utils.getNodeQName(children.item(j));
323
324                 if ((simpleKind != null)
325                         && simpleKind.getLocalPart().equals("simpleType")
326                         && Constants.isSchemaXSD(
327                                 simpleKind.getNamespaceURI())) {
328                     simpleNode = children.item(j);
329                     node = simpleNode;
330                 }
331             }
332         }
333
334         // Get the node kind, expecting a schema simpleType
335
nodeKind = Utils.getNodeQName(node);
336
337         if ((nodeKind != null) && nodeKind.getLocalPart().equals("simpleType")
338                 && Constants.isSchemaXSD(nodeKind.getNamespaceURI())) {
339
340             // Under the simpleType there should be a restriction.
341
// (There may be other #text nodes, which we will ignore).
342
NodeList JavaDoc children = node.getChildNodes();
343             Node JavaDoc restrictionNode = null;
344
345             for (int j = 0;
346                  (j < children.getLength()) && (restrictionNode == null);
347                  j++) {
348                 QName JavaDoc restrictionKind = Utils.getNodeQName(children.item(j));
349
350                 if ((restrictionKind != null)
351                         && restrictionKind.getLocalPart().equals("restriction")
352                         && Constants.isSchemaXSD(
353                                 restrictionKind.getNamespaceURI())) {
354                     restrictionNode = children.item(j);
355                 }
356             }
357
358             // The restriction node indicates the type being restricted
359
// (the base attribute contains this type).
360
// The base type must be a simple type, and not boolean
361
TypeEntry baseEType = null;
362
363             if (restrictionNode != null) {
364                 QName JavaDoc baseType = Utils.getTypeQName(restrictionNode,
365                         new BooleanHolder JavaDoc(), false);
366
367                 baseEType = symbolTable.getType(baseType);
368
369                 if (baseEType != null) {
370                     String JavaDoc javaName = baseEType.getName();
371
372                     if (javaName.equals("boolean")
373                             || !SchemaUtils.isSimpleSchemaType(
374                                     baseEType.getQName())) {
375                         baseEType = null;
376                     }
377                 }
378             }
379
380             // Process the enumeration elements underneath the restriction node
381
if ((baseEType != null) && (restrictionNode != null)) {
382                 Vector JavaDoc v = new Vector JavaDoc();
383                 NodeList JavaDoc enums = restrictionNode.getChildNodes();
384
385                 for (int i = 0; i < enums.getLength(); i++) {
386                     QName JavaDoc enumKind = Utils.getNodeQName(enums.item(i));
387
388                     if ((enumKind != null)
389                             && enumKind.getLocalPart().equals("enumeration")
390                             && Constants.isSchemaXSD(
391                                     enumKind.getNamespaceURI())) {
392
393                         // Put the enum value in the vector.
394
Node JavaDoc enumNode = enums.item(i);
395                         String JavaDoc value = Utils.getAttribute(enumNode, "value");
396
397                         if (value != null) {
398                             v.add(value);
399                         }
400                     }
401                 }
402
403                 // is this really an enumeration?
404
if (v.isEmpty()) {
405                     return null;
406                 }
407
408                 // The first element in the vector is the base type (an TypeEntry).
409
v.add(0, baseEType);
410
411                 return v;
412             }
413         }
414
415         return null;
416     }
417
418     /**
419      * Capitalize the first character of the name.
420      *
421      * @param name
422      * @return
423      */

424     public static String JavaDoc capitalizeFirstChar(String JavaDoc name) {
425
426         if ((name == null) || name.equals("")) {
427             return name;
428         }
429
430         char start = name.charAt(0);
431
432         if (Character.isLowerCase(start)) {
433             start = Character.toUpperCase(start);
434
435             return start + name.substring(1);
436         }
437
438         return name;
439     } // capitalizeFirstChar
440

441     /**
442      * Prepend an underscore to the name
443      *
444      * @param name
445      * @return
446      */

447     public static String JavaDoc addUnderscore(String JavaDoc name) {
448
449         if ((name == null) || name.equals("")) {
450             return name;
451         }
452
453         return "_" + name;
454     }
455
456     /**
457      * Map an XML name to a valid Java identifier
458      *
459      * @param name
460      * @return
461      */

462     public static String JavaDoc xmlNameToJava(String JavaDoc name) {
463
464         // NOTE: This method should really go away and all callers should call
465
// JavaUtils.xmlNameToJava directly. But there are a lot of them and I wanted
466
// to keep the changes to a minimum. Besides, these are static methods so the should
467
// be inlined.
468
return JavaUtils.xmlNameToJava(name);
469     }
470
471     /**
472      * Map an XML name to a valid Java identifier w/ capitolized first letter
473      *
474      * @param name
475      * @return
476      */

477     public static String JavaDoc xmlNameToJavaClass(String JavaDoc name) {
478         return capitalizeFirstChar(xmlNameToJava(name));
479     }
480
481     /**
482      * Method makePackageName
483      *
484      * @param namespace
485      * @return
486      */

487     public static String JavaDoc makePackageName(String JavaDoc namespace) {
488
489         String JavaDoc hostname = null;
490         String JavaDoc path = "";
491
492         // get the target namespace of the document
493
try {
494             URL JavaDoc u = new URL JavaDoc(namespace);
495
496             hostname = u.getHost();
497             path = u.getPath();
498         } catch (MalformedURLException JavaDoc e) {
499             if (namespace.indexOf(":") > -1) {
500                 hostname = namespace.substring(namespace.indexOf(":") + 1);
501
502                 if (hostname.indexOf("/") > -1) {
503                     hostname = hostname.substring(0, hostname.indexOf("/"));
504                 }
505             } else {
506                 hostname = namespace;
507             }
508         }
509
510         // if we didn't file a hostname, bail
511
if (hostname == null) {
512             return null;
513         }
514
515         // convert illegal java identifier
516
hostname = hostname.replace('-', '_');
517         path = path.replace('-', '_');
518
519         // chomp off last forward slash in path, if necessary
520
if ((path.length() > 0) && (path.charAt(path.length() - 1) == '/')) {
521             path = path.substring(0, path.length() - 1);
522         }
523
524         // tokenize the hostname and reverse it
525
StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(hostname, ".:");
526         String JavaDoc[] words = new String JavaDoc[st.countTokens()];
527
528         for (int i = 0; i < words.length; ++i) {
529             words[i] = st.nextToken();
530         }
531
532         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(namespace.length());
533
534         for (int i = words.length - 1; i >= 0; --i) {
535             addWordToPackageBuffer(sb, words[i], (i == words.length - 1));
536         }
537
538         // tokenize the path
539
StringTokenizer JavaDoc st2 = new StringTokenizer JavaDoc(path, "/");
540
541         while (st2.hasMoreTokens()) {
542             addWordToPackageBuffer(sb, st2.nextToken(), false);
543         }
544
545         return sb.toString();
546     }
547
548     /**
549      * Massage <tt>word</tt> into a form suitable for use in a Java package name.
550      * Append it to the target string buffer with a <tt>.</tt> delimiter iff
551      * <tt>word</tt> is not the first word in the package name.
552      *
553      * @param sb the buffer to append to
554      * @param word the word to append
555      * @param firstWord a flag indicating whether this is the first word
556      */

557     private static void addWordToPackageBuffer(StringBuffer JavaDoc sb, String JavaDoc word,
558                                                boolean firstWord) {
559
560         if (JavaUtils.isJavaKeyword(word)) {
561             word = JavaUtils.makeNonJavaKeyword(word);
562         }
563
564         // separate with dot after the first word
565
if (!firstWord) {
566             sb.append('.');
567         }
568
569         // prefix digits with underscores
570
if (Character.isDigit(word.charAt(0))) {
571             sb.append('_');
572         }
573
574         // replace periods with underscores
575
if (word.indexOf('.') != -1) {
576             char[] buf = word.toCharArray();
577
578             for (int i = 0; i < word.length(); i++) {
579                 if (buf[i] == '.') {
580                     buf[i] = '_';
581                 }
582             }
583
584             word = new String JavaDoc(buf);
585         }
586
587         sb.append(word);
588     }
589
590     /**
591      * Query Java Local Name
592      *
593      * @param fullName
594      * @return
595      */

596     public static String JavaDoc getJavaLocalName(String JavaDoc fullName) {
597         return fullName.substring(fullName.lastIndexOf('.') + 1);
598     } // getJavaLocalName
599

600     /**
601      * Query Java Package Name
602      *
603      * @param fullName
604      * @return
605      */

606     public static String JavaDoc getJavaPackageName(String JavaDoc fullName) {
607
608         if (fullName.lastIndexOf('.') > 0) {
609             return fullName.substring(0, fullName.lastIndexOf('.'));
610         } else {
611             return "";
612         }
613     } // getJavaPackageName
614

615     /**
616      * Does the given file already exist in the given namespace?
617      *
618      * @param name
619      * @param namespace
620      * @param namespaces
621      * @return
622      * @throws IOException
623      */

624     public static boolean fileExists(
625             String JavaDoc name, String JavaDoc namespace, Namespaces namespaces)
626             throws IOException JavaDoc {
627
628         String JavaDoc packageName = namespaces.getAsDir(namespace);
629         String JavaDoc fullName = packageName + name;
630
631         return new File JavaDoc(fullName).exists();
632     } // fileExists
633

634     /** A simple map of the primitive types and their holder objects */
635     private static HashMap JavaDoc TYPES = new HashMap JavaDoc(7);
636
637     static {
638         TYPES.put("int", "java.lang.Integer");
639         TYPES.put("float", "java.lang.Float");
640         TYPES.put("boolean", "java.lang.Boolean");
641         TYPES.put("double", "java.lang.Double");
642         TYPES.put("byte", "java.lang.Byte");
643         TYPES.put("short", "java.lang.Short");
644         TYPES.put("long", "java.lang.Long");
645     }
646
647     /**
648      * Return a string with "var" wrapped as an Object type if needed
649      *
650      * @param type
651      * @param var
652      * @return
653      */

654     public static String JavaDoc wrapPrimitiveType(TypeEntry type, String JavaDoc var) {
655
656         String JavaDoc objType = (type == null)
657                 ? null
658                 : (String JavaDoc) TYPES.get(type.getName());
659
660         if (objType != null) {
661             return "new " + objType + "(" + var + ")";
662         } else if ((type != null) && type.getName().equals("byte[]")
663                 && type.getQName().getLocalPart().equals("hexBinary")) {
664
665             // Need to wrap byte[] in special HexBinary object to get the correct serialization
666
return "new org.apache.axis.types.HexBinary(" + var + ")";
667         } else {
668             return var;
669         }
670     } // wrapPrimitiveType
671

672     /**
673      * Return the Object variable 'var' cast to the appropriate type
674      * doing the right thing for the primitive types.
675      *
676      * @param var
677      * @return
678      */

679     public static String JavaDoc getResponseString(Parameter param,
680                                            String JavaDoc var) {
681         if (param.getType() == null) {
682             return ";";
683         }
684         String JavaDoc typeName = param.getType().getName();
685         MimeInfo mimeInfo = param.getMIMEInfo();
686
687         String JavaDoc mimeType = (mimeInfo == null)
688                 ? null
689                 : mimeInfo.getType();
690         String JavaDoc mimeDimensions = (mimeInfo == null)
691                 ? ""
692                 : mimeInfo.getDimensions();
693
694         if (mimeType != null) {
695             if (mimeType.equals("image/gif") || mimeType.equals("image/jpeg")) {
696                 return "(java.awt.Image" + mimeDimensions + ") " + var + ";";
697             } else if (mimeType.equals("text/plain")) {
698                 return "(java.lang.String" + mimeDimensions + ") " + var + ";";
699             } else if (mimeType.equals("text/xml")
700                     || mimeType.equals("application/xml")) {
701                 return "(javax.xml.transform.Source" + mimeDimensions + ") "
702                         + var + ";";
703             } else if (mimeType.startsWith("multipart/")) {
704                 return "(javax.mail.internet.MimeMultipart" + mimeDimensions
705                         + ") " + var + ";";
706             } else if (mimeType.startsWith("application/octetstream")
707                     || mimeType.startsWith("application/octet-stream")) {
708                 //the hyphenated test is new and RFC compliant; the old one was retained
709
//for backwards compatibility.
710
return "(org.apache.axis.attachments.OctetStream"
711                         + mimeDimensions + ") " + var + ";";
712             } else {
713                 return "(javax.activation.DataHandler" + mimeDimensions + ") "
714                         + var + ";";
715             }
716         }
717
718         String JavaDoc objType = (String JavaDoc) TYPES.get(typeName);
719
720         if (objType != null) {
721             // If minOccurs="0" and singular or array with nillable underlying
722
// type get the corresponding wrapper type.
723
if ((param.isOmittable() && param.getType().getDimensions().equals(""))
724                 || param.getType().getUnderlTypeNillable()) {
725
726                 typeName = getWrapperType(param.getType());
727             } else {
728                 return "((" + objType + ") " + var + ")." + typeName +
729                         "Value();";
730             }
731         }
732
733         return "(" + typeName + ") " + var + ";";
734     } // getResponseString
735

736     /**
737      * Method isPrimitiveType
738      *
739      * @param type
740      * @return
741      */

742     public static boolean isPrimitiveType(TypeEntry type) {
743         return TYPES.get(type.getName()) != null;
744     } // isPrimitiveType
745

746     /**
747      * Return a "wrapper" type for the given type name. In other words,
748      * if it's a primitive type ("int") return the java wrapper class
749      * ("java.lang.Integer"). Otherwise return the type name itself.
750      *
751      * @param type
752      * @return the name of a java wrapper class for the type, or the type's
753      * name if it's not primitive.
754      */

755     public static String JavaDoc getWrapperType(String JavaDoc type) {
756         String JavaDoc ret = (String JavaDoc)TYPES.get(type);
757         return (ret == null) ? type : ret;
758     }
759
760     /**
761      * Returns a "wrapper" type for the given TypeEntry.
762      *
763      * @param type
764      * @return the name of a java wrapper class for the type, or the type's
765      * name if it's not a primitive.
766      */

767     public static String JavaDoc getWrapperType(TypeEntry type) {
768         String JavaDoc dims = type.getDimensions();
769         if (!dims.equals("")) {
770
771             TypeEntry te = type.getRefType();
772             if (te != null
773                 && !te.getDimensions().equals("")) {
774
775                 return getWrapperType(te) + dims;
776             }
777             if (te instanceof BaseType
778                 || te instanceof DefinedElement
779                     && te.getRefType() instanceof BaseType) {
780
781                 return getWrapperType(te) + dims;
782             }
783         }
784         return getWrapperType(type.getName());
785     }
786
787     /**
788      * Return the operation QName. The namespace is determined from
789      * the soap:body namespace, if it exists, otherwise it is "".
790      *
791      * @param bindingOper the operation
792      * @param bEntry the symbol table binding entry
793      * @param symbolTable SymbolTable
794      * @return the operation QName
795      */

796     public static QName JavaDoc getOperationQName(BindingOperation bindingOper,
797                                           BindingEntry bEntry,
798                                           SymbolTable symbolTable) {
799
800         Operation operation = bindingOper.getOperation();
801         String JavaDoc operationName = operation.getName();
802
803         // For the wrapped case, use the part element's name...which is
804
// is the same as the operation name, but may have a different
805
// namespace ?
806
// example:
807
// <part name="paramters" element="ns:myelem">
808
if ((bEntry.getBindingStyle() == Style.DOCUMENT)
809                 && symbolTable.isWrapped()) {
810             Input input = operation.getInput();
811
812             if (input != null) {
813                 Map JavaDoc parts = input.getMessage().getParts();
814
815                 if ((parts != null) && !parts.isEmpty()) {
816                     Iterator JavaDoc i = parts.values().iterator();
817                     Part p = (Part) i.next();
818
819                     return p.getElementName();
820                 }
821             }
822         }
823
824         String JavaDoc ns = null;
825
826         // Get a namespace from the soap:body tag, if any
827
// example:
828
// <soap:body namespace="this_is_what_we_want" ..>
829
BindingInput bindInput = bindingOper.getBindingInput();
830
831         if (bindInput != null) {
832             Iterator JavaDoc it = bindInput.getExtensibilityElements().iterator();
833
834             while (it.hasNext()) {
835                 ExtensibilityElement elem = (ExtensibilityElement) it.next();
836
837                 if (elem instanceof SOAPBody) {
838                     SOAPBody body = (SOAPBody) elem;
839
840                     ns = body.getNamespaceURI();
841                     if (bEntry.getInputBodyType(operation) == Use.ENCODED && (ns == null || ns.length() == 0)) {
842                         log.warn(Messages.getMessage("badNamespaceForOperation00",
843                                 bEntry.getName(),
844                                 operation.getName()));
845
846                     }
847                     break;
848                 } else if (elem instanceof MIMEMultipartRelated) {
849                     Object JavaDoc part = null;
850                     javax.wsdl.extensions.mime.MIMEMultipartRelated mpr =
851                             (javax.wsdl.extensions.mime.MIMEMultipartRelated) elem;
852                     List JavaDoc l =
853                             mpr.getMIMEParts();
854
855                     for (int j = 0;
856                          (l != null) && (j < l.size()) && (part == null);
857                          j++) {
858                         javax.wsdl.extensions.mime.MIMEPart mp =
859                                 (javax.wsdl.extensions.mime.MIMEPart) l.get(j);
860                         List JavaDoc ll =
861                                 mp.getExtensibilityElements();
862
863                         for (int k = 0; (ll != null) && (k < ll.size())
864                                 && (part == null); k++) {
865                             part = ll.get(k);
866
867                             if (part instanceof SOAPBody) {
868                                 SOAPBody body = (SOAPBody) part;
869
870                                 ns = body.getNamespaceURI();
871                                 if (bEntry.getInputBodyType(operation) == Use.ENCODED && (ns == null || ns.length() == 0)) {
872                                     log.warn(Messages.getMessage("badNamespaceForOperation00",
873                                             bEntry.getName(),
874                                             operation.getName()));
875
876                                 }
877                                 break;
878                             } else {
879                                 part = null;
880                             }
881                         }
882                     }
883                 } else if (elem instanceof UnknownExtensibilityElement) {
884
885                     // TODO: After WSDL4J supports soap12, change this code
886
UnknownExtensibilityElement unkElement =
887                             (UnknownExtensibilityElement) elem;
888                     QName JavaDoc name =
889                             unkElement.getElementType();
890
891                     if (name.getNamespaceURI().equals(Constants.URI_WSDL12_SOAP)
892                             && name.getLocalPart().equals("body")) {
893                         ns = unkElement.getElement().getAttribute("namespace");
894                     }
895                 }
896             }
897         }
898
899         // If we didn't get a namespace from the soap:body, then
900
// use "". We should probably use the targetNamespace,
901
// but the target namespace of what? binding? portType?
902
// Also, we don't have enough info for to get it.
903
if (ns == null) {
904             ns = "";
905         }
906
907         return new QName JavaDoc(ns, operationName);
908     }
909
910     /**
911      * Return the SOAPAction (if any) of this binding operation
912      *
913      * @param bindingOper the operation to look at
914      * @return the SOAPAction or null if not found
915      */

916     public static String JavaDoc getOperationSOAPAction(BindingOperation bindingOper) {
917         // Find the SOAPAction.
918
List JavaDoc elems = bindingOper.getExtensibilityElements();
919         Iterator JavaDoc it = elems.iterator();
920         boolean found = false;
921         String JavaDoc action = null;
922
923         while (!found && it.hasNext()) {
924             ExtensibilityElement elem =
925                     (ExtensibilityElement) it.next();
926
927             if (elem instanceof SOAPOperation) {
928                 SOAPOperation soapOp = (SOAPOperation) elem;
929                 action = soapOp.getSoapActionURI();
930                 found = true;
931             } else if (elem instanceof UnknownExtensibilityElement) {
932
933                 // TODO: After WSDL4J supports soap12, change this code
934
UnknownExtensibilityElement unkElement =
935                         (UnknownExtensibilityElement) elem;
936                 QName JavaDoc name =
937                         unkElement.getElementType();
938
939                 if (name.getNamespaceURI().equals(
940                         Constants.URI_WSDL12_SOAP)
941                         && name.getLocalPart().equals("operation")) {
942                     action = unkElement.getElement().getAttribute(
943                                     "soapAction");
944                     found = true;
945                 }
946             }
947         }
948         return action;
949     }
950
951     /**
952      * Common code for generating a QName in emitted code. Note that there's
953      * no semicolon at the end, so we can use this in a variety of contexts.
954      *
955      * @param qname
956      * @return
957      */

958     public static String JavaDoc getNewQName(javax.xml.namespace.QName JavaDoc qname) {
959         return "new javax.xml.namespace.QName(\"" + qname.getNamespaceURI()
960                 + "\", \"" + qname.getLocalPart() + "\")";
961     }
962
963     public static String JavaDoc getNewQNameWithLastLocalPart(javax.xml.namespace.QName JavaDoc qname) {
964         return "new javax.xml.namespace.QName(\"" + qname.getNamespaceURI()
965                 + "\", \"" + getLastLocalPart(qname.getLocalPart()) + "\")";
966     }
967
968     /**
969      * Get the parameter type name. If this is a MIME type, then
970      * figure out the appropriate type from the MIME type, otherwise
971      * use the name of the type itself.
972      *
973      * @param parm
974      * @return
975      */

976     public static String JavaDoc getParameterTypeName(Parameter parm) {
977
978         String JavaDoc ret;
979
980         if (parm.getMIMEInfo() == null) {
981             ret = parm.getType().getName();
982
983             // If minOccurs="0" and singular or array with nillable underlying
984
// type get the corresponding wrapper type.
985
if ((parm.isOmittable() && parm.getType().getDimensions().equals(""))
986                 || parm.getType().getUnderlTypeNillable()) {
987
988                 ret = getWrapperType(parm.getType());
989             }
990         } else {
991             String JavaDoc mime = parm.getMIMEInfo().getType();
992
993             ret = JavaUtils.mimeToJava(mime);
994
995             if (ret == null) {
996                 ret = parm.getType().getName();
997             } else {
998                 ret += parm.getMIMEInfo().getDimensions();
999             }
1000        }
1001
1002        return ret;
1003    } // getParameterTypeName
1004

1005    /**
1006     * Get the QName that could be used in the xsi:type
1007     * when serializing an object for this parameter/return
1008     *
1009     * @param param is a parameter
1010     * @return the QName of the parameter's xsi type
1011     */

1012    public static QName JavaDoc getXSIType(Parameter param) {
1013
1014        if (param.getMIMEInfo() != null) {
1015            return getMIMETypeQName(param.getMIMEInfo().getType());
1016        }
1017
1018        return getXSIType(param.getType());
1019    } // getXSIType
1020

1021    /**
1022     * Get the QName that could be used in the xsi:type
1023     * when serializing an object of the given type.
1024     *
1025     * @param te is the type entry
1026     * @return the QName of the type's xsi type
1027     */

1028    public static QName JavaDoc getXSIType(TypeEntry te) {
1029
1030        QName JavaDoc xmlType = null;
1031
1032        // If the TypeEntry describes an Element, get
1033
// the referenced Type.
1034
if ((te != null) && (te instanceof Element)
1035                && (te.getRefType() != null)) {
1036            te = te.getRefType();
1037        }
1038
1039        // If the TypeEntry is a CollectionTE, use
1040
// the TypeEntry representing the component Type
1041
// So for example a parameter that takes a
1042
// collection type for
1043
// <element name="A" type="xsd:string" maxOccurs="unbounded"/>
1044
// will be
1045
// new ParameterDesc(<QName of A>, IN,
1046
// <QName of xsd:string>,
1047
// String[])
1048
if ((te != null) && (te instanceof CollectionTE)
1049                && (te.getRefType() != null)) {
1050            te = te.getRefType();
1051        }
1052
1053        if (te != null) {
1054            xmlType = te.getQName();
1055        }
1056
1057        return xmlType;
1058    }
1059
1060    /**
1061     * Given a MIME type, return the AXIS-specific type QName.
1062     *
1063     * @param mimeName the MIME type name
1064     * @return the AXIS-specific QName for the MIME type
1065     */

1066    public static QName JavaDoc getMIMETypeQName(String JavaDoc mimeName) {
1067
1068        if ("text/plain".equals(mimeName)) {
1069            return Constants.MIME_PLAINTEXT;
1070        } else if ("image/gif".equals(mimeName)
1071                || "image/jpeg".equals(mimeName)) {
1072            return Constants.MIME_IMAGE;
1073        } else if ("text/xml".equals(mimeName)
1074                || "applications/xml".equals(mimeName)) {
1075            return Constants.MIME_SOURCE;
1076        } else if ("application/octet-stream".equals(mimeName) ||
1077                   "application/octetstream".equals(mimeName)) {
1078            return Constants.MIME_OCTETSTREAM;
1079        } else if ((mimeName != null) && mimeName.startsWith("multipart/")) {
1080            return Constants.MIME_MULTIPART;
1081        } else {
1082            return Constants.MIME_DATA_HANDLER;
1083        }
1084    } // getMIMEType
1085

1086    /**
1087     * Are there any MIME parameters in the given binding?
1088     *
1089     * @param bEntry
1090     * @return
1091     */

1092    public static boolean hasMIME(BindingEntry bEntry) {
1093
1094        List JavaDoc operations = bEntry.getBinding().getBindingOperations();
1095
1096        for (int i = 0; i < operations.size(); ++i) {
1097            BindingOperation operation = (BindingOperation) operations.get(i);
1098
1099            if (hasMIME(bEntry, operation)) {
1100                return true;
1101            }
1102        }
1103
1104        return false;
1105    } // hasMIME
1106

1107    /**
1108     * Are there any MIME parameters in the given binding's operation?
1109     *
1110     * @param bEntry
1111     * @param operation
1112     * @return
1113     */

1114    public static boolean hasMIME(BindingEntry bEntry,
1115                                  BindingOperation operation) {
1116
1117        Parameters parameters = bEntry.getParameters(operation.getOperation());
1118
1119        if (parameters != null) {
1120            for (int idx = 0; idx < parameters.list.size(); ++idx) {
1121                Parameter p = (Parameter) parameters.list.get(idx);
1122
1123                if (p.getMIMEInfo() != null) {
1124                    return true;
1125                }
1126            }
1127        }
1128
1129        return false;
1130    } // hasMIME
1131

1132    /** Field constructorMap */
1133    private static HashMap JavaDoc constructorMap = new HashMap JavaDoc(50);
1134
1135    /** Field constructorThrowMap */
1136    private static HashMap JavaDoc constructorThrowMap = new HashMap JavaDoc(50);
1137
1138    static {
1139
1140        // Type maps to a valid initialization value for that type
1141
// Type var = new Type(arg)
1142
// Where "Type" is the key and "new Type(arg)" is the string stored
1143
// Used in emitting test cases and server skeletons.
1144
constructorMap.put("int", "0");
1145        constructorMap.put("float", "0");
1146        constructorMap.put("boolean", "true");
1147        constructorMap.put("double", "0");
1148        constructorMap.put("byte", "(byte)0");
1149        constructorMap.put("short", "(short)0");
1150        constructorMap.put("long", "0");
1151        constructorMap.put("java.lang.Boolean", "new java.lang.Boolean(false)");
1152        constructorMap.put("java.lang.Byte", "new java.lang.Byte((byte)0)");
1153        constructorMap.put("java.lang.Double", "new java.lang.Double(0)");
1154        constructorMap.put("java.lang.Float", "new java.lang.Float(0)");
1155        constructorMap.put("java.lang.Integer", "new java.lang.Integer(0)");
1156        constructorMap.put("java.lang.Long", "new java.lang.Long(0)");
1157        constructorMap.put("java.lang.Short", "new java.lang.Short((short)0)");
1158        constructorMap.put("java.math.BigDecimal",
1159                "new java.math.BigDecimal(0)");
1160        constructorMap.put("java.math.BigInteger",
1161                "new java.math.BigInteger(\"0\")");
1162        constructorMap.put("java.lang.Object", "new java.lang.String()");
1163        constructorMap.put("byte[]", "new byte[0]");
1164        constructorMap.put("java.util.Calendar",
1165                "java.util.Calendar.getInstance()");
1166        constructorMap.put(
1167                "javax.xml.namespace.QName",
1168                "new javax.xml.namespace.QName(\"http://double-double\", \"toil-and-trouble\")");
1169        constructorMap.put(
1170                "org.apache.axis.types.NonNegativeInteger",
1171                "new org.apache.axis.types.NonNegativeInteger(\"0\")");
1172        constructorMap.put("org.apache.axis.types.PositiveInteger",
1173                "new org.apache.axis.types.PositiveInteger(\"1\")");
1174        constructorMap.put(
1175                "org.apache.axis.types.NonPositiveInteger",
1176                "new org.apache.axis.types.NonPositiveInteger(\"0\")");
1177        constructorMap.put("org.apache.axis.types.NegativeInteger",
1178                "new org.apache.axis.types.NegativeInteger(\"-1\")");
1179
1180        // These constructors throw exception
1181
constructorThrowMap.put(
1182                "org.apache.axis.types.Time",
1183                "new org.apache.axis.types.Time(\"15:45:45.275Z\")");
1184        constructorThrowMap.put("org.apache.axis.types.UnsignedLong",
1185                "new org.apache.axis.types.UnsignedLong(0)");
1186        constructorThrowMap.put("org.apache.axis.types.UnsignedInt",
1187                "new org.apache.axis.types.UnsignedInt(0)");
1188        constructorThrowMap.put("org.apache.axis.types.UnsignedShort",
1189                "new org.apache.axis.types.UnsignedShort(0)");
1190        constructorThrowMap.put("org.apache.axis.types.UnsignedByte",
1191                "new org.apache.axis.types.UnsignedByte(0)");
1192        constructorThrowMap.put(
1193                "org.apache.axis.types.URI",
1194                "new org.apache.axis.types.URI(\"urn:testing\")");
1195        constructorThrowMap.put("org.apache.axis.types.Year",
1196                "new org.apache.axis.types.Year(2000)");
1197        constructorThrowMap.put("org.apache.axis.types.Month",
1198                "new org.apache.axis.types.Month(1)");
1199        constructorThrowMap.put("org.apache.axis.types.Day",
1200                "new org.apache.axis.types.Day(1)");
1201        constructorThrowMap.put("org.apache.axis.types.YearMonth",
1202                "new org.apache.axis.types.YearMonth(2000,1)");
1203        constructorThrowMap.put("org.apache.axis.types.MonthDay",
1204                "new org.apache.axis.types.MonthDay(1, 1)");
1205    }
1206
1207    /**
1208     * Return a constructor for the provided Parameter
1209     * This string will be suitable for assignment:
1210     * <p/>
1211     * Foo var = <i>string returned</i>
1212     * <p/>
1213     * Handles basic java types (int, float, etc), wrapper types (Integer, etc)
1214     * and certain java.math (BigDecimal, BigInteger) types.
1215     * Will also handle all Axis specific types (org.apache.axis.types.*)
1216     * <p/>
1217     * Caller should expect to wrap the construction in a try/catch block
1218     * if bThrow is set to <i>true</i>.
1219     *
1220     * @param param info about the parameter we need a constructor for
1221     * @param symbolTable used to lookup enumerations
1222     * @param bThrow set to true if contructor needs try/catch block
1223     * @return
1224     */

1225    public static String JavaDoc getConstructorForParam(Parameter param,
1226                                                SymbolTable symbolTable,
1227                                                BooleanHolder JavaDoc bThrow) {
1228
1229        String JavaDoc paramType = param.getType().getName();
1230        if (param.isOmittable()) {
1231            paramType = Utils.getWrapperType(paramType);
1232        }
1233        String JavaDoc mimeType = (param.getMIMEInfo() == null)
1234                ? null
1235                : param.getMIMEInfo().getType();
1236        String JavaDoc mimeDimensions = (param.getMIMEInfo() == null)
1237                ? ""
1238                : param.getMIMEInfo().getDimensions();
1239        String JavaDoc out = null;
1240
1241        // Handle mime types
1242
if (mimeType != null) {
1243            if (mimeType.equals("image/gif") || mimeType.equals("image/jpeg")) {
1244                return "null";
1245            } else if (mimeType.equals("text/xml")
1246                    || mimeType.equals("application/xml")) {
1247                if (mimeDimensions.length() <= 0) {
1248                    return "new javax.xml.transform.stream.StreamSource()";
1249                } else {
1250                    return "new javax.xml.transform.stream.StreamSource[0]";
1251                }
1252            } else if (mimeType.equals("application/octet-stream")||
1253                       mimeType.equals("application/octetstream")) {
1254                if (mimeDimensions.length() <= 0) {
1255                    return "new org.apache.axis.attachments.OctetStream()";
1256                } else {
1257                    return "new org.apache.axis.attachments.OctetStream[0]";
1258                }
1259            } else {
1260                return "new " + Utils.getParameterTypeName(param) + "()";
1261            }
1262        }
1263
1264        // Look up paramType in the table
1265
out = (String JavaDoc) constructorMap.get(paramType);
1266
1267        if (out != null) {
1268            return out;
1269        }
1270
1271        // Look up paramType in the table of constructors that can throw exceptions
1272
out = (String JavaDoc) constructorThrowMap.get(paramType);
1273
1274        if (out != null) {
1275            bThrow.value = true;
1276
1277            return out;
1278        }
1279
1280        // Handle arrays
1281
if (paramType.endsWith("[]")) {
1282            return "new " + JavaUtils.replace(paramType, "[]", "[0]");
1283        }
1284
1285        /** * We have some constructed type. */
1286
1287        // Check for enumeration
1288
Vector JavaDoc v = Utils.getEnumerationBaseAndValues(param.getType().getNode(),
1289                symbolTable);
1290
1291        if (v != null) {
1292
1293            // This constructed type is an enumeration. Use the first one.
1294
String JavaDoc enumeration =
1295                    (String JavaDoc) JavaEnumTypeWriter.getEnumValueIds(v).get(0);
1296
1297            return paramType + "." + enumeration;
1298        }
1299
1300        if(param.getType().getRefType()!= null){
1301            // Check for enumeration
1302
Vector JavaDoc v2 = Utils.getEnumerationBaseAndValues(param.getType().getRefType().getNode(),
1303                    symbolTable);
1304
1305            if (v2 != null) {
1306
1307                // This constructed type is an enumeration. Use the first one.
1308
String JavaDoc enumeration =
1309                        (String JavaDoc) JavaEnumTypeWriter.getEnumValueIds(v2).get(0);
1310
1311                return paramType + "." + enumeration;
1312            }
1313        }
1314
1315        // This constructed type is a normal type, instantiate it.
1316
return "new " + paramType + "()";
1317    }
1318
1319    public static boolean shouldEmit(TypeEntry type) {
1320        // 1) Don't register types that are base (primitive) types
1321
// or attributeGroups or xs:groups.
1322
// If the baseType != null && getRefType() != null this
1323
// is a simpleType that must be registered.
1324
// 2) Don't register the special types for collections
1325
// (indexed properties) or elements
1326
// 3) Don't register types that are not referenced
1327
// or only referenced in a literal context.
1328
return (!(((type.getBaseType() != null) && (type.getRefType() == null))
1329                || (type instanceof CollectionTE)
1330                || (type instanceof Element) || !type.isReferenced()
1331                || type.isOnlyLiteralReferenced()
1332                || ((type.getNode() != null)
1333                && (isXsNode(type.getNode(), "group") ||
1334                        isXsNode(type.getNode(), "attributeGroup")))));
1335    }
1336
1337
1338    /**
1339    * Determines if the DOM Node represents an xs:<node>
1340    */

1341    public static boolean isXsNode (Node JavaDoc node, String JavaDoc nameName)
1342    {
1343        return (node.getLocalName().equals(nameName)
1344                && Constants.isSchemaXSD (node.getNamespaceURI ()));
1345    }
1346
1347
1348    public static QName JavaDoc getItemQName(TypeEntry te) {
1349        if (te instanceof DefinedElement) {
1350            te = te.getRefType();
1351        }
1352        return te.getItemQName();
1353    }
1354
1355    public static QName JavaDoc getItemType(TypeEntry te) {
1356        if (te instanceof DefinedElement) {
1357            te = te.getRefType();
1358        }
1359        return te.getComponentType();
1360    }
1361} // class Utils
1362
Popular Tags