Package: CarbonPolicyFinder$1

CarbonPolicyFinder$1

nameinstructionbranchcomplexitylinemethod
removeEldestEntry(Map.Entry)
M: 10 C: 0
0%
M: 2 C: 0
0%
M: 2 C: 0
0%
M: 1 C: 0
0%
M: 1 C: 0
0%
{...}
M: 6 C: 0
0%
M: 0 C: 0
100%
M: 1 C: 0
0%
M: 1 C: 0
0%
M: 1 C: 0
0%

Coverage

1: /*
2: * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
3: *
4: * WSO2 Inc. licenses this file to you under the Apache License,
5: * Version 2.0 (the "License"); you may not use this file except
6: * in compliance with the License.
7: * You may obtain a copy of the License at
8: *
9: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing,
12: * software distributed under the License is distributed on an
13: * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14: * KIND, either express or implied. See the License for the
15: * specific language governing permissions and limitations
16: * under the License.
17: */
18:
19: package org.wso2.carbon.identity.entitlement.policy.finder;
20:
21: import org.apache.commons.logging.Log;
22: import org.apache.commons.logging.LogFactory;
23: import org.wso2.balana.AbstractPolicy;
24: import org.wso2.balana.Policy;
25: import org.wso2.balana.PolicyMetaData;
26: import org.wso2.balana.PolicyReference;
27: import org.wso2.balana.PolicySet;
28: import org.wso2.balana.VersionConstraints;
29: import org.wso2.balana.combine.PolicyCombiningAlgorithm;
30: import org.wso2.balana.ctx.EvaluationCtx;
31: import org.wso2.balana.ctx.Status;
32: import org.wso2.balana.finder.PolicyFinder;
33: import org.wso2.balana.finder.PolicyFinderResult;
34: import org.wso2.carbon.context.CarbonContext;
35: import org.wso2.carbon.identity.entitlement.EntitlementException;
36: import org.wso2.carbon.identity.entitlement.PDPConstants;
37: import org.wso2.carbon.identity.entitlement.PolicyOrderComparator;
38: import org.wso2.carbon.identity.entitlement.cache.PolicyStatus;
39: import org.wso2.carbon.identity.entitlement.common.EntitlementConstants;
40: import org.wso2.carbon.identity.entitlement.dto.PolicyDTO;
41: import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent;
42: import org.wso2.carbon.identity.entitlement.pdp.EntitlementEngine;
43: import org.wso2.carbon.identity.entitlement.policy.PolicyReader;
44: import org.wso2.carbon.identity.entitlement.policy.collection.PolicyCollection;
45: import org.wso2.carbon.identity.entitlement.policy.collection.SimplePolicyCollection;
46: import org.wso2.carbon.identity.entitlement.policy.store.DefaultPolicyDataStore;
47: import org.wso2.carbon.identity.entitlement.policy.store.PolicyDataStore;
48:
49: import java.net.URI;
50: import java.net.URISyntaxException;
51: import java.util.ArrayList;
52: import java.util.Collection;
53: import java.util.Collections;
54: import java.util.Date;
55: import java.util.Iterator;
56: import java.util.LinkedHashMap;
57: import java.util.List;
58: import java.util.Map;
59: import java.util.Properties;
60:
61: /**
62: * Policy finder of the WSO2 entitlement engine. This an implementation of <code>PolicyFinderModule</code>
63: * of Balana engine. Extensions can be plugged with this.
64: */
65: public class CarbonPolicyFinder extends org.wso2.balana.finder.PolicyFinderModule {
66:
67: private static Log log = LogFactory.getLog(CarbonPolicyFinder.class);
68: public PolicyReader policyReader;
69: private List<PolicyFinderModule> finderModules = null;
70: private PolicyCollection policyCollection;
71:
72: private List<PolicyDTO> policyCollectionOrder = new ArrayList<PolicyDTO>();
73:
74: private PolicyFinder finder;
75: /**
76: * this is a flag to keep whether init it has finished or not.
77: */
78: private volatile boolean initFinish;
79: private LinkedHashMap<URI, AbstractPolicy> policyReferenceCache = null;
80: private int maxReferenceCacheEntries = PDPConstants.MAX_NO_OF_IN_MEMORY_POLICIES;
81:
82:
83: @Override
84: public void init(PolicyFinder finder) {
85: initFinish = false;
86: this.finder = finder;
87: init();
88: policyReferenceCache.clear();
89: }
90:
91: private synchronized void init() {
92:
93: if (initFinish) {
94: return;
95: }
96:
97: log.info("Initializing of policy store is started at : " + new Date());
98:
99: String maxEntries = EntitlementServiceComponent.getEntitlementConfig().getEngineProperties().
100: getProperty(PDPConstants.MAX_POLICY_REFERENCE_ENTRIES);
101:
102: if (maxEntries != null) {
103: try {
104: maxReferenceCacheEntries = Integer.parseInt(maxEntries.trim());
105: } catch (Exception e) {
106: //ignore
107: }
108: }
109:
110: policyReferenceCache = new LinkedHashMap<URI, AbstractPolicy>() {
111:
112: @Override
113: protected boolean removeEldestEntry(Map.Entry eldest) {
114: // oldest entry of the cache would be removed when max cache size become, i.e 50
115:• return size() > maxReferenceCacheEntries;
116: }
117:
118: };
119:
120: PolicyCombiningAlgorithm policyCombiningAlgorithm = null;
121: // get registered finder modules
122: Map<PolicyFinderModule, Properties> finderModules = EntitlementServiceComponent.
123: getEntitlementConfig().getPolicyFinderModules();
124:
125: if (finderModules != null) {
126: this.finderModules = new ArrayList<PolicyFinderModule>(finderModules.keySet());
127: }
128:
129: PolicyCollection tempPolicyCollection = null;
130:
131: // get policy collection
132: Map<PolicyCollection, Properties> policyCollections = EntitlementServiceComponent.
133: getEntitlementConfig().getPolicyCollections();
134: if (policyCollections != null && policyCollections.size() > 0) {
135: tempPolicyCollection = policyCollections.entrySet().iterator().next().getKey();
136: } else {
137: tempPolicyCollection = new SimplePolicyCollection();
138: }
139:
140: // get policy reader
141: policyReader = PolicyReader.getInstance(finder);
142:
143: if (this.finderModules != null && this.finderModules.size() > 0) {
144: // find policy combining algorithm.
145:
146: // here we can get policy data store by using EntitlementAdminEngine. But we are not
147: // use it here. As we need not to have a dependant on EntitlementAdminEngine
148: PolicyDataStore policyDataStore;
149: Map<PolicyDataStore, Properties> dataStoreModules = EntitlementServiceComponent.
150: getEntitlementConfig().getPolicyDataStore();
151: if (dataStoreModules != null && dataStoreModules.size() > 0) {
152: policyDataStore = dataStoreModules.entrySet().iterator().next().getKey();
153: } else {
154: policyDataStore = new DefaultPolicyDataStore();
155: }
156: policyCombiningAlgorithm = policyDataStore.getGlobalPolicyAlgorithm();
157:
158: tempPolicyCollection.setPolicyCombiningAlgorithm(policyCombiningAlgorithm);
159:
160: for (PolicyFinderModule finderModule : this.finderModules) {
161: log.info("Start retrieving policies from " + finderModule + " at : " + new Date());
162: String[] policies = finderModule.getActivePolicies();
163: for (int a = 0; a < policies.length; a++) {
164: String policy = policies[a];
165: AbstractPolicy abstractPolicy = policyReader.getPolicy(policy);
166: if (abstractPolicy != null) {
167: PolicyDTO policyDTO = new PolicyDTO();
168: policyDTO.setPolicyId(abstractPolicy.getId().toString());
169: policyDTO.setPolicyOrder(a);
170: policyCollectionOrder.add(policyDTO);
171: tempPolicyCollection.addPolicy(abstractPolicy);
172: }
173: }
174: log.info("Finish retrieving policies from " + finderModule + " at : " + new Date());
175: }
176: } else {
177: log.warn("No Carbon policy finder modules are registered");
178:
179: }
180:
181: policyCollection = tempPolicyCollection;
182: initFinish = true;
183: log.info("Initializing of policy store is finished at : " + new Date());
184: }
185:
186: @Override
187: public String getIdentifier() {
188: return super.getIdentifier();
189: }
190:
191: @Override
192: public boolean isRequestSupported() {
193: return true;
194: }
195:
196: @Override
197: public boolean isIdReferenceSupported() {
198: return true;
199: }
200:
201:
202: private void orderPolicyCache() {
203: LinkedHashMap<URI, AbstractPolicy> policyMap = policyCollection.getPolicyMap();
204: Collections.sort(policyCollectionOrder, new PolicyOrderComparator());
205: LinkedHashMap<URI, AbstractPolicy> newPolicyMap = new LinkedHashMap<URI, AbstractPolicy>();
206: Iterator<PolicyDTO> policyDTOIterator = policyCollectionOrder.iterator();
207: while (policyDTOIterator.hasNext()) {
208: try {
209: URI policyURI = new URI(policyDTOIterator.next().getPolicyId());
210: newPolicyMap.put(policyURI, policyMap.get(policyURI));
211:
212: } catch (URISyntaxException e) {
213: e.printStackTrace();
214: }
215: }
216: }
217:
218: @Override
219: public PolicyFinderResult findPolicy(EvaluationCtx context) {
220:
221: if (EntitlementEngine.getInstance().getPolicyCache().isInvalidate()) {
222:
223: init(this.finder);
224: policyReferenceCache.clear();
225: EntitlementEngine.getInstance().clearDecisionCache();
226: EntitlementEngine.getInstance().resetCacheInvalidateState();
227: if (log.isDebugEnabled()) {
228: int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
229: log.debug("Invalidation cache message is received. " +
230: "Re-initialized policy finder module of current node and invalidate decision " +
231: "caching for tenantId : " + tenantId);
232: }
233: } else {
234: Collection<PolicyStatus> policies =
235: EntitlementEngine.getInstance().getPolicyCache().getInvalidatedPolicies();
236: if (policies != null) {
237: if (policies.size() > 0) {
238: synchronized (policies) {
239: boolean isReorder = false;
240: policyReferenceCache.clear();
241: EntitlementEngine.getInstance().clearDecisionCache();
242: for (PolicyStatus policyStatus : policies) {
243:
244: if (EntitlementConstants.PolicyPublish.ACTION_DELETE
245: .equals(policyStatus.getPolicyAction())) {
246: policyCollection.deletePolicy(policyStatus.getPolicyId());
247: policyCollectionOrder.remove(new PolicyDTO(policyStatus.getPolicyId()));
248: } else if (EntitlementConstants.PolicyPublish.ACTION_UPDATE
249: .equals(policyStatus.getPolicyAction())) {
250: AbstractPolicy abstractPolicy = loadPolicy(policyStatus.getPolicyId());
251: policyCollection.addPolicy(abstractPolicy);
252: } else if (EntitlementConstants.PolicyPublish.ACTION_CREATE
253: .equals(policyStatus.getPolicyAction())) {
254: AbstractPolicy abstractPolicy = loadPolicy(policyStatus.getPolicyId());
255: policyCollection.addPolicy(abstractPolicy);
256: isReorder = true;
257: } else if (EntitlementConstants.PolicyPublish.ACTION_ORDER
258: .equals(policyStatus.getPolicyAction())) {
259: int order = getPolicyOrder(policyStatus.getPolicyId());
260: if (order != -1) {
261: PolicyDTO policyDTO = new PolicyDTO(policyStatus.getPolicyId());
262: if (policyCollectionOrder.indexOf(policyDTO) != -1) {
263: policyCollectionOrder.get(policyCollectionOrder.indexOf(policyDTO))
264: .setPolicyOrder(order);
265: isReorder = true;
266: }
267: }
268: }
269:
270: }
271: if (isReorder) {
272: orderPolicyCache();
273: }
274: policies.clear();
275: }
276:
277:
278: }
279: }
280: }
281:
282: try {
283: AbstractPolicy policy = policyCollection.getEffectivePolicy(context);
284: if (policy == null) {
285: return new PolicyFinderResult();
286: } else {
287: return new PolicyFinderResult(policy);
288: }
289: } catch (EntitlementException e) {
290: ArrayList<String> code = new ArrayList<String>();
291: code.add(Status.STATUS_PROCESSING_ERROR);
292: Status status = new Status(code, e.getMessage());
293: return new PolicyFinderResult(status);
294: }
295: }
296:
297:
298: private AbstractPolicy loadPolicy(String policyId) {
299: if (this.finderModules != null) {
300: for (PolicyFinderModule finderModule : this.finderModules) {
301: String policyString = finderModule.getPolicy(policyId);
302: if (policyString != null) {
303: AbstractPolicy policy = policyReader.getPolicy(policyString);
304: if (policy != null) {
305: return policy;
306: }
307: }
308: }
309: }
310: return null;
311: }
312:
313: private int getPolicyOrder(String policyId) {
314: int order = -1;
315: if (this.finderModules != null) {
316:
317: for (PolicyFinderModule finderModule : this.finderModules) {
318: if ((order = finderModule.getPolicyOrder(policyId)) != -1) {
319: break;
320: }
321: }
322: }
323: return order;
324: }
325:
326: @Override
327: public PolicyFinderResult findPolicy(URI idReference, int type, VersionConstraints constraints,
328: PolicyMetaData parentMetaData) {
329:
330: AbstractPolicy policy = policyReferenceCache.get(idReference);
331:
332: if (policy == null) {
333: if (this.finderModules != null) {
334: for (PolicyFinderModule finderModule : this.finderModules) {
335: String policyString = finderModule.getReferencedPolicy(idReference.toString());
336: if (policyString != null) {
337: policy = policyReader.getPolicy(policyString);
338: if (policy != null) {
339: policyReferenceCache.put(idReference, policy);
340: break;
341: }
342: }
343: }
344: }
345: }
346:
347: if (policy != null) {
348: // we found a valid version, so see if it's the right kind,
349: // and if it is then we return it
350: if (type == PolicyReference.POLICY_REFERENCE) {
351: if (policy instanceof Policy) {
352: return new PolicyFinderResult(policy);
353: }
354: } else {
355: if (policy instanceof PolicySet) {
356: return new PolicyFinderResult(policy);
357: }
358: }
359: }
360:
361: return new PolicyFinderResult();
362: }
363:
364: public void clearPolicyCache() {
365: EntitlementEngine.getInstance().getPolicyCache().clear();
366: }
367: }