1 /*
   2  * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package com.sun.tools.internal.ws.processor.generator;
  27 
  28 import com.sun.codemodel.internal.*;
  29 import com.sun.tools.internal.ws.api.TJavaGeneratorExtension;
  30 import com.sun.tools.internal.ws.processor.model.*;
  31 import com.sun.tools.internal.ws.processor.model.java.JavaInterface;
  32 import com.sun.tools.internal.ws.processor.model.java.JavaMethod;
  33 import com.sun.tools.internal.ws.processor.model.java.JavaParameter;
  34 import com.sun.tools.internal.ws.processor.model.jaxb.JAXBType;
  35 import com.sun.tools.internal.ws.processor.model.jaxb.JAXBTypeAndAnnotation;
  36 import com.sun.tools.internal.ws.wscompile.ErrorReceiver;
  37 import com.sun.tools.internal.ws.wscompile.Options;
  38 import com.sun.tools.internal.ws.wscompile.WsimportOptions;
  39 import com.sun.tools.internal.ws.wscompile.AbortException;
  40 import com.sun.tools.internal.ws.wsdl.document.soap.SOAPStyle;
  41 import com.sun.tools.internal.ws.wsdl.document.PortType;
  42 import com.sun.tools.internal.ws.wsdl.document.Kinds;
  43 import com.sun.tools.internal.ws.resources.GeneratorMessages;
  44 
  45 import javax.jws.WebMethod;
  46 import javax.jws.WebParam;
  47 import javax.jws.WebService;
  48 import javax.jws.soap.SOAPBinding;
  49 import javax.xml.bind.annotation.XmlSeeAlso;
  50 import javax.xml.namespace.QName;
  51 import javax.xml.ws.Holder;
  52 import java.util.ArrayList;
  53 import java.util.List;
  54 
  55 import org.xml.sax.Locator;
  56 
  57 public class SeiGenerator extends GeneratorBase {
  58     private String serviceNS;
  59     private TJavaGeneratorExtension extension;
  60     private List<TJavaGeneratorExtension> extensionHandlers;
  61 
  62     public static void generate(Model model, WsimportOptions options, ErrorReceiver receiver, TJavaGeneratorExtension... extensions){
  63         SeiGenerator seiGenerator = new SeiGenerator();
  64         seiGenerator.init(model, options, receiver, extensions);
  65         seiGenerator.doGeneration();
  66     }
  67 
  68     public void init(Model model, WsimportOptions options, ErrorReceiver receiver, TJavaGeneratorExtension... extensions) {
  69         init(model, options, receiver);
  70         extensionHandlers = new ArrayList<TJavaGeneratorExtension>();
  71 
  72         // register handlers for default extensions
  73 
  74         // 2.2 Spec requires generation of @Action when wsam:Action is explicitly stated in wsdl
  75         if (options.target.isLaterThan(Options.Target.V2_2)) {
  76            register(new W3CAddressingJavaGeneratorExtension());
  77         }
  78 
  79         for (TJavaGeneratorExtension j : extensions)
  80             register(j);
  81 
  82         this.extension = new JavaGeneratorExtensionFacade(extensionHandlers.toArray(new TJavaGeneratorExtension[0]));
  83     }
  84 
  85     private void write(Port port) {
  86         JavaInterface intf = port.getJavaInterface();
  87         String className = Names.customJavaTypeClassName(intf);
  88 
  89         if (donotOverride && GeneratorUtil.classExists(options, className)) {
  90             log("Class " + className + " exists. Not overriding.");
  91             return;
  92         }
  93 
  94 
  95         JDefinedClass cls = null;
  96         try {
  97             cls = getClass(className, ClassType.INTERFACE);
  98         } catch (JClassAlreadyExistsException e) {
  99             QName portTypeName =
 100                 (QName) port.getProperty(
 101                         ModelProperties.PROPERTY_WSDL_PORT_TYPE_NAME);
 102             Locator loc = null;
 103             if(portTypeName != null){
 104                 PortType pt = port.portTypes.get(portTypeName);
 105                 if(pt!=null)
 106                     loc = pt.getLocator();
 107             }
 108             receiver.error(loc, GeneratorMessages.GENERATOR_SEI_CLASS_ALREADY_EXIST(intf.getName(), portTypeName));
 109             return;
 110         }
 111         // If the class has methods it has already been defined
 112         // so skip it.
 113         if (!cls.methods().isEmpty())
 114             return;
 115 
 116         //write class comment - JAXWS warning
 117         JDocComment comment = cls.javadoc();
 118 
 119         String ptDoc = intf.getJavaDoc();
 120         if(ptDoc != null){
 121             comment.add(ptDoc);
 122             comment.add("\n\n");
 123         }
 124 
 125         for(String doc:getJAXWSClassComment()){
 126                 comment.add(doc);
 127         }
 128 
 129 
 130         //@WebService
 131         JAnnotationUse webServiceAnn = cls.annotate(cm.ref(WebService.class));
 132         writeWebServiceAnnotation(port, webServiceAnn);
 133 
 134         //@HandlerChain
 135         writeHandlerConfig(Names.customJavaTypeClassName(port.getJavaInterface()), cls, options);
 136 
 137         //@SOAPBinding
 138         writeSOAPBinding(port, cls);
 139 
 140         //@XmlSeeAlso
 141         if(options.target.isLaterThan(Options.Target.V2_1))
 142             writeXmlSeeAlso(cls);
 143 
 144         for (Operation operation: port.getOperations()) {
 145             JavaMethod method = operation.getJavaMethod();
 146 
 147             //@WebMethod
 148             JMethod m;
 149             JDocComment methodDoc;
 150             String methodJavaDoc = operation.getJavaDoc();
 151             if(method.getReturnType().getName().equals("void")){
 152                 m = cls.method(JMod.PUBLIC, void.class, method.getName());
 153                 methodDoc = m.javadoc();
 154             }else {
 155                 JAXBTypeAndAnnotation retType = method.getReturnType().getType();
 156                 m = cls.method(JMod.PUBLIC, retType.getType(), method.getName());
 157                 retType.annotate(m);
 158                 methodDoc = m.javadoc();
 159                 JCommentPart ret = methodDoc.addReturn();
 160                 ret.add("returns "+retType.getName());
 161             }
 162             if(methodJavaDoc != null)
 163                 methodDoc.add(methodJavaDoc);
 164 
 165             writeWebMethod(operation, m);
 166             JClass holder = cm.ref(Holder.class);
 167             for (JavaParameter parameter: method.getParametersList()) {
 168                 JVar var;
 169                 JAXBTypeAndAnnotation paramType = parameter.getType().getType();
 170                 if (parameter.isHolder()) {
 171                     var = m.param(holder.narrow(paramType.getType().boxify()), parameter.getName());
 172                 }else{
 173                     var = m.param(paramType.getType(), parameter.getName());
 174                 }
 175 
 176                 //annotate parameter with JAXB annotations
 177                 paramType.annotate(var);
 178                 methodDoc.addParam(var);
 179                 JAnnotationUse paramAnn = var.annotate(cm.ref(WebParam.class));
 180                 writeWebParam(operation, parameter, paramAnn);
 181             }
 182             com.sun.tools.internal.ws.wsdl.document.Operation wsdlOp = operation.getWSDLPortTypeOperation();
 183             for(Fault fault:operation.getFaultsSet()){
 184                 m._throws(fault.getExceptionClass());
 185                 methodDoc.addThrows(fault.getExceptionClass());
 186                 wsdlOp.putFault(fault.getWsdlFaultName(), fault.getExceptionClass());
 187             }
 188 
 189             //It should be the last thing to invoke after JMethod is built completely
 190             extension.writeMethodAnnotations(wsdlOp, m);
 191         }
 192     }
 193 
 194     private void writeXmlSeeAlso(JDefinedClass cls) {
 195         if (model.getJAXBModel().getS2JJAXBModel() != null) {
 196             List<JClass> objectFactories = model.getJAXBModel().getS2JJAXBModel().getAllObjectFactories();
 197 
 198             //if there are no object facotires, dont generate @XmlSeeAlso
 199             if(objectFactories.size() == 0)
 200                 return;
 201 
 202             JAnnotationUse xmlSeeAlso = cls.annotate(cm.ref(XmlSeeAlso.class));
 203             JAnnotationArrayMember paramArray = xmlSeeAlso.paramArray("value");
 204             for (JClass of : objectFactories) {
 205                 paramArray = paramArray.param(of);
 206             }
 207         }
 208 
 209     }
 210 
 211     private void writeWebMethod(Operation operation, JMethod m) {
 212         Response response = operation.getResponse();
 213         JAnnotationUse webMethodAnn = m.annotate(cm.ref(WebMethod.class));
 214         String operationName = (operation instanceof AsyncOperation)?
 215                 ((AsyncOperation)operation).getNormalOperation().getName().getLocalPart():
 216                 operation.getName().getLocalPart();
 217 
 218         if(!m.name().equals(operationName)){
 219             webMethodAnn.param("operationName", operationName);
 220         }
 221 
 222         if (operation.getSOAPAction() != null && operation.getSOAPAction().length() > 0){
 223             webMethodAnn.param("action", operation.getSOAPAction());
 224         }
 225 
 226         if (operation.getResponse() == null){
 227             m.annotate(javax.jws.Oneway.class);
 228         }else if (!operation.getJavaMethod().getReturnType().getName().equals("void") &&
 229                  operation.getResponse().getParametersList().size() > 0){
 230             Block block;
 231             String resultName = null;
 232             String nsURI = null;
 233             if (operation.getResponse().getBodyBlocks().hasNext()) {
 234                 block = operation.getResponse().getBodyBlocks().next();
 235                 resultName = block.getName().getLocalPart();
 236                 if(isDocStyle || block.getLocation() == Block.HEADER){
 237                     nsURI = block.getName().getNamespaceURI();
 238                 }
 239             }
 240 
 241             for (Parameter parameter : operation.getResponse().getParametersList()) {
 242                 if (parameter.getParameterIndex() == -1) {
 243                     if(operation.isWrapped()||!isDocStyle){
 244                         if(parameter.getBlock().getLocation() == Block.HEADER){
 245                             resultName = parameter.getBlock().getName().getLocalPart();
 246                         }else{
 247                             resultName = parameter.getName();
 248                         }
 249                         if (isDocStyle || (parameter.getBlock().getLocation() == Block.HEADER)) {
 250                             nsURI = parameter.getType().getName().getNamespaceURI();
 251                         }
 252                     }else if(isDocStyle){
 253                         JAXBType t = (JAXBType)parameter.getType();
 254                         resultName = t.getName().getLocalPart();
 255                         nsURI = t.getName().getNamespaceURI();
 256                     }
 257                     if(!(operation instanceof AsyncOperation)){
 258                         JAnnotationUse wr = null;
 259 
 260                         if(!resultName.equals("return")){
 261                             wr = m.annotate(javax.jws.WebResult.class);
 262                             wr.param("name", resultName);
 263                         }
 264                         if((nsURI != null) && (!nsURI.equals(serviceNS) || (isDocStyle && operation.isWrapped()))){
 265                             if(wr == null)
 266                                 wr = m.annotate(javax.jws.WebResult.class);
 267                             wr.param("targetNamespace", nsURI);
 268                         }
 269                         //doclit wrapped could have additional headers
 270                         if(!(isDocStyle && operation.isWrapped()) ||
 271                                 (parameter.getBlock().getLocation() == Block.HEADER)){
 272                             if(wr == null)
 273                                 wr = m.annotate(javax.jws.WebResult.class);
 274                             wr.param("partName", parameter.getName());
 275                         }
 276                         if(parameter.getBlock().getLocation() == Block.HEADER){
 277                             if(wr == null)
 278                                 wr = m.annotate(javax.jws.WebResult.class);
 279                             wr.param("header",true);
 280                         }
 281                     }
 282                 }
 283 
 284             }
 285         }
 286 
 287         //DOC/BARE
 288         if (!sameParamStyle) {
 289             if(!operation.isWrapped()) {
 290                JAnnotationUse sb = m.annotate(SOAPBinding.class);
 291                sb.param("parameterStyle", SOAPBinding.ParameterStyle.BARE);
 292             }
 293         }
 294 
 295         if (operation.isWrapped() && operation.getStyle().equals(SOAPStyle.DOCUMENT)) {
 296             Block reqBlock = operation.getRequest().getBodyBlocks().next();
 297             JAnnotationUse reqW = m.annotate(javax.xml.ws.RequestWrapper.class);
 298             reqW.param("localName", reqBlock.getName().getLocalPart());
 299             reqW.param("targetNamespace", reqBlock.getName().getNamespaceURI());
 300             reqW.param("className", reqBlock.getType().getJavaType().getName());
 301 
 302             if (response != null) {
 303                 JAnnotationUse resW = m.annotate(javax.xml.ws.ResponseWrapper.class);
 304                 Block resBlock = response.getBodyBlocks().next();
 305                 resW.param("localName", resBlock.getName().getLocalPart());
 306                 resW.param("targetNamespace", resBlock.getName().getNamespaceURI());
 307                 resW.param("className", resBlock.getType().getJavaType().getName());
 308             }
 309         }
 310     }
 311 
 312     private boolean isMessageParam(Parameter param, Message message) {
 313         Block block = param.getBlock();
 314 
 315         return (message.getBodyBlockCount() > 0 && block.equals(message.getBodyBlocks().next())) ||
 316                (message.getHeaderBlockCount() > 0 &&
 317                block.equals(message.getHeaderBlocks().next()));
 318     }
 319 
 320     private boolean isHeaderParam(Parameter param, Message message) {
 321         if (message.getHeaderBlockCount() == 0)
 322             return false;
 323 
 324         for (Block headerBlock : message.getHeaderBlocksMap().values())
 325             if (param.getBlock().equals(headerBlock))
 326                 return true;
 327 
 328         return false;
 329     }
 330 
 331     private boolean isAttachmentParam(Parameter param, Message message){
 332         if (message.getAttachmentBlockCount() == 0)
 333             return false;
 334 
 335         for (Block attBlock : message.getAttachmentBlocksMap().values())
 336             if (param.getBlock().equals(attBlock))
 337                 return true;
 338 
 339         return false;
 340     }
 341 
 342     private boolean isUnboundParam(Parameter param, Message message){
 343         if (message.getUnboundBlocksCount() == 0)
 344             return false;
 345 
 346         for (Block unboundBlock : message.getUnboundBlocksMap().values())
 347             if (param.getBlock().equals(unboundBlock))
 348                 return true;
 349 
 350         return false;
 351     }
 352 
 353     private void writeWebParam(Operation operation, JavaParameter javaParameter, JAnnotationUse paramAnno) {
 354         Parameter param = javaParameter.getParameter();
 355         Request req = operation.getRequest();
 356         Response res = operation.getResponse();
 357 
 358         boolean header = isHeaderParam(param, req) ||
 359             (res != null && isHeaderParam(param, res));
 360 
 361         String name;
 362         boolean isWrapped = operation.isWrapped();
 363 
 364         if((param.getBlock().getLocation() == Block.HEADER) || (isDocStyle && !isWrapped))
 365             name = param.getBlock().getName().getLocalPart();
 366         else
 367             name = param.getName();
 368 
 369         paramAnno.param("name", name);
 370 
 371         String ns= null;
 372 
 373         if (isDocStyle) {
 374             ns = param.getBlock().getName().getNamespaceURI(); // its bare nsuri
 375             if(isWrapped){
 376                 ns = param.getType().getName().getNamespaceURI();
 377             }
 378         }else if(header){
 379             ns = param.getBlock().getName().getNamespaceURI();
 380         }
 381 
 382         if((ns != null) && (!ns.equals(serviceNS) || (isDocStyle && isWrapped)))
 383             paramAnno.param("targetNamespace", ns);
 384 
 385         if (header) {
 386             paramAnno.param("header", true);
 387         }
 388 
 389         if (param.isINOUT()){
 390             paramAnno.param("mode", javax.jws.WebParam.Mode.INOUT);
 391         }else if ((res != null) && (isMessageParam(param, res) || isHeaderParam(param, res) || isAttachmentParam(param, res) ||
 392                 isUnboundParam(param,res) || param.isOUT())){
 393             paramAnno.param("mode", javax.jws.WebParam.Mode.OUT);
 394         }
 395 
 396         //doclit wrapped could have additional headers
 397         if(!(isDocStyle && isWrapped) || header)
 398             paramAnno.param("partName", javaParameter.getParameter().getName());
 399     }
 400 
 401     private boolean isDocStyle = true;
 402     private boolean sameParamStyle = true;
 403     private void writeSOAPBinding(Port port, JDefinedClass cls) {
 404         JAnnotationUse soapBindingAnn = null;
 405         isDocStyle = port.getStyle() == null || port.getStyle().equals(SOAPStyle.DOCUMENT);
 406         if(!isDocStyle){
 407             soapBindingAnn = cls.annotate(SOAPBinding.class);
 408             soapBindingAnn.param("style", SOAPBinding.Style.RPC);
 409             port.setWrapped(true);
 410         }
 411         if(isDocStyle){
 412             boolean first = true;
 413             boolean isWrapper = true;
 414             for(Operation operation:port.getOperations()){
 415                 if(first){
 416                     isWrapper = operation.isWrapped();
 417                     first = false;
 418                     continue;
 419                 }
 420                 sameParamStyle = (isWrapper == operation.isWrapped());
 421                 if(!sameParamStyle)
 422                     break;
 423             }
 424             if(sameParamStyle)
 425                 port.setWrapped(isWrapper);
 426         }
 427         if(sameParamStyle && !port.isWrapped()){
 428             if(soapBindingAnn == null)
 429                 soapBindingAnn = cls.annotate(SOAPBinding.class);
 430             soapBindingAnn.param("parameterStyle", SOAPBinding.ParameterStyle.BARE);
 431         }
 432     }
 433 
 434     private void writeWebServiceAnnotation(Port port, JAnnotationUse wsa) {
 435         QName name = (QName) port.getProperty(ModelProperties.PROPERTY_WSDL_PORT_TYPE_NAME);
 436         wsa.param("name", name.getLocalPart());
 437         wsa.param("targetNamespace", name.getNamespaceURI());
 438     }
 439 
 440 
 441 
 442 
 443     public void visit(Model model) throws Exception {
 444         for(Service s:model.getServices()){
 445             s.accept(this);
 446         }
 447     }
 448 
 449     public void visit(Service service) throws Exception {
 450         String jd = model.getJavaDoc();
 451         if(jd != null){
 452             JPackage pkg = cm._package(options.defaultPackage);
 453             pkg.javadoc().add(jd);
 454         }
 455 
 456         for(Port p:service.getPorts()){
 457             visitPort(service, p);
 458         }
 459     }
 460 
 461     private void visitPort(Service service, Port port) {
 462         if (port.isProvider()) {
 463             return;                // Not generating for Provider based endpoint
 464         }
 465         write(port);
 466     }
 467 
 468     private void register(TJavaGeneratorExtension h) {
 469         extensionHandlers.add(h);
 470     }
 471 }