summaryrefslogtreecommitdiffstats
path: root/tags/java/sca/2.0-M3-RC3a/modules/assembly/src/main/java/org/apache/tuscany/sca/assembly/builder/impl/PolicyConfigurationUtil.java
blob: a7a40e62e6ec8db0acd66743885d3ac51b2bfff9 (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
/*
 * 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.assembly.builder.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.xml.namespace.QName;

import org.apache.tuscany.sca.assembly.Base;
import org.apache.tuscany.sca.assembly.Binding;
import org.apache.tuscany.sca.assembly.Component;
import org.apache.tuscany.sca.assembly.Contract;
import org.apache.tuscany.sca.assembly.Implementation;
import org.apache.tuscany.sca.policy.ExtensionType;
import org.apache.tuscany.sca.policy.Intent;
import org.apache.tuscany.sca.policy.IntentMap;
import org.apache.tuscany.sca.policy.PolicySet;
import org.apache.tuscany.sca.policy.PolicySubject;
import org.apache.tuscany.sca.policy.util.PolicyComputationUtils;
import org.apache.tuscany.sca.policy.util.PolicyValidationException;
import org.apache.tuscany.sca.policy.util.PolicyValidationUtils;

/**
 * This class contains policy computation methods common to computing implementation and binding policies
 *
 * @version $Rev$ $Date$
 */
abstract class PolicyConfigurationUtil {
    
    private static List<Intent> computeInheritableIntents(ExtensionType attachPointType, 
                                                   List<Intent> inheritableIntents) throws PolicyValidationException {
        List<Intent> validInheritableIntents = new ArrayList<Intent>();
        
        //expand profile intents in inherited intents
        PolicyComputationUtils.expandProfileIntents(inheritableIntents);

        //validate if inherited intent applies to the attachpoint (binding / implementation) and 
        //only add such intents to the attachpoint (binding / implementation)
        for (Intent intent : inheritableIntents) {
            if ( !intent.isUnresolved() ) { 
                for (ExtensionType constrained : intent.getConstrainedTypes()) {
                    if ( PolicyValidationUtils.isConstrained(constrained, attachPointType)) {
                        validInheritableIntents.add(intent);
                        break;
                    }
                }
            } else {
                throw new PolicyValidationException("Policy Intent '" + intent.getName() + "' is not defined in this domain");
            }
        }
        
        return validInheritableIntents;
    }
    
    private static void normalizeIntents(PolicySubject intentAttachPoint) {
        //expand profile intents specified in the attachpoint (binding / implementation)
        PolicyComputationUtils.expandProfileIntents(intentAttachPoint.getRequiredIntents());

        //remove duplicates and ...
        //where qualified form of intent exists retain it and remove the qualifiable intent
        filterDuplicatesAndQualifiableIntents(intentAttachPoint);
    }
    
    private static void trimInherentlyProvidedIntents(ExtensionType attachPointType, List<Intent>intents) {
        //exclude intents that are inherently supported by the 
        //attachpoint-type (binding-type  / implementation-type)
        List<Intent> requiredIntents = new ArrayList<Intent>(intents);
        for ( Intent intent : requiredIntents ) {
            if ( isProvidedInherently(attachPointType, intent) ) {
                intents.remove(intent);
            }
        }
    }
    
    
    private static List<PolicySet> computeInheritablePolicySets(List<PolicySet> inheritablePolicySets) 
                                                               throws PolicyValidationException {
        // FIXME:
        return inheritablePolicySets;
    }
    
    private static void normalizePolicySets(PolicySubject subject ) {
        //get rid of duplicate entries
        Set<PolicySet> policySetTable = new HashSet<PolicySet>(subject.getPolicySets());
        
        subject.getPolicySets().clear();
        subject.getPolicySets().addAll(policySetTable);
            
        //expand profile intents
        for ( PolicySet policySet : subject.getPolicySets() ) {
            PolicyComputationUtils.expandProfileIntents(policySet.getProvidedIntents());
        }
    }
    
    private static void trimProvidedIntents(List<Intent> requiredIntents, List<PolicySet> policySets) {
        for ( PolicySet policySet : policySets ) {
            trimProvidedIntents(requiredIntents, policySet);
        }
    }
    
    private static void determineApplicableDomainPolicySets(List<PolicySet> applicablePolicySets,
                                                     PolicySubject policySetAttachPoint,
                                                     ExtensionType intentAttachPointType) {

        if (policySetAttachPoint.getRequiredIntents().size() > 0) {

            // form a list of all intents required by the attach point
            List<Intent> combinedTargetIntents = new ArrayList<Intent>();
            combinedTargetIntents.addAll(policySetAttachPoint.getRequiredIntents());
            for (PolicySet targetPolicySet : policySetAttachPoint.getPolicySets()) {
                combinedTargetIntents.addAll(PolicyComputationUtils.findAndExpandProfileIntents(targetPolicySet.getProvidedIntents()));
            }

            //since the set of applicable policysets for this attachpoint is known 
            //we only need to check in that list if there is a policyset that matches
            for (PolicySet policySet : applicablePolicySets) {
                // do not use the policy set if it provides intents that conflict with required intents
                boolean conflict = false;
                List<Intent> providedIntents = PolicyComputationUtils.findAndExpandProfileIntents(policySet.getProvidedIntents());
                checkConflict: for (Intent intent : providedIntents) {
                    for (Intent excluded : intent.getExcludedIntents()) {
                        if (combinedTargetIntents.contains(excluded)) {
                            conflict = true;
                            break checkConflict;
                        }
                    }
                }
                if (conflict)
                    continue;
                int prevSize = policySetAttachPoint.getRequiredIntents().size();
                trimProvidedIntents(policySetAttachPoint.getRequiredIntents(), policySet);
                // if any intent was trimmed off, then this policyset must
                // be attached to the intent attachpoint's policyset
                if (prevSize != policySetAttachPoint.getRequiredIntents().size()) {
                    policySetAttachPoint.getPolicySets().add(policySet);
                }
            } 
        }
    }
    
    private static boolean isProvidedInherently(ExtensionType attachPointType, Intent intent) {
        return ( attachPointType != null && 
                 (( attachPointType.getAlwaysProvidedIntents() != null &&
                     attachPointType.getAlwaysProvidedIntents().contains(intent) ) || 
                  ( attachPointType.getMayProvidedIntents() != null &&
                     attachPointType.getMayProvidedIntents().contains(intent) )
                 ) );
     }
    
    private static void trimProvidedIntents(List<Intent> requiredIntents, PolicySet policySet) {
        for ( Intent providedIntent : policySet.getProvidedIntents() ) {
            if ( requiredIntents.contains(providedIntent) ) {
                requiredIntents.remove(providedIntent);
            } 
        }
        
        for ( IntentMap intentMap : policySet.getIntentMaps() ) {
            if ( requiredIntents.contains(intentMap.getProvidedIntent()) ) {
                requiredIntents.remove(intentMap.getProvidedIntent());
            } 
        }
    }
    
    private static void filterDuplicatesAndQualifiableIntents(PolicySubject intentAttachPoint) {
        //remove duplicates
        Map<QName, Intent> intentsTable = new HashMap<QName, Intent>();
        for ( Intent intent : intentAttachPoint.getRequiredIntents() ) {
            intentsTable.put(intent.getName(), intent);
        }
        
        //where qualified form of intent exists retain it and remove the qualifiable intent
        Map<QName, Intent> intentsTableCopy = new HashMap<QName, Intent>(intentsTable);
        //if qualified form of intent exists remove the unqualified form
        for ( Intent intent : intentsTableCopy.values() ) {
            if ( intent.getQualifiableIntent()!=null ) {
                if ( intentsTable.get(intent.getQualifiableIntent().getName()) != null ) {
                    intentsTable.remove(intent.getQualifiableIntent().getName());
                }
            }
        }
        intentAttachPoint.getRequiredIntents().clear();
        intentAttachPoint.getRequiredIntents().addAll(intentsTable.values());
    }

    static void computeBindingIntentsAndPolicySets(Contract contract)  throws PolicyValidationException {
        for (Binding binding : contract.getBindings()) {
            if (binding instanceof PolicySubject) {
                PolicySubject policiedBinding = (PolicySubject)binding;
                computeIntents((PolicySubject)binding, contract.getRequiredIntents());
                
                computePolicySets(policiedBinding, contract.getPolicySets());
    
                PolicyComputationUtils.checkForMutuallyExclusiveIntents(
                    policiedBinding.getRequiredIntents(),
                    policiedBinding.getPolicySets(),
                    policiedBinding.getType(),
                    contract.getName());
            }
        }
        
        if ( contract.getCallback() != null ) {
            for (Binding binding : contract.getCallback().getBindings()) {
                if (binding instanceof PolicySubject) {
                    PolicySubject policiedBinding = (PolicySubject)binding;
                    computeIntents((PolicySubject)binding, contract.getCallback().getRequiredIntents());
            
                    computePolicySets(policiedBinding, contract.getCallback().getPolicySets());
    
                    PolicyComputationUtils.checkForMutuallyExclusiveIntents(
                        policiedBinding.getRequiredIntents(),
                        policiedBinding.getPolicySets(),
                        policiedBinding.getType(),
                        contract.getName() + " callback");
    
                }
            }
        }
    }

    private static void computeIntents(PolicySubject policiedBinding, List<Intent> inheritedIntents) 
                                                                    throws PolicyValidationException {
            //since the parent component could also contain intents that apply to implementation
            //and binding elements within, we filter out only those that apply to this binding type
            List<Intent> prunedIntents = computeInheritableIntents(policiedBinding.getType(), 
                                                                   inheritedIntents);
            policiedBinding.getRequiredIntents().addAll(prunedIntents);
            
            normalizeIntents(policiedBinding);
    }

    private static void computePolicySets(PolicySubject policiedBinding,
                                   List<PolicySet> inheritedPolicySets) throws PolicyValidationException {
                
        List<PolicySet> prunedPolicySets = computeInheritablePolicySets(inheritedPolicySets);
        policiedBinding.getPolicySets().addAll(prunedPolicySets);
        normalizePolicySets(policiedBinding);
    }

    static void determineApplicableBindingPolicySets(Contract source, Contract target) throws PolicyConfigurationException {
        List<Intent> intentsCopy = null;
        for (Binding aBinding : source.getBindings()) {
            if (aBinding instanceof PolicySubject) {
                PolicySubject policiedBinding = (PolicySubject)aBinding;
                ExtensionType bindingType = policiedBinding.getType();
    
                
                intentsCopy = new ArrayList<Intent>(policiedBinding.getRequiredIntents());
                // add the target component's intents to the reference binding
                if (target != null) {
                    for (Intent intent : target.getRequiredIntents()) {
                        if (!policiedBinding.getRequiredIntents().contains(intent)) {
                            for (ExtensionType constrained : intent.getConstrainedTypes()) {
                                if (bindingType != null && bindingType.getType().getNamespaceURI()
                                    .equals(constrained.getType().getNamespaceURI())
                                    && bindingType.getType().getLocalPart().startsWith(constrained
                                        .getType().getLocalPart())) {
                                    policiedBinding.getRequiredIntents().add(intent);
                                    break;
                                }
                            }
                        }
                    }
                }
    
                trimInherentlyProvidedIntents(policiedBinding.getType(), 
                                              policiedBinding.getRequiredIntents());
                trimProvidedIntents(policiedBinding.getRequiredIntents(), policiedBinding
                    .getPolicySets());
    
                // determine additional policysets that match remaining intents
                // TODO: resolved to domain policy registry and attach suitable
                // policy sets to the binding
                // for now using the SCA Definitions instead of registry
                // if there are intents that are not provided by any policy set
                // throw a warning
                determineApplicableDomainPolicySets(source, policiedBinding);
                
                //the intents list could have been trimmed when matching for policysets
                //since the bindings may need the original set of intents we copy that back
                policiedBinding.getRequiredIntents().clear();
                policiedBinding.getRequiredIntents().addAll(intentsCopy);
                
            }
        }
    }

    private static void determineApplicableDomainPolicySets(Contract contract, 
                                                     PolicySubject policiedBinding) 
                                                            throws PolicyConfigurationException {
        // FIXME:
        /*
        //if ( domainPolicySets != null) {
            determineApplicableDomainPolicySets(policiedBinding.getApplicablePolicySets(), 
                                                policiedBinding,
                                                policiedBinding.getType());
            
            if ( policiedBinding.getRequiredIntents().size() > 0 ) {
                if ( contract instanceof Service ) {
                    throw new PolicyConfigurationException("The following are unfulfilled intents for " +
                            "binding in service - " + contract.getName() + "\nUnfulfilled Intents = " + 
                            policiedBinding.getRequiredIntents());
                } else {
                    throw new PolicyConfigurationException("The are unfulfilled intents for " +
                            "binding in reference - " + contract.getName() + "\nUnfulfilled Intents = " + 
                            policiedBinding.getRequiredIntents());
                }
            }
        //}
         */
    }

    private static void aggregateAndPruneApplicablePolicySets(List<PolicySet> source, List<PolicySet> target) {
        target.addAll(source);
        //strip duplicates
        Hashtable<QName, PolicySet> policySetTable = new Hashtable<QName, PolicySet>();
        for ( PolicySet policySet : target ) {
            policySetTable.put(policySet.getName(), policySet);
        }
        
        target.clear();
        target.addAll(policySetTable.values());
    }

    static <C extends Contract> void inheritDefaultPolicies(Base parent, List<C> contracts) {
    
        for (Contract contract : contracts) {
    
            // The contract inherits default policies from the parent composite/component.
            if ( parent instanceof PolicySubject )  {
                PolicyComputationUtils.addDefaultPolicies(
                                         ((PolicySubject)parent).getRequiredIntents(),
                                         ((PolicySubject)parent).getPolicySets(),
                                         contract.getRequiredIntents(),
                                         contract.getPolicySets());
            }
    
            // The contract's callback inherits default policies from the contract.
            if (contract.getCallback() != null) {
                PolicyComputationUtils.addDefaultPolicies(
                                         contract.getRequiredIntents(),
                                         contract.getPolicySets(),
                                         contract.getCallback().getRequiredIntents(),
                                         contract.getCallback().getPolicySets());
            }
    
        }
    }

    static void computeImplementationIntentsAndPolicySets(Implementation implementation, Component parent)  
                                                                throws PolicyValidationException, PolicyConfigurationException {
        if ( implementation instanceof PolicySubject ) {
            PolicySubject policiedImplementation = (PolicySubject)implementation;
            //since for an implementation the component has its policy intents and policysets its possible
            //that there are some intents there that does not constrain the implementation.. so prune 
            List<Intent> prunedIntents = computeInheritableIntents(policiedImplementation.getType(), 
                                                                   parent.getRequiredIntents());
            parent.getRequiredIntents().clear();
            parent.getRequiredIntents().addAll(prunedIntents);
            normalizeIntents(parent);
    
            List<PolicySet> prunedPolicySets = computeInheritablePolicySets(parent.getPolicySets());
            parent.getPolicySets().clear();
            parent.getPolicySets().addAll(prunedPolicySets);
            normalizePolicySets(parent);
    
            PolicyComputationUtils.checkForMutuallyExclusiveIntents(
                parent.getRequiredIntents(),
                parent.getPolicySets(),
                policiedImplementation.getType(),
                parent.getName());
    
            determineApplicableImplementationPolicySets(parent);
    
        }
    }

    private static void determineApplicableImplementationPolicySets(Component component) throws PolicyConfigurationException {
        List<Intent> intentsCopy = null;
        if ( component.getImplementation() instanceof PolicySubject ) {
            PolicySubject policiedImplementation = (PolicySubject)component.getImplementation();
                
            intentsCopy = new ArrayList<Intent>(component.getRequiredIntents());
            trimInherentlyProvidedIntents(policiedImplementation.getType(), 
                                          component.getRequiredIntents());
            trimProvidedIntents(component.getRequiredIntents(), component.getPolicySets());
                
            //determine additional policysets that match remaining intents
            //if there are intents that are not provided by any policy set throw a warning
            //TODO: resolved to domain policy registry and attach suitable policy sets to the implementation
            //...for now using the SCA Definitions instead of registry
            //if ( domainPolicySets != null)  {
                                                    
                if (component.getRequiredIntents().size() > 0) {
                    throw new PolicyConfigurationException("The following are unfulfilled intents for component implementation - " + component
                        .getName() + "\nUnfulfilled Intents = " + component.getRequiredIntents());
                }
            //}
            
            //the intents list could have been trimmed when matching for policysets
            //since the bindings may need the original set of intents we copy that back
            component.getRequiredIntents().clear();
            component.getRequiredIntents().addAll(intentsCopy);
        }
    }
}