KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2  * The Apache Software License, Version 1.1
3  *
4  *
5  * Copyright (c) 2001-2003 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 "Axis" 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. For more
52  * information on the Apache Software Foundation, please see
53  * <http://www.apache.org/>.
54  */

55 package org.jboss.axis.wsdl.toJava;
56
57 import org.jboss.axis.Constants;
58 import org.jboss.axis.enums.Style;
59 import org.jboss.axis.utils.JavaUtils;
60 import org.jboss.axis.wsdl.symbolTable.BindingEntry;
61 import org.jboss.axis.wsdl.symbolTable.CollectionTE;
62 import org.jboss.axis.wsdl.symbolTable.Element;
63 import org.jboss.axis.wsdl.symbolTable.MessageEntry;
64 import org.jboss.axis.wsdl.symbolTable.MimeInfo;
65 import org.jboss.axis.wsdl.symbolTable.Parameter;
66 import org.jboss.axis.wsdl.symbolTable.Parameters;
67 import org.jboss.axis.wsdl.symbolTable.SchemaUtils;
68 import org.jboss.axis.wsdl.symbolTable.SymbolTable;
69 import org.jboss.axis.wsdl.symbolTable.TypeEntry;
70 import org.w3c.dom.Node JavaDoc;
71 import org.w3c.dom.NodeList JavaDoc;
72
73 import javax.wsdl.BindingInput;
74 import javax.wsdl.BindingOperation;
75 import javax.wsdl.Input;
76 import javax.wsdl.Message;
77 import javax.wsdl.Operation;
78 import javax.wsdl.Part;
79 import javax.wsdl.extensions.ExtensibilityElement;
80 import javax.wsdl.extensions.UnknownExtensibilityElement;
81 import javax.wsdl.extensions.mime.MIMEMultipartRelated;
82 import javax.wsdl.extensions.soap.SOAPBody;
83 import javax.xml.namespace.QName JavaDoc;
84 import javax.xml.rpc.holders.BooleanHolder JavaDoc;
85 import java.io.File JavaDoc;
86 import java.io.IOException JavaDoc;
87 import java.net.MalformedURLException JavaDoc;
88 import java.net.URL JavaDoc;
89 import java.util.HashMap JavaDoc;
90 import java.util.Iterator JavaDoc;
91 import java.util.List JavaDoc;
92 import java.util.Map JavaDoc;
93 import java.util.StringTokenizer JavaDoc;
94 import java.util.Vector JavaDoc;
95
96 public class Utils extends org.jboss.axis.wsdl.symbolTable.Utils
97 {
98    /**
99     * Given a type, return the Java mapping of that type's holder.
100     */

101    public static String JavaDoc holder(MimeInfo mimeInfo, TypeEntry type, Emitter emitter)
102    {
103       String JavaDoc mimeType = mimeInfo == null ? null : mimeInfo.getType();
104       String JavaDoc mimeDimensions = mimeInfo == null ? "" : mimeInfo.getDimensions();
105
106       // Add the holders that JAX-RPC forgot about - the MIME type holders.
107
if (mimeType != null)
108       {
109          if (mimeType.equals("image/gif") ||
110                  mimeType.equals("image/jpeg"))
111          {
112             return "org.jboss.axis.holders.ImageHolder" + mimeDimensions;
113          }
114          else if (mimeType.equals("text/plain"))
115          {
116             return "javax.xml.rpc.holders.StringHolder" + mimeDimensions;
117          }
118          else if (mimeType.startsWith("multipart/"))
119          {
120             return "org.jboss.axis.holders.MimeMultipartHolder" + mimeDimensions;
121          }
122          else if (mimeType.startsWith("application/octetstream")
123                  || mimeType.startsWith("application/octet-stream"))
124          {
125             return "org.jboss.axis.holders.OctetStreamHolder" + mimeDimensions;
126          }
127          else if (mimeType.equals("text/xml") ||
128                  mimeType.equals("application/xml"))
129          {
130             return "org.jboss.axis.holders.SourceHolder" + mimeDimensions;
131          }
132       }
133
134       String JavaDoc typeValue = type.getName();
135
136       // byte[] has a reserved holders
137
if (typeValue.equals("byte[]"))
138       {
139          return "javax.xml.rpc.holders.ByteArrayHolder";
140       }
141       // Anything else with [] gets its holder from the qname
142
else if (typeValue.endsWith("[]"))
143       {
144          String JavaDoc name = emitter.getJavaName(type.getQName());
145          // This could be a special QName for a indexed property.
146
// If so, change the [] to Array.
147
name = JavaUtils.replace(name, "[]", "Array");
148          name = addPackageName(name, "holders");
149          return name + "Holder";
150       }
151       // String also has a reserved holder
152
else if (typeValue.equals("String"))
153       {
154          return "javax.xml.rpc.holders.StringHolder";
155       }
156       else if (typeValue.equals("java.lang.String"))
157       {
158          return "javax.xml.rpc.holders.StringHolder";
159       }
160       // Object also has a reserved holder
161
else if (typeValue.equals("Object"))
162       {
163          return "javax.xml.rpc.holders.ObjectHolder";
164       }
165       else if (typeValue.equals("java.lang.Object"))
166       {
167          return "javax.xml.rpc.holders.ObjectHolder";
168       }
169       // Java primitive types have reserved holders
170
else if (typeValue.equals("int")
171               || typeValue.equals("long")
172               || typeValue.equals("short")
173               || typeValue.equals("float")
174               || typeValue.equals("double")
175               || typeValue.equals("boolean")
176               || typeValue.equals("byte"))
177       {
178          return "javax.xml.rpc.holders." + capitalizeFirstChar(typeValue) + "Holder";
179       }
180       // Java language classes have reserved holders (with ClassHolder)
181
else if (typeValue.startsWith("java.lang."))
182       {
183          return "javax.xml.rpc.holders" +
184                  typeValue.substring(typeValue.lastIndexOf(".")) +
185                  "WrapperHolder";
186       }
187       else if (typeValue.indexOf(".") < 0)
188       {
189          return "javax.xml.rpc.holders" +
190                  typeValue +
191                  "WrapperHolder";
192       }
193       // The classes have reserved holders because they
194
// represent schema/soap encoding primitives
195
else if (typeValue.equals("java.math.BigDecimal"))
196       {
197          return "javax.xml.rpc.holders.BigDecimalHolder";
198       }
199       else if (typeValue.equals("java.math.BigInteger"))
200       {
201          return "javax.xml.rpc.holders.BigIntegerHolder";
202       }
203       else if (typeValue.equals("java.util.Date"))
204       {
205          return "org.jboss.axis.holders.DateHolder";
206       }
207       else if (typeValue.equals("java.util.Calendar"))
208       {
209          return "javax.xml.rpc.holders.CalendarHolder";
210       }
211       else if (typeValue.equals("javax.xml.namespace.QName"))
212       {
213          return "javax.xml.rpc.holders.QNameHolder";
214       }
215       else if (typeValue.equals("javax.activation.DataHandler"))
216       {
217          return "org.jboss.axis.holders.DataHandlerHolder";
218       }
219       // Check for Axis specific types and return their holders
220
else if (typeValue.startsWith("org.jboss.axis.types."))
221       {
222          int i = typeValue.lastIndexOf('.');
223          String JavaDoc t = typeValue.substring(i + 1);
224          return "org.jboss.axis.holders." + t + "Holder";
225       }
226       // For everything else add "holders" package and append
227
// holder to the class name.
228
else
229       {
230          return addPackageName(typeValue, "holders") + "Holder";
231       }
232    } // holder
233

234    /**
235     * Add package to name
236     *
237     * @param className full name of the class.
238     * @param newPkg name of the package to append
239     * @return String name with package name added
240     */

241    public static String JavaDoc addPackageName(String JavaDoc className, String JavaDoc newPkg)
242    {
243       int index = className.lastIndexOf(".");
244       if (index >= 0)
245       {
246          return className.substring(0, index)
247                  + "." + newPkg
248                  + className.substring(index);
249       }
250       else
251       {
252          return newPkg + "." + className;
253       }
254    }
255
256    /**
257     * Given a fault message, return the fully qualified Java class name
258     * of the exception to be generated from this fault
259     *
260     * @param faultMessage The WSDL fault message
261     * @param symbolTable the current symbol table
262     * @return A Java class name for the fault
263     */

264    public static String JavaDoc getFullExceptionName(Message faultMessage,
265                                              SymbolTable symbolTable)
266    {
267       MessageEntry me = symbolTable.getMessageEntry(faultMessage.getQName());
268       return (String JavaDoc)me.getDynamicVar(JavaGeneratorFactory.EXCEPTION_CLASS_NAME);
269    } // getFullExceptionName
270

271    /**
272     * Given a fault message, return the XML type of the exception data.
273     *
274     * @param faultMessage The WSDL fault message object
275     * @param symbolTable the current symbol table
276     * @return A QName for the XML type of the data
277     */

278    public static QName JavaDoc getFaultDataType(Message faultMessage,
279                                         SymbolTable symbolTable)
280    {
281       MessageEntry me = symbolTable.getMessageEntry(faultMessage.getQName());
282       return (QName JavaDoc)me.getDynamicVar(JavaGeneratorFactory.EXCEPTION_DATA_TYPE);
283    } // getFaultDataType
284

285    /**
286     * Given a fault message, return TRUE if the fault is a complex type fault
287     *
288     * @param faultMessage The WSDL fault message object
289     * @param symbolTable the current symbol table
290     * @return A Java class name for the fault
291     */

292    public static boolean isFaultComplex(Message faultMessage,
293                                         SymbolTable symbolTable)
294    {
295       MessageEntry me = symbolTable.getMessageEntry(faultMessage.getQName());
296       Boolean JavaDoc ret = (Boolean JavaDoc)me.getDynamicVar(JavaGeneratorFactory.COMPLEX_TYPE_FAULT);
297       if (ret != null)
298       {
299          return ret.booleanValue();
300       }
301       else
302       {
303          return false;
304       }
305    } // isFaultComplex
306

307    /**
308     * If the specified node represents a supported JAX-RPC enumeration,
309     * a Vector is returned which contains the base type and the enumeration values.
310     * The first element in the vector is the base type (an TypeEntry).
311     * Subsequent elements are values (Strings).
312     * If this is not an enumeration, null is returned.
313     */

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

418    public static String JavaDoc capitalizeFirstChar(String JavaDoc name)
419    {
420       if (name == null || name.equals(""))
421          return name;
422
423       char start = name.charAt(0);
424
425       if (Character.isLowerCase(start))
426       {
427          start = Character.toUpperCase(start);
428          return start + name.substring(1);
429       }
430       return name;
431    } // capitalizeFirstChar
432

433    /**
434     * Prepend an underscore to the name
435     */

436    public static String JavaDoc addUnderscore(String JavaDoc name)
437    {
438       if (name == null || name.equals(""))
439          return name;
440       return "_" + name;
441    }
442
443    /**
444     * Map an XML name to a valid Java identifier
445     */

446    public static String JavaDoc xmlNameToJava(String JavaDoc name)
447    {
448       // NOTE: This method should really go away and all callers should call
449
// JavaUtils.xmlNameToJava directly. But there are a lot of them and I wanted
450
// to keep the changes to a minimum. Besides, these are static methods so the should
451
// be inlined.
452
return JavaUtils.xmlNameToJava(name);
453    }
454
455    /**
456     * Map an XML name to a valid Java identifier w/ capitolized first letter
457     */

458    public static String JavaDoc xmlNameToJavaClass(String JavaDoc name)
459    {
460       return capitalizeFirstChar(xmlNameToJava(name));
461    }
462
463    public static String JavaDoc makePackageName(String JavaDoc namespace)
464    {
465       String JavaDoc hostname = null;
466       String JavaDoc path = "";
467
468       // get the target namespace of the document
469
try
470       {
471          URL JavaDoc u = new URL JavaDoc(namespace);
472          hostname = u.getHost();
473          path = u.getPath();
474       }
475       catch (MalformedURLException JavaDoc e)
476       {
477          if (namespace.indexOf(":") > -1)
478          {
479             hostname = namespace.substring(namespace.indexOf(":") + 1);
480             if (hostname.indexOf("/") > -1)
481                hostname = hostname.substring(0, hostname.indexOf("/"));
482          }
483          else
484          {
485             hostname = namespace;
486          }
487       }
488
489       // if we didn't file a hostname, bail
490
if (hostname == null)
491       {
492          return null;
493       }
494
495       //convert illegal java identifier
496
hostname = hostname.replace('-', '_');
497       path = path.replace('-', '_');
498
499       // chomp off last forward slash in path, if necessary
500
if (path.length() > 0 && path.charAt(path.length() - 1) == '/')
501       {
502          path = path.substring(0, path.length() - 1);
503       }
504
505       // tokenize the hostname and reverse it
506
StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(hostname, ".:");
507       String JavaDoc[] words = new String JavaDoc[st.countTokens()];
508       for (int i = 0; i < words.length; ++i)
509          words[i] = st.nextToken();
510
511       StringBuffer JavaDoc sb = new StringBuffer JavaDoc(namespace.length());
512       for (int i = words.length - 1; i >= 0; --i)
513       {
514          addWordToPackageBuffer(sb, words[i], (i == words.length - 1));
515       }
516
517       // tokenize the path
518
StringTokenizer JavaDoc st2 = new StringTokenizer JavaDoc(path, "/");
519       while (st2.hasMoreTokens())
520       {
521          addWordToPackageBuffer(sb, st2.nextToken(), false);
522       }
523       return sb.toString();
524    }
525
526    /**
527     * Massage <tt>word</tt> into a form suitable for use in a Java package name.
528     * Append it to the target string buffer with a <tt>.</tt> delimiter iff
529     * <tt>word</tt> is not the first word in the package name.
530     *
531     * @param sb the buffer to append to
532     * @param word the word to append
533     * @param firstWord a flag indicating whether this is the first word
534     */

535    private static void addWordToPackageBuffer(StringBuffer JavaDoc sb, String JavaDoc word, boolean firstWord)
536    {
537       if (JavaUtils.isJavaKeyword(word))
538       {
539          word = JavaUtils.makeNonJavaKeyword(word);
540       }
541       // separate with dot after the first word
542
if (!firstWord)
543          sb.append('.');
544
545       // prefix digits with underscores
546
if (Character.isDigit(word.charAt(0)))
547          sb.append('_');
548
549       // replace periods with underscores
550
if (word.indexOf('.') != -1)
551       {
552          char[] buf = word.toCharArray();
553          for (int i = 0; i < word.length(); i++)
554          {
555             if (buf[i] == '.')
556             {
557                buf[i] = '_';
558             }
559          }
560          word = new String JavaDoc(buf);
561       }
562       sb.append(word);
563    }
564
565    /**
566     * Query Java Local Name
567     */

568    public static String JavaDoc getJavaLocalName(String JavaDoc fullName)
569    {
570       return fullName.substring(fullName.lastIndexOf('.') + 1);
571    } // getJavaLocalName
572

573    /**
574     * Query Java Package Name
575     */

576    public static String JavaDoc getJavaPackageName(String JavaDoc fullName)
577    {
578       if (fullName.lastIndexOf('.') > 0)
579       {
580          return fullName.substring(0, fullName.lastIndexOf('.'));
581       }
582       else
583       {
584          return "";
585       }
586    } // getJavaPackageName
587

588    /**
589     * Does the given file already exist in the given namespace?
590     */

591    public static boolean fileExists(String JavaDoc name, String JavaDoc namespace,
592                                     Namespaces namespaces) throws IOException JavaDoc
593    {
594       String JavaDoc packageName = namespaces.getAsDir(namespace);
595       String JavaDoc fullName = packageName + name;
596       return new File JavaDoc(fullName).exists();
597    } // fileExists
598

599    /**
600     * A simple map of the primitive types and their holder objects
601     */

602    private static HashMap JavaDoc TYPES = new HashMap JavaDoc(7);
603
604    static
605    {
606       TYPES.put("int", "java.lang.Integer");
607       TYPES.put("float", "java.lang.Float");
608       TYPES.put("boolean", "java.lang.Boolean");
609       TYPES.put("double", "java.lang.Double");
610       TYPES.put("byte", "java.lang.Byte");
611       TYPES.put("short", "java.lang.Short");
612       TYPES.put("long", "java.lang.Long");
613    }
614
615    /**
616     * Return a string with "var" wrapped as an Object type if needed
617     */

618    public static String JavaDoc wrapPrimitiveType(TypeEntry type, String JavaDoc var)
619    {
620       String JavaDoc objType = type == null ? null : (String JavaDoc)TYPES.get(type.getName());
621       if (objType != null)
622       {
623          return "new " + objType + "(" + var + ")";
624       }
625       else if (type != null &&
626               type.getName().equals("byte[]") &&
627               type.getQName().getLocalPart().equals("hexBinary"))
628       {
629          // Need to wrap byte[] in special HexBinary object to get the correct serialization
630
return "new org.jboss.axis.types.HexBinary(" + var + ")";
631       }
632       else
633       {
634          return var;
635       }
636    } // wrapPrimitiveType
637

638    /**
639     * Return the Object variable 'var' cast to the appropriate type
640     * doing the right thing for the primitive types.
641     */

642    public static String JavaDoc getResponseString(TypeEntry type, MimeInfo mimeInfo,
643                                           String JavaDoc var)
644    {
645       String JavaDoc mimeType = mimeInfo == null ? null : mimeInfo.getType();
646       String JavaDoc mimeDimensions = mimeInfo == null ? "" : mimeInfo.getDimensions();
647       if (type == null)
648       {
649          return ";";
650       }
651       else if (mimeType != null)
652       {
653          if (mimeType.equals("image/jpeg"))
654          {
655             return "(java.awt.Image" + mimeDimensions + ") " + var + ";";
656          }
657          else if (mimeType.equals("text/plain"))
658          {
659             return "(java.lang.String" + mimeDimensions + ") " + var + ";";
660          }
661          else if (mimeType.equals("text/xml") ||
662                  mimeType.equals("application/xml"))
663          {
664             return "(javax.xml.transform.Source" + mimeDimensions + ") " + var + ";";
665          }
666          else if (mimeType.startsWith("multipart/"))
667          {
668             return "(javax.mail.internet.MimeMultipart" + mimeDimensions + ") " + var + ";";
669          }
670          else if (mimeType.startsWith("application/octetstream"))
671          {
672             return "(org.jboss.axis.attachments.OctetStream" + mimeDimensions + ") " + var + ";";
673          }
674          else
675          {
676             return "(" + type.getName() + ") " + var + ";";
677          }
678       }
679       else
680       {
681          String JavaDoc objType = (String JavaDoc)TYPES.get(type.getName());
682          if (objType != null)
683          {
684             return "((" + objType + ") " + var + ")." + type.getName() + "Value();";
685          }
686          else
687          {
688             return "(" + type.getName() + ") " + var + ";";
689          }
690       }
691    } // getResponseString
692

693    public static boolean isPrimitiveType(TypeEntry type)
694    {
695       return TYPES.get(type.getName()) != null;
696    } // isPrimitiveType
697

698    /**
699     * Return the operation QName. The namespace is determined from
700     * the soap:body namespace, if it exists, otherwise it is "".
701     *
702     * @param bindingOper the operation
703     * @param bEntry the symbol table binding entry
704     * @param symbolTable SymbolTable
705     * @return the operation QName
706     */

707    public static QName JavaDoc getOperationQName(BindingOperation bindingOper,
708                                          BindingEntry bEntry,
709                                          SymbolTable symbolTable)
710    {
711
712       Operation operation = bindingOper.getOperation();
713       String JavaDoc operationName = operation.getName();
714
715       // For the wrapped case, use the part element's name...which is
716
// is the same as the operation name, but may have a different
717
// namespace ?
718
// example:
719
// <part name="paramters" element="ns:myelem">
720
if (bEntry.getBindingStyle() == Style.DOCUMENT &&
721               symbolTable.isWrapped())
722       {
723          Input input = operation.getInput();
724          if (input != null)
725          {
726             Map JavaDoc parts = input.getMessage().getParts();
727             if (parts != null && !parts.isEmpty())
728             {
729                Iterator JavaDoc i = parts.values().iterator();
730                Part p = (Part)i.next();
731                return p.getElementName();
732             }
733          }
734       }
735
736       String JavaDoc ns = null;
737
738       // Get a namespace from the soap:body tag, if any
739
// example:
740
// <soap:body namespace="this_is_what_we_want" ..>
741
BindingInput bindInput = bindingOper.getBindingInput();
742       if (bindInput != null)
743       {
744          Iterator JavaDoc it = bindInput.getExtensibilityElements().iterator();
745          while (it.hasNext())
746          {
747             ExtensibilityElement elem = (ExtensibilityElement)it.next();
748             if (elem instanceof SOAPBody)
749             {
750                SOAPBody body = (SOAPBody)elem;
751                ns = body.getNamespaceURI();
752                break;
753             }
754             else if (elem instanceof MIMEMultipartRelated)
755             {
756                Object JavaDoc part = null;
757                javax.wsdl.extensions.mime.MIMEMultipartRelated mpr =
758                        (javax.wsdl.extensions.mime.MIMEMultipartRelated)elem;
759                List JavaDoc l = mpr.getMIMEParts();
760                for (int j = 0; l != null && j < l.size() && part == null; j++)
761                {
762                   javax.wsdl.extensions.mime.MIMEPart mp = (javax.wsdl.extensions.mime.MIMEPart)l.get(j);
763                   List JavaDoc ll = mp.getExtensibilityElements();
764                   for (int k = 0; ll != null && k < ll.size() && part == null; k++)
765                   {
766                      part = ll.get(k);
767                      if (part instanceof SOAPBody)
768                      {
769                         SOAPBody body = (SOAPBody)part;
770                         ns = body.getNamespaceURI();
771                         break;
772                      }
773                      else
774                      {
775                         part = null;
776                      }
777                   }
778                }
779             }
780             else if (elem instanceof UnknownExtensibilityElement)
781             {
782                //TODO: After WSDL4J supports soap12, change this code
783
UnknownExtensibilityElement unkElement = (UnknownExtensibilityElement)elem;
784                QName JavaDoc name = unkElement.getElementType();
785                if (name.getNamespaceURI().equals(Constants.URI_WSDL12_SOAP) &&
786                        name.getLocalPart().equals("body"))
787                {
788                   ns = unkElement.getElement().getAttribute("namespace");
789                }
790             }
791          }
792       }
793
794       // If we didn't get a namespace from the soap:body, then
795
// use "". We should probably use the targetNamespace,
796
// but the target namespace of what? binding? portType?
797
// Also, we don't have enough info for to get it.
798
if (ns == null)
799       {
800          ns = "";
801       }
802
803       return new QName JavaDoc(ns, operationName);
804    }
805
806    /**
807     * Common code for generating a QName in emitted code. Note that there's
808     * no semicolon at the end, so we can use this in a variety of contexts.
809     */

810    public static String JavaDoc getNewQName(javax.xml.namespace.QName JavaDoc qname)
811    {
812       return "new javax.xml.namespace.QName(\"" +
813               qname.getNamespaceURI() + "\", \"" +
814               qname.getLocalPart() + "\")";
815    }
816
817    /**
818     * Get the parameter type name. If this is a MIME type, then
819     * figure out the appropriate type from the MIME type, otherwise
820     * use the name of the type itself.
821     */

822    public static String JavaDoc getParameterTypeName(Parameter parm)
823    {
824       String JavaDoc ret;
825       if (parm.getMIMEInfo() == null)
826       {
827          ret = parm.getType().getName();
828       }
829       else
830       {
831          String JavaDoc mime = parm.getMIMEInfo().getType();
832          ret = JavaUtils.mimeToJava(mime);
833          if (ret == null)
834          {
835             ret = parm.getType().getName();
836          }
837          else
838          {
839             ret += parm.getMIMEInfo().getDimensions();
840          }
841       }
842       return ret;
843    } // getParameterTypeName
844

845    /**
846     * Get the QName that could be used in the xsi:type
847     * when serializing an object for this parameter/return
848     *
849     * @param param is a parameter
850     * @return the QName of the parameter's xsi type
851     */

852    public static QName JavaDoc getXSIType(Parameter param)
853    {
854       if (param.getMIMEInfo() != null)
855       {
856          return getMIMETypeQName(param.getMIMEInfo().getType());
857       }
858       return getXSIType(param.getType());
859    } // getXSIType
860

861    /**
862     * Get the QName that could be used in the xsi:type
863     * when serializing an object of the given type.
864     *
865     * @param te is the type entry
866     * @return the QName of the type's xsi type
867     */

868    public static QName JavaDoc getXSIType(TypeEntry te)
869    {
870       QName JavaDoc xmlType = null;
871
872       // If the TypeEntry describes an Element, get
873
// the referenced Type.
874
if (te != null &&
875               te instanceof Element &&
876               te.getRefType() != null)
877       {
878          te = te.getRefType();
879       }
880       // If the TypeEntry is a CollectionTE, use
881
// the TypeEntry representing the component Type
882
// So for example a parameter that takes a
883
// collection type for
884
// <element name="A" type="xsd:string" maxOccurs="unbounded"/>
885
// will be
886
// new ParameterDesc(<QName of A>, IN,
887
// <QName of xsd:string>,
888
// String[])
889
if (te != null &&
890               te instanceof CollectionTE &&
891               te.getRefType() != null)
892       {
893          te = te.getRefType();
894       }
895       if (te != null)
896       {
897          xmlType = te.getQName();
898       }
899       return xmlType;
900    }
901
902    /**
903     * Given a MIME type, return the AXIS-specific type QName.
904     *
905     * @param mimeName the MIME type name
906     * @return the AXIS-specific QName for the MIME type
907     */

908    public static QName JavaDoc getMIMETypeQName(String JavaDoc mimeName)
909    {
910       if ("text/plain".equals(mimeName))
911       {
912          return Constants.MIME_PLAINTEXT;
913       }
914       else if ("image/gif".equals(mimeName) || "image/jpeg".equals(mimeName))
915       {
916          return Constants.MIME_IMAGE;
917       }
918       else if ("text/xml".equals(mimeName) || "application/xml".equals(mimeName))
919       {
920          return Constants.MIME_SOURCE;
921       }
922       else if ("application/octetstream".equals(mimeName))
923       {
924          return Constants.MIME_OCTETSTREAM;
925       }
926       else if (mimeName != null && mimeName.startsWith("multipart/"))
927       {
928          return Constants.MIME_MULTIPART;
929       }
930       else
931       {
932          return null;
933       }
934    } // getMIMEType
935

936
937    /**
938     * Are there any MIME parameters in the given binding?
939     */

940    public static boolean hasMIME(BindingEntry bEntry)
941    {
942       List JavaDoc operations = bEntry.getBinding().getBindingOperations();
943       for (int i = 0; i < operations.size(); ++i)
944       {
945          BindingOperation operation = (BindingOperation)operations.get(i);
946          if (hasMIME(bEntry, operation))
947          {
948             return true;
949          }
950       }
951       return false;
952    } // hasMIME
953

954    /**
955     * Are there any MIME parameters in the given binding's operation?
956     */

957    public static boolean hasMIME(BindingEntry bEntry, BindingOperation operation)
958    {
959       Parameters parameters =
960               bEntry.getParameters(operation.getOperation());
961       if (parameters != null)
962       {
963          for (int idx = 0; idx < parameters.list.size(); ++idx)
964          {
965             Parameter p = (Parameter)parameters.list.get(idx);
966             if (p.getMIMEInfo() != null)
967             {
968                return true;
969             }
970          }
971       }
972       return false;
973    } // hasMIME
974

975    private static HashMap JavaDoc constructorMap = new HashMap JavaDoc(50);
976    private static HashMap JavaDoc constructorThrowMap = new HashMap JavaDoc(50);
977
978    static
979    {
980       // Type maps to a valid initialization value for that type
981
// Type var = new Type(arg)
982
// Where "Type" is the key and "new Type(arg)" is the string stored
983
// Used in emitting test cases and server skeletons.
984
constructorMap.put("int", "0");
985       constructorMap.put("float", "0");
986       constructorMap.put("boolean", "true");
987       constructorMap.put("double", "0");
988       constructorMap.put("byte", "(byte)0");
989       constructorMap.put("short", "(short)0");
990       constructorMap.put("long", "0");
991       constructorMap.put("java.lang.Boolean", "new java.lang.Boolean(false)");
992       constructorMap.put("java.lang.Byte", "new java.lang.Byte((byte)0)");
993       constructorMap.put("java.lang.Double", "new java.lang.Double(0)");
994       constructorMap.put("java.lang.Float", "new java.lang.Float(0)");
995       constructorMap.put("java.lang.Integer", "new java.lang.Integer(0)");
996       constructorMap.put("java.lang.Long", "new java.lang.Long(0)");
997       constructorMap.put("java.lang.Short", "new java.lang.Short((short)0)");
998       constructorMap.put("java.math.BigDecimal", "new java.math.BigDecimal(0)");
999       constructorMap.put("java.math.BigInteger", "new java.math.BigInteger(\"0\")");
1000      constructorMap.put("java.lang.Object", "new java.lang.String()");
1001      constructorMap.put("byte[]", "new byte[0]");
1002      constructorMap.put("java.util.Calendar", "java.util.Calendar.getInstance()");
1003      constructorMap.put("javax.xml.namespace.QName", "new javax.xml.namespace.QName(\"http://double-double\", \"toil-and-trouble\")");
1004      constructorMap.put("org.jboss.axis.types.NonNegativeInteger", "new org.jboss.axis.types.NonNegativeInteger(\"0\")");
1005      constructorMap.put("org.jboss.axis.types.PositiveInteger", "new org.jboss.axis.types.PositiveInteger(\"1\")");
1006      constructorMap.put("org.jboss.axis.types.NonPositiveInteger", "new org.jboss.axis.types.NonPositiveInteger(\"0\")");
1007      constructorMap.put("org.jboss.axis.types.NegativeInteger", "new org.jboss.axis.types.NegativeInteger(\"-1\")");
1008
1009      // These constructors throw exception
1010
constructorThrowMap.put("org.jboss.axis.types.Time", "new org.jboss.axis.types.Time(\"15:45:45.275Z\")");
1011      constructorThrowMap.put("org.jboss.axis.types.UnsignedLong", "new org.jboss.axis.types.UnsignedLong(0)");
1012      constructorThrowMap.put("org.jboss.axis.types.UnsignedInt", "new org.jboss.axis.types.UnsignedInt(0)");
1013      constructorThrowMap.put("org.jboss.axis.types.UnsignedShort", "new org.jboss.axis.types.UnsignedShort(0)");
1014      constructorThrowMap.put("org.jboss.axis.types.UnsignedByte", "new org.jboss.axis.types.UnsignedByte(0)");
1015      constructorThrowMap.put("org.jboss.axis.types.URI", "new org.jboss.axis.types.URI(\"urn:testing\")");
1016      constructorThrowMap.put("org.jboss.axis.types.Year", "new org.jboss.axis.types.Year(2000)");
1017      constructorThrowMap.put("org.jboss.axis.types.Month", "new org.jboss.axis.types.Month(1)");
1018      constructorThrowMap.put("org.jboss.axis.types.Day", "new org.jboss.axis.types.Day(1)");
1019      constructorThrowMap.put("org.jboss.axis.types.YearMonth", "new org.jboss.axis.types.YearMonth(2000,1)");
1020      constructorThrowMap.put("org.jboss.axis.types.MonthDay", "new org.jboss.axis.types.MonthDay(1, 1)");
1021   }
1022
1023
1024   /**
1025    * Return a constructor for the provided Parameter
1026    * This string will be suitable for assignment:
1027    * <p/>
1028    * Foo var = <i>string returned</i>
1029    * <p/>
1030    * Handles basic java types (int, float, etc), wrapper types (Integer, etc)
1031    * and certain java.math (BigDecimal, BigInteger) types.
1032    * Will also handle all Axis specific types (org.jboss.axis.types.*)
1033    * <p/>
1034    * Caller should expect to wrap the construction in a try/catch block
1035    * if bThrow is set to <i>true</i>.
1036    *
1037    * @param param info about the parameter we need a constructor for
1038    * @param symbolTable used to lookup enumerations
1039    * @param bThrow set to true if contructor needs try/catch block
1040    */

1041   public static String JavaDoc getConstructorForParam(Parameter param,
1042                                               SymbolTable symbolTable,
1043                                               BooleanHolder JavaDoc bThrow)
1044   {
1045
1046      String JavaDoc paramType = param.getType().getName();
1047      String JavaDoc mimeType = param.getMIMEInfo() == null ? null : param.getMIMEInfo().getType();
1048      String JavaDoc mimeDimensions = param.getMIMEInfo() == null ? "" : param.getMIMEInfo().getDimensions();
1049      String JavaDoc out = null;
1050
1051      // Handle mime types
1052
if (mimeType != null)
1053      {
1054         if (mimeType.equals("image/gif") ||
1055                 mimeType.equals("image/jpeg"))
1056         {
1057            return "null";
1058         }
1059         else if (mimeType.equals("text/xml") ||
1060                 mimeType.equals("application/xml"))
1061         {
1062            if (mimeDimensions.length() <= 0)
1063               return "new javax.xml.transform.stream.StreamSource()";
1064            else
1065               return "new javax.xml.transform.stream.StreamSource[0]";
1066         }
1067         else if (mimeType.equals("application/octetstream"))
1068         {
1069            if (mimeDimensions.length() <= 0)
1070               return "new org.jboss.axis.attachments.OctetStream()";
1071            else
1072               return "new org.jboss.axis.attachments.OctetStream[0]";
1073         }
1074         else
1075         {
1076            return "new " + Utils.getParameterTypeName(param) + "()";
1077         }
1078      }
1079
1080      // Look up paramType in the table
1081
out = (String JavaDoc)constructorMap.get(paramType);
1082      if (out != null)
1083      {
1084         return out;
1085      }
1086
1087      // Look up paramType in the table of constructors that can throw exceptions
1088
out = (String JavaDoc)constructorThrowMap.get(paramType);
1089      if (out != null)
1090      {
1091         bThrow.value = true;
1092         return out;
1093      }
1094
1095      // Handle arrays
1096
if (paramType.endsWith("[]"))
1097      {
1098         return "new " + JavaUtils.replace(paramType, "[]", "[0]");
1099      }
1100
1101      /*** We have some constructed type. */
1102
1103      // Check for enumeration
1104
Vector JavaDoc v = Utils.getEnumerationBaseAndValues(param.getType().getNode(), symbolTable);
1105      if (v != null)
1106      {
1107         // This constructed type is an enumeration. Use the first one.
1108
String JavaDoc enumeration = (String JavaDoc)
1109                 JavaEnumTypeWriter.getEnumValueIds(v).get(0);
1110         return paramType + "." + enumeration;
1111      }
1112
1113      // This constructed type is a normal type, instantiate it.
1114
return "new " + paramType + "()";
1115
1116   }
1117
1118} // class Utils
1119
Popular Tags