summaryrefslogtreecommitdiffstats
path: root/tags/java/sca/1.5.1/tools/wsdl2java/src/main/java/org/apache/tuscany/tools/wsdl2java/generate/JavaInterfaceGenerator.java
blob: 8e0c3683a368e522b0523b78b5706439faccb8be (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.    
 */
package org.apache.tuscany.tools.wsdl2java.generate;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.wsdl.Binding;
import javax.wsdl.Definition;
import javax.wsdl.Fault;
import javax.wsdl.Message;
import javax.wsdl.Operation;
import javax.wsdl.Part;
import javax.wsdl.Port;
import javax.wsdl.PortType;
import javax.wsdl.Service;
import javax.wsdl.WSDLException;
import javax.wsdl.factory.WSDLFactory;
import javax.wsdl.xml.WSDLReader;
import javax.xml.namespace.QName;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.axis2.AxisFault;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.description.WSDL11ToAxisServiceBuilder;
import org.apache.axis2.util.FileWriter;
import org.apache.axis2.util.XMLUtils;
import org.apache.axis2.wsdl.codegen.CodeGenConfiguration;
import org.apache.axis2.wsdl.codegen.CodeGenerationException;
import org.apache.axis2.wsdl.codegen.extension.CodeGenExtension;
import org.apache.axis2.wsdl.codegen.extension.DefaultDatabindingExtension;
import org.apache.axis2.wsdl.codegen.extension.PackageFinder;
import org.apache.axis2.wsdl.codegen.extension.WSDLValidatorExtension;
import org.apache.axis2.wsdl.databinding.JavaTypeMapper;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import com.sun.tools.xjc.api.XJC;

public class JavaInterfaceGenerator {

    private List codegenExtensions = new ArrayList();
    private List<CodeGenConfiguration> codegenConfigurations= new LinkedList<CodeGenConfiguration>();
    private String outputLocation;
    


    public JavaInterfaceGenerator(String uri, String ports[], String outputLocation, String packageName,
                                  Map<QName, SDODataBindingTypeMappingEntry> typeMapping) throws CodeGenerationException {
        this.outputLocation = outputLocation;
        
        Definition definition;
        try {
            definition = readWSDL(uri);
        } catch (WSDLException e) {
            throw new CodeGenerationException(e);
        }
        
        HashSet<String> interestedPorts = ports == null ? null : new HashSet<String>(Arrays.asList(ports));
        
       // Service service=(Service)definition.getServices().values().().next();
        
        HashSet<QName> donePortTypes= new HashSet<QName>();
        
        for (Iterator sIter  = definition.getServices().values().iterator(); sIter.hasNext(); ) {
            Service service = (Service) sIter.next();
            
            QName serviceQname = service.getQName();
             for (Iterator pIter= service.getPorts().values().iterator(); pIter.hasNext(); ) {
                 Port port= (Port) pIter.next();
                if(interestedPorts != null && ! interestedPorts.contains(port.getName())) continue;//not iterested.
                 PortType portType= getPortType(port);
                 if(null == portType) continue; // not connected.
                 QName pQName= portType.getQName();
                 if(donePortTypes.contains(pQName)) continue; //allready did it.
                 donePortTypes.add(pQName);
              
                if (packageName == null) {
                    //use JAXWS/JAXB NS->package default algorithm, not the SDO/EMF one
                    packageName = XJC.getDefaultPackageName(definition.getTargetNamespace());
                }
                //
                // Use WSDL4J object to generate exception classes
                //
                generateFaults(packageName, portType, typeMapping);
                JavaTypeMapper typeMapper = new JavaTypeMapper();
                for (Map.Entry<QName, SDODataBindingTypeMappingEntry> e : typeMapping.entrySet()) {
                    typeMapper.addTypeMappingObject(e.getKey(), e.getValue());
                    // Added for generation of exceptions from faults
                    typeMapper.addTypeMappingName(e.getKey(), e.getValue().getClassName());
                }


                AxisService axisService;
                WSDL11ToAxisServiceBuilder builder;
                try {
                    //
                    // Added since at a newer level of Axis2, this doesn't work 
                    //  without the setCodegen(true)
                    //
                    builder = new WSDL11ToAxisServiceBuilder(definition, serviceQname, port.getName());
                    builder.setCodegen(true);
                    axisService = builder.populateService();
                } catch (AxisFault e) {
                    throw new CodeGenerationException(e);
                }

                axisService.setName(port.getBinding().getPortType().getQName().getLocalPart());
                CodeGenConfiguration codegenConfiguration = new CodeGenConfiguration(Collections.EMPTY_MAP);
                codegenConfigurations.add(codegenConfiguration);
                codegenConfiguration.setAxisService(axisService);
                codegenConfiguration.setAdvancedCodeGenEnabled(false);
                codegenConfiguration.setAsyncOn(false);
                codegenConfiguration.setDatabindingType("sdo");
                codegenConfiguration.setGenerateAll(true);
                codegenConfiguration.setGenerateDeployementDescriptor(false);
                codegenConfiguration.setOutputLanguage("java");
                codegenConfiguration.setOutputLocation(new File(outputLocation));
                codegenConfiguration.setPackageName(packageName);
                codegenConfiguration.setPackClasses(false);
                codegenConfiguration.setPolicyMap(Collections.EMPTY_MAP);
                codegenConfiguration.setPortName(port.getName());
                codegenConfiguration.setServerSide(false);
                codegenConfiguration.setServiceName(service.getQName().getLocalPart());
                // This lines up with the sync/async variable from the XSL template
                codegenConfiguration.setSyncOn(true);
                codegenConfiguration.setTypeMapper(typeMapper);

// JIRA TUSCANY-1561 Port to Axis2 1.3                
//                codegenConfiguration.setWriteMessageReceiver(false);
                codegenConfiguration.setSkipMessageReceiver(true);
                
                codegenConfiguration.setWriteTestCase(false);
                addExtension(new WSDLValidatorExtension(), codegenConfiguration);
                addExtension(new PackageFinder(), codegenConfiguration);
                addExtension(new SDODataBindingCodegenExtension(typeMapper), codegenConfiguration);
                addExtension(new DefaultDatabindingExtension(), codegenConfiguration);
            }            
        }        
    }


    private PortType getPortType(Port port) {
       Binding binding = port.getBinding();
       if(null != binding){
          return binding.getPortType();
       }
       return null;
        
    }


    @SuppressWarnings("unchecked")
    private void addExtension(CodeGenExtension ext, CodeGenConfiguration codegenConfiguration) {
        //ext.init(codegenConfiguration);
        codegenExtensions.add(new Object[]{ext, codegenConfiguration});
    }

    public void generate() throws CodeGenerationException {
        try {
            for (int i = 0; i < codegenExtensions.size(); i++) {
                // CodeGenExtension
                Object[] pair = (Object[])codegenExtensions.get(i);

                CodeGenExtension cge = (CodeGenExtension)pair[0];
                CodeGenConfiguration cgf = (CodeGenConfiguration)pair[1];

                cge.engage(cgf);
            }

            for (CodeGenConfiguration codegenConfiguration : codegenConfigurations) {
                JavaInterfaceEmitter emitter = new JavaInterfaceEmitter();
                emitter.setCodeGenConfiguration(codegenConfiguration);
                emitter.setMapper(codegenConfiguration.getTypeMapper());

                emitter.writeInterface(false);
            }

        } catch (Exception e) {
            throw new CodeGenerationException(e);
        }
    }

    /**
     * Read the WSDL file
     * 
     * @param uri
     * @return
     * @throws WSDLException
     */
    private Definition readWSDL(String uri) throws WSDLException {

        WSDLReader reader = WSDLFactory.newInstance().newWSDLReader();
        reader.setFeature("javax.wsdl.importDocuments", true);

        File file = new File(uri);
        String baseURI;

        if (uri.startsWith("http://")) {
            baseURI = uri;
        } else {
            if (file.getParentFile() == null) {
                try {
                    baseURI = new File(".").getCanonicalFile().toURI().toString();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            } else {
                baseURI = file.getParentFile().toURI().toString();
            }
        }

        Document doc;
        try {
            doc = XMLUtils.newDocument(uri);
        } catch (ParserConfigurationException e) {
            throw new WSDLException(WSDLException.PARSER_ERROR, "Parser Configuration Error", e);
        } catch (SAXException e) {
            throw new WSDLException(WSDLException.PARSER_ERROR, "Parser SAX Error", e);

        } catch (IOException e) {
            throw new WSDLException(WSDLException.INVALID_WSDL, "IO Error", e);
        }

        return reader.readWSDL(baseURI, doc);
    }
    
    private void generateFaults(String packageName, PortType portType, Map<QName, SDODataBindingTypeMappingEntry> typeMapping) 
        throws CodeGenerationException{
        
        for (Object o: portType.getOperations()) {
            Operation op = (Operation)o;
            Map messageMap = op.getFaults();
            Iterator iter = messageMap.values().iterator();
            while (iter.hasNext()) {
                Fault fault = (Fault)iter.next();
                Message faultMsg = fault.getMessage();
                Iterator iter2 = faultMsg.getParts().values().iterator();
                Part faultMsgPart = (Part)iter2.next();
                // TODO - if other parts throw exc
                QName faultMsgQName = faultMsg.getQName();
                QName faultMsgPartElementQName = faultMsgPart.getElementName();
                String faultClassName = typeMapping.get(faultMsgPartElementQName).getClassName();                
                writeException(packageName, faultMsgQName, faultClassName, faultMsgPartElementQName);
            }
        }
    }
    
    private void writeException(String packageName, QName faultMsgQName, String faultClassName, QName faultMsgPartElementQName) 
        throws CodeGenerationException{        
        
        try {
            String faultWrapperClassName = 
                WSDL2JavaGenerator.normalizeClassName(faultMsgQName.getLocalPart());
            
            File outputDir = new File(this.outputLocation);
            
            if (!outputDir.exists()) {
                outputDir.mkdirs();
            }
            File outputFile = FileWriter.createClassFile(outputDir,
                    packageName, faultWrapperClassName, ".java");

            FileOutputStream fileStream = new FileOutputStream(outputFile);       
            PrintStream stream = new PrintStream(fileStream); 

            System.out.println(">>  Generating Java exception class " + packageName + "." + faultWrapperClassName);

            stream.println();
            stream.println("package " + packageName + ";");
            stream.println();
            stream.println("import javax.xml.ws.WebFault;");
            stream.println();
            stream.println("@WebFault(name=\"" + faultMsgPartElementQName.getLocalPart()
                + "\", targetNamespace=\""
                + faultMsgPartElementQName.getNamespaceURI()
                + "\")");
            stream.println("public class " + faultWrapperClassName  + " extends Exception {");
            stream.println();
            stream.println("    private " + faultClassName + " fault;");
            stream.println();
            stream.println("    public " + faultWrapperClassName + "(String message, " + faultClassName + " fault) {");
            stream.println("        super(message);");
            stream.println("        this.fault = fault;");
            stream.println("    }");
            stream.println();
            stream.println("    public " + faultWrapperClassName + "(String message, " + faultClassName + " fault, Throwable cause) {");
            stream.println("        super(message, cause);");
            stream.println("        this.fault = fault;");
            stream.println("    }");
            stream.println();
            stream.println("    public " + faultClassName + " getFaultInfo() {");
            stream.println("        return this.fault;");
            stream.println("    }");
            stream.println("}");
            stream.println();
        } catch (Exception e) {
            throw new CodeGenerationException(e);
        }
    }
}