summaryrefslogtreecommitdiffstats
path: root/sca-java-2.x/tags/2.0.1-RC1/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/xml/BPELDocumentModelResolver.java
blob: 2821130ca7463e8bd51609b1ba5b253810c0658d (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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
/*
 * 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.sca.implementation.bpel.xml;

import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.wsdl.Definition;
import javax.wsdl.PortType;
import javax.wsdl.extensions.ExtensibilityElement;
import javax.xml.namespace.QName;

import org.apache.tuscany.sca.contribution.Contribution;
import org.apache.tuscany.sca.contribution.Import;
import org.apache.tuscany.sca.contribution.namespace.NamespaceImport;
import org.apache.tuscany.sca.contribution.processor.ContributionResolveException;
import org.apache.tuscany.sca.contribution.processor.ProcessorContext;
import org.apache.tuscany.sca.contribution.resolver.ModelResolver;
import org.apache.tuscany.sca.core.FactoryExtensionPoint;
import org.apache.tuscany.sca.implementation.bpel.BPELProcessDefinition;
import org.apache.tuscany.sca.interfacedef.InvalidInterfaceException;
import org.apache.tuscany.sca.interfacedef.wsdl.BPELPartnerLinkTypeExt;
import org.apache.tuscany.sca.interfacedef.wsdl.WSDLDefinition;
import org.apache.tuscany.sca.interfacedef.wsdl.WSDLFactory;
import org.apache.tuscany.sca.interfacedef.wsdl.WSDLInterface;
import org.apache.tuscany.sca.interfacedef.wsdl.WSDLObject;
import org.apache.tuscany.sca.monitor.Monitor;
import org.apache.tuscany.sca.monitor.Problem;
import org.apache.tuscany.sca.monitor.Problem.Severity;

/**
 * A Model Resolver for BPEL process models.
 *
 * @version $Rev$ $Date$
 */
public class BPELDocumentModelResolver implements ModelResolver {
	
    private WSDLFactory wsdlFactory;
    private Contribution contribution;
    private Map<QName, BPELProcessDefinition> map = new HashMap<QName, BPELProcessDefinition>();
    
    public BPELDocumentModelResolver(Contribution contribution, FactoryExtensionPoint modelFactories) {
    	this.wsdlFactory = modelFactories.getFactory(WSDLFactory.class);
        this.contribution = contribution;
    }

    public void addModel(Object resolved, ProcessorContext context) {
        BPELProcessDefinition process = (BPELProcessDefinition)resolved;
        map.put(process.getName(), process);
    }
    
    public Object removeModel(Object resolved, ProcessorContext context) {
        return map.remove(((BPELProcessDefinition)resolved).getName());
    }
    
    public <T> T resolveModel(Class<T> modelClass, T unresolved, ProcessorContext context) {    	
    	BPELProcessDefinition resolved = null;
    	QName qname = ((BPELProcessDefinition)unresolved).getName();
    	
    	// Lookup a definition for the given namespace, from imports
    	List<String> locations = new ArrayList<String>();
        // Collection of namespace imports with location
        Map<String, NamespaceImport> locationMap = new HashMap<String, NamespaceImport>();
        for (Import import_ : this.contribution.getImports()) {
            if (import_ instanceof NamespaceImport) {
                NamespaceImport namespaceImport = (NamespaceImport)import_;
                if (namespaceImport.getNamespace().equals(qname.getNamespaceURI())) {
                    if (namespaceImport.getLocation() == null) {
	                    // Delegate the resolution to the import resolver
	                    resolved = namespaceImport.getModelResolver().resolveModel(BPELProcessDefinition.class, (BPELProcessDefinition)unresolved, context);
	                    if (!resolved.isUnresolved()) {
	                        return modelClass.cast(resolved);
	                    }
                    } else {
                    	// We might have multiple imports for the same namespace,
                		// need to search them in lexical order.
                		locations.add(namespaceImport.getLocation());
                    }
                }
            }
        }
        // Search namespace imports with locations in lexical order
        Collections.sort(locations);
        for (String location : locations) {
        	NamespaceImport namespaceImport = (NamespaceImport)locationMap.get(location);
        	// Delegate the resolution to the namespace import resolver
            resolved = namespaceImport.getModelResolver().resolveModel(BPELProcessDefinition.class, (BPELProcessDefinition)unresolved, context);
            if (!resolved.isUnresolved()) {
                return modelClass.cast(resolved);
            }
        }
        
        
        // Not found, Lookup a definition for the given namespace, within contribution       
        resolved = (BPELProcessDefinition) map.get(qname);
        
        if(resolved != null && resolved.isUnresolved()) {
        	try {
        		resolve(resolved, context);
        	} catch(Exception e) {
        		//FIXME
        	}
        }
        
        if (resolved != null) {
            return modelClass.cast(resolved);
        }        
        
        return (T)unresolved;
    }
    
    public void resolve(BPELProcessDefinition unresolved, ProcessorContext context) throws ContributionResolveException {
        // FIXME - serious resolving needs to happen here
    	
    	// Step 1 is to resolve the WSDL files referenced from this BPEL process
    	// - one complexity here is that the WSDL definitions hold BPEL extension elements for
    	// the partnerLinkType declarations - and these must be used in later steps
    	//
    	// Step 2 is to take all the partnerLink definitions and establish the PortType being
    	// used, by tracing through the related partnerLinkType declarations - the PortType is
    	// effectively a definition of the interface used by the partnerLink.
    	// - another consideration here is that each partnerLink can involve 2 interfaces, one
    	// for the forward calls to the process, the other for calls from the process - depending
    	// on whether the partnerLink is a reference or a service, one of these interfaces is a
    	// callback interface.

    	List<BPELImportElement> theImports = unresolved.getImports();
    	Set<Definition> wsdlDefinitions = getImportedWSDLDefinitions( theImports, contribution.getModelResolver(), context );
    	
    	// Fetch the sets of partner links, port types and interfaces
    	List<BPELPartnerLinkTypeElement> thePLinkTypes = getPartnerLinkTypes( wsdlDefinitions, context.getMonitor() );
    	Collection<WSDLInterface> theInterfaces = (Collection<WSDLInterface>)new ArrayList<WSDLInterface>();
    	Collection<PortType> thePortTypes = getAllPortTypes( theImports, theInterfaces, contribution.getModelResolver(), context );
    	
    	// Store the Port Types and the Interfaces for later calculation of the component type...
    	unresolved.getPortTypes().addAll(thePortTypes);
    	unresolved.getInterfaces().addAll(theInterfaces);
    	
    	// Now, for each partnerLink in the BPEL process, find the related partnerLinkType element 
        List<BPELPartnerLinkElement> thePartnerLinks = unresolved.getPartnerLinks();
        for (BPELPartnerLinkElement thePartnerLink : thePartnerLinks) {
            QName partnerLinkType = thePartnerLink.getPartnerLinkType();
            BPELPartnerLinkTypeElement pLinkType = findPartnerLinkType(partnerLinkType, thePLinkTypes);
            if (pLinkType == null) {
                error(context.getMonitor(), "PartnerLinkNoMatchingType", thePartnerLink, thePartnerLink.getName());
            } else {
                thePartnerLink.setPartnerLinkType(pLinkType);
            }
        } // end for
        
        unresolved.setUnresolved(false);
    	
    } // end resolve    
    
    /**
     * Get all the WSDL definitions referenced through the import statements of the BPEL process
     * @param theImports - a list of the import statements
     * @return - a Set containing all the referenced WSDL definitions
     */
    private Set<Definition> getImportedWSDLDefinitions( List<BPELImportElement> theImports, ModelResolver resolver, ProcessorContext context ) {
    	Set<Definition> wsdlDefinitions = null;
    	for (BPELImportElement theImport : theImports) {
            if (theImport.getImportType().equals(BPELProcessorConstants.WSDL_NS)) {
            	// If the Import is a WSDL import, resolve the WSDL
            	WSDLDefinition theWSDL = resolveWSDLDefinition( theImport.getLocation(), 
            			                                        theImport.getNamespace(), resolver, context );
                if( theWSDL != null ) {
	            	theImport.setWSDLDefinition( theWSDL );
	            	
	                // Find all the WSDL definitions matching the imported namespace
	            	if( wsdlDefinitions == null ) {
	            		wsdlDefinitions = new HashSet<Definition>();
	            	} // end if 
	            	
	                wsdlDefinitions.add(theWSDL.getDefinition());
                } // end if
            } // end if
        } // end for
        
        return wsdlDefinitions;
    } // end getImportedWSDLDefinitions
    
    /**
     * Resolve a reference to a WSDL, given by a namespace and a location
     * @param wsdlLocation - a string containing the WSDL location
     * @param wsdlNamespace - a string containing the WSDL namespace
     * @param resolver - a model resolver
     * @param context 
     * @return - a WSDLDefinition object for the referenced WSDL, or null if the WSDL cannot be resolved
     */
    private WSDLDefinition resolveWSDLDefinition( String wsdlLocation, String wsdlNamespace, ModelResolver resolver, ProcessorContext context ) {
        
        // Resolve the WSDL definition
        WSDLDefinition proxy = wsdlFactory.createWSDLDefinition();
        proxy.setUnresolved(true);
        proxy.setNamespace(wsdlNamespace);
        if (wsdlLocation != null) {
            proxy.setLocation(URI.create(wsdlLocation));
        }
        WSDLDefinition resolved = resolver.resolveModel(WSDLDefinition.class, proxy, context);
        if (resolved != null && !resolved.isUnresolved()) {
        	return resolved;
        } else {
            error(context.getMonitor(), "CannotResolveWSDLReference", resolver, wsdlLocation, wsdlNamespace);
            return null;
        } // end if
    } // end resolveWSDLDefinition
    

    /**
     * Retrieve all the Partner Link types defined in the imported WSDL files
     * 
     * @param wsdlDefinitions - the set of imported WSDL definitions
     * @return - a List of PartnerLinkType elements
     */
    @SuppressWarnings("unchecked")
    private List<BPELPartnerLinkTypeElement> getPartnerLinkTypes( Set<Definition> wsdlDefinitions, Monitor monitor ) throws ContributionResolveException {
    	
    	List<BPELPartnerLinkTypeElement> thePLinks = new ArrayList<BPELPartnerLinkTypeElement>();

        // The BPEL partnerLinkType elements are extension elements within the WSDL definitions
        for (Definition wsdlDefinition: wsdlDefinitions) {
            for (ExtensibilityElement theElement : (List<ExtensibilityElement>)wsdlDefinition.getExtensibilityElements()) {
                QName elementType = theElement.getElementType();
                if (elementType.equals(BPELProcessorConstants.LINKTYPE_ELEMENT) || elementType.equals(BPELProcessorConstants.LINKTYPE_ELEMENT_20)) {
                    BPELPartnerLinkTypeExt pLinkExt = (BPELPartnerLinkTypeExt)theElement;
                    
                    // Fetch the name of the partnerLinkType
                    QName qName = new QName(wsdlDefinition.getTargetNamespace(), pLinkExt.getName());
                    BPELPartnerLinkTypeElement pLinkElement = new BPELPartnerLinkTypeElement(qName);

                    // The partnerLinkType must have one and may have 2 role child elements
                    int count = 0;
                    for (int i = 0; i < 2; i++) {
                        if( count > 1 ) break;
                    	if (pLinkExt.getRoleName(i) == null) continue;
                        PortType pType = wsdlDefinition.getPortType(pLinkExt.getRolePortType(i));
                        if (count == 0) {
                            pLinkElement.setRole1(pLinkExt.getRoleName(i), pLinkExt.getRolePortType(i), pType);
                        } else {
                            pLinkElement.setRole2(pLinkExt.getRoleName(i), pLinkExt.getRolePortType(i), pType);
                        } // end if
                        count++;
                    } // end for

                    if (count == 0) {
                        error(monitor, "PartnerLinkTypeNoRoles", theElement, pLinkElement.getName());
                        throw new ContributionResolveException("partnerLinkType " + pLinkElement.getName() + " has no Roles defined");
                    } else
                        thePLinks.add(pLinkElement);
                } // end if
            } // end for
        } // end for
        return thePLinks;
    } // end getPartnerLinkTypes
    

    /**
     * Finds a partnerLinkType definition within the WSDLs imported by the BPEL
     * process.
     * 
     * @param partnerLinkTypeName - the name of the partnerLinkType
     * @param theImports a list of the WSDL import declarations
     * @return a BPELPartnerLinkTypeElement for the partnerLinkType or null if it cannot be
     * found
     */
    private BPELPartnerLinkTypeElement findPartnerLinkType( QName partnerLinkTypeName, List<BPELPartnerLinkTypeElement> thePLinkTypes) {
    	// We must find the partner link type element from amongst the imported WSDLs
    	for ( BPELPartnerLinkTypeElement thePLinkType : thePLinkTypes ){
    		if( thePLinkType.getName().equals(partnerLinkTypeName) ) return thePLinkType;
     	} // end for
    	return null;
    } // end findPartnerLinkType
    

    /**
     * Returns all the portTypes referenced by the process.
     * 
     * @param theImports
     * @param theInterfaces
     * @param resolver
     * @return
     * @throws ContributionResolveException
     */
    @SuppressWarnings("unchecked")
    private Collection<PortType> getAllPortTypes(List<BPELImportElement> theImports,
                                                 Collection<WSDLInterface> theInterfaces, 
                                                 ModelResolver resolver,
                                                 ProcessorContext context) throws ContributionResolveException {

        Set<PortType> thePortTypes = new HashSet<PortType>();
        for (BPELImportElement theImport : theImports) {
            if (theImport.getImportType().equals(BPELProcessorConstants.WSDL_NS)) {
                
                // Find all the WSDL definitions matching the imported namespace
                List<Definition> wsdlDefinitions = new ArrayList<Definition>();
                WSDLDefinition theWSDL = theImport.getWSDLDefinition();
                wsdlDefinitions.add(theWSDL.getDefinition());
                for (WSDLDefinition importedWSDL: theWSDL.getImportedDefinitions()) {
                    wsdlDefinitions.add(importedWSDL.getDefinition());
                }
                for (Definition wsdlDefinition: wsdlDefinitions) {

                    Collection<PortType> portTypes = (Collection<PortType>)wsdlDefinition.getPortTypes().values();
                    
                    // Create WSDLInterface elements for each unique PortType found
                    for (PortType portType : portTypes) {
                    	if( thePortTypes.contains(portType) ) continue;
                    	thePortTypes.add( portType );
                    		
                        WSDLObject<PortType> wsdlPortType = theWSDL.getWSDLObject(PortType.class, portType.getQName());
                        WSDLInterface wsdlInterface;
                        if (wsdlPortType != null) {
                            // Introspect the WSDL portType and add the resulting WSDLInterface to the resolver
                            try {
                                wsdlInterface = wsdlFactory.createWSDLInterface(wsdlPortType.getElement(), theWSDL, resolver, context.getMonitor());
                                wsdlInterface.setWsdlDefinition(theWSDL);
                            } catch (InvalidInterfaceException e) {
                                ContributionResolveException ce = 
                                	new ContributionResolveException("Unable to create WSDLInterface for portType " + portType.getQName(),e);
                                error(context.getMonitor(), "ContributionResolveException", resolver, ce);
                                throw ce;
                            } // end try
                            resolver.addModel(wsdlInterface, context);
                            theInterfaces.add(wsdlInterface);
                        } // end if
                    } // end for
                }
            }
        } // end for

        return thePortTypes;
    } // end getAllPortTypes
    
    /**
     * Report a warning.
     * 
     * @param problems
     * @param message
     * @param model
     */
    private void warning(Monitor monitor, String message, Object model, Object... messageParameters) {
        if (monitor != null) {
            Problem problem = monitor.createProblem(this.getClass().getName(), "impl-bpel-validation-messages", Severity.WARNING, model, message, (Object[])messageParameters);
            monitor.problem(problem);
        }
    }

    /**
     * Report a error.
     * 
     * @param problems
     * @param message
     * @param model
     */
    private void error(Monitor monitor, String message, Object model, Object... messageParameters) {
        if (monitor != null) {
            Problem problem = monitor.createProblem(this.getClass().getName(), "impl-bpel-validation-messages", Severity.ERROR, model, message, (Object[])messageParameters);
            monitor.problem(problem);
        }
    }

    /**
     * Report a exception.
     * 
     * @param problems
     * @param message
     * @param model
     */
    private void error(Monitor monitor, String message, Object model, Exception ex) {
        if (monitor != null) {
            Problem problem = monitor.createProblem(this.getClass().getName(), "impl-bpel-validation-messages", Severity.ERROR, model, message, ex);
            monitor.problem(problem);
        }
    }
    
}