summaryrefslogtreecommitdiffstats
path: root/sca-java-2.x/tags/2.0.1-RC1/modules/builder/src/main/java/org/apache/tuscany/sca/builder/impl/CompositePolicyBuilderImpl.java
blob: 9ef41dcf33af6a0c3a48364d9a264e1906eb1b51 (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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
/*
 * 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.builder.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.xml.namespace.QName;

import org.apache.tuscany.sca.assembly.Base;
import org.apache.tuscany.sca.assembly.Component;
import org.apache.tuscany.sca.assembly.ComponentReference;
import org.apache.tuscany.sca.assembly.ComponentService;
import org.apache.tuscany.sca.assembly.Composite;
import org.apache.tuscany.sca.assembly.Endpoint;
import org.apache.tuscany.sca.assembly.EndpointReference;
import org.apache.tuscany.sca.assembly.Implementation;
import org.apache.tuscany.sca.assembly.builder.BuilderContext;
import org.apache.tuscany.sca.assembly.builder.CompositeBuilder;
import org.apache.tuscany.sca.assembly.builder.CompositeBuilderException;
import org.apache.tuscany.sca.assembly.builder.PolicyBuilder;
import org.apache.tuscany.sca.assembly.xml.Constants;
import org.apache.tuscany.sca.core.ExtensionPointRegistry;
import org.apache.tuscany.sca.interfacedef.Operation;
import org.apache.tuscany.sca.monitor.Monitor;
import org.apache.tuscany.sca.policy.Intent;
import org.apache.tuscany.sca.policy.PolicyExpression;
import org.apache.tuscany.sca.policy.PolicySet;
import org.apache.tuscany.sca.policy.PolicySubject;
import org.apache.tuscany.sca.policy.util.PolicyHelper;

/**
 * A composite builder that computes policy sets based on attached intents and policy sets.
 * Useful if you want to build the model without making any runtime decisions such as
 * reference/services matching
 *
 * @version $Rev$ $Date$
 */
public class CompositePolicyBuilderImpl extends ComponentPolicyBuilderImpl implements CompositeBuilder {
    private final static QName NOLISTENER_INTENT = new QName(Base.SCA11_NS, "noListener");
    private CompositeBuilder policyAppliesToBuilder = null;
    
    public CompositePolicyBuilderImpl(ExtensionPointRegistry registry) {
        super(registry);
        
        policyAppliesToBuilder = new PolicyAppliesToBuilderImpl(registry);
    }

    public String getID() {
        return "org.apache.tuscany.sca.assembly.builder.CompositePolicyBuilder";
    }

    public Composite build(Composite composite, BuilderContext context) throws CompositeBuilderException {
        computePolicies(composite, context);
        checkPolicies(composite, context);
        buildPolicies(composite, context);
        return composite;
    }

    protected void computePolicies(Composite composite, BuilderContext context) {
        Monitor monitor = context.getMonitor();
        monitor.pushContext("Composite: " + composite.getName().toString());

        try {
            resolveAndCheck(composite, context);

            // compute policies recursively
            for (Component component : composite.getComponents()) {
                monitor.pushContext("Component: " + component.getName());

                //resolve component level
                resolveAndCheck(component, context);
                
                try {
                    Implementation implementation = component.getImplementation();
                    
                    for (ComponentService componentService : component.getServices()) {
                        monitor.pushContext("Service: " + componentService.getName());

                        try {
                            resolveAndCheck(componentService, context);

                            if (componentService.getInterfaceContract() != null) {
                                resolveAndCheck(componentService.getInterfaceContract().getInterface(), context);

                                resolveAndCheck(componentService.getInterfaceContract().getCallbackInterface(), context);

                            }

                            for (Endpoint ep : componentService.getEndpoints()) {
                              
                                
                                // Inherit from binding
                                inherit(ep, null, true, ep.getBinding());
                                
                                // Inherit from composite/component/service
                                inherit(ep, null, true, ep.getService(), ep.getComponent(), composite );
                                
                                if (componentService.getInterfaceContract() != null) {
                                    // Inherit from the component.service.interface
                                	// Do not check mutual exclusion here.. interfaces do not follow normal rules
                                	// of the structural hierarchy (Policy spec 4.10)
                                    inherit(ep, null, false, componentService.getInterfaceContract().getInterface());
                                }
                                
                                // add in default binding mayProvides intents
                                addDefaultIntents(ep, ep.getBinding(), context);

                                // Replace profile intents with their required intents
                                // Replace unqualified intents if there is a qualified intent in the list
                                // Replace qualifiable intents with the default qualied intent
                                resolveAndNormalize(ep, context);
                                
                                // Replace qualifiable intents with their default qualifier
                                expandDefaultIntents(ep, context);
                                
                                // Remove the intents whose @contraints do not include the current element
                                removeConstrainedIntents(ep, context);
                                
                                // Remove any direct policy sets if an external one has been applied
                                removeDirectPolicySetsIfExternalExists(ep, context);
                                
                                // Validate that noListener is not specified on a service endpoint
                                checkForNoListenerIntent(ep, context);
                                
                                // check that all intents are resolved
                                checkIntentsResolved(ep, context);

                                // check that the resulting endpoint has no mutually exclusive intents
                                checkMutualExclusion(ep, context);
                            }
                        } finally {
                            monitor.popContext();
                        }
                    }

                    for (ComponentReference componentReference : component.getReferences()) {
                        monitor.pushContext("Reference: " + componentReference.getName().toString());

                        try {

                            if (componentReference.getInterfaceContract() != null) {
                                resolveAndCheck(componentReference.getInterfaceContract().getInterface(), context);

                                resolveAndCheck(componentReference.getInterfaceContract().getCallbackInterface(),
                                                context);
                            }

                            for (EndpointReference epr : componentReference.getEndpointReferences()) {
                                                             
                                // Inherit from binding
                                inherit(epr, null, true, epr.getBinding());

                                // Inherit from composite/component/reference
                                inherit(epr, null, true,  epr.getReference(), epr.getComponent(),  composite);
                                
                                // Inherit from the component.reference.interface
                                if (componentReference.getInterfaceContract() != null) {
                                	// Do not check mutual exclusion here.. interfaces do not follow normal rules
                                	// of the structural hierarchy (Policy spec 4.10)
                                    inherit(epr, null, true, componentReference.getInterfaceContract().getInterface());
                                }  
                                
                                // add in default binding mayProvides intents
                                addDefaultIntents(epr, epr.getBinding(), context);

                                // Replace profile intents with their required intents
                                // Replace unqualified intents if there is a qualified intent in the list
                                // Replace qualifiable intents with the default qualified intent
                                resolveAndNormalize(epr, context);
                                
                                // Replace qualifiable intents with their default qualifier
                                expandDefaultIntents(epr, context);
                                
                                // Remove the intents whose @contraints do not include the current element
                                removeConstrainedIntents(epr, context);
                                
                                removeDirectPolicySetsIfExternalExists(epr, context);
                                
                                // check that all intents are resolved
                                checkIntentsResolved(epr, context);

                                // check that the resulting endpoint reference has no mutually exclusive intents
                                checkMutualExclusion(epr, context);
                            }
                        } finally {
                            monitor.popContext();
                        }
                    }

                    if (implementation instanceof Composite) {                    	                     		
                    	resolveAndCheck(implementation, context);
                        inherit(implementation, Intent.Type.implementation, true, component, composite);                                             
                        computePolicies((Composite)implementation, context);
                        expandDefaultIntents(implementation,context);
                        checkIntentsResolved(implementation,context);
                    } else {
                        resolveAndCheck(implementation, context);
                        if (implementation != null) {
                            inherit(implementation, Intent.Type.implementation, true, component, composite);
                            
                            // Remove the intents whose @contraints do not include the current element
                            removeConstrainedIntents(implementation, context);
                            
                            removeDirectPolicySetsIfExternalExists(implementation, context);
                            
                         // Replace qualifiable intents with their default qualifier
                            expandDefaultIntents(implementation, context);
                            
                            // check that all intents are resolved
                            checkIntentsResolved(implementation, context);
                        }
                    }
                } finally {
                    monitor.popContext();
                }
            }
            removeConstrainedIntents(composite, context);
        } finally {
            monitor.popContext();
        }
    }
 
    private void validateTransactionIntents(Composite composite, BuilderContext context) {    	    		       	   
    	 
    	for ( Component component : composite.getComponents() ) {    	
    		if ( component.getImplementation() != null ) {
    			if ( component.getImplementation() instanceof Composite ) 
    				validateTransactionIntents((Composite) component.getImplementation(), context);    		   
    			
    			for ( Intent implIntent : component.getImplementation().getRequiredIntents() ) {
    				if ( Constants.MANAGED_TRANSACTION_LOCAL_INTENT.equals(implIntent.getName() ) ) {
    					for ( ComponentReference reference : component.getReferences() ) {
    						for ( EndpointReference epr : reference.getEndpointReferences() ) {
    							for ( Intent eprIntent : epr.getRequiredIntents() ) {
    								if ( Constants.TRANSACTED_ONE_WAY_INTENT.equals(eprIntent.getName())) {
    									error(context.getMonitor(), 
    										"TransactedOneWayWithManagedTransactionLocal", 
    		    			    			this,
    		    			    			"reference",
    		    			    			epr.getComponent().getName(),
    		    			    			epr.getReference().getName());
    								} else if ( Constants.PROPAGATES_TRANSACTION_INTENT.equals(eprIntent.getName())) {
    									error(context.getMonitor(),
    											"PropagatesTransactionWithLocalTran",
    											this,
    											"reference",
    											epr.getComponent().getName(),
    											epr.getReference().getName());
    								}
    							}
    						}
    					}    	
    					for ( ComponentService service : component.getServices() ) {
    						for ( Endpoint ep : service.getEndpoints() ) {
    							for ( Intent epIntent : ep.getRequiredIntents() ) {
    								if ( Constants.TRANSACTED_ONE_WAY_INTENT.equals(epIntent.getName())) {
    									error(context.getMonitor(),
    											"TransactedOneWayWithManagedTransactionLocal",
    											this,
    											"service",
    											ep.getComponent().getName(),
    											ep.getService().getName());
    								} else if ( Constants.PROPAGATES_TRANSACTION_INTENT.equals(epIntent.getName())) {
    									error(context.getMonitor(),
    											"PropagatesTransactionWithLocalTran",
    											this,
    											"service",
    											ep.getComponent().getName(),
    											ep.getService().getName());
    								}
    							}
    						}
    					}
    				} else if ( Constants.NO_MANAGED_TRANSACTION_INTENT.equals(implIntent.getName())) {
    					for ( ComponentService service : component.getServices() ) {
    						for ( Endpoint ep : service.getEndpoints() ) {
    							for ( Intent epIntent : ep.getRequiredIntents() ) {
    								if ( Constants.PROPAGATES_TRANSACTION_INTENT.equals(epIntent.getName())) {
    									error(context.getMonitor(), 
    										"PropagatesTransactionWithNoManagedTran", 
    		    			    			this,
    		    			    			"service",
    		    			    			ep.getComponent().getName(),
    		    			    			ep.getService().getName());
    								}
    							}
    						}
    					}
    					for ( ComponentReference reference : component.getReferences() ) {
    						for ( EndpointReference epr : reference.getEndpointReferences() ) {
    							for ( Intent eprIntent : epr.getRequiredIntents() ) {
    								if ( Constants.PROPAGATES_TRANSACTION_INTENT.equals(eprIntent.getName())) {
    									error(context.getMonitor(),
    											"PropagatesTransactionWithNoManagedTran",
    											this,
    											"reference",
    											epr.getComponent().getName(),
    											epr.getReference().getName());
    								}
    							}
    						}
    					}
    				}
    			}
    			     		
/*  TUSCANY-4006 - This is allowed; transactedOneWay applies only to the one-way methods when an interface also has two-way operations
 */			
       			for ( ComponentReference reference : component.getReferences()) {
    				for ( EndpointReference epr : reference.getEndpointReferences() ) {
    					for ( Intent eprIntent : epr.getRequiredIntents() ) {
    						if ( Constants.TRANSACTED_ONE_WAY_INTENT.equals(eprIntent.getName()) ) {
    							for ( Operation o : epr.getComponentReferenceInterfaceContract().getInterface().getOperations() ) {
    								if ( !o.isNonBlocking() ) {
    									error(context.getMonitor(),
    											"TransactedOneWayWithTwoWayOp",
    											this,
    											reference.getName(),
    											o.getName());
    								}
    									
    							}
    						} else if ( Constants.IMMEDIATE_ONE_WAY_INTENT.equals(eprIntent.getName())) {
    							for ( Operation o : epr.getComponentReferenceInterfaceContract().getInterface().getOperations() ) {
    								if ( !o.isNonBlocking() ) {
    									error(context.getMonitor(),
    											"ImmediateOneWayWithTwoWayOp",
    											this,
    											reference.getName(),
    											o.getName());
    								}
    									
    							}
    						}
    					}    					
    				}   				
    			}
/*
*/    			
    		}   
    	}
    }
    	        					 	
   

	private void checkForNoListenerIntent(Endpoint ep, BuilderContext context) {
		PolicyHelper helper = new PolicyHelper();
		if ( helper.getIntent(ep, NOLISTENER_INTENT) != null ) {
			  error(context.getMonitor(), 
                      "NoListenerIntentSpecifiedOnService", 
                      this,
                      ep.toString());
		} 				
		
	}

	private void removeDirectPolicySetsIfExternalExists(PolicySubject subject,
			BuilderContext context) {
    	boolean foundExternalPolicySet = false;
		for (PolicySet ps : subject.getPolicySets() ) {
			if ( ps.isExternalAttachment() ) {
				foundExternalPolicySet = true;
				break;
			}
		}
		
		if ( foundExternalPolicySet ) {
			List<PolicySet> copy = new ArrayList<PolicySet>(subject.getPolicySets());
			for ( PolicySet ps : copy ) {
				if ( !ps.isExternalAttachment() ) {
					subject.getPolicySets().remove(ps);
				}
			}
		}
		
	} 

	/**
     * This is mainly about removing policies that don't "applyTo" the element where
     * they have ended up after all the attachment and inheritance processing
     * 
     * @param composite
     * @param context
     */
    protected void checkPolicies(Composite composite, BuilderContext context) throws CompositeBuilderException{
        policyAppliesToBuilder.build(composite, context);
        validateTransactionIntents(composite, context);
    }

    protected void buildPolicies(Composite composite, BuilderContext context) {

        // build policies recursively
        for (Component component : composite.getComponents()) {
            Implementation implementation = component.getImplementation();
            if (implementation instanceof Composite) {
                buildPolicies((Composite)implementation, context);
            }
        }

        for (Component component : composite.getComponents()) {

            for (ComponentService componentService : component.getServices()) {
                for (Endpoint ep : componentService.getEndpoints()) {
                    Set<String> policyNames = getPolicyNames(ep);
                    
                    // check that only one policy language is present in the endpoint's policy sets
                    if (policyNames.size() > 1){
                        error(context.getMonitor(), 
                              "MultiplePolicyLanguagesInEP", 
                              this,
                              ep.toString(), 
                              policyNames.toString());
                    } else {
                        for (PolicySet ps : ep.getPolicySets()) {
                            for (PolicyExpression exp : ps.getPolicies()) {
                                PolicyBuilder builder = builders.getPolicyBuilder(exp.getName());
                                if (builder != null) {
                                    builder.build(ep, context);
                                }                
                            }
                        }                        
                    }
                }
            }

            for (ComponentReference componentReference : component.getReferences()) {
                for (EndpointReference epr : componentReference.getEndpointReferences()) {
                    Set<String> policyNames = getPolicyNames(epr);
                    
                    // check that only one policy language is present in the endpoint references's policy sets
                    if (policyNames.size() > 1){
                        error(context.getMonitor(),  
                              "MultiplePolicyLanguagesInEPR",
                              this,
                              epr.toString(), 
                              policyNames.toString());
                    } else {                    
                        for (PolicySet ps : epr.getPolicySets()) {
                            for (PolicyExpression exp : ps.getPolicies()) {
                                PolicyBuilder builder = builders.getPolicyBuilder(exp.getName());
                                if (builder != null) {
                                    builder.build(epr, context);
                                }
                            }
                        }
                    }
                }
            }

            Implementation implementation = component.getImplementation();
            if (implementation != null) {
                Set<String> policyNames = getPolicyNames(implementation);
                
                // check that only one policy language is present in the implementations's policy sets
                if (policyNames.size() > 1){
                    error(context.getMonitor(), 
                          "MultiplePolicyLanguagesInImplementation", 
                          this,
                          component.toString(), 
                          policyNames.toString());
                } else {
                    for (PolicySet ps : implementation.getPolicySets()) {
                        for (PolicyExpression exp : ps.getPolicies()) {                    
                            PolicyBuilder builder = builders.getPolicyBuilder(exp.getName());
                            if (builder != null) {
                                builder.build(component, implementation, context);
                            }
                        }
                    }
                }
            }
        }
    }
}