summaryrefslogtreecommitdiffstats
path: root/sca-java-2.x/tags/2.0.1-RC1/modules/builder/src/main/java/org/apache/tuscany/sca/builder/impl/PolicyAppliesToBuilderImpl.java
blob: 60b82b99f423f66fc528d58c442a6fed353e97c5 (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
/*
 * 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.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;

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.CompositeBuilderException;

import org.apache.tuscany.sca.context.CompositeContext;
import org.apache.tuscany.sca.core.ExtensionPointRegistry;
import org.apache.tuscany.sca.definitions.Definitions;
import org.apache.tuscany.sca.policy.PolicySet;
import org.apache.tuscany.sca.policy.PolicySubject;
import org.apache.tuscany.sca.runtime.RuntimeComponent;
import org.apache.tuscany.sca.runtime.RuntimeEndpointReference;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * A builder that checks that policy sets apply to the elements to which they are attached. 
 * Any that don't are removed. It first creates a DOM model for the composite so that the xpath
 * expression can be evaluated. For each element that holds a policy set it calculates the 
 * appliesTo nodes and checks that the current element is in the set. If not the policySet is
 * removed from the element   
 *
 * @version $Rev$ $Date$
 */
public class PolicyAppliesToBuilderImpl extends PolicyAttachmentBuilderImpl {

    public PolicyAppliesToBuilderImpl(ExtensionPointRegistry registry) {
        super(registry);
    }

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

    // Build the whole composite
    public Composite build(Composite composite, BuilderContext context)
        throws CompositeBuilderException {
        try {

	    Definitions definitions = context.getDefinitions();
            if (definitions == null || (definitions.getPolicySets().isEmpty() && definitions.getExternalAttachments().isEmpty()) ) {
                return composite;
            }
            // create a DOM for the Domain Composite Infoset
            Document document = saveAsDOM(composite);
            
            // create a cache of evaluated node against each policy set so we don't
            // have to keep evaluating policy sets that appear in multiple places
            Map<PolicySet, List<PolicySubject>> appliesToSubjects = new HashMap<PolicySet, List<PolicySubject>>();
            
            // for all implementations, endpoint and endpoint references check that 
            // the policy sets validly apply
            return checkAppliesTo(document, appliesToSubjects, composite, context);
           
        } catch (Exception e) {
            throw new CompositeBuilderException(e);
        }
    }
    
    // Build just an endpoint reference that has just been matched against an endpoint. This
    // can often happen at runtime so the policy attachTo for a reference policy cannot
    // be assessed at build time
    // THIS DOESN'T HANDLE THE NESTED COMPOSITE CASE
    public void build(EndpointReference epr) throws CompositeBuilderException {
        try {
            
            // What we really need to be doing here is...
            //
            // - correct the composite model to add the service binding to the reference
            // - turn the composite model into a DOM
            // - apply the reference policy XPath and assess whether it appliesTo the binding
            //
            // I've had a go at making the code do that below. However there is some question
            // about what the appliesTo field means and it's hard to get here from the 
            // binder so until we sort out the appliesTo question this code isn't used
                       
            CompositeContext compositeContext = ((RuntimeComponent)epr.getComponent()).getComponentContext().getCompositeContext();
            Composite domainComposite = compositeContext.getDomainComposite();
            Definitions systemDefinitions = compositeContext.getSystemDefinitions();
            
            if (systemDefinitions == null || 
                (systemDefinitions.getPolicySets().isEmpty() && 
                 systemDefinitions.getExternalAttachments().isEmpty()) ) {
                return;
            }
            
            // temporarily add the endpoint binding to the reference model so that the
            // XPath expression can be evaluated correctly
            epr.getReference().getBindings().add(epr.getTargetEndpoint().getBinding());
            
            // create a DOM for the Domain Composite Infoset
            Document document = saveAsDOM(domainComposite);
            
            // remove the binding again to retain the untainted model 
            epr.getReference().getBindings().remove(epr.getTargetEndpoint().getBinding());
            
            // create a cache of evaluated node against each policy set so we don't
            // have to keep evaluating policy sets that appear in multiple places
            Map<PolicySet, List<PolicySubject>> appliesToSubjects = new HashMap<PolicySet, List<PolicySubject>>();
            
            // can we get the composite within which the erp is defined
            
            for (PolicySet ps : new ArrayList<PolicySet>(epr.getPolicySets()) ) {
                // Check if this PolicySet applies to the binding, component reference, component, or composite. If not,
                // remove it from the list of policy sets for this endpoint. 
                if ( epr.getBinding() instanceof PolicySubject ) {
                    if (isApplicableToSubject(document, appliesToSubjects, domainComposite, (PolicySubject)epr.getBinding(), ps))
                        continue;
                }
                if (isApplicableToSubject(document, appliesToSubjects, domainComposite, epr.getReference(), ps))
                    continue;
                else if ( (epr.getReference().getInterfaceContract() != null) && 
                          (isApplicableToSubject(document, appliesToSubjects, domainComposite, epr.getReference().getInterfaceContract().getInterface(), ps)))
                    continue;
                else if ( isApplicableToSubject(document, appliesToSubjects, domainComposite, epr.getComponent(), ps))
                    continue;
                else if ( isApplicableToSubject(document, appliesToSubjects, domainComposite, domainComposite, ps))
                    continue;
                else
                    epr.getPolicySets().remove(ps);             
            }
          
        } catch (Exception e) {
            throw new CompositeBuilderException(e);
        }
    }    
    
    private Composite checkAppliesTo(Document document, Map<PolicySet, List<PolicySubject>> appliesToSubjects, Composite topComposite, BuilderContext context) throws Exception {
 
    	for ( Component component : topComposite.getComponents() ) {
    		if ( component.getImplementation() instanceof Composite ) {
    			Composite nested = (Composite) component.getImplementation();
    			checkAppliesTo(saveAsDOM(nested),new HashMap<PolicySet, List<PolicySubject>>(), nested, context );
    		}
    	}

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

    		for (ComponentService componentService : component.getServices()) {
    	
    			for (Endpoint ep : componentService.getEndpoints()) {  
    				for ( PolicySet ps : new ArrayList<PolicySet>(ep.getPolicySets()) ) {
    					// Check if this PolicySet applies to the binding, component service, interface, component, or composite. If not,
    					// remove it from the list of policy sets for this endpoint. 
    					if ( ep.getBinding() instanceof PolicySubject ) {
    						if (isApplicableToSubject(document, appliesToSubjects, topComposite, (PolicySubject)ep.getBinding(), ps))
    							continue;
    					}
    					
    					if (isApplicableToSubject(document, appliesToSubjects, topComposite, componentService, ps))
    						continue;
    					else if ( (componentService.getInterfaceContract() != null ) && (isApplicableToSubject(document, appliesToSubjects, topComposite, componentService.getInterfaceContract().getInterface(), ps)))
    						continue;
    					else if ( isApplicableToSubject(document, appliesToSubjects, topComposite, component, ps))
    						continue;
    					else if ( isApplicableToSubject(document, appliesToSubjects, topComposite, topComposite, ps))
    						continue;
    					else
    						ep.getPolicySets().remove(ps);
    				}
    			}
    		}

    		for (ComponentReference componentReference : component.getReferences()) {    			
    			for (EndpointReference epr : componentReference.getEndpointReferences()) {
    			    // don't process the EPR yet if it's not resolved
                    if (epr.getStatus() == EndpointReference.Status.WIRED_TARGET_NOT_FOUND ||
                        epr.getBinding() == null){ 
                        continue;
                    }
                    
    				for (PolicySet ps : new ArrayList<PolicySet>(epr.getPolicySets()) ) {
                        // Check if this PolicySet applies to the binding, component reference, component, or composite. If not,
                        // remove it from the list of policy sets for this endpoint. 
    					if ( epr.getBinding() instanceof PolicySubject ) {
    						if (isApplicableToSubject(document, appliesToSubjects, topComposite, (PolicySubject)epr.getBinding(), ps))
    							continue;
    					}
    					if (isApplicableToSubject(document, appliesToSubjects, topComposite, componentReference, ps))
    						continue;
    					else if ( (componentReference.getInterfaceContract() != null) && (isApplicableToSubject(document, appliesToSubjects, topComposite, componentReference.getInterfaceContract().getInterface(), ps)))
    						continue;
    					else if ( isApplicableToSubject(document, appliesToSubjects, topComposite, component, ps))
    						continue;
    					else if ( isApplicableToSubject(document, appliesToSubjects, topComposite, topComposite, ps))
    						continue;
    					else
    						epr.getPolicySets().remove(ps);    			
    				}
    			}
    		}

    		Implementation implementation = component.getImplementation();
    		if (implementation != null && 
    				implementation instanceof PolicySubject) {
    			for ( PolicySet ps : new ArrayList<PolicySet>(implementation.getPolicySets())) {    		
    				if (!isApplicableToSubject(document, appliesToSubjects, topComposite, implementation, ps))
    					implementation.getPolicySets().remove(ps);
    			}
    		}
    		
    	}
    	return topComposite;
    }

	/**
     * Checks that the provided policy sets applies to the provided policy subject
     * 
     * @param document
     * @param appliesToSubjects
     * @param policySubject
     * @param policySet
     * @return
	 * @throws XPathExpressionException    
     */
    private boolean isApplicableToSubject(Document document, Map<PolicySet, List<PolicySubject>> appliesToSubjects, Composite composite, PolicySubject policySubject, PolicySet policySet) throws XPathExpressionException {
                  
        List<PolicySubject> subjects = appliesToSubjects.get(policySet);
            
        if (subjects == null){
        	XPathExpression appliesTo = policySet.getAppliesToXPathExpression();
        	if (appliesTo != null) {
        		NodeList nodes = (NodeList)appliesTo.evaluate(document, XPathConstants.NODESET);
                    
        		if (nodes.getLength() > 0){
        			subjects = new ArrayList<PolicySubject>();
        			appliesToSubjects.put(policySet, subjects);
        		}
                    
        		for (int i = 0; i < nodes.getLength(); i++) {
        			Node node = nodes.item(i);
        			String index = getStructuralURI(node);
        			PolicySubject subject = lookup(composite, index);
        			if ( subject != null ) 
        				subjects.add(subject);
        		}
        	}
        }
            
        if (subjects != null){
        	if (!subjects.contains(policySubject)){
        		return false;
        	} else {
        		return true;
        	}
        } 
        
        return false;
                   
    }    
}