diff --git a/components/action-mgt/org.wso2.carbon.identity.action.execution/pom.xml b/components/action-mgt/org.wso2.carbon.identity.action.execution/pom.xml index 4173b2637d37..ba62777f4345 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.execution/pom.xml +++ b/components/action-mgt/org.wso2.carbon.identity.action.execution/pom.xml @@ -21,7 +21,7 @@ org.wso2.carbon.identity.framework action-mgt - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../pom.xml diff --git a/components/action-mgt/org.wso2.carbon.identity.action.execution/src/main/java/org/wso2/carbon/identity/action/execution/impl/ActionExecutorServiceImpl.java b/components/action-mgt/org.wso2.carbon.identity.action.execution/src/main/java/org/wso2/carbon/identity/action/execution/impl/ActionExecutorServiceImpl.java index 94e054d0fecf..d4c1ffc4eee8 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.execution/src/main/java/org/wso2/carbon/identity/action/execution/impl/ActionExecutorServiceImpl.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.execution/src/main/java/org/wso2/carbon/identity/action/execution/impl/ActionExecutorServiceImpl.java @@ -114,13 +114,10 @@ public ActionExecutionStatus execute(ActionType actionType, Map execute(ActionType actionType, String[] actionId validateActionIdList(actionType, actionIdList); Action action = getActionByActionId(actionType, actionIdList[0], tenantDomain); - DIAGNOSTIC_LOGGER.logActionInitiation(action); try { return execute(action, eventContext); } catch (ActionExecutionRuntimeException e) { - DIAGNOSTIC_LOGGER.logSkippedActionExecution(actionType); LOG.debug("Skip executing actions for action type: " + actionType.name(), e); - // Skip executing actions when no action available or due to a failure in retrieving actions, - // is considered as action execution being successful. + // Skip executing actions when no action available is considered as action execution being successful. return new SuccessStatus.Builder().setResponseContext(eventContext).build(); } } @@ -172,6 +166,7 @@ private ActionExecutionStatus execute(Action action, Map even ActionExecutionResponseProcessor actionExecutionResponseProcessor = getResponseProcessor(actionType); if (action.getStatus() == Action.Status.ACTIVE) { + DIAGNOSTIC_LOGGER.logActionInitiation(action); return executeAction(action, actionRequest, eventContext, actionExecutionResponseProcessor); } else { // If no active actions are detected, it is regarded as the action execution being successful. @@ -191,13 +186,13 @@ private Action getActionByActionId(ActionType actionType, String actionId, Strin } private List getActionsByActionType(ActionType actionType, String tenantDomain) throws - ActionExecutionRuntimeException { + ActionExecutionException { try { return ActionExecutionServiceComponentHolder.getInstance().getActionManagementService() .getActionsByActionType(Action.ActionTypes.valueOf(actionType.name()).getPathParam(), tenantDomain); } catch (ActionMgtException e) { - throw new ActionExecutionRuntimeException("Error occurred while retrieving actions.", e); + throw new ActionExecutionException("Error occurred while retrieving actions.", e); } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.execution/src/main/java/org/wso2/carbon/identity/action/execution/util/ActionExecutionDiagnosticLogger.java b/components/action-mgt/org.wso2.carbon.identity.action.execution/src/main/java/org/wso2/carbon/identity/action/execution/util/ActionExecutionDiagnosticLogger.java index 31a2f9c45cfd..4b3f750de2d7 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.execution/src/main/java/org/wso2/carbon/identity/action/execution/util/ActionExecutionDiagnosticLogger.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.execution/src/main/java/org/wso2/carbon/identity/action/execution/util/ActionExecutionDiagnosticLogger.java @@ -21,7 +21,6 @@ import org.apache.http.client.methods.HttpPost; import org.wso2.carbon.identity.action.execution.ActionExecutionLogConstants; import org.wso2.carbon.identity.action.execution.model.ActionInvocationResponse; -import org.wso2.carbon.identity.action.execution.model.ActionType; import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.central.log.mgt.utils.LoggerUtils; import org.wso2.carbon.utils.DiagnosticLog; @@ -47,19 +46,6 @@ public void logActionInitiation(Action action) { DiagnosticLog.ResultStatus.SUCCESS)); } - public void logSkippedActionExecution(ActionType actionType) { - - if (!LoggerUtils.isDiagnosticLogsEnabled()) { - return; - } - - triggerLogEvent( - initializeDiagnosticLogBuilder( - ActionExecutionLogConstants.ActionIDs.EXECUTE_ACTION, - "Skip executing action for " + actionType + " type.", - DiagnosticLog.ResultStatus.FAILED)); - } - public void logActionRequest(Action action) { if (!LoggerUtils.isDiagnosticLogsEnabled()) { diff --git a/components/action-mgt/org.wso2.carbon.identity.action.execution/src/test/java/org/wso2/carbon/identity/action/execution/impl/ActionExecutorServiceImplTest.java b/components/action-mgt/org.wso2.carbon.identity.action.execution/src/test/java/org/wso2/carbon/identity/action/execution/impl/ActionExecutorServiceImplTest.java index 5f1ece8a0c9e..96ac65dacdd3 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.execution/src/test/java/org/wso2/carbon/identity/action/execution/impl/ActionExecutorServiceImplTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.execution/src/test/java/org/wso2/carbon/identity/action/execution/impl/ActionExecutorServiceImplTest.java @@ -230,6 +230,16 @@ public void testActionExecuteWithActionIdFailureWhenInvalidActionIdGiven() throw actionExecutorService.execute(ActionType.PRE_ISSUE_ACCESS_TOKEN, new String[]{any()}, any(), any()); } + @Test(expectedExceptions = ActionExecutionException.class, + expectedExceptionsMessageRegExp = "Error occurred while retrieving actions.") + public void testActionExecuteWithActionFailureWhenInvalidActionGiven() throws Exception { + + when(actionManagementService.getActionsByActionType(any(), any())).thenThrow( + new ActionMgtException("Error occurred while retrieving actions.")); + + actionExecutorService.execute(ActionType.PRE_ISSUE_ACCESS_TOKEN, any(), any()); + } + @Test(expectedExceptions = ActionExecutionException.class, expectedExceptionsMessageRegExp = "Failed to build the request payload for action type: " + "PRE_ISSUE_ACCESS_TOKEN") diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml b/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml index 4b4be8e287d9..3f9169cfbbb4 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.identity.framework action-mgt - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../pom.xml diff --git a/components/action-mgt/pom.xml b/components/action-mgt/pom.xml index 086df4b98999..064962145d1b 100644 --- a/components/action-mgt/pom.xml +++ b/components/action-mgt/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.identity.framework identity-framework - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../../pom.xml diff --git a/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.collection.mgt/pom.xml b/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.collection.mgt/pom.xml index 7e15e252ad8d..2fafe440f411 100644 --- a/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.collection.mgt/pom.xml +++ b/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.collection.mgt/pom.xml @@ -21,7 +21,7 @@ org.wso2.carbon.identity.framework api-resource-mgt - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../pom.xml diff --git a/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/pom.xml b/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/pom.xml index 5c8e2851fed6..562f53a5c63a 100644 --- a/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/pom.xml +++ b/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/pom.xml @@ -21,7 +21,7 @@ org.wso2.carbon.identity.framework api-resource-mgt - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../pom.xml org.wso2.carbon.identity.api.resource.mgt diff --git a/components/api-resource-mgt/pom.xml b/components/api-resource-mgt/pom.xml index d5ec1fba483c..860d34576a87 100644 --- a/components/api-resource-mgt/pom.xml +++ b/components/api-resource-mgt/pom.xml @@ -21,7 +21,7 @@ org.wso2.carbon.identity.framework identity-framework - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../../pom.xml diff --git a/components/application-mgt/org.wso2.carbon.identity.application.common/pom.xml b/components/application-mgt/org.wso2.carbon.identity.application.common/pom.xml index 64c0eb0bb01e..19d6925b5cdc 100644 --- a/components/application-mgt/org.wso2.carbon.identity.application.common/pom.xml +++ b/components/application-mgt/org.wso2.carbon.identity.application.common/pom.xml @@ -18,7 +18,7 @@ org.wso2.carbon.identity.framework application-mgt - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../pom.xml diff --git a/components/application-mgt/org.wso2.carbon.identity.application.mgt.ui/pom.xml b/components/application-mgt/org.wso2.carbon.identity.application.mgt.ui/pom.xml index c9f7619c45db..2ec12e157a22 100644 --- a/components/application-mgt/org.wso2.carbon.identity.application.mgt.ui/pom.xml +++ b/components/application-mgt/org.wso2.carbon.identity.application.mgt.ui/pom.xml @@ -19,7 +19,7 @@ org.wso2.carbon.identity.framework application-mgt - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../pom.xml diff --git a/components/application-mgt/org.wso2.carbon.identity.application.mgt/pom.xml b/components/application-mgt/org.wso2.carbon.identity.application.mgt/pom.xml index b44bde459e8f..9e031c9f1947 100644 --- a/components/application-mgt/org.wso2.carbon.identity.application.mgt/pom.xml +++ b/components/application-mgt/org.wso2.carbon.identity.application.mgt/pom.xml @@ -21,7 +21,7 @@ org.wso2.carbon.identity.framework application-mgt - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../pom.xml org.wso2.carbon.identity.application.mgt diff --git a/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/test/resources/repository/conf/identity/identity.xml b/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/test/resources/repository/conf/identity/identity.xml index fdf6f07a9355..b6626035b87e 100644 --- a/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/test/resources/repository/conf/identity/identity.xml +++ b/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/test/resources/repository/conf/identity/identity.xml @@ -294,7 +294,6 @@ - - - - - - - - - - - - diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.endpoint/README.md b/components/entitlement/org.wso2.carbon.identity.entitlement.endpoint/README.md deleted file mode 100644 index f3ec4a2ff85b..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.endpoint/README.md +++ /dev/null @@ -1,24 +0,0 @@ -REST API implementation for WSO2 IS -=================================== - -This is a REST implementation of the WSO2 IS Entitlement Service, done as a part of GSoC 2016 - -The code is still in early stages, and I would highly appreciate if you could carry out tests and provide feedback / issues / comments on it. - -Design and implementation -------------------------- - -Design and implementation details of the endpoint is available at [http://manzzup.blogspot.com/2016/08/gsoc-2016-rest-implementation-for-wso2.html](http://manzzup.blogspot.com/2016/08/gsoc-2016-rest-implementation-for-wso2.html) - - -Procedure --------- - -1. Download the target/entitlement.war file -2. Place it in your **{IS ROOT}/repository/deployement/server/webapps** (Tested for IS 5.2.0) -3. You can hot deploy the war file as well -4. Once deployed the WADL definitions for the service can be seen at, **https://localhost:9443/entitlement/entitlement/Decision?_wadl** -5. The service curently support both JSON and XML -6. TO test various service methods, use the curl requests and json/xml request definitions available under resources/curlTests - -Thank you!! diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.endpoint/REQUIRED_CHANGES.md b/components/entitlement/org.wso2.carbon.identity.entitlement.endpoint/REQUIRED_CHANGES.md deleted file mode 100644 index 81640581ce27..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.endpoint/REQUIRED_CHANGES.md +++ /dev/null @@ -1,26 +0,0 @@ -Changes need to be done for different wso2 components for completion of the endpoint -==================================================================================== - -Balana ------- - -1) Public constructor for [MultiRequests](https://github.com/wso2/balana/blob/master/modules/balana-core/src/main/java/org/wso2/balana/xacml3/MultiRequests.java) - -Needs the public constructor for manual creation of `RequestCtx` object in JSONParser - -2) Public getter for obligationId in [Obligation](https://github.com/wso2/balana/blob/master/modules/balana-core/src/main/java/org/wso2/balana/xacml3/Obligation.java) - -Refer the following [PR](https://github.com/wso2/balana/pull/41) - -3) Public method in [PDP](https://github.com/wso2/balana/blob/master/modules/balana-core/src/main/java/org/wso2/balana/PDP.java) that -can convert a given XACML String to `ResponseCtx` object. - -This process only done internally in `evaluate` method bodies. But in the REST endpoint, someone can send the request in XACML -but needs the response in JSON, for which the `evaluate` method should either return a ResponseCtx object or a JSON String. Since -JSON is not already supported in Balana, if there's a converter method to produce `RequestCtx` from XACML String, the exsting -evaluate method can be used. - -4) Integrating the JSON support - -JSON support is give using 2 supporter classes in the REST source code. But since the functionality of the code is better related -to balana, it's better to implement them inside Balana. diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.endpoint/pom.xml b/components/entitlement/org.wso2.carbon.identity.entitlement.endpoint/pom.xml index 2a683f22138d..631d34da6f96 100644 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.endpoint/pom.xml +++ b/components/entitlement/org.wso2.carbon.identity.entitlement.endpoint/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.identity.framework entitlement ../pom.xml - 7.6.20-SNAPSHOT + 7.7.0-SNAPSHOT org.wso2.carbon.identity.entitlement.endpoint diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.endpoint/src/main/webapp/META-INF/webapp-classloading.xml b/components/entitlement/org.wso2.carbon.identity.entitlement.endpoint/src/main/webapp/META-INF/webapp-classloading.xml deleted file mode 100644 index aa3a4c279762..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.endpoint/src/main/webapp/META-INF/webapp-classloading.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - false - - - CXF3,Carbon - diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.endpoint/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/entitlement/org.wso2.carbon.identity.entitlement.endpoint/src/main/webapp/WEB-INF/cxf-servlet.xml deleted file mode 100644 index a9cac8d44233..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.endpoint/src/main/webapp/WEB-INF/cxf-servlet.xml +++ /dev/null @@ -1,99 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.endpoint/src/main/webapp/WEB-INF/web.xml b/components/entitlement/org.wso2.carbon.identity.entitlement.endpoint/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 7b1c2f3bbd89..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.endpoint/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,131 +0,0 @@ - - - - - - - Entitlement-Service-Provider - - - HttpHeaderSecurityFilter - org.apache.catalina.filters.HttpHeaderSecurityFilter - - hstsEnabled - false - - - - - HttpHeaderSecurityFilter - * - - - - ContentTypeBasedCachePreventionFilter - - org.wso2.carbon.ui.filters.cache.ContentTypeBasedCachePreventionFilter - - - patterns - "text/html" ,"application/json" ,"plain/text" - - - filterAction - enforce - - - httpHeaders - - Cache-Control: no-store, no-cache, must-revalidate, private - - - - - - ContentTypeBasedCachePreventionFilter - * - - - - - ApiOriginFilter - org.wso2.carbon.identity.entitlement.endpoint.filter.ApiOriginFilter - - - ApiOriginFilter - /* - - - - EntitlementServlet - EntitlementServlet - Entitlement Endpoints - org.apache.cxf.transport.servlet.CXFServlet - 1 - - - - swagger.api.basepath - https://localhost:9443/entitlement - - - - - EntitlementServlet - /* - - - - 60 - - true - - - - - - secured services - /decision/* - - - - - - CONFIDENTIAL - - - - - org.wso2.carbon.identity.entitlement.endpoint.impl.ApplicationInitializer - - - - - - diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/pom.xml b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/pom.xml index d93944923a25..f987d471181e 100644 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/pom.xml +++ b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/pom.xml @@ -21,7 +21,7 @@ org.wso2.carbon.identity.framework entitlement - 7.6.20-SNAPSHOT + 7.7.0-SNAPSHOT ../pom.xml diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/EntitlementPolicyBean.java b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/EntitlementPolicyBean.java deleted file mode 100644 index b6e97e01b7f8..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/EntitlementPolicyBean.java +++ /dev/null @@ -1,485 +0,0 @@ -/* - * Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.entitlement.ui; - -import org.wso2.balana.utils.policy.dto.BasicRuleDTO; -import org.wso2.balana.utils.policy.dto.BasicTargetDTO; -import org.wso2.carbon.identity.entitlement.stub.dto.EntitlementFinderDataHolder; -import org.wso2.carbon.identity.entitlement.stub.dto.EntitlementTreeNodeDTO; -import org.wso2.carbon.identity.entitlement.ui.dto.ExtendAttributeDTO; -import org.wso2.carbon.identity.entitlement.ui.dto.ObligationDTO; -import org.wso2.carbon.identity.entitlement.ui.dto.PolicyRefIdDTO; -import org.wso2.carbon.identity.entitlement.ui.dto.PolicySetDTO; -import org.wso2.carbon.identity.entitlement.ui.dto.RuleDTO; -import org.wso2.carbon.identity.entitlement.ui.dto.SimplePolicyEditorDTO; -import org.wso2.carbon.identity.entitlement.ui.dto.TargetDTO; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * This Bean is used to keep the user data temporary while travelling through - * the UI wizard - */ - -/** - * @deprecated As this moved to org.wso2.carbon.identity.entitlement.common - */ -@Deprecated -public class EntitlementPolicyBean { - - public Map functionIdMap = new HashMap(); - public Map functionIdElementValueMap = new HashMap(); - private String policyName; - private String algorithmName; - private String policyDescription; - private String userInputData; - private List subscribersList = new ArrayList(); - private SimplePolicyEditorDTO SimplePolicyEditorDTO; - private Map categoryMap = new HashMap(); - private Map targetFunctionMap = new HashMap(); - private Map attributeIdMap = new HashMap(); - private Map ruleFunctionMap = new HashMap(); - private boolean editPolicy; - private String[] policyCombiningAlgorithms = new String[0]; - private Map entitlementFinders = - new HashMap(); - private Map selectedEntitlementData = new HashMap(); - private Map entitlementLevelData = - new HashMap(); - private BasicTargetDTO basicTargetDTO = null; - private TargetDTO targetDTO = null; - private PolicySetDTO policySetDTO = null; - private List basicRuleDTOs = new ArrayList(); - - private List ruleDTOs = new ArrayList(); - - private List extendAttributeDTOs = new ArrayList(); - - private List obligationDTOs = new ArrayList(); - - private String ruleElementOrder; - - private String policyReferenceOrder; - - private Set preFunctions = new HashSet(); - - private List policyRefIds = new ArrayList(); - - /** - * This method is temporally used to clear the entitlement bean. Need to - * update with a method proper implementation TODO - */ - public void cleanEntitlementPolicyBean() { - - policyName = null; - - algorithmName = null; - - policyDescription = null; - - userInputData = null; - - editPolicy = false; - - policySetDTO = null; - - functionIdMap.clear(); - - functionIdElementValueMap.clear(); - - basicRuleDTOs.clear(); - - removeBasicTargetElementDTO(); - - targetDTO = null; - - ruleDTOs.clear(); - - extendAttributeDTOs.clear(); - - obligationDTOs.clear(); - - SimplePolicyEditorDTO = null; - - basicTargetDTO = null; - - policyReferenceOrder = null; - - policyRefIds.clear(); - - } - - public String getPolicyName() { - return policyName; - } - - public void setPolicyName(String policyName) { - this.policyName = policyName; - } - - public String getAlgorithmName() { - return algorithmName; - } - - public void setAlgorithmName(String algorithmName) { - this.algorithmName = algorithmName; - } - - public String getPolicyDescription() { - return policyDescription; - } - - public void setPolicyDescription(String policyDescription) { - this.policyDescription = policyDescription; - } - - public String getUserInputData() { - return userInputData; - } - - public void setUserInputData(String userInputData) { - this.userInputData = userInputData; - } - - public List getBasicRuleDTOs() { - return basicRuleDTOs; - } - - public void setBasicRuleDTOs(List basicRuleDTOs) { - this.basicRuleDTOs = basicRuleDTOs; - } - - public void setBasicRuleElementDTOs(BasicRuleDTO basicRuleDTO) { - if (basicRuleDTOs.size() > 0) { - Iterator iterator = basicRuleDTOs.listIterator(); - while (iterator.hasNext()) { - BasicRuleDTO elementDTO = (BasicRuleDTO) iterator - .next(); - if (elementDTO.getRuleId().equals( - basicRuleDTO.getRuleId())) { - if (elementDTO.isCompletedRule()) { - basicRuleDTO.setCompletedRule(true); - } - iterator.remove(); - } - } - } - this.basicRuleDTOs.add(basicRuleDTO); - } - - public BasicRuleDTO getBasicRuleElement(String ruleId) { - if (basicRuleDTOs.size() > 0) { - for (BasicRuleDTO basicRuleDTO : basicRuleDTOs) { - if (basicRuleDTO.getRuleId().equals(ruleId)) { - return basicRuleDTO; - } - } - } - return null; - } - - public boolean removeBasicRuleElement(String ruleId) { - if (basicRuleDTOs.size() > 0 && ruleId != null) { - for (BasicRuleDTO basicRuleDTO : basicRuleDTOs) { - if (ruleId.equals(basicRuleDTO.getRuleId())) { - return basicRuleDTOs.remove(basicRuleDTO); - } - } - } - return false; - } - - public void removeBasicRuleElements() { - if (basicRuleDTOs.size() > 0) { - Iterator iterator = basicRuleDTOs.listIterator(); - while (iterator.hasNext()) { - iterator.next(); - iterator.remove(); - } - } - } - - -/////////////////////////////////////// new - - public List getRuleDTOs() { - return ruleDTOs; - } - - public void setRuleDTOs(List ruleDTOs) { - this.ruleDTOs = ruleDTOs; - } - - public void setRuleDTO(RuleDTO ruleDTO) { - if (ruleDTOs.size() > 0) { - Iterator iterator = ruleDTOs.listIterator(); - while (iterator.hasNext()) { - RuleDTO elementDTO = (RuleDTO) iterator.next(); - if (elementDTO.getRuleId().equals( - ruleDTO.getRuleId())) { - if (elementDTO.isCompletedRule()) { - ruleDTO.setCompletedRule(true); - } - iterator.remove(); - } - } - } - this.ruleDTOs.add(ruleDTO); - } - - public RuleDTO getRuleDTO(String ruleId) { - if (ruleDTOs.size() > 0) { - for (RuleDTO ruleDTO : ruleDTOs) { - if (ruleDTO.getRuleId().equals(ruleId)) { - return ruleDTO; - } - } - } - return null; - } - - public boolean removeRuleDTO(String ruleId) { - if (ruleDTOs.size() > 0) { - for (RuleDTO ruleDTO : ruleDTOs) { - if (ruleDTO.getRuleId().equals(ruleId)) { - return ruleDTOs.remove(ruleDTO); - } - } - } - return false; - } - - public void removeRuleDTOs() { - if (ruleDTOs.size() > 0) { - Iterator iterator = ruleDTOs.listIterator(); - while (iterator.hasNext()) { - iterator.next(); - iterator.remove(); - } - } - } - - public List getExtendAttributeDTOs() { - return extendAttributeDTOs; - } - - public void setExtendAttributeDTOs(List extendAttributeDTOs) { - this.extendAttributeDTOs = extendAttributeDTOs; - } - - public List getObligationDTOs() { - return obligationDTOs; - } - - public void setObligationDTOs(List obligationDTOs) { - this.obligationDTOs = obligationDTOs; - } - - public void addExtendAttributeDTO(ExtendAttributeDTO extendAttributeDTO) { - this.extendAttributeDTOs.add(extendAttributeDTO); - } - - /////////////////////////// //////// - public BasicTargetDTO getBasicTargetDTO() { - return basicTargetDTO; - } - - public void setBasicTargetDTO( - BasicTargetDTO basicTargetDTO) { - this.basicTargetDTO = basicTargetDTO; - } - - public void removeBasicTargetElementDTO() { - this.basicTargetDTO = null; - } - - public boolean isEditPolicy() { - return editPolicy; - } - - public void setEditPolicy(boolean editPolicy) { - this.editPolicy = editPolicy; - } - - public String[] getPolicyCombiningAlgorithms() { - return Arrays.copyOf(policyCombiningAlgorithms, policyCombiningAlgorithms.length); - } - - public void setPolicyCombiningAlgorithms(String[] policyCombiningAlgorithms) { - this.policyCombiningAlgorithms = Arrays.copyOf(policyCombiningAlgorithms, policyCombiningAlgorithms.length); - } - - public PolicySetDTO getPolicySetDTO() { - return policySetDTO; - } - - public void setPolicySetDTO(PolicySetDTO policySetDTO) { - this.policySetDTO = policySetDTO; - } - - public String getRuleElementOrder() { - return ruleElementOrder; - } - - public void setRuleElementOrder(String ruleElementOrder) { - this.ruleElementOrder = ruleElementOrder; - } - - - public TargetDTO getTargetDTO() { - return targetDTO; - } - - public void setTargetDTO(TargetDTO targetDTO) { - this.targetDTO = targetDTO; - } - - public Map getCategoryMap() { - return categoryMap; - } - - public void setCategoryMap(Map categoryMap) { - this.categoryMap = categoryMap; - } - - public Set getCategorySet() { - return categoryMap.keySet(); - } - - public Map getRuleFunctionMap() { - return ruleFunctionMap; - } - - public void setRuleFunctionMap(Map ruleFunctionMap) { - this.ruleFunctionMap = ruleFunctionMap; - } - - public Map getTargetFunctionMap() { - return targetFunctionMap; - } - - public void setTargetFunctionMap(Map targetFunctionMap) { - this.targetFunctionMap = targetFunctionMap; - } - - public Map getAttributeIdMap() { - return attributeIdMap; - } - - public void setAttributeIdMap(Map attributeIdMap) { - this.attributeIdMap = attributeIdMap; - } - - public Set getPreFunctions() { - return preFunctions; - } - - public void addPreFunction(String preFunction) { - this.preFunctions.add(preFunction); - } - - - public SimplePolicyEditorDTO getSimplePolicyEditorDTO() { - return SimplePolicyEditorDTO; - } - - public void setSimplePolicyEditorDTO(SimplePolicyEditorDTO simplePolicyEditorDTO) { - this.SimplePolicyEditorDTO = simplePolicyEditorDTO; - } - - public Map getEntitlementFinders() { - return entitlementFinders; - } - - public Set getEntitlementFinders(String category) { - Set holders = new HashSet(); - for (Map.Entry entry : entitlementFinders.entrySet()) { - EntitlementFinderDataHolder holder = entry.getValue(); - if (Arrays.asList(holder.getSupportedCategory()).contains(category)) { - holders.add(holder); - } - } - return holders; - } - - public void setEntitlementFinders(String name, EntitlementFinderDataHolder entitlementFinders) { - this.entitlementFinders.put(name, entitlementFinders); - } - - public Map getSelectedEntitlementData() { - return selectedEntitlementData; - } - - public Map getEntitlementLevelData() { - return entitlementLevelData; - } - - public List getPolicyRefIds() { - return policyRefIds; - } - - public void setPolicyRefIds(List policyRefIds) { - this.policyRefIds = policyRefIds; - } - - public void addPolicyRefId(PolicyRefIdDTO policyRefId) { - Iterator iterator = policyRefIds.listIterator(); - while (iterator.hasNext()) { - PolicyRefIdDTO dto = (PolicyRefIdDTO) iterator.next(); - if (policyRefId != null && dto.getId().equalsIgnoreCase(policyRefId.getId())) { - iterator.remove(); - } - } - this.policyRefIds.add(policyRefId); - } - - public void removePolicyRefId(String policyRefId) { - Iterator iterator = policyRefIds.listIterator(); - while (iterator.hasNext()) { - PolicyRefIdDTO dto = (PolicyRefIdDTO) iterator.next(); - if (policyRefId != null && dto.getId().equalsIgnoreCase(policyRefId)) { - iterator.remove(); - } - } - } - - public String getPolicyReferenceOrder() { - return policyReferenceOrder; - } - - public void setPolicyReferenceOrder(String policyReferenceOrder) { - this.policyReferenceOrder = policyReferenceOrder; - } - - public List getSubscribersList() { - return subscribersList; - } - - public void setSubscribersList(String[] subscribersList) { - List list = new ArrayList(Arrays.asList(subscribersList)); - this.subscribersList.addAll(list); - } -} \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/EntitlementPolicyConstants.java b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/EntitlementPolicyConstants.java deleted file mode 100644 index 78a48fb4f0db..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/EntitlementPolicyConstants.java +++ /dev/null @@ -1,251 +0,0 @@ -/* -* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.ui; - -/** - * Constants related with XACML policy such as per-defined Element Names and NameSpaces - */ - -/** - * @deprecated As this moved to org.wso2.carbon.identity.entitlement.common - */ -@Deprecated -public class EntitlementPolicyConstants { - - public static final int DEFAULT_ITEMS_PER_PAGE = 10; - public static final String ENTITLEMENT_ADMIN_CLIENT = "EntitlementAdminClient"; - public static final String ENTITLEMENT_SUBSCRIBER_CLIENT = "EntitlementSubscriberClient"; - - public static final String ENTITLEMENT_CURRENT_VERSION = "currentVersion"; - - public static final String XACML3_POLICY_NAMESPACE = "urn:oasis:names:tc:xacml:3.0:core:schema:wd-17"; - - public static final String ATTRIBUTE_NAMESPACE = "urn:oasis:names:tc:xacml:2.0:example:attribute:"; - - public static final String POLICY_ELEMENT = "Policy"; - - public static final String APPLY_ELEMENT = "Apply"; - - public static final String MATCH_ELEMENT = "Match"; - - public static final String SUBJECT_ELEMENT = "Subject"; - - public static final String ACTION_ELEMENT = "Action"; - - public static final String RESOURCE_ELEMENT = "Resource"; - - public static final String ENVIRONMENT_ELEMENT = "Environment"; - - public static final String POLICY_ID = "PolicyId"; - - public static final String RULE_ALGORITHM = "RuleCombiningAlgId"; - - public static final String POLICY_VERSION = "Version"; - - public static final String DESCRIPTION_ELEMENT = "Description"; - - public static final String TARGET_ELEMENT = "Target"; - - public static final String RULE_ELEMENT = "Rule"; - - public static final String CONDITION_ELEMENT = "Condition"; - - public static final String FUNCTION_ELEMENT = "Function"; - - public static final String ATTRIBUTE_SELECTOR = "AttributeSelector"; - - public static final String ATTRIBUTE_VALUE = "AttributeValue"; - - public static final String FUNCTION = "Function"; - - public static final String VARIABLE_REFERENCE = "VariableReference"; - - public static final String ATTRIBUTE_DESIGNATOR = "AttributeDesignator"; - - public static final String ATTRIBUTE_ID = "AttributeId"; - - public static final String CATEGORY = "Category"; - - public static final String ATTRIBUTE = "Attribute"; - - public static final String ATTRIBUTES = "Attributes"; - - public static final String INCLUDE_RESULT = "IncludeInResult"; - - public static final String DATA_TYPE = "DataType"; - - public static final String ISSUER = "Issuer"; - - public static final String MUST_BE_PRESENT = "MustBePresent"; - - public static final String REQUEST_CONTEXT_PATH = "RequestContextPath"; - - public static final String MATCH_ID = "MatchId"; - - public static final String RULE_ID = "RuleId"; - - public static final String RULE_EFFECT = "Effect"; - - public static final String RULE_DESCRIPTION = "Description"; - - public static final String FUNCTION_ID = "FunctionId"; - - public static final String VARIABLE_ID = "VariableId"; - - public static final String OBLIGATION_EXPRESSIONS = "ObligationExpressions"; - - public static final String OBLIGATION_EXPRESSION = "ObligationExpression"; - - public static final String OBLIGATION_ID = "ObligationId"; - - public static final String OBLIGATION_EFFECT = "FulfillOn"; - - public static final String ADVICE_EXPRESSIONS = "AdviceExpressions"; - - public static final String ADVICE_EXPRESSION = "AdviceExpression"; - - public static final String ADVICE_ID = "AdviceId"; - - public static final String ADVICE_EFFECT = "AppliesTo"; - - public static final String ATTRIBUTE_ASSIGNMENT = "AttributeAssignmentExpression"; - - public static final String STRING_DATA_TYPE = "http://www.w3.org/2001/XMLSchema#string"; - - public static final String INT_DATA_TYPE = "http://www.w3.org/2001/XMLSchema#integer"; - - public static final String BOOLEAN_DATA_TYPE = "http://www.w3.org/2001/XMLSchema#boolean"; - - public static final String DATE_DATA_TYPE = "http://www.w3.org/2001/XMLSchema#date"; - - public static final String TIME_DATA_TYPE = "http://www.w3.org/2001/XMLSchema#time"; - - public static final String DATE_TIME_DATA_TYPE = "http://www.w3.org/2001/XMLSchema#dateTime"; - - public static final String FUNCTION_BAG = "urn:oasis:names:tc:xacml:1.0:function:string-bag"; - - public static final String SUBJECT_ID_DEFAULT = "urn:oasis:names:tc:xacml:1.0:subject:subject-id"; - - public static final String SUBJECT_ID_ROLE = "http://wso2.org/claims/roles"; - - public static final String RESOURCE_ID = "urn:oasis:names:tc:xacml:1.0:resource:resource-id"; - - public static final String RESOURCE_ID_DEFAULT = "urn:oasis:names:tc:xacml:1.0:resource:resource"; - -// public static final String FUNCTION_EQUAL = "urn:oasis:names:tc:xacml:1.0:function:string-equal"; -// -// public static final String FUNCTION_ONE_AND_ONLY = "urn:oasis:names:tc:xacml:1.0:function:string-one-and-only"; -// -// public static final String FUNCTION_IS_IN = "urn:oasis:names:tc:xacml:1.0:function:string-is-in"; -// -// public static final String FUNCTION_REGEXP = "urn:oasis:names:tc:xacml:1.0:function:string-regexp-match"; -// -// public static final String FUNCTION_AT_LEAST = "urn:oasis:names:tc:xacml:1.0:function:string-at-least-one-member-of"; -// -// public static final String FUNCTION_UNION = "urn:oasis:names:tc:xacml:1.0:function:string-union"; -// -// public static final String FUNCTION_SUBSET = "urn:oasis:names:tc:xacml:1.0:function:string-subset"; -// -// public static final String FUNCTION_SET_EQUAL = "urn:oasis:names:tc:xacml:1.0:function:string-set-equals"; -// -// public static final String FUNCTION_ANY_OF = "urn:oasis:names:tc:xacml:1.0:function:any-of"; -// -// public static final String FUNCTION_AND = "urn:oasis:names:tc:xacml:1.0:function:and"; -// -// public static final String EQUAL_TO = "equals to"; -// -// public static final String MATCH_TO = "matching-with"; -// -// public static final String IS_IN = "in"; -// -// public static final String REGEXP_MATCH = "matching reg-ex to"; -// -// public static final String AT_LEAST = "at-least-one-member-of"; -// -// public static final String AT_LEAST_ONE_MATCH = "at-least-one-matching-member-of"; -// -// public static final String AT_LEAST_ONE_MATCH_REGEXP = "at-least-one-matching-reg-ex-member-of"; -// -// public static final String SUBSET_OF = "a-sub-set-of"; -// -// public static final String SET_OF = "a-matching-set-of"; -// -// public static final String MATCH_REGEXP_SET_OF = "a matching reg-ex set of"; - - public static final String RULE_EFFECT_PERMIT = "Permit"; - - public static final String RULE_EFFECT_NOT_APPLICABLE = "Not Applicable"; - - public static final String RULE_EFFECT_DENY = "Deny"; - - public static final String ACTION_ID = "urn:oasis:names:tc:xacml:1.0:action:action-id"; - - public static final String ENVIRONMENT_ID = "urn:oasis:names:tc:xacml:1.0:environment:environment-id"; - - public static final String SUBJECT_TYPE_ROLES = "Roles"; - - public static final String SUBJECT_TYPE_USERS = "Users"; - - public static final String DEFAULT_CARBON_DIALECT = "http://wso2.org/claims"; - - public static final String IMPORT_POLICY_REGISTRY = "Registry"; - - public static final String IMPORT_POLICY_FILE_SYSTEM = "FileSystem"; - - public static final String REQ_RES_CONTEXT_XACML2 = "urn:oasis:names:tc:xacml:2.0:context:schema:os"; - - public static final String REQ_RES_CONTEXT_XACML3 = "urn:oasis:names:tc:xacml:3.0:core:schema:wd-17"; - - public static final String REQ_SCHEME = "http://www.w3.org/2001/XMLSchema-instance"; - - public static final String RETURN_POLICY_LIST = "ReturnPolicyIdList"; - - public static final String COMBINED_DECISION = "CombinedDecision"; - - public static final String REQUEST_ELEMENT = "Request"; - - public static final String POLICY_SET_ID = "PolicySetId"; - - public static final String POLICY_ALGORITHM = "PolicyCombiningAlgId"; - - public static final String POLICY_SET_ELEMENT = "PolicySet"; - - public static final String POLICY_REFERENCE = "PolicyIdReference"; - - public static final String POLICY_SET_REFERENCE = "PolicySetIdReference"; - - public static final String ATTRIBUTE_SEPARATOR = ","; - - public static final String COMBO_BOX_DEFAULT_VALUE = "---Select---"; - - public static final String COMBO_BOX_ANY_VALUE = "Any"; - - public static final String SEARCH_ERROR = "Search_Error"; - - public static final String DEFAULT_META_DATA_MODULE_NAME = "Carbon Attribute Finder Module"; - - public static final int BASIC_POLICY_EDITOR_RULE_DATA_AMOUNT = 23; - - public static final int BASIC_POLICY_EDITOR_TARGET_DATA_AMOUNT = 20; - - public static final String ENTITLEMENT_PUBLISHER_PROPERTY = "entitlementPublisherPropertyDTO"; - - public static final String ENTITLEMENT_PUBLISHER_MODULE = "entitlementPublisherModuleHolders"; - -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/EntitlementPolicyCreationException.java b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/EntitlementPolicyCreationException.java deleted file mode 100644 index a37955b9bda6..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/EntitlementPolicyCreationException.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.entitlement.ui; - -import org.wso2.carbon.identity.base.IdentityException; - -/** - * @deprecated As this moved to org.wso2.carbon.identity.entitlement.common - */ -@Deprecated -public class EntitlementPolicyCreationException extends IdentityException { - - private static final long serialVersionUID = -574465923080421499L; - - public EntitlementPolicyCreationException(String message) { - super(message); - } - - public EntitlementPolicyCreationException(String message, Throwable e) { - super(message, e); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/EntitlementPolicyCreator.java b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/EntitlementPolicyCreator.java deleted file mode 100644 index d1b3a5723b2b..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/EntitlementPolicyCreator.java +++ /dev/null @@ -1,219 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.ui; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.balana.utils.exception.PolicyBuilderException; -import org.wso2.balana.utils.policy.PolicyBuilder; -import org.wso2.balana.utils.policy.dto.BasicPolicyDTO; -import org.wso2.balana.utils.policy.dto.ObligationElementDTO; -import org.wso2.balana.utils.policy.dto.PolicyElementDTO; -import org.wso2.balana.utils.policy.dto.PolicySetElementDTO; -import org.wso2.balana.utils.policy.dto.RequestElementDTO; -import org.wso2.balana.utils.policy.dto.RuleElementDTO; -import org.wso2.balana.utils.policy.dto.TargetElementDTO; -import org.wso2.carbon.identity.entitlement.common.PolicyEditorException; -import org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient; -import org.wso2.carbon.identity.entitlement.ui.dto.PolicyDTO; -import org.wso2.carbon.identity.entitlement.ui.dto.PolicyRefIdDTO; -import org.wso2.carbon.identity.entitlement.ui.dto.PolicySetDTO; -import org.wso2.carbon.identity.entitlement.ui.dto.RequestDTO; -import org.wso2.carbon.identity.entitlement.ui.dto.RuleDTO; -import org.wso2.carbon.identity.entitlement.ui.dto.SimplePolicyEditorDTO; -import org.wso2.carbon.identity.entitlement.ui.util.PolicyCreatorUtil; -import org.wso2.carbon.identity.entitlement.ui.util.PolicyEditorUtil; - -import java.util.List; - -/** - * create XACML policy and convert it to a String Object - */ -public class EntitlementPolicyCreator { - - private static Log log = LogFactory.getLog(EntitlementPolicyCreator.class); - - /** - * Create XACML policy using the data received from basic policy wizard - * - * @param basicPolicyDTO BasicPolicyDTO - * @return String object of the XACML policy - * @throws PolicyEditorException throws - */ - public String createBasicPolicy(BasicPolicyDTO basicPolicyDTO) throws PolicyEditorException { - - if (basicPolicyDTO == null) { - throw new PolicyEditorException("Policy object can not be null"); - } - - try { - return PolicyBuilder.getInstance().build(basicPolicyDTO); - } catch (PolicyBuilderException e) { - log.error(e); - throw new PolicyEditorException("Error while building policy"); - } - } - - - /** - * Create XACML policy using the data received from basic policy wizard - * - * @param policyDTO PolicyDTO - * @return String object of the XACML policy - * @throws PolicyEditorException throws - */ - public String createPolicy(PolicyDTO policyDTO) throws PolicyEditorException { - - if (policyDTO == null) { - throw new PolicyEditorException("Policy object can not be null"); - } - - PolicyElementDTO policyElementDTO = new PolicyElementDTO(); - policyElementDTO.setPolicyName(policyDTO.getPolicyId()); - policyElementDTO.setRuleCombiningAlgorithms(policyDTO.getRuleAlgorithm()); - policyElementDTO.setPolicyDescription(policyDTO.getDescription()); - policyElementDTO.setVersion(policyDTO.getVersion()); - - if (policyDTO.getTargetDTO() != null) { - TargetElementDTO targetElementDTO = PolicyEditorUtil. - createTargetElementDTO(policyDTO.getTargetDTO()); - policyElementDTO.setTargetElementDTO(targetElementDTO); - } - - if (policyDTO.getRuleDTOs() != null) { - for (RuleDTO ruleDTO : policyDTO.getRuleDTOs()) { - RuleElementDTO ruleElementDTO = PolicyEditorUtil.createRuleElementDTO(ruleDTO); - policyElementDTO.addRuleElementDTO(ruleElementDTO); - } - } - - if (policyDTO.getObligationDTOs() != null) { - List obligationElementDTOs = PolicyEditorUtil. - createObligation(policyDTO.getObligationDTOs()); - policyElementDTO.setObligationElementDTOs(obligationElementDTOs); - } - - try { - return PolicyBuilder.getInstance().build(policyElementDTO); - } catch (PolicyBuilderException e) { - throw new PolicyEditorException("Error while building XACML Policy"); - } - } - - - /** - * Create XACML policy using the data received from basic policy wizard - * - * @param policyEditorDTO complete policy editor object - * @return String object of the XACML policy - * @throws PolicyEditorException throws - */ - public String createSOAPolicy(SimplePolicyEditorDTO policyEditorDTO) throws PolicyEditorException { - - return PolicyEditorUtil.createSOAPolicy(policyEditorDTO); - } - - - /** - * Create policy set using the added policy ot policy sets - * - * @param policySetDTO policy set element - * @param client - * @return String object of the XACML policy Set - * @throws PolicyEditorException throws - */ - public String createPolicySet(PolicySetDTO policySetDTO, - EntitlementPolicyAdminServiceClient client) throws PolicyEditorException { - - if (policySetDTO == null) { - throw new PolicyEditorException("Policy Set object can not be null"); - } - - PolicySetElementDTO policyElementDTO = new PolicySetElementDTO(); - policyElementDTO.setPolicySetId(policySetDTO.getPolicySetId()); - policyElementDTO.setPolicyCombiningAlgId(policySetDTO.getPolicyCombiningAlgId()); - policyElementDTO.setDescription(policySetDTO.getDescription()); - policyElementDTO.setVersion(policySetDTO.getVersion()); - - if (policySetDTO.getTargetDTO() != null) { - TargetElementDTO targetElementDTO = PolicyEditorUtil. - createTargetElementDTO(policySetDTO.getTargetDTO()); - policyElementDTO.setTargetElementDTO(targetElementDTO); - } - - if (policySetDTO.getPolicyIdReferences() != null) { - - for (PolicyRefIdDTO dto : policySetDTO.getPolicyRefIdDTOs()) { - if (dto.isReferenceOnly()) { - if (dto.isPolicySet()) { - policyElementDTO.getPolicySetIdReferences().add(dto.getId()); - } else { - policyElementDTO.getPolicyIdReferences().add(dto.getId()); - } - } else { - org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO policyDTO = null; - try { - policyDTO = client.getPolicy(dto.getId(), false); - } catch (Exception e) { - //ignore - } - if (policyDTO != null && policyDTO.getPolicy() != null) { - if (dto.isPolicySet()) { - policyElementDTO.getPolicySets().add(policyDTO.getPolicy()); - } else { - policyElementDTO.getPolicies().add(policyDTO.getPolicy()); - } - } - } - } - } - - if (policySetDTO.getObligations() != null) { - List obligationElementDTOs = PolicyEditorUtil. - createObligation(policySetDTO.getObligations()); - policyElementDTO.setObligationElementDTOs(obligationElementDTOs); - } - - try { - return PolicyBuilder.getInstance().build(policyElementDTO); - } catch (PolicyBuilderException e) { - throw new PolicyEditorException("Error while building XACML Policy"); - } - } - - - /** - * Create basic XACML request - * - * @param requestDTO request element - * @return String object of the XACML request - * @throws EntitlementPolicyCreationException throws - */ - public String createBasicRequest(RequestDTO requestDTO) - throws EntitlementPolicyCreationException, PolicyEditorException { - try { - - RequestElementDTO requestElementDTO = PolicyCreatorUtil.createRequestElementDTO(requestDTO); - return PolicyBuilder.getInstance().buildRequest(requestElementDTO); - } catch (PolicyBuilderException e) { - throw new PolicyEditorException("Error while building XACML Request"); - } - - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/PolicyEditorConstants.java b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/PolicyEditorConstants.java deleted file mode 100644 index c3426693ee35..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/PolicyEditorConstants.java +++ /dev/null @@ -1,213 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.ui; - -/** - * Policy editor related constants - */ - -/** - * @deprecated As this moved to org.wso2.carbon.identity.entitlement.common - */ -@Deprecated -public class PolicyEditorConstants { - - - public static final String ATTRIBUTE_SEPARATOR = ","; - - public static final String TARGET_ELEMENT = "Target"; - - public static final String ANY_OF_ELEMENT = "AnyOf"; - - public static final String ALL_OF_ELEMENT = "AllOf"; - - public static final String COMBINE_FUNCTION_AND = "AND"; - - public static final String COMBINE_FUNCTION_OR = "OR"; - - public static final String COMBINE_FUNCTION_END = "END"; - - public static final String MATCH_ELEMENT = "Match"; - - public static final String MATCH_ID = "MatchId"; - - public static final String ATTRIBUTE_ID = "AttributeId"; - - public static final String CATEGORY = "Category"; - - public static final String DATA_TYPE = "DataType"; - - public static final String ISSUER = "Issuer"; - - public static final String SOA_CATEGORY_USER = "Subject"; - - public static final String SOA_CATEGORY_SUBJECT = "Subject"; - - public static final String SOA_CATEGORY_RESOURCE = "Resource"; - - public static final String SOA_CATEGORY_ACTION = "Action"; - - public static final String SOA_CATEGORY_ENVIRONMENT = "Environment"; - - public static final String MUST_BE_PRESENT = "MustBePresent"; - - public static final String ATTRIBUTE_DESIGNATOR = "AttributeDesignator"; - public static final String RULE_EFFECT_PERMIT = "Permit"; - public static final String RULE_EFFECT_DENY = "Deny"; - public static final String RULE_ALGORITHM_IDENTIFIER_1 = "urn:oasis:names:tc:xacml:1.0:" + - "rule-combining-algorithm:"; - public static final String RULE_ALGORITHM_IDENTIFIER_3 = "urn:oasis:names:tc:xacml:3.0:" + - "rule-combining-algorithm:"; - public static final String POLICY_ALGORITHM_IDENTIFIER_1 = "urn:oasis:names:tc:xacml:1.0:" + - "policy-combining-algorithm:"; - public static final String POLICY_ALGORITHM_IDENTIFIER_3 = "urn:oasis:names:tc:xacml:3.0:" + - "policy-combining-algorithm:"; - public static final String POLICY_EDITOR_SEPARATOR = "|"; - public static final int POLICY_EDITOR_ROW_DATA = 7; - public static final String DYNAMIC_SELECTOR_CATEGORY = "Category"; - public static final String DYNAMIC_SELECTOR_FUNCTION = "Function"; - public static final String SUBJECT_ID_DEFAULT = "urn:oasis:names:tc:xacml:1.0:subject:subject-id"; - public static final String SUBJECT_ID_ROLE = "http://wso2.org/claims/roles"; - public static final String RESOURCE_ID_DEFAULT = "urn:oasis:names:tc:xacml:1.0:resource:resource-id"; - public static final String ACTION_ID_DEFAULT = "urn:oasis:names:tc:xacml:1.0:action:action-id"; - public static final String ENVIRONMENT_ID_DEFAULT = "urn:oasis:names:tc:xacml:1.0:environment:environment-id"; - public static final String RESOURCE_CATEGORY_URI = "urn:oasis:names:tc:xacml:3.0:" + - "attribute-category:resource"; - public static final String SUBJECT_CATEGORY_URI = "urn:oasis:names:tc:xacml:1.0:" + - "subject-category:access-subject"; - public static final String ACTION_CATEGORY_URI = "urn:oasis:names:tc:xacml:3.0:" + - "attribute-category:action"; - public static final String ENVIRONMENT_CATEGORY_URI = "urn:oasis:names:tc:xacml:3.0:" + - "attribute-category:environment"; - public static final String ENVIRONMENT_CURRENT_DATE = "urn:oasis:names:tc:xacml:1.0:environment:current-date"; - public static final String ENVIRONMENT_CURRENT_TIME = "urn:oasis:names:tc:xacml:1.0:environment:current-time"; - public static final String ENVIRONMENT_CURRENT_DATETIME = "urn:oasis:names:tc:xacml:1.0:environment:current-dateTime"; - public static final String SOA_POLICY_EDITOR = "SOA"; - - public static final class PreFunctions { - - public static final String PRE_FUNCTION_IS = "is"; - - public static final String PRE_FUNCTION_IS_NOT = "is-not"; - - public static final String PRE_FUNCTION_ARE = "are"; - - public static final String PRE_FUNCTION_ARE_NOT = "are-not"; - - public static final String CAN_DO = "can"; - - public static final String CAN_NOT_DO = "can not"; - } - - public static final class TargetPreFunctions { - - public static final String PRE_FUNCTION_IS = "is"; - - } - - public static final class TargetFunctions { - - public static final String FUNCTION_EQUAL = "equal"; - - } - - public static final class DataType { - - public static final String DAY_TIME_DURATION = "http://www.w3.org/2001/XMLSchema#dayTimeDuration"; - - public static final String YEAR_MONTH_DURATION = "http://www.w3.org/2001/XMLSchema#yearMonthDuration"; - - public static final String STRING = "http://www.w3.org/2001/XMLSchema#string"; - - public static final String TIME = "http://www.w3.org/2001/XMLSchema#time"; - - public static final String IP_ADDRESS = "urn:oasis:names:tc:xacml:2.0:data-type:ipAddress"; - - public static final String DATE_TIME = "http://www.w3.org/2001/XMLSchema#dateTime"; - - public static final String DATE = "http://www.w3.org/2001/XMLSchema#date"; - - public static final String DOUBLE = "http://www.w3.org/2001/XMLSchema#double"; - - public static final String INT = "http://www.w3.org/2001/XMLSchema#integer"; - - } - - public static final class CombiningAlog { - - public static final String DENY_OVERRIDE_ID = "deny-overrides"; - - public static final String PERMIT_OVERRIDE_ID = "permit-overrides"; - - public static final String FIRST_APPLICABLE_ID = "first-applicable"; - - public static final String ORDER_PERMIT_OVERRIDE_ID = "ordered-permit-overrides"; - - public static final String ORDER_DENY_OVERRIDE_ID = "ordered-deny-overrides"; - - public static final String DENY_UNLESS_PERMIT_ID = "deny-unless-permit"; - - public static final String PERMIT_UNLESS_DENY_ID = "permit-unless-deny"; - - public static final String ONLY_ONE_APPLICABLE_ID = "only-one-applicable"; - - } - - public static class FunctionIdentifier { - - public static final String ANY = "*"; - - public static final String EQUAL_RANGE = "["; - - public static final String EQUAL_RANGE_CLOSE = "]"; - - public static final String RANGE = "("; - - public static final String RANGE_CLOSE = ")"; - - public static final String GREATER = ">"; - - public static final String GREATER_EQUAL = ">="; - - public static final String LESS = "<"; - - public static final String LESS_EQUAL = "<="; - - public static final String REGEX = "{"; - - public static final String AND = "&"; - - public static final String OR = "|"; - - } - - public static final class AttributeId { - - public static final String ENV_DOMAIN = "Domain"; - - public static final String ENV_DATE = "Date"; - - public static final String ENV_DATE_TIME = "DateTime"; - - public static final String ENV_IP = "IP"; - - public static final String ENV_TIME = "Time"; - - public static final String USER_AGE = "Age"; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/PropertyDTOComparator.java b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/PropertyDTOComparator.java deleted file mode 100644 index 943654eecde7..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/PropertyDTOComparator.java +++ /dev/null @@ -1,48 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.ui; - -import org.wso2.carbon.identity.entitlement.stub.dto.PublisherPropertyDTO; - -import java.util.Comparator; - -/** - * Comparator implementation to sort the ModulePropertyDTO object array - */ - -/** - * @deprecated As this moved to org.wso2.carbon.identity.entitlement.common - */ -@Deprecated -public class PropertyDTOComparator implements Comparator { - - @Override - public int compare(Object o1, Object o2) { - - PublisherPropertyDTO dto1 = (PublisherPropertyDTO) o1; - PublisherPropertyDTO dto2 = (PublisherPropertyDTO) o2; - if (dto1.getDisplayOrder() < dto2.getDisplayOrder()) { - return -1; - } else if (dto1.getDisplayOrder() == dto2.getDisplayOrder()) { - return 0; - } else { - return 1; - } - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/client/EntitlementAdminServiceClient.java b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/client/EntitlementAdminServiceClient.java deleted file mode 100644 index ebc9ea6a5830..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/client/EntitlementAdminServiceClient.java +++ /dev/null @@ -1,236 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.ui.client; - -import org.apache.axis2.AxisFault; -import org.apache.axis2.client.Options; -import org.apache.axis2.client.ServiceClient; -import org.apache.axis2.context.ConfigurationContext; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.entitlement.stub.EntitlementAdminServiceStub; -import org.wso2.carbon.identity.entitlement.stub.dto.PDPDataHolder; -import org.wso2.carbon.identity.entitlement.stub.dto.PIPFinderDataHolder; -import org.wso2.carbon.identity.entitlement.stub.dto.PolicyFinderDataHolder; - -/** - * - */ -public class EntitlementAdminServiceClient { - - private static final Log log = LogFactory.getLog(EntitlementAdminServiceClient.class); - private EntitlementAdminServiceStub stub; - - /** - * Instantiates EntitlementServiceClient - * - * @param cookie For session management - * @param backendServerURL URL of the back end server where EntitlementPolicyAdminService is - * running. - * @param configCtx ConfigurationContext - * @throws org.apache.axis2.AxisFault - */ - public EntitlementAdminServiceClient(String cookie, String backendServerURL, - ConfigurationContext configCtx) throws AxisFault { - String serviceURL = backendServerURL + "EntitlementAdminService"; - stub = new EntitlementAdminServiceStub(configCtx, serviceURL); - ServiceClient client = stub._getServiceClient(); - Options option = client.getOptions(); - option.setManageSession(true); - option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie); - } - - /** - * Clears the decision cache maintained by the PDP. - * - * @throws AxisFault - */ - public void clearDecisionCache() throws AxisFault { - - try { - stub.clearDecisionCache(); - } catch (Exception e) { - String message = e.getMessage(); - handleException(message, e); - } - } - - /** - * Clears the attribute cache maintained by the PDP. - * - * @throws AxisFault - */ - public void clearAttributeCache() throws AxisFault { - - try { - stub.clearAllAttributeCaches(); - } catch (Exception e) { - String message = e.getMessage(); - handleException(message, e); - } - } - - - /** - * Evaluate XACML request with PDP - * - * @param request XACML request as String - * @return XACML response as String - * @throws AxisFault if fails - */ - public String getDecision(String request) throws AxisFault { - try { - return stub.doTestRequest(request); - } catch (Exception e) { - handleException("Error occurred while test policy evaluation", e); - } - return null; - } - - /** - * Evaluate XACML request with PDP - * - * @param policies - * @param request XACML request as String - * @return XACML response as String - * @throws AxisFault if fails - */ - public String getDecision(String request, String[] policies) throws AxisFault { - try { - return stub.doTestRequestForGivenPolicies(request, policies); - } catch (Exception e) { - handleException("Error occurred while test policy evaluation", e); - } - return null; - } - - public PDPDataHolder getPDPData() throws AxisFault { - - try { - return stub.getPDPData(); - } catch (Exception e) { - handleException(e.getMessage(), e); - } - - return null; - } - - - public PolicyFinderDataHolder getPolicyFinderData(String finderName) throws AxisFault { - - try { - return stub.getPolicyFinderData(finderName); - } catch (Exception e) { - handleException(e.getMessage(), e); - } - - return null; - } - - public PIPFinderDataHolder getPIPAttributeFinderData(String finderName) throws AxisFault { - - try { - return stub.getPIPAttributeFinderData(finderName); - } catch (Exception e) { - handleException(e.getMessage(), e); - } - - return null; - } - - public PIPFinderDataHolder getPIPResourceFinderData(String finderName) throws AxisFault { - - try { - return stub.getPIPResourceFinderData(finderName); - } catch (Exception e) { - handleException(e.getMessage(), e); - } - - return null; - } - - public void refreshAttributeFinder(String finderName) throws AxisFault { - - try { - stub.refreshAttributeFinder(finderName); - } catch (Exception e) { - handleException(e.getMessage(), e); - } - } - - public void refreshResourceFinder(String finderName) throws AxisFault { - - try { - stub.refreshResourceFinder(finderName); - } catch (Exception e) { - handleException(e.getMessage(), e); - } - } - - public void refreshPolicyFinder(String finderName) throws AxisFault { - - try { - stub.refreshPolicyFinders(finderName); - } catch (Exception e) { - handleException(e.getMessage(), e); - } - } - - /** - * Get globally defined policy combining algorithm - * - * @return policy combining algorithm as a String - * @throws AxisFault - */ - public String getGlobalPolicyAlgorithm() throws AxisFault { - try { - return stub.getGlobalPolicyAlgorithm(); - } catch (Exception e) { - handleException(e.getMessage(), e); - } - - return null; - } - - /** - * Set policy combining algorithm globally - * - * @param policyAlgorithm policy combining algorithm as a String - * @throws AxisFault - */ - public void setGlobalPolicyAlgorithm(String policyAlgorithm) throws AxisFault { - try { - stub.setGlobalPolicyAlgorithm(policyAlgorithm); - } catch (Exception e) { - handleException(e.getMessage(), e); - } - } - - /** - * Logs and wraps the given exception. - * - * @param msg Error message - * @param e Exception - * @throws AxisFault - */ - private void handleException(String msg, Exception e) throws AxisFault { - log.error(msg, e); - throw new AxisFault(msg, e); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/client/EntitlementPolicyAdminServiceClient.java b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/client/EntitlementPolicyAdminServiceClient.java deleted file mode 100644 index 6d18ce3c2dcf..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/client/EntitlementPolicyAdminServiceClient.java +++ /dev/null @@ -1,480 +0,0 @@ -/* -* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.ui.client; - -import org.apache.axis2.AxisFault; -import org.apache.axis2.client.Options; -import org.apache.axis2.client.ServiceClient; -import org.apache.axis2.context.ConfigurationContext; -import org.apache.commons.fileupload.FileItemFactory; -import org.apache.commons.fileupload.FileUploadException; -import org.apache.commons.fileupload.disk.DiskFileItemFactory; -import org.apache.commons.fileupload.servlet.ServletFileUpload; -import org.apache.commons.fileupload.servlet.ServletRequestContext; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.entitlement.stub.EntitlementPolicyAdminServiceEntitlementException; -import org.wso2.carbon.identity.entitlement.stub.EntitlementPolicyAdminServiceStub; -import org.wso2.carbon.identity.entitlement.stub.dto.EntitlementFinderDataHolder; -import org.wso2.carbon.identity.entitlement.stub.dto.EntitlementTreeNodeDTO; -import org.wso2.carbon.identity.entitlement.stub.dto.PaginatedPolicySetDTO; -import org.wso2.carbon.identity.entitlement.stub.dto.PaginatedStatusHolder; -import org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO; -import org.wso2.carbon.identity.entitlement.stub.dto.PublisherDataHolder; - -import java.util.List; - - -public class EntitlementPolicyAdminServiceClient { - - private static final Log log = LogFactory.getLog(EntitlementPolicyAdminServiceClient.class); - private EntitlementPolicyAdminServiceStub stub; - - /** - * Instantiates EntitlementServiceClient - * - * @param cookie For session management - * @param backendServerURL URL of the back end server where EntitlementPolicyAdminService is - * running. - * @param configCtx ConfigurationContext - * @throws org.apache.axis2.AxisFault - */ - public EntitlementPolicyAdminServiceClient(String cookie, String backendServerURL, - ConfigurationContext configCtx) throws AxisFault { - String serviceURL = backendServerURL + "EntitlementPolicyAdminService"; - stub = new EntitlementPolicyAdminServiceStub(configCtx, serviceURL); - ServiceClient client = stub._getServiceClient(); - Options option = client.getOptions(); - option.setManageSession(true); - option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie); - } - - /** - * @param policyTypeFilter - * @param policySearchString - * @param pageNumber - * @param isPDPPolicy - * @return PaginatedPolicySetDTO object containing the number of pages and the set of policies that reside in the - * given page. - * @throws AxisFault - */ - public PaginatedPolicySetDTO getAllPolicies(String policyTypeFilter, String policySearchString, - int pageNumber, boolean isPDPPolicy) throws AxisFault { - try { - return stub.getAllPolicies(policyTypeFilter, policySearchString, pageNumber, isPDPPolicy); - } catch (Exception e) { - String message = "Error while loading all policies from backend service"; - handleException(e); - } - PaginatedPolicySetDTO paginatedPolicySetDTO = new PaginatedPolicySetDTO(); - paginatedPolicySetDTO.setPolicySet(new PolicyDTO[0]); - return paginatedPolicySetDTO; - } - - /** - * Gets policy DTO for given policy id - * - * @param policyId policy id - * @param isPDPPolicy - * @return returns policy DTO - * @throws AxisFault throws - */ - public PolicyDTO getPolicy(String policyId, boolean isPDPPolicy) throws AxisFault { - PolicyDTO dto = null; - try { - dto = stub.getPolicy(policyId, isPDPPolicy); - if (dto != null && dto.getPolicy() != null) { - dto.setPolicy(dto.getPolicy().trim().replaceAll("><", ">\n<")); - } - } catch (Exception e) { - handleException(e); - } - return dto; - } - - /** - * Gets policy DTO for given policy id with given version - * - * @param policyId policy id - * @param version - * @return returns policy DTO - * @throws AxisFault throws - */ - public PolicyDTO getPolicyByVersion(String policyId, String version) throws AxisFault { - PolicyDTO dto = null; - try { - dto = stub.getPolicyByVersion(policyId, version); - if (dto != null && dto.getPolicy() != null) { - dto.setPolicy(dto.getPolicy().trim().replaceAll("><", ">\n<")); - } - } catch (Exception e) { - handleException(e); - } - return dto; - } - - /** - * Gets light weight policy DTO for given policy id - * - * @param policyId policy id - * @return returns policy DTO - * @throws AxisFault throws - */ - public PolicyDTO getLightPolicy(String policyId) throws AxisFault { - PolicyDTO dto = null; - try { - dto = stub.getLightPolicy(policyId); - } catch (Exception e) { - handleException(e); - } - return dto; - } - - /** - * Rollbacks policy DTO for given policy version - * - * @param policyId policy id - * @param version policy version - * @throws AxisFault throws - */ - public void rollBackPolicy(String policyId, String version) throws AxisFault { - - try { - stub.rollBackPolicy(policyId, version); - } catch (Exception e) { - handleException(e); - } - } - - - /** - * @param policyIds - * @throws AxisFault - */ - public void removePolicies(String[] policyIds, boolean dePromote) throws AxisFault { - try { - stub.removePolicies(policyIds, dePromote); - } catch (Exception e) { - handleException(e); - } - } - - public void dePromotePolicy(String policyId) throws AxisFault { - try { - stub.dePromotePolicy(policyId); - } catch (Exception e) { - handleException(e); - } - } - - public void enableDisablePolicy(String policyId, boolean enable) throws AxisFault { - try { - stub.enableDisablePolicy(policyId, enable); - } catch (Exception e) { - handleException(e); - } - } - - public void orderPolicy(String policyId, int order) throws AxisFault { - try { - stub.orderPolicy(policyId, order); - } catch (Exception e) { - handleException(e); - } - } - - /** - * @param policy - * @throws AxisFault - */ - public void updatePolicy(PolicyDTO policy) throws AxisFault { - try { - if (policy.getPolicy() != null && policy.getPolicy().trim().length() > 0) { - policy.setPolicy(policy.getPolicy().trim().replaceAll(">\\s+<", "><")); - } - stub.updatePolicy(policy); - } catch (Exception e) { - handleException(e); - } - } - - /** - * @param policy - * @throws AxisFault - */ - public void addPolicy(PolicyDTO policy) throws AxisFault { - try { - policy.setPolicy(policy.getPolicy().trim().replaceAll(">\\s+<", "><")); - stub.addPolicy(policy); - } catch (Exception e) { - handleException(e); - } - } - - /** - * adding an entitlement policy which is extracted using file upload executor - * - * @param content content of the policy as a String Object - * @throws AxisFault, throws if fails - */ - public void uploadPolicy(String content) throws AxisFault { - - PolicyDTO dto = new PolicyDTO(); - dto.setPolicy(content); - dto.setPolicy(dto.getPolicy().trim().replaceAll(">\\s+<", "><")); - try { - stub.addPolicy(dto); - } catch (Exception e) { - handleException(e); - } - } - - /** - * Import XACML policy from registry - * - * @deprecated since the functionality cannot be support by the rdbms based implementation - * @param policyRegistryPath registry path - * @throws AxisFault - */ - @Deprecated - public void importPolicyFromRegistry(String policyRegistryPath) throws AxisFault { - - try { - stub.importPolicyFromRegistry(policyRegistryPath); - } catch (Exception e) { - handleException(e); - } - } - - /** - * Returns the list of policy set ids available in PDP - * - * @return list of policy set ids - * @throws AxisFault - */ - public String[] getAllPolicyIds() throws AxisFault { - - try { - return stub.getAllPolicyIds("*"); - } catch (Exception e) { - handleException(e); - } - return null; - } - - - /** - * @param requestContext - * @return - * @throws FileUploadException - */ - private List parseRequest(ServletRequestContext requestContext) throws FileUploadException { - FileItemFactory factory = new DiskFileItemFactory(); - ServletFileUpload upload = new ServletFileUpload(factory); - return upload.parseRequest(requestContext); - } - - /** - * Gets attribute value tree for given attribute type - * - * @param dataModule - * @param category - * @param regexp - * @param dataLevel - * @param limit - * @return attribute value tree - * @throws AxisFault throws - */ - public EntitlementTreeNodeDTO getEntitlementData(String dataModule, String category, - String regexp, int dataLevel, int limit) throws AxisFault { - try { - return stub.getEntitlementData(dataModule, category, regexp, dataLevel, limit); - } catch (Exception e) { - handleException(e); - } - - return null; - } - - /** - * @return - * @throws AxisFault - */ - public EntitlementFinderDataHolder[] getEntitlementDataModules() throws AxisFault { - - try { - return stub.getEntitlementDataModules(); - } catch (Exception e) { - handleException(e); - } - - return null; - } - - /** - * Gets all subscriber ids - * - * @param subscriberSearchString subscriberSearchString - * @return subscriber ids as String array - * @throws AxisFault throws - */ - public String[] getSubscriberIds(String subscriberSearchString) throws AxisFault { - - try { - return stub.getSubscriberIds(subscriberSearchString); - } catch (Exception e) { - handleException(e); - } - - return null; - } - - /** - * Gets subscriber data - * - * @param id subscriber id - * @return subscriber data as SubscriberDTO object - * @throws AxisFault throws - */ - public PublisherDataHolder getSubscriber(String id) throws AxisFault { - - try { - return stub.getSubscriber(id); - } catch (Exception e) { - handleException(e); - } - - return null; - } - - /** - * Updates or creates subscriber data - * - * @param holder subscriber data as ModuleDataHolder object - * @param update - * @throws AxisFault throws - */ - public void updateSubscriber(PublisherDataHolder holder, boolean update) throws AxisFault { - - try { - if (update) { - stub.updateSubscriber(holder); - } else { - stub.addSubscriber(holder); - } - } catch (Exception e) { - handleException(e); - } - } - - /** - * Removes publisher data - * - * @param id subscriber id - * @throws AxisFault throws - */ - public void deleteSubscriber(String id) throws AxisFault { - - try { - stub.deleteSubscriber(id); - } catch (Exception e) { - handleException(e); - } - } - - /** - * Publishes given set of policies to given set of subscribers - * - * @param policies policy ids as String array, if null or empty, all policies are published - * @param subscriberId subscriber ids as String array, if null or empty, publish to all subscribers - * @param version - * @param action - * @param enabled - * @param order - * @throws AxisFault throws - */ - public void publish(String[] policies, String[] subscriberId, String action, String version, - boolean enabled, int order) throws AxisFault { - try { - stub.publishPolicies(policies, subscriberId, action, version, enabled, order); - } catch (Exception e) { - handleException(e); - } - } - - - /** - * Get all publisher modules properties that is needed to configure - * - * @return publisher modules properties as ModuleDataHolder - * @throws AxisFault throws - */ - public PublisherDataHolder[] getPublisherModuleData() throws AxisFault { - - try { - return stub.getPublisherModuleData(); - } catch (Exception e) { - handleException(e); - } - - return new PublisherDataHolder[0]; - } - - public String[] getPolicyVersions(String policyId) throws AxisFault { - try { - return stub.getPolicyVersions(policyId); - } catch (Exception e) { - handleException(e); - } - - return new String[0]; - } - - public PaginatedStatusHolder getStatusData(String about, String key, String type, - String searchString, int pageNumber) throws AxisFault { - try { - return stub.getStatusData(about, key, type, searchString, pageNumber); - } catch (Exception e) { - handleException(e); - } - return null; - } - - /** - * Logs and wraps the given exception. - * - * @param e Exception - * @throws AxisFault - */ - private void handleException(Exception e) throws AxisFault { - - String errorMessage = "Unknown"; - - if (e instanceof EntitlementPolicyAdminServiceEntitlementException) { - EntitlementPolicyAdminServiceEntitlementException entitlementException = - (EntitlementPolicyAdminServiceEntitlementException) e; - if (entitlementException.getFaultMessage().getEntitlementException() != null) { - errorMessage = entitlementException.getFaultMessage().getEntitlementException().getMessage(); - } - } else { - errorMessage = e.getMessage(); - } - - throw new AxisFault(errorMessage, e); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/client/EntitlementPolicyUploadExecutor.java b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/client/EntitlementPolicyUploadExecutor.java deleted file mode 100644 index 3885571a45eb..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/client/EntitlementPolicyUploadExecutor.java +++ /dev/null @@ -1,115 +0,0 @@ -/* -* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.ui.client; - -import org.apache.commons.lang.StringUtils; -import org.wso2.carbon.CarbonConstants; -import org.wso2.carbon.CarbonException; -import org.wso2.carbon.ui.CarbonUIMessage; -import org.wso2.carbon.ui.transports.fileupload.AbstractFileUploadExecutor; -import org.wso2.carbon.utils.FileItemData; -import org.wso2.carbon.utils.ServerConstants; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * This class is responsible for uploading entitlement policy files. - * And this uses the AbstractFileUploadExecutor - * which has written to handle the carbon specific file uploading - */ -public class EntitlementPolicyUploadExecutor extends AbstractFileUploadExecutor { - - private static final String[] ALLOWED_FILE_EXTENSIONS = new String[]{".xml"}; - - private String errorRedirectionPage; - - @Override - public boolean execute(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) - throws CarbonException, IOException { - - String webContext = (String) httpServletRequest.getAttribute(CarbonConstants.WEB_CONTEXT); - String serverURL = (String) httpServletRequest.getAttribute(CarbonConstants.SERVER_URL); - String cookie = (String) httpServletRequest.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - errorRedirectionPage = getContextRoot(httpServletRequest) + "/" + webContext - + "/entitlement/index.jsp"; - - Map> fileItemsMap = getFileItemsMap(); - if (fileItemsMap == null || fileItemsMap.isEmpty()) { - String msg = "File uploading failed. No files are specified"; - log.error(msg); - CarbonUIMessage.sendCarbonUIMessage(msg, CarbonUIMessage.ERROR, httpServletRequest, - httpServletResponse, errorRedirectionPage); - return false; - } - - EntitlementPolicyAdminServiceClient client = - new EntitlementPolicyAdminServiceClient(cookie, serverURL, configurationContext); - List fileItems = fileItemsMap.get("policyFromFileSystem"); - String msg; - try { - for (FileItemData fileItem : fileItems) { - String filename = getFileName(fileItem.getFileItem().getName()); - checkServiceFileExtensionValidity(filename, ALLOWED_FILE_EXTENSIONS); - - if (!filename.endsWith(".xml")) { - throw new CarbonException("File with extension " + - getFileName(fileItem.getFileItem().getName()) + " is not supported!"); - } else { - try (BufferedReader br = new BufferedReader(new InputStreamReader( - fileItem.getDataHandler().getInputStream()))) { - - String temp; - String policyContent = ""; - while ((temp = br.readLine()) != null) { - policyContent += temp; - } - if (StringUtils.isNotEmpty(policyContent)) { - client.uploadPolicy(policyContent); - } - } catch (IOException ex) { - throw new CarbonException("Policy file " + filename + "cannot be read"); - } - } - } - httpServletResponse.setContentType("text/html; charset=utf-8"); - msg = "Policy have been uploaded successfully."; - CarbonUIMessage.sendCarbonUIMessage(msg, CarbonUIMessage.INFO, httpServletRequest, - httpServletResponse, getContextRoot(httpServletRequest) - + "/" + webContext + "/entitlement/index.jsp"); - return true; - } catch (Exception e) { - msg = "Policy uploading failed. " + e.getMessage(); - log.error(msg); - CarbonUIMessage.sendCarbonUIMessage(msg, CarbonUIMessage.ERROR, httpServletRequest, - httpServletResponse, errorRedirectionPage); - } - return false; - } - - @Override - protected String getErrorRedirectionPage() { - return errorRedirectionPage; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/client/EntitlementServiceClient.java b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/client/EntitlementServiceClient.java deleted file mode 100644 index d3569795a632..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/client/EntitlementServiceClient.java +++ /dev/null @@ -1,103 +0,0 @@ -/* -* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.ui.client; - -import org.apache.axis2.AxisFault; -import org.apache.axis2.client.Options; -import org.apache.axis2.client.ServiceClient; -import org.apache.axis2.context.ConfigurationContext; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.entitlement.stub.EntitlementServiceStub; -import org.wso2.carbon.identity.entitlement.stub.dto.EntitledResultSetDTO; - -public class EntitlementServiceClient { - - private static final Log log = LogFactory.getLog(EntitlementServiceClient.class); - private EntitlementServiceStub stub; - - /** - * Instantiates EntitlementServiceClient - * - * @param cookie For session management - * @param backendServerURL URL of the back end server where EntitlementService is running. - * @param configCtx ConfigurationContext - * @throws org.apache.axis2.AxisFault - */ - public EntitlementServiceClient(String cookie, String backendServerURL, - ConfigurationContext configCtx) throws AxisFault { - String serviceURL = backendServerURL + "EntitlementService"; - stub = new EntitlementServiceStub(configCtx, serviceURL); - ServiceClient client = stub._getServiceClient(); - Options option = client.getOptions(); - option.setManageSession(true); - option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie); - } - - /** - * Evaluate XACML request with PDP - * - * @param request XACML request as String - * @return XACML response as String - * @throws AxisFault if fails - */ - public String getDecision(String request) throws AxisFault { - try { - return stub.getDecision(request); - } catch (Exception e) { - handleException("Error occurred while policy evaluation", e); - } - return null; - } - - /** - * Gets user or role entitled resources - * - * @param subjectName user or role name - * @param resourceName resource name - * @param subjectId attribute id of the subject, user or role - * @param action action name - * @param enableChildSearch whether search is done for the child resources under the given resource name - * @return entitled resources as String array - * @throws org.apache.axis2.AxisFault throws - */ - public EntitledResultSetDTO getEntitledAttributes(String subjectName, String resourceName, - String subjectId, String action, boolean enableChildSearch) - throws AxisFault { - try { - return stub.getEntitledAttributes(subjectName, resourceName, subjectId, action, - enableChildSearch); - } catch (Exception e) { - handleException(e.getMessage(), e); - } - - return null; - } - - /** - * Logs and wraps the given exception. - * - * @param msg Error message - * @param e Exception - * @throws AxisFault - */ - private void handleException(String msg, Exception e) throws AxisFault { - log.error(msg, e); - throw new AxisFault(msg, e); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/BasicRequestDTO.java b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/BasicRequestDTO.java deleted file mode 100644 index dd5e585e3ab0..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/BasicRequestDTO.java +++ /dev/null @@ -1,102 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.ui.dto; - -import java.util.List; - -/** - * @deprecated As this moved to org.wso2.carbon.identity.entitlement.common - */ -@Deprecated -public class BasicRequestDTO { - - - private List rowDTOs; - - private String resources; - - private String subjects; - - private String actions; - - private String enviornement; - - private String userAttributeValue; - - private String userAttributeId; - - public String getResources() { - return resources; - } - - public void setResources(String resources) { - this.resources = resources; - } - - public String getSubjects() { - return subjects; - } - - public void setSubjects(String subjects) { - this.subjects = subjects; - } - - public String getActions() { - return actions; - } - - public void setActions(String actions) { - this.actions = actions; - } - - public String getUserAttributeValue() { - return userAttributeValue; - } - - public void setUserAttributeValue(String userAttributeValue) { - this.userAttributeValue = userAttributeValue; - } - - public String getUserAttributeId() { - return userAttributeId; - } - - public void setUserAttributeId(String userAttributeId) { - this.userAttributeId = userAttributeId; - } - - public String getEnviornement() { - return enviornement; - } - - public void setEnviornement(String enviornement) { - this.enviornement = enviornement; - } - - public List getRowDTOs() { - return rowDTOs; - } - - public void setRowDTOs(List rowDTOs) { - this.rowDTOs = rowDTOs; - } - - public void addRowDTOs(RowDTO rowDTO) { - this.rowDTOs.add(rowDTO); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/ElementCountDTO.java b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/ElementCountDTO.java deleted file mode 100644 index 6de1eea4cb84..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/ElementCountDTO.java +++ /dev/null @@ -1,66 +0,0 @@ -/* -* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.ui.dto; - -/** - * @deprecated As this moved to org.wso2.carbon.identity.entitlement.common - */ -@Deprecated -public class ElementCountDTO { - - private int subElementCount; - - private int attributeDesignatorsElementCount; - - private int attributeValueElementCount; - - private int attributeSelectorElementCount; - - public int getSubElementCount() { - return subElementCount; - } - - public void setSubElementCount(int subElementCount) { - this.subElementCount = subElementCount; - } - - public int getAttributeSelectorElementCount() { - return attributeSelectorElementCount; - } - - public void setAttributeSelectorElementCount(int attributeSelectorElementCount) { - this.attributeSelectorElementCount = attributeSelectorElementCount; - } - - public int getAttributeValueElementCount() { - return attributeValueElementCount; - } - - public void setAttributeValueElementCount(int attributeValueElementCount) { - this.attributeValueElementCount = attributeValueElementCount; - } - - public int getAttributeDesignatorsElementCount() { - return attributeDesignatorsElementCount; - } - - public void setAttributeDesignatorsElementCount(int attributeDesignatorsElementCount) { - this.attributeDesignatorsElementCount = attributeDesignatorsElementCount; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/ExtendAttributeDTO.java b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/ExtendAttributeDTO.java deleted file mode 100644 index a584f39e9944..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/ExtendAttributeDTO.java +++ /dev/null @@ -1,133 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.ui.dto; - -/** - * extended attribute value element - */ -/** - * @deprecated As this moved to org.wso2.carbon.identity.entitlement.common - */ -@Deprecated -public class ExtendAttributeDTO { - - private String id; - - private String selector; - - private String function; - - private String category; - - private String attributeValue; - - private String attributeId; - - private String dataType; - - private String issuer; - - private boolean notCompleted; - - public ExtendAttributeDTO() { - } - - public ExtendAttributeDTO(ExtendAttributeDTO dto) { - this.id = dto.getId(); - this.selector = dto.getSelector(); - this.function = dto.getFunction(); - this.category = dto.getCategory(); - this.attributeValue = dto.getAttributeValue(); - this.attributeId = dto.getAttributeId(); - this.dataType = dto.getDataType(); - this.issuer = dto.getIssuer(); - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getSelector() { - return selector; - } - - public void setSelector(String selector) { - this.selector = selector; - } - - public String getDataType() { - return dataType; - } - - public void setDataType(String dataType) { - this.dataType = dataType; - } - - public String getAttributeValue() { - return attributeValue; - } - - public void setAttributeValue(String attributeValue) { - this.attributeValue = attributeValue; - } - - public String getAttributeId() { - return attributeId; - } - - public void setAttributeId(String attributeId) { - this.attributeId = attributeId; - } - - public String getCategory() { - return category; - } - - public void setCategory(String category) { - this.category = category; - } - - public String getFunction() { - return function; - } - - public void setFunction(String function) { - this.function = function; - } - - public String getIssuer() { - return issuer; - } - - public void setIssuer(String issuer) { - this.issuer = issuer; - } - - public boolean isNotCompleted() { - return notCompleted; - } - - public void setNotCompleted(boolean notCompleted) { - this.notCompleted = notCompleted; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/ObligationDTO.java b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/ObligationDTO.java deleted file mode 100644 index fe7eabbf251b..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/ObligationDTO.java +++ /dev/null @@ -1,99 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.ui.dto; - -/** - * encapsulates obligation and advice expression data that requires for policy editor - */ -/** - * @deprecated As this moved to org.wso2.carbon.identity.entitlement.common - */ -@Deprecated -public class ObligationDTO { - - private String type; - - private String obligationId; - - private String effect; - - private String attributeValue; - - private String attributeValueDataType; - - private String resultAttributeId; - - private boolean notCompleted; - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getResultAttributeId() { - return resultAttributeId; - } - - public void setResultAttributeId(String resultAttributeId) { - this.resultAttributeId = resultAttributeId; - } - - public String getAttributeValue() { - return attributeValue; - } - - public void setAttributeValue(String attributeValue) { - this.attributeValue = attributeValue; - } - - public String getAttributeValueDataType() { - return attributeValueDataType; - } - - public void setAttributeValueDataType(String attributeValueDataType) { - this.attributeValueDataType = attributeValueDataType; - } - - public String getEffect() { - return effect; - } - - public void setEffect(String effect) { - this.effect = effect; - } - - public String getObligationId() { - return obligationId; - } - - public void setObligationId(String obligationId) { - this.obligationId = obligationId; - } - - public boolean isNotCompleted() { - return notCompleted; - } - - public void setNotCompleted(boolean notCompleted) { - this.notCompleted = notCompleted; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/PolicyDTO.java b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/PolicyDTO.java deleted file mode 100644 index 7ab54877cd74..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/PolicyDTO.java +++ /dev/null @@ -1,109 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.ui.dto; - -import java.util.ArrayList; -import java.util.List; - -/** - * @deprecated As this moved to org.wso2.carbon.identity.entitlement.common - */ -@Deprecated -public class PolicyDTO { - - private String policyId; - - private String ruleAlgorithm; - - private String description; - - private String ruleOrder; - - private String version; - - private TargetDTO targetDTO; - - private List ruleDTOs = new ArrayList(); - - private List obligationDTOs = new ArrayList(); - - public String getRuleAlgorithm() { - return ruleAlgorithm; - } - - public void setRuleAlgorithm(String ruleAlgorithm) { - this.ruleAlgorithm = ruleAlgorithm; - } - - public String getPolicyId() { - return policyId; - } - - public void setPolicyId(String policyId) { - this.policyId = policyId; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getRuleOrder() { - return ruleOrder; - } - - public void setRuleOrder(String ruleOrder) { - this.ruleOrder = ruleOrder; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public TargetDTO getTargetDTO() { - return targetDTO; - } - - public void setTargetDTO(TargetDTO targetDTO) { - this.targetDTO = targetDTO; - } - - public List getRuleDTOs() { - return ruleDTOs; - } - - public void setRuleDTOs(List ruleDTOs) { - this.ruleDTOs = ruleDTOs; - } - - public List getObligationDTOs() { - return obligationDTOs; - } - - public void setObligationDTOs(List obligationDTOs) { - this.obligationDTOs = obligationDTOs; - } -} \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/PolicyRefIdDTO.java b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/PolicyRefIdDTO.java deleted file mode 100644 index 4b835399e18a..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/PolicyRefIdDTO.java +++ /dev/null @@ -1,55 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.ui.dto; - -/** - * @deprecated As this moved to org.wso2.carbon.identity.entitlement.common - */ -@Deprecated -public class PolicyRefIdDTO { - - private String id; - - private boolean referenceOnly; - - private boolean policySet; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public boolean isPolicySet() { - return policySet; - } - - public void setPolicySet(boolean policySet) { - this.policySet = policySet; - } - - public boolean isReferenceOnly() { - return referenceOnly; - } - - public void setReferenceOnly(boolean referenceOnly) { - this.referenceOnly = referenceOnly; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/PolicySetDTO.java b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/PolicySetDTO.java deleted file mode 100644 index cfa9cdb11957..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/PolicySetDTO.java +++ /dev/null @@ -1,149 +0,0 @@ -/* -* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.ui.dto; - -import java.util.ArrayList; -import java.util.List; - -/** - * @deprecated As this moved to org.wso2.carbon.identity.entitlement.common - */ -@Deprecated -public class PolicySetDTO { - - private String policySetId; - - private String policyCombiningAlgId; - - private String version; - - private TargetDTO targetDTO; - - private String description; - - private List policySets = new ArrayList(); - - private List policies = new ArrayList(); - - private List policySetIdReferences = new ArrayList(); - - private List PolicyIdReferences = new ArrayList(); - - private List obligations = new ArrayList(); - - private List policyRefIdDTOs = new ArrayList(); - - private String policyOrder; - - public String getPolicySetId() { - return policySetId; - } - - public void setPolicySetId(String policySetId) { - this.policySetId = policySetId; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public String getPolicyCombiningAlgId() { - return policyCombiningAlgId; - } - - public void setPolicyCombiningAlgId(String policyCombiningAlgId) { - this.policyCombiningAlgId = policyCombiningAlgId; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public List getPolicySets() { - return policySets; - } - - public void setPolicySets(List policySets) { - this.policySets = policySets; - } - - public List getPolicies() { - return policies; - } - - public void setPolicy(String policy) { - this.policies.add(policy); - } - - public List getPolicySetIdReferences() { - return policySetIdReferences; - } - - public void setPolicySetIdReferences(List policySetIdReferences) { - this.policySetIdReferences = policySetIdReferences; - } - - public List getPolicyIdReferences() { - return PolicyIdReferences; - } - - public void setPolicyIdReferences(List policyIdReferences) { - PolicyIdReferences = policyIdReferences; - } - - public List getObligations() { - return obligations; - } - - public void setObligations(List obligations) { - this.obligations = obligations; - } - - public TargetDTO getTargetDTO() { - return targetDTO; - } - - public void setTargetDTO(TargetDTO targetDTO) { - this.targetDTO = targetDTO; - } - - public String getPolicyOrder() { - return policyOrder; - } - - public void setPolicyOrder(String policyOrder) { - this.policyOrder = policyOrder; - } - - public List getPolicyRefIdDTOs() { - return policyRefIdDTOs; - } - - public void setPolicyRefIdDTOs(List policyRefIdDTOs) { - this.policyRefIdDTOs = policyRefIdDTOs; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/RequestDTO.java b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/RequestDTO.java deleted file mode 100644 index dc6753f1b4dc..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/RequestDTO.java +++ /dev/null @@ -1,68 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.ui.dto; - -import java.util.List; - -/** - * @deprecated As this moved to org.wso2.carbon.identity.entitlement.common - */ -@Deprecated -public class RequestDTO { - - private boolean multipleRequest; - - private boolean returnPolicyIdList; - - private boolean combinedDecision; - - private List rowDTOs; - - public boolean isCombinedDecision() { - return combinedDecision; - } - - public void setCombinedDecision(boolean combinedDecision) { - this.combinedDecision = combinedDecision; - } - - public List getRowDTOs() { - return rowDTOs; - } - - public void setRowDTOs(List rowDTOs) { - this.rowDTOs = rowDTOs; - } - - public boolean isReturnPolicyIdList() { - return returnPolicyIdList; - } - - public void setReturnPolicyIdList(boolean returnPolicyIdList) { - this.returnPolicyIdList = returnPolicyIdList; - } - - public boolean isMultipleRequest() { - return multipleRequest; - } - - public void setMultipleRequest(boolean multipleRequest) { - this.multipleRequest = multipleRequest; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/RowDTO.java b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/RowDTO.java deleted file mode 100644 index ccf5bb3770b9..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/RowDTO.java +++ /dev/null @@ -1,119 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.ui.dto; - -/** - * @deprecated As this moved to org.wso2.carbon.identity.entitlement.common - */ -@Deprecated -public class RowDTO { - - private String category; - - private String preFunction; - - private String function; - - private String attributeValue; - - private String attributeId; - - private String attributeDataType; - - private String combineFunction; - - private boolean notCompleted; - - public RowDTO() { - } - - public RowDTO(RowDTO rowDTO) { - this.category = rowDTO.getCategory(); - this.preFunction = rowDTO.getPreFunction(); - this.function = rowDTO.getFunction(); - this.attributeValue = rowDTO.getAttributeValue(); - this.attributeId = rowDTO.getAttributeId(); - this.combineFunction = rowDTO.getCombineFunction(); - this.attributeDataType = rowDTO.getAttributeDataType(); - } - - public String getCategory() { - return category; - } - - public void setCategory(String category) { - this.category = category; - } - - public String getCombineFunction() { - return combineFunction; - } - - public void setCombineFunction(String combineFunction) { - this.combineFunction = combineFunction; - } - - public String getAttributeDataType() { - return attributeDataType; - } - - public void setAttributeDataType(String attributeDataType) { - this.attributeDataType = attributeDataType; - } - - public String getAttributeId() { - return attributeId; - } - - public void setAttributeId(String attributeId) { - this.attributeId = attributeId; - } - - public String getAttributeValue() { - return attributeValue; - } - - public void setAttributeValue(String attributeValue) { - this.attributeValue = attributeValue; - } - - public String getFunction() { - return function; - } - - public void setFunction(String function) { - this.function = function; - } - - public String getPreFunction() { - return preFunction; - } - - public void setPreFunction(String preFunction) { - this.preFunction = preFunction; - } - - public boolean isNotCompleted() { - return notCompleted; - } - - public void setNotCompleted(boolean notCompleted) { - this.notCompleted = notCompleted; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/RuleDTO.java b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/RuleDTO.java deleted file mode 100644 index ad6e15f3d379..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/RuleDTO.java +++ /dev/null @@ -1,121 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.ui.dto; - -import java.util.ArrayList; -import java.util.List; - -/** - * @deprecated As this moved to org.wso2.carbon.identity.entitlement.common - */ -@Deprecated -public class RuleDTO { - - private String ruleId; - - private String ruleEffect; - - private String ruleDescription; - - private TargetDTO targetDTO = new TargetDTO(); - - private List rowDTOList = new ArrayList(); - - private List attributeDTOs = new ArrayList(); - - private List obligationDTOs = new ArrayList(); - - private boolean completedRule; - - public String getRuleId() { - return ruleId; - } - - public void setRuleId(String ruleId) { - this.ruleId = ruleId; - } - - public String getRuleEffect() { - return ruleEffect; - } - - public void setRuleEffect(String ruleEffect) { - this.ruleEffect = ruleEffect; - } - - public String getRuleDescription() { - return ruleDescription; - } - - public void setRuleDescription(String ruleDescription) { - this.ruleDescription = ruleDescription; - } - - public List getRowDTOList() { - return rowDTOList; - } - - public void setRowDTOList(List rowDTOList) { - this.rowDTOList = rowDTOList; - } - - public void addRowDTO(RowDTO rowDTO) { - this.rowDTOList.add(rowDTO); - } - - public TargetDTO getTargetDTO() { - return targetDTO; - } - - public void setTargetDTO(TargetDTO targetDTO) { - this.targetDTO = targetDTO; - } - - public boolean isCompletedRule() { - return completedRule; - } - - public void setCompletedRule(boolean completedRule) { - this.completedRule = completedRule; - } - - public List getAttributeDTOs() { - return attributeDTOs; - } - - public void setAttributeDTOs(List attributeDTOs) { - this.attributeDTOs = attributeDTOs; - } - - public void addAttributeDTO(ExtendAttributeDTO attributeDTO) { - this.attributeDTOs.add(attributeDTO); - } - - public List getObligationDTOs() { - return obligationDTOs; - } - - public void setObligationDTOs(List obligationDTOs) { - this.obligationDTOs = obligationDTOs; - } - - public void addObligationDTO(ObligationDTO obligationDTO) { - this.obligationDTOs.add(obligationDTO); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/SimplePolicyEditorDTO.java b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/SimplePolicyEditorDTO.java deleted file mode 100644 index 9cb122bdf501..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/SimplePolicyEditorDTO.java +++ /dev/null @@ -1,146 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.ui.dto; - -import java.util.ArrayList; -import java.util.List; - -/** - * @deprecated As this moved to org.wso2.carbon.identity.entitlement.common - */ -@Deprecated -public class SimplePolicyEditorDTO { - - private String policyId; - - private String appliedCategory; - - private String description; - - private String userAttributeValue; - - private String userAttributeId; - - private String resourceValue; - - private String actionValue; - - private String environmentValue; - - private String function; - - private String environmentId; - - private List SimplePolicyEditorElementDTOs = - new ArrayList(); - - public String getPolicyId() { - return policyId; - } - - public void setPolicyId(String policyId) { - this.policyId = policyId; - } - - public String getAppliedCategory() { - return appliedCategory; - } - - public void setAppliedCategory(String appliedCategory) { - this.appliedCategory = appliedCategory; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public List getSimplePolicyEditorElementDTOs() { - return SimplePolicyEditorElementDTOs; - } - - public void setSimplePolicyEditorElementDTOs(List - simplePolicyEditorElementDTOs) { - this.SimplePolicyEditorElementDTOs = simplePolicyEditorElementDTOs; - } - - public void setBasicPolicyEditorElementDTO(SimplePolicyEditorElementDTO - SimplePolicyEditorElementDTO) { - this.SimplePolicyEditorElementDTOs.add(SimplePolicyEditorElementDTO); - } - - public String getUserAttributeValue() { - return userAttributeValue; - } - - public void setUserAttributeValue(String userAttributeValue) { - this.userAttributeValue = userAttributeValue; - } - - public String getEnvironmentValue() { - return environmentValue; - } - - public void setEnvironmentValue(String environmentValue) { - this.environmentValue = environmentValue; - } - - public String getFunction() { - return function; - } - - public void setFunction(String function) { - this.function = function; - } - - public String getActionValue() { - return actionValue; - } - - public void setActionValue(String actionValue) { - this.actionValue = actionValue; - } - - public String getResourceValue() { - return resourceValue; - } - - public void setResourceValue(String resourceValue) { - this.resourceValue = resourceValue; - } - - public String getUserAttributeId() { - return userAttributeId; - } - - public void setUserAttributeId(String userAttributeId) { - this.userAttributeId = userAttributeId; - } - - public String getEnvironmentId() { - return environmentId; - } - - public void setEnvironmentId(String environmentId) { - this.environmentId = environmentId; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/SimplePolicyEditorElementDTO.java b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/SimplePolicyEditorElementDTO.java deleted file mode 100644 index 43d8d6ad4c49..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/SimplePolicyEditorElementDTO.java +++ /dev/null @@ -1,136 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.ui.dto; - -/** - * @deprecated As this moved to org.wso2.carbon.identity.entitlement.common - */ -@Deprecated -public class SimplePolicyEditorElementDTO { - - private String userAttributeId; - - private String userAttributeValue; - - private String actionValue; - - private String resourceValue; - - private String environmentId; - - private String environmentValue; - - private String operationType; - - private String functionOnResources; - - private String functionOnActions; - - private String functionOnUsers; - - private String functionOnEnvironments; - - public String getUserAttributeId() { - return userAttributeId; - } - - public void setUserAttributeId(String userAttributeId) { - this.userAttributeId = userAttributeId; - } - - public String getOperationType() { - return operationType; - } - - public void setOperationType(String operationType) { - this.operationType = operationType; - } - - public String getEnvironmentValue() { - return environmentValue; - } - - public void setEnvironmentValue(String environmentValue) { - this.environmentValue = environmentValue; - } - - public String getEnvironmentId() { - return environmentId; - } - - public void setEnvironmentId(String environmentId) { - this.environmentId = environmentId; - } - - public String getResourceValue() { - return resourceValue; - } - - public void setResourceValue(String resourceValue) { - this.resourceValue = resourceValue; - } - - public String getUserAttributeValue() { - return userAttributeValue; - } - - public void setUserAttributeValue(String userAttributeValue) { - this.userAttributeValue = userAttributeValue; - } - - public String getActionValue() { - return actionValue; - } - - public void setActionValue(String actionValue) { - this.actionValue = actionValue; - } - - public String getFunctionOnUsers() { - return functionOnUsers; - } - - public void setFunctionOnUsers(String functionOnUsers) { - this.functionOnUsers = functionOnUsers; - } - - public String getFunctionOnActions() { - return functionOnActions; - } - - public void setFunctionOnActions(String functionOnActions) { - this.functionOnActions = functionOnActions; - } - - public String getFunctionOnResources() { - return functionOnResources; - } - - public void setFunctionOnResources(String functionOnResources) { - this.functionOnResources = functionOnResources; - } - - public String getFunctionOnEnvironments() { - return functionOnEnvironments; - } - - public void setFunctionOnEnvironments(String functionOnEnvironments) { - this.functionOnEnvironments = functionOnEnvironments; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/TargetDTO.java b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/TargetDTO.java deleted file mode 100644 index 5b073fa9c6ef..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/dto/TargetDTO.java +++ /dev/null @@ -1,45 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.ui.dto; - -import java.util.ArrayList; -import java.util.List; - -/** - * @deprecated As this moved to org.wso2.carbon.identity.entitlement.common - */ -@Deprecated -public class TargetDTO { - - private List rowDTOList = new ArrayList(); - - public List getRowDTOList() { - return rowDTOList; - } - - public void setRowDTOList(List rowDTOList) { - this.rowDTOList = rowDTOList; - } - - public void addRowDTO(RowDTO rowDTO) { - this.rowDTOList.add(rowDTO); - } - - -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/util/ClientUtil.java b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/util/ClientUtil.java deleted file mode 100644 index d8eef8a6830f..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/util/ClientUtil.java +++ /dev/null @@ -1,108 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.ui.util; - -import org.apache.axiom.om.OMElement; -import org.apache.axiom.om.OMNamespace; -import org.apache.axiom.om.impl.llom.util.AXIOMUtil; -import org.wso2.carbon.identity.entitlement.stub.dto.StatusHolder; -import org.wso2.carbon.identity.entitlement.ui.EntitlementPolicyConstants; - -import javax.xml.namespace.QName; - - -/** - * @deprecated As this moved to org.wso2.carbon.identity.entitlement.common - */ -@Deprecated -public class ClientUtil { - - /** - * Helper method to extract the boolean response - * - * @param xmlstring XACML resource as String - * @return Decision - * @throws Exception if fails - */ - public static String getStatus(String xmlstring) throws Exception { - - OMElement response = null; - OMElement result = null; - OMElement decision = null; - response = AXIOMUtil.stringToOM(xmlstring); - - OMNamespace nameSpace = response.getNamespace(); - - if (nameSpace != null) { - result = response.getFirstChildWithName(new QName(nameSpace.getNamespaceURI(), "Result")); - } else { - result = response.getFirstElement(); - } - if (result != null) { - if (nameSpace != null) { - decision = result.getFirstChildWithName(new QName(nameSpace.getNamespaceURI(), "Decision")); - } else { - decision = result.getFirstChildWithName(new QName("Decision")); - } - if (decision != null) { - return decision.getText(); - } - } - - return "Invalid Status"; - } - - public static String[] doPagingForStrings(int pageNumber, int itemsPerPageInt, String[] names) { - - String[] returnedSubscriberNameSet; - - int startIndex = pageNumber * itemsPerPageInt; - int endIndex = (pageNumber + 1) * itemsPerPageInt; - if (itemsPerPageInt < names.length) { - returnedSubscriberNameSet = new String[itemsPerPageInt]; - } else { - returnedSubscriberNameSet = new String[names.length]; - } - for (int i = startIndex, j = 0; i < endIndex && i < names.length; i++, j++) { - returnedSubscriberNameSet[j] = names[i]; - } - - return returnedSubscriberNameSet; - } - - public static StatusHolder[] doModuleStatusHoldersPaging(int pageNumber, - StatusHolder[] moduleStatusHolderSet) { - - int itemsPerPageInt = EntitlementPolicyConstants.DEFAULT_ITEMS_PER_PAGE; - StatusHolder[] returnedModuleStatusHolderSet; - - int startIndex = pageNumber * itemsPerPageInt; - int endIndex = (pageNumber + 1) * itemsPerPageInt; - if (itemsPerPageInt < moduleStatusHolderSet.length) { - returnedModuleStatusHolderSet = new StatusHolder[itemsPerPageInt]; - } else { - returnedModuleStatusHolderSet = new StatusHolder[moduleStatusHolderSet.length]; - } - for (int i = startIndex, j = 0; i < endIndex && i < moduleStatusHolderSet.length; i++, j++) { - returnedModuleStatusHolderSet[j] = moduleStatusHolderSet[i]; - } - - return returnedModuleStatusHolderSet; - } - -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/util/PolicyCreatorUtil.java b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/util/PolicyCreatorUtil.java deleted file mode 100644 index 95801574cacd..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/util/PolicyCreatorUtil.java +++ /dev/null @@ -1,2199 +0,0 @@ -/* -* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.ui.util; - -import org.wso2.balana.utils.policy.dto.AttributeElementDTO; -import org.wso2.balana.utils.policy.dto.AttributesElementDTO; -import org.wso2.balana.utils.policy.dto.RequestElementDTO; -import org.wso2.carbon.identity.entitlement.ui.EntitlementPolicyConstants; -import org.wso2.carbon.identity.entitlement.ui.dto.RequestDTO; -import org.wso2.carbon.identity.entitlement.ui.dto.RowDTO; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * @deprecated As this moved to org.wso2.carbon.identity.entitlement.common - */ -@Deprecated -public class PolicyCreatorUtil { -// -// /** -// * This method creates a policy element of the XACML policy -// * @param policyElementDTO policy element data object -// * @param doc XML document -// * @return policyElement -// */ -// -// public static Element createPolicyElement(PolicyElementDTO policyElementDTO, Document doc) { -// -// Element policyElement = doc.createElement(EntitlementPolicyConstants.POLICY_ELEMENT); -// -// policyElement.setAttribute("xmlns", EntitlementPolicyConstants.XACML3_POLICY_NAMESPACE); -// -// if(policyElementDTO.getPolicyName() != null && policyElementDTO.getPolicyName().trim().length() > 0) { -// policyElement.setAttribute(EntitlementPolicyConstants.POLICY_ID, policyElementDTO. -// getPolicyName()); -// } else { -// return null; -// } -// -// if(policyElementDTO.getRuleCombiningAlgorithms() != null && policyElementDTO. -// getRuleCombiningAlgorithms().trim().length() > 0) { -// if(PolicyEditorConstants.CombiningAlog.FIRST_APPLICABLE_ID.equals(policyElementDTO. -// getRuleCombiningAlgorithms().trim())){ -// policyElement.setAttribute(EntitlementPolicyConstants.RULE_ALGORITHM, -// PolicyEditorConstants.RULE_ALGORITHM_IDENTIFIER_1 + policyElementDTO. -// getRuleCombiningAlgorithms()); -// } else { -// policyElement.setAttribute(EntitlementPolicyConstants.RULE_ALGORITHM, -// PolicyEditorConstants.RULE_ALGORITHM_IDENTIFIER_3 + policyElementDTO. -// getRuleCombiningAlgorithms()); -// } -// } else { -// return null; -// } -// -// if(policyElementDTO.getVersion() != null && policyElementDTO.getVersion().trim().length() > 0){ -// policyElement.setAttribute(EntitlementPolicyConstants.POLICY_VERSION, -// policyElementDTO.getVersion()); -// } else { -// // policy version is handled by wso2 registry. therefore we can ignore it, although it -// // is a required attribute -// policyElement.setAttribute(EntitlementPolicyConstants.POLICY_VERSION, "1.0"); -// } -// -// if(policyElementDTO.getPolicyDescription() != null && policyElementDTO. -// getPolicyDescription().trim().length() > 0) { -// -// Element descriptionElement = doc.createElement(EntitlementPolicyConstants. -// DESCRIPTION_ELEMENT); -// descriptionElement.setTextContent(policyElementDTO.getPolicyDescription()); -// policyElement.appendChild(descriptionElement); -// } -// -// return policyElement; -// } -// -// ////XACML3 -// -// /** -// * This method creates a match element (subject,action,resource or environment) of the XACML policy -// * @param matchElementDTO match element data object -// * @param doc XML document -// * @return match Element -// */ -// public static Element createMatchElement(MatchElementDTO matchElementDTO, Document doc) { -// -// Element matchElement = null; -// if(matchElementDTO.getMatchId() != null && matchElementDTO.getMatchId().trim().length() > 0) { -// -// matchElement = doc.createElement(EntitlementPolicyConstants.MATCH_ELEMENT); -// -// matchElement.setAttribute(EntitlementPolicyConstants.MATCH_ID, -// matchElementDTO.getMatchId()); -// -// if(matchElementDTO.getAttributeValueElementDTO() != null) { -// Element attributeValueElement = createAttributeValueElement(matchElementDTO. -// getAttributeValueElementDTO(), doc); -// matchElement.appendChild(attributeValueElement); -// } -// -// if(matchElementDTO.getAttributeDesignatorDTO() != null ) { -// Element attributeDesignatorElement = createAttributeDesignatorElement(matchElementDTO. -// getAttributeDesignatorDTO(), doc); -// matchElement.appendChild(attributeDesignatorElement); -// } -// -// if(matchElementDTO.getAttributeSelectorDTO() != null ) { -// Element attributeSelectorElement = createAttributeSelectorElement(matchElementDTO. -// getAttributeSelectorDTO(), doc); -// matchElement.appendChild(attributeSelectorElement); -// } -// } -// return matchElement; -// } -// -// /** -// * This method creates the attribute value element -// * @param attributeValueElementDTO attribute value element data object -// * @param doc XML document -// * @return attribute value element -// */ -// public static Element createAttributeValueElement(AttributeValueElementDTO -// attributeValueElementDTO, Document doc) { -// -// Element attributeValueElement = doc.createElement(EntitlementPolicyConstants.ATTRIBUTE_VALUE); -// -// if(attributeValueElementDTO.getAttributeValue() != null && attributeValueElementDTO. -// getAttributeValue().trim().length() > 0) { -// -// attributeValueElement.setTextContent(attributeValueElementDTO.getAttributeValue().trim()); -// -// if(attributeValueElementDTO.getAttributeDataType()!= null && attributeValueElementDTO. -// getAttributeDataType().trim().length() > 0){ -// attributeValueElement.setAttribute(EntitlementPolicyConstants.DATA_TYPE, -// attributeValueElementDTO.getAttributeDataType()); -// } else { -// attributeValueElement.setAttribute(EntitlementPolicyConstants.DATA_TYPE, -// EntitlementPolicyConstants.STRING_DATA_TYPE); -// } -// -// } -// -// return attributeValueElement; -// -// } -// -// /** -// * This creates XML representation of Attributes Element using AttributesElementDTO object -// * -// * @param elementDTO AttributesElementDTO -// * @param doc Document -// * @return DOM element -// */ -// public static Element createAttributesElement(AttributesElementDTO elementDTO, Document doc){ -// -// Element attributesElement = doc.createElement(EntitlementPolicyConstants.ATTRIBUTES); -// -// attributesElement.setAttribute(EntitlementPolicyConstants.CATEGORY, elementDTO.getCategory()); -// -// List attributeElementDTOs = elementDTO.getAttributeElementDTOs(); -// if(attributeElementDTOs != null && attributeElementDTOs.size() > 0){ -// for(AttributeElementDTO attributeElementDTO : attributeElementDTOs){ -// Element attributeElement = doc.createElement(EntitlementPolicyConstants.ATTRIBUTE); -// attributeElement.setAttribute(EntitlementPolicyConstants.ATTRIBUTE_ID, -// attributeElementDTO.getAttributeId()); -// attributeElement.setAttribute(EntitlementPolicyConstants.INCLUDE_RESULT, -// Boolean.toString(attributeElementDTO.isIncludeInResult())); -// -// if(attributeElementDTO.getIssuer() != null && -// attributeElementDTO.getIssuer().trim().length() > 0){ -// attributeElement.setAttribute(EntitlementPolicyConstants.ISSUER, -// attributeElementDTO.getIssuer()); -// } -// -// List values = attributeElementDTO.getAttributeValues(); -// for(String value : values){ -// Element attributeValueElement = doc.createElement(EntitlementPolicyConstants. -// ATTRIBUTE_VALUE); -// attributeValueElement.setAttribute(EntitlementPolicyConstants.DATA_TYPE, -// attributeElementDTO.getDataType()); -// attributeValueElement.setTextContent(value.trim()); -// attributeElement.appendChild(attributeValueElement); -// } -// attributesElement.appendChild(attributeElement); -// } -// } -// return attributesElement; -// } -// -// -// public static Element createFunctionElement(FunctionDTO functionDTO, Document doc) { -// -// Element functionElement = doc.createElement(EntitlementPolicyConstants.FUNCTION); -// -// if(functionDTO.getFunctionId() != null && functionDTO.getFunctionId().trim().length() > 0) { -// functionElement.setAttribute(EntitlementPolicyConstants.FUNCTION_ID, -// functionDTO.getFunctionId()); -// } -// -// return functionElement; -// } -// -//// public static Element createAttributeDesignatorElement(AttributeDesignatorDTO -//// attributeDesignatorDTO, Document doc) { -//// -//// String attributeDesignatorElementName = attributeDesignatorDTO.getElementName() + -//// EntitlementPolicyConstants.ATTRIBUTE_DESIGNATOR; -//// -//// Element attributeDesignatorElement = doc.createElement(attributeDesignatorElementName); -//// -//// if(attributeDesignatorDTO.getAttributeId() != null && attributeDesignatorDTO. -//// getAttributeId().trim().length() > 0 ){ -//// -//// attributeDesignatorElement.setAttribute(EntitlementPolicyConstants.ATTRIBUTE_ID, -//// attributeDesignatorDTO.getAttributeId()); -//// -//// if(attributeDesignatorDTO.getDataType() != null && attributeDesignatorDTO. -//// getDataType().trim().length() > 0) { -//// attributeDesignatorElement.setAttribute(EntitlementPolicyConstants.DATA_TYPE, -//// attributeDesignatorDTO.getDataType()); -//// } else { -//// attributeDesignatorElement.setAttribute(EntitlementPolicyConstants.DATA_TYPE, -//// EntitlementPolicyConstants.STRING_DATA_TYPE); -//// } -//// -//// if(attributeDesignatorDTO.getIssuer() != null && attributeDesignatorDTO.getIssuer(). -//// trim().length() > 0) { -//// attributeDesignatorElement.setAttribute(EntitlementPolicyConstants.ISSUER, -//// attributeDesignatorDTO.getIssuer()); -//// } -//// -//// if(attributeDesignatorDTO.getMustBePresent() != null && attributeDesignatorDTO. -//// getMustBePresent().trim().length() > 0){ -//// attributeDesignatorElement.setAttribute(EntitlementPolicyConstants.MUST_BE_PRESENT, -//// attributeDesignatorDTO.getMustBePresent()); -//// } -//// -//// if(attributeDesignatorDTO.getSubjectCategory() != null){ -//// attributeDesignatorElement.setAttribute(EntitlementPolicyConstants.MUST_BE_PRESENT, -//// attributeDesignatorDTO.getSubjectCategory()); -//// } -//// -//// } -//// -//// return attributeDesignatorElement; -//// } -// -// -// public static Element createAttributeDesignatorElement(AttributeDesignatorDTO -// attributeDesignatorDTO, Document doc) { -// -// String attributeDesignatorElementName = -// EntitlementPolicyConstants.ATTRIBUTE_DESIGNATOR; -// -// Element attributeDesignatorElement = doc.createElement(attributeDesignatorElementName); -// -// String attributeId = attributeDesignatorDTO.getAttributeId(); -// String category = attributeDesignatorDTO.getCategory(); -// -// if(attributeId != null && attributeId.trim().length() > 0 && category != null && -// category.trim().length() > 0){ -// -// attributeDesignatorElement.setAttribute(EntitlementPolicyConstants.ATTRIBUTE_ID, -// attributeDesignatorDTO.getAttributeId()); -// -// attributeDesignatorElement.setAttribute(EntitlementPolicyConstants.CATEGORY, -// attributeDesignatorDTO.getCategory()); -// -// if(attributeDesignatorDTO.getDataType() != null && attributeDesignatorDTO. -// getDataType().trim().length() > 0) { -// attributeDesignatorElement.setAttribute(EntitlementPolicyConstants.DATA_TYPE, -// attributeDesignatorDTO.getDataType()); -// } else { -// attributeDesignatorElement.setAttribute(EntitlementPolicyConstants.DATA_TYPE, -// EntitlementPolicyConstants.STRING_DATA_TYPE); -// } -// -// if(attributeDesignatorDTO.getIssuer() != null && attributeDesignatorDTO.getIssuer(). -// trim().length() > 0) { -// attributeDesignatorElement.setAttribute(EntitlementPolicyConstants.ISSUER, -// attributeDesignatorDTO.getIssuer()); -// } -// -// if(attributeDesignatorDTO.getMustBePresent() != null && attributeDesignatorDTO. -// getMustBePresent().trim().length() > 0){ -// attributeDesignatorElement.setAttribute(EntitlementPolicyConstants.MUST_BE_PRESENT, -// attributeDesignatorDTO.getMustBePresent()); -// } else { -// attributeDesignatorElement.setAttribute(EntitlementPolicyConstants.MUST_BE_PRESENT, -// "true"); -// } -// -// } -// -// return attributeDesignatorElement; -// } -// -// -// public static Element createAttributeSelectorElement(AttributeSelectorDTO attributeSelectorDTO, -// Document doc) { -// -// Element attributeSelectorElement = doc.createElement(EntitlementPolicyConstants. -// ATTRIBUTE_SELECTOR); -// -// if(attributeSelectorDTO.getAttributeSelectorRequestContextPath() != null && -// attributeSelectorDTO.getAttributeSelectorRequestContextPath().trim().length() > 0) { -// -// attributeSelectorElement.setAttribute(EntitlementPolicyConstants.REQUEST_CONTEXT_PATH, -// EntitlementPolicyConstants.ATTRIBUTE_NAMESPACE + attributeSelectorDTO. -// getAttributeSelectorRequestContextPath()); -// -// if(attributeSelectorDTO.getAttributeSelectorDataType() != null && -// attributeSelectorDTO.getAttributeSelectorDataType().trim().length() > 0) { -// attributeSelectorElement.setAttribute(EntitlementPolicyConstants.DATA_TYPE, -// attributeSelectorDTO.getAttributeSelectorDataType()); -// } else { -// attributeSelectorElement.setAttribute(EntitlementPolicyConstants.DATA_TYPE, -// EntitlementPolicyConstants.STRING_DATA_TYPE); -// } -// -// if(attributeSelectorDTO.getAttributeSelectorMustBePresent() != null && -// attributeSelectorDTO.getAttributeSelectorMustBePresent().trim().length() > 0) { -// attributeSelectorElement.setAttribute(EntitlementPolicyConstants.MUST_BE_PRESENT, -// attributeSelectorDTO.getAttributeSelectorMustBePresent()); -// } -// -// } -// -// return attributeSelectorElement; -// } -// -// public static Element createObligationsElement(List obligationElementDTOs, -// Document doc){ -// -// -// Element obligationExpressions = null; -// Element adviceExpressions = null; -// -// if(obligationElementDTOs != null && obligationElementDTOs.size() > 0){ -// -// for(ObligationElementDTO dto : obligationElementDTOs){ -// String id = dto.getId(); -// String effect = dto.getEffect(); -// -// if(id != null && id.trim().length() > 0 && effect != null){ -// if(dto.getType() == ObligationElementDTO.ADVICE){ -// if(adviceExpressions == null){ -// adviceExpressions = doc. -// createElement(EntitlementPolicyConstants.ADVICE_EXPRESSIONS); -// } -// -// Element adviceExpression = doc. -// createElement(EntitlementPolicyConstants.ADVICE_EXPRESSION); -// adviceExpression.setAttribute(EntitlementPolicyConstants.ADVICE_ID, id); -// adviceExpression.setAttribute(EntitlementPolicyConstants.ADVICE_EFFECT, effect); -// List elementDTOs = dto.getAssignmentElementDTOs(); -// if(elementDTOs != null){ -// for(AttributeAssignmentElementDTO elementDTO : elementDTOs){ -// Element element = createAttributeAssignmentElement(elementDTO, doc); -// if(element != null){ -// adviceExpression.appendChild(element); -// } -// } -// } -// adviceExpressions.appendChild(adviceExpression); -// } else { -// -// if(obligationExpressions == null){ -// obligationExpressions = doc. -// createElement(EntitlementPolicyConstants.OBLIGATION_EXPRESSIONS); -// } -// -// Element obligationExpression = doc. -// createElement(EntitlementPolicyConstants.OBLIGATION_EXPRESSION); -// obligationExpression.setAttribute(EntitlementPolicyConstants.OBLIGATION_ID, id); -// obligationExpression.setAttribute(EntitlementPolicyConstants.OBLIGATION_EFFECT, -// effect); -// List elementDTOs = dto.getAssignmentElementDTOs(); -// if(elementDTOs != null){ -// for(AttributeAssignmentElementDTO elementDTO : elementDTOs){ -// Element element = createAttributeAssignmentElement(elementDTO, doc); -// if(element != null){ -// obligationExpression.appendChild(element); -// } -// } -// } -// obligationExpressions.appendChild(obligationExpression); -// } -// } -// } -// } -// -// if(adviceExpressions != null){ -// return adviceExpressions; -// } -// -// return obligationExpressions; -// } -// -// public static Element createAttributeAssignmentElement(AttributeAssignmentElementDTO assignmentElementDTO, -// Document doc){ -// -// String attributeId = assignmentElementDTO.getAttributeId(); -// -// if(attributeId != null && attributeId.trim().length() > 0){ -// -// String category = assignmentElementDTO.getCategory(); -// String issuer = assignmentElementDTO.getIssuer(); -// ApplyElementDTO applyElementDTO = assignmentElementDTO.getApplyElementDTO(); -// AttributeDesignatorDTO designatorDTO = assignmentElementDTO.getDesignatorDTO(); -// AttributeValueElementDTO valueElementDTO = assignmentElementDTO.getValueElementDTO(); -// -// Element attributeAssignment = doc. -// createElement(EntitlementPolicyConstants.ATTRIBUTE_ASSIGNMENT); -// attributeAssignment.setAttribute(EntitlementPolicyConstants.ATTRIBUTE_ID, -// attributeId); -// if(category != null && category.trim().length() > 0){ -// attributeAssignment.setAttribute(EntitlementPolicyConstants.CATEGORY, category); -// } -// -// if(issuer != null && issuer.trim().length() > 0){ -// attributeAssignment.setAttribute(EntitlementPolicyConstants.ISSUER, issuer); -// } -// -// if(applyElementDTO != null){ -// attributeAssignment.appendChild(createApplyElement(applyElementDTO, doc)); -// } -// -// if(designatorDTO != null){ -// attributeAssignment.appendChild(createAttributeDesignatorElement(designatorDTO, doc)); -// } -// -// if(valueElementDTO != null){ -// attributeAssignment.appendChild(createAttributeValueElement(valueElementDTO, doc)); -// } -// -// return attributeAssignment; -// } -// -// return null; -// } -// -// public static Element createSubElement(SubElementDTO subElementDTO, Document doc) { -// -// String subElementName = subElementDTO.getElementName(); -// -// Element subElement = doc.createElement(subElementName); -// -// for( MatchElementDTO matchElementDTO : subElementDTO.getMatchElementDTOs()) { -// Element matchElement = createMatchElement(matchElementDTO, doc); -// if(matchElement != null) { -// subElement.appendChild(matchElement); -// } -// } -// -// return subElement; -// } -// -// public static Element createTargetElement(List subElementDTOs, Document doc) { -// -// Element targetElement = doc.createElement(EntitlementPolicyConstants.TARGET_ELEMENT); -// String subjectElementName = EntitlementPolicyConstants.SUBJECT_ELEMENT + "s"; -// String actionElementName = EntitlementPolicyConstants.ACTION_ELEMENT + "s"; -// String resourceElementName = EntitlementPolicyConstants.RESOURCE_ELEMENT + "s"; -// String enviornementElementName = EntitlementPolicyConstants.ENVIRONMENT_ELEMENT + "s"; -// -// Element subjectElement = doc.createElement(subjectElementName); -// Element actionElement = doc.createElement(actionElementName); -// Element resourceElement = doc.createElement(resourceElementName); -// Element enviornementElement = doc.createElement(enviornementElementName); -// -// -// for(SubElementDTO subElementDTO : subElementDTOs) { -// -// if(subElementDTO.getElementName().equals(EntitlementPolicyConstants.SUBJECT_ELEMENT)) { -// Element subParentElement = createSubElement(subElementDTO, doc); -// subjectElement.appendChild(subParentElement); -// } -// -// if(subElementDTO.getElementName().equals(EntitlementPolicyConstants.ACTION_ELEMENT)) { -// Element subParentElement = createSubElement(subElementDTO, doc); -// actionElement.appendChild(subParentElement); -// } -// -// if(subElementDTO.getElementName().equals(EntitlementPolicyConstants.RESOURCE_ELEMENT)) { -// Element subParentElement = createSubElement(subElementDTO, doc); -// resourceElement.appendChild(subParentElement); -// } -// -// if(subElementDTO.getElementName().equals(EntitlementPolicyConstants.ENVIRONMENT_ELEMENT)) { -// Element subParentElement = createSubElement(subElementDTO, doc); -// enviornementElement.appendChild(subParentElement); -// } -// } -// -// targetElement.appendChild(subjectElement); -// targetElement.appendChild(actionElement); -// targetElement.appendChild(resourceElement); -// targetElement.appendChild(enviornementElement); -// -// return targetElement; -// } -// -// -// public static Element createRuleElement(RuleElementDTO ruleElementDTO, Document doc) { -// -// TargetElementDTO targetElementDTO = ruleElementDTO.getTargetElementDTO(); -// ConditionElementDT0 conditionElementDT0 = ruleElementDTO.getConditionElementDT0(); -// List obligationElementDTOs = ruleElementDTO.getObligationElementDTOs(); -// -// Element ruleElement = doc.createElement(EntitlementPolicyConstants.RULE_ELEMENT); -// -// if(ruleElementDTO.getRuleId() != null && ruleElementDTO.getRuleId().trim().length() > 0){ -// ruleElement.setAttribute(EntitlementPolicyConstants.RULE_ID, ruleElementDTO.getRuleId()); -// } -// -// if(ruleElementDTO.getRuleEffect() != null && ruleElementDTO.getRuleEffect().trim().length() > 0){ -// ruleElement.setAttribute(EntitlementPolicyConstants.RULE_EFFECT, -// ruleElementDTO.getRuleEffect()); -// } -// -// if(ruleElementDTO.getRuleDescription() != null && ruleElementDTO.getRuleDescription(). -// trim().length() > 0){ -// Element descriptionElement = doc.createElement(EntitlementPolicyConstants. -// DESCRIPTION_ELEMENT); -// descriptionElement.setTextContent(ruleElementDTO.getRuleDescription()); -// ruleElement.appendChild(descriptionElement); -// } -// -// if(targetElementDTO != null ){ -// Element targetElement = PolicyEditorUtil.createTargetElement(targetElementDTO, doc); -// ruleElement.appendChild(targetElement); -// } -// -// if(conditionElementDT0 != null){ -// ruleElement.appendChild(createConditionElement(conditionElementDT0, doc)); -// } -// -// -// if(obligationElementDTOs != null && obligationElementDTOs.size() > 0){ -// List obligations = new ArrayList(); -// List advices = new ArrayList(); -// for(ObligationElementDTO obligationElementDTO : obligationElementDTOs){ -// if(obligationElementDTO.getType() == ObligationElementDTO.ADVICE){ -// advices.add(obligationElementDTO); -// } else { -// obligations.add(obligationElementDTO); -// } -// } -// Element obligation = createObligationsElement(obligations, doc); -// Element advice = createObligationsElement(advices, doc); -// if(obligation != null){ -// ruleElement.appendChild(obligation); -// } -// if(advice != null){ -// ruleElement.appendChild(advice); -// } -// } -// -// return ruleElement; -// } -// -// -// public static Element createConditionElement(ConditionElementDT0 conditionElementDT0, Document doc) { -// -// Element conditionElement = doc.createElement(EntitlementPolicyConstants.CONDITION_ELEMENT); -// -// if(conditionElementDT0.getApplyElement() != null){ -// conditionElement.appendChild(createApplyElement(conditionElementDT0.getApplyElement(), doc)); -// -// } else if(conditionElementDT0.getAttributeValueElementDTO() != null) { -// Element attributeValueElement = createAttributeValueElement(conditionElementDT0. -// getAttributeValueElementDTO(), doc); -// conditionElement.appendChild(attributeValueElement); -// -// } else if(conditionElementDT0.getAttributeDesignator() != null) { -// AttributeDesignatorDTO attributeDesignatorDTO = conditionElementDT0.getAttributeDesignator(); -// conditionElement.appendChild(createAttributeDesignatorElement(attributeDesignatorDTO, doc)); -// -// } else if(conditionElementDT0.getFunctionFunctionId() != null) { -// Element functionElement = doc.createElement(EntitlementPolicyConstants.FUNCTION_ELEMENT); -// functionElement.setAttribute(EntitlementPolicyConstants.FUNCTION_ID, -// conditionElementDT0.getFunctionFunctionId()); -// conditionElement.appendChild(functionElement); -// } else if(conditionElementDT0.getVariableId() != null){ -// Element variableReferenceElement = doc.createElement(EntitlementPolicyConstants. -// VARIABLE_REFERENCE); -// variableReferenceElement.setAttribute(EntitlementPolicyConstants.VARIABLE_ID, -// conditionElementDT0.getVariableId()); -// conditionElement.appendChild(variableReferenceElement); -// } -// -// return conditionElement; -// -// } -// -// public static Element createApplyElement(ApplyElementDTO applyElementDTO, Document doc) { -// -// Element applyElement = doc.createElement(EntitlementPolicyConstants.APPLY_ELEMENT); -// -// if(applyElementDTO.getFunctionId() != null && applyElementDTO.getFunctionId().trim().length() > 0){ -// applyElement.setAttribute(EntitlementPolicyConstants.FUNCTION_ID, -// applyElementDTO.getFunctionId()); -// } -// -// if(applyElementDTO.getFunctionFunctionId() != null && applyElementDTO. -// getFunctionFunctionId().trim().length() > 0){ -// FunctionDTO functionDTO = new FunctionDTO(); -// functionDTO.setFunctionId(applyElementDTO.getFunctionFunctionId()); -// Element functionElement = createFunctionElement(functionDTO, doc); -// applyElement.appendChild(functionElement); -// } -// -// List applyElementDTOs = applyElementDTO.getApplyElements(); -// -// if(applyElementDTOs != null && applyElementDTOs.size() > 0) { -// -// for(ApplyElementDTO elementDTO : applyElementDTOs) { -// Element subApplyElement = createApplyElement(elementDTO, doc); -// applyElement.appendChild(subApplyElement); -// } -// } -// -// List attributeValueElementDTOs = applyElementDTO. -// getAttributeValueElementDTOs(); -// if(attributeValueElementDTOs != null && attributeValueElementDTOs.size() > 0) { -// -// for(AttributeValueElementDTO attributeValueElementDTO : attributeValueElementDTOs) { -// Element attributeValueElement = createAttributeValueElement(attributeValueElementDTO, -// doc); -// -// applyElement.appendChild(attributeValueElement); -// } -// } -// -// List attributeDesignatorDTOs = applyElementDTO.getAttributeDesignators(); -// if(attributeDesignatorDTOs != null && attributeDesignatorDTOs.size() > 0) { -// -// for(AttributeDesignatorDTO attributeDesignatorDTO : attributeDesignatorDTOs) { -// Element attributeDesignatorElement = -// createAttributeDesignatorElement(attributeDesignatorDTO, doc); -// applyElement.appendChild(attributeDesignatorElement); -// } -// } -// -// List attributeSelectorDTOs = applyElementDTO.getAttributeSelectors(); -// if(attributeSelectorDTOs != null && attributeSelectorDTOs.size() > 0) { -// -// for(AttributeSelectorDTO attributeSelectorDTO : attributeSelectorDTOs) { -// Element attributeSelectorElement = createAttributeSelectorElement(attributeSelectorDTO, -// doc); -// applyElement.appendChild(attributeSelectorElement); -// } -// } -// return applyElement; -// } -// -// /////// -// public static ApplyElementDTO createApplyElementForBagFunctions(String functionId, -// String category, -// String attributeId, -// String[] attributeValues, -// String dataType){ -// -// ApplyElementDTO applyElementDTO = new ApplyElementDTO(); -// -// if(attributeValues != null && functionId != null && functionId.trim().length() > 0 && -// category != null && category.trim().length() > 0 && -// attributeId != null && attributeId.trim().length() > 0){ -// -// ApplyElementDTO applyElementDTOBag = new ApplyElementDTO(); -// for(String attributeValue :attributeValues){ -// attributeValue = attributeValue.trim(); -// AttributeValueElementDTO attributeValueElementDTO = new AttributeValueElementDTO(); -// if(dataType != null && dataType.trim().length() > 0){ -// attributeValueElementDTO.setAttributeDataType(dataType); -// } else { -// attributeValueElementDTO.setAttributeDataType(EntitlementPolicyConstants.STRING_DATA_TYPE); -// } -// attributeValueElementDTO.setAttributeValue(attributeValue.trim()); -// applyElementDTOBag.setAttributeValueElementDTO(attributeValueElementDTO); -// } -// -// applyElementDTOBag.setFunctionId(EntitlementPolicyConstants.FUNCTION_BAG); -// -// AttributeDesignatorDTO attributeDesignatorDTO = new AttributeDesignatorDTO(); -// if(dataType != null && dataType.trim().length() > 0){ -// attributeDesignatorDTO.setDataType(dataType); -// } else { -// attributeDesignatorDTO.setDataType(EntitlementPolicyConstants.STRING_DATA_TYPE); -// } -// attributeDesignatorDTO.setAttributeId(attributeId); -// attributeDesignatorDTO.setCategory(category); -// -// applyElementDTO.setApplyElement(applyElementDTOBag); -// applyElementDTO.setAttributeDesignators(attributeDesignatorDTO); -// applyElementDTO.setFunctionId(functionId); -// -// } -// -// return applyElementDTO; -// } -// -// public static ApplyElementDTO createApplyElementForNonBagFunctions(String functionId, -// String category, -// String attributeId, -// String attributeValue, -// String dataType){ -// -// ApplyElementDTO applyElementDTO = new ApplyElementDTO(); -// -// if(attributeValue != null && attributeValue.trim().length() > 0 && functionId != null && -// functionId.trim().length() > 0 && category != null && -// category.trim().length() > 0 && attributeId != null && -// attributeId.trim().length() > 0) { -// -// AttributeValueElementDTO attributeValueElementDTO = new AttributeValueElementDTO(); -// if(dataType != null && dataType.trim().length() > 0){ -// attributeValueElementDTO.setAttributeDataType(dataType); -// } else { -// attributeValueElementDTO.setAttributeDataType(EntitlementPolicyConstants.STRING_DATA_TYPE); -// } -// attributeValueElementDTO.setAttributeValue(attributeValue.trim()); -// -// AttributeDesignatorDTO attributeDesignatorDTO = new AttributeDesignatorDTO(); -// if(dataType != null && dataType.trim().length() > 0){ -// attributeDesignatorDTO.setDataType(dataType); -// } else { -// attributeDesignatorDTO.setDataType(EntitlementPolicyConstants.STRING_DATA_TYPE); -// } -// attributeDesignatorDTO.setAttributeId(attributeId); -// attributeDesignatorDTO.setCategory(category); -// -// applyElementDTO.setAttributeValueElementDTO(attributeValueElementDTO); -// applyElementDTO.setAttributeDesignators(attributeDesignatorDTO); -// applyElementDTO.setFunctionId(functionId); -// -// } -// -// return applyElementDTO; -// } -// -// public static ApplyElementDTO createApplyElementForNonBagFunctionsWithAnyOf(String functionId, -// String attributeDesignatorType, -// String attributeDesignatorId, -// String attributeValue){ -// -// ApplyElementDTO applyElementDTO = new ApplyElementDTO(); -// -// if(attributeValue != null && attributeValue.trim().length() > 0 && functionId != null && -// functionId.trim().length() > 0 && attributeDesignatorType != null && -// attributeDesignatorType.trim().length() > 0 && attributeDesignatorId != null && -// attributeDesignatorId.trim().length() > 0) { -// -// AttributeValueElementDTO attributeValueElementDTO = new AttributeValueElementDTO(); -// attributeValueElementDTO.setAttributeDataType(EntitlementPolicyConstants.STRING_DATA_TYPE); -// attributeValueElementDTO.setAttributeValue(attributeValue.trim()); -// -// AttributeDesignatorDTO attributeDesignatorDTO = new AttributeDesignatorDTO(); -// attributeDesignatorDTO.setDataType(EntitlementPolicyConstants.STRING_DATA_TYPE); -// attributeDesignatorDTO.setAttributeId(attributeDesignatorId); -// attributeDesignatorDTO.setCategory(attributeDesignatorType); -// -// applyElementDTO.setFunctionFunctionId(functionId); -// applyElementDTO.setAttributeValueElementDTO(attributeValueElementDTO); -// applyElementDTO.setAttributeDesignators(attributeDesignatorDTO); -// applyElementDTO.setFunctionId(EntitlementPolicyConstants.FUNCTION_ANY_OF); -// -// } -// -// return applyElementDTO; -// } -// -// -// public static MatchElementDTO createMatchElementForNonBagFunctions(String functionId, -// String attributeValue, -// String category, -// String attributeId, -// String dataType) { -// MatchElementDTO matchElementDTO = new MatchElementDTO(); -// -// if(functionId != null && functionId.trim().length() > 0 && attributeValue != null && -// attributeValue.trim().length() > 0&& category != null && -// category.trim().length() > 0 && attributeId != null && -// attributeId.trim().length() > 0) { -// AttributeValueElementDTO attributeValueElementDTO = new AttributeValueElementDTO(); -// if(dataType != null && dataType.trim().length() > 0){ -// attributeValueElementDTO.setAttributeDataType(dataType); -// } else { -// attributeValueElementDTO.setAttributeDataType(EntitlementPolicyConstants.STRING_DATA_TYPE); -// } -// attributeValueElementDTO.setAttributeValue(attributeValue.trim()); -// -// AttributeDesignatorDTO attributeDesignatorDTO = new AttributeDesignatorDTO(); -// if(dataType != null && dataType.trim().length() > 0){ -// attributeValueElementDTO.setAttributeDataType(dataType); -// } else { -// attributeValueElementDTO.setAttributeDataType(EntitlementPolicyConstants.STRING_DATA_TYPE); -// } -// attributeDesignatorDTO.setAttributeId(attributeId); -// attributeDesignatorDTO.setCategory(category); -// -// matchElementDTO.setMatchId(functionId); -// matchElementDTO.setAttributeValueElementDTO(attributeValueElementDTO); -// matchElementDTO.setAttributeDesignatorDTO(attributeDesignatorDTO); -// } -// -// return matchElementDTO; -// } -// -// public static Element createBasicRuleElementDTO(BasicRuleDTO basicRuleDTO, -// Document doc) { -// -// String functionOnResources = basicRuleDTO.getFunctionOnResources(); -// String functionOnSubjects = basicRuleDTO.getFunctionOnSubjects(); -// String functionOnActions = basicRuleDTO.getFunctionOnActions(); -// String functionOnEnvironment = basicRuleDTO.getFunctionOnEnvironment(); -// String resourceNames = basicRuleDTO.getResourceList(); -// String actionNames = basicRuleDTO.getActionList(); -// String subjectNames = basicRuleDTO.getSubjectList(); -// String environmentNames = basicRuleDTO.getEnvironmentList(); -// String resourceId = basicRuleDTO.getResourceId(); -// String subjectId = basicRuleDTO.getSubjectId(); -// String actionId = basicRuleDTO.getActionId(); -// String environmentId = basicRuleDTO.getEnvironmentId(); -// String resourceDataType = basicRuleDTO.getResourceDataType(); -// String subjectDataType = basicRuleDTO.getSubjectDataType(); -// String actionDataType = basicRuleDTO.getActionDataType(); -// String environmentDataType = basicRuleDTO.getEnvironmentDataType(); -// -// -// Element resourcesElement = null; -// Element actionsElement = null; -// Element subjectsElement = null; -// Element environmentsElement = null; -// Element targetElement = null; -// Element applyElement = null; -// Element conditionElement = null; -// Element ruleElement = null ; -// -// ApplyElementDTO applyElementDTO = new ApplyElementDTO(); -// -// if(resourceNames != null && resourceNames.trim().length() > 0) { -// String[] resources = resourceNames.split(EntitlementPolicyConstants.ATTRIBUTE_SEPARATOR); -// if(resourceId == null || resourceId.trim().length() < 1){ -// resourceId = EntitlementPolicyConstants.RESOURCE_ID; -// } -// if(functionOnResources.equals(EntitlementPolicyConstants.EQUAL_TO) || -// functionOnResources.equals(EntitlementPolicyConstants.REGEXP_MATCH) ) { -// resourcesElement = doc.createElement(PolicyEditorConstants.ANY_OF_ELEMENT); -// Element resourceElement = doc.createElement(PolicyEditorConstants.ALL_OF_ELEMENT); -// MatchElementDTO matchElementDTO = createMatchElementForNonBagFunctions( -// getFunctionId(functionOnResources), -// resources[0].trim(), PolicyEditorConstants.RESOURCE_CATEGORY_URI, resourceId, resourceDataType); -// Element matchElement= createMatchElement(matchElementDTO, doc); -// if(matchElement != null){ -// resourceElement.appendChild(matchElement); -// } -// resourcesElement.appendChild(resourceElement); -// -// } else if(functionOnResources.contains("less") || functionOnResources.contains("greater")){ -// -// AttributeDesignatorDTO designatorDTO = new AttributeDesignatorDTO(); -// designatorDTO.setCategory(PolicyEditorConstants.RESOURCE_CATEGORY_URI); -// designatorDTO.setAttributeId(resourceId); -// designatorDTO.setDataType(resourceDataType); -// designatorDTO.setMustBePresent("true"); -// try { -// ApplyElementDTO elementDTO = PolicyEditorUtil. -// processGreaterLessThanFunctions(functionOnResources, resourceDataType, -// resourceNames, designatorDTO); -// applyElementDTO.setApplyElement(elementDTO); -// } catch (PolicyEditorException e) { -// //ignore TODO -// } -// } else if(functionOnResources.equals(EntitlementPolicyConstants.IS_IN)) { -// ApplyElementDTO elementDTO = createApplyElementForNonBagFunctions( -// getFunctionId(functionOnResources), -// PolicyEditorConstants.RESOURCE_CATEGORY_URI, resourceId, resources[0].trim(), resourceDataType); -// applyElementDTO.setApplyElement(elementDTO); -// } else { -// ApplyElementDTO elementDTO = createApplyElementForBagFunctions( -// getFunctionId(functionOnResources), -// PolicyEditorConstants.RESOURCE_CATEGORY_URI, resourceId, resources, resourceDataType); -// applyElementDTO.setApplyElement(elementDTO); -// } -// } -// -// if(actionNames != null && actionNames.trim().length() > 0) { -// String[] actions = actionNames.split(EntitlementPolicyConstants.ATTRIBUTE_SEPARATOR); -// if(actionId == null || actionId.trim().length() < 1){ -// actionId = EntitlementPolicyConstants.ACTION_ID; -// } -// if(functionOnActions.equals(EntitlementPolicyConstants.EQUAL_TO) || -// functionOnActions.equals(EntitlementPolicyConstants.REGEXP_MATCH)) { -// actionsElement = doc.createElement(PolicyEditorConstants.ANY_OF_ELEMENT); -// Element actionElement = doc.createElement(PolicyEditorConstants.ALL_OF_ELEMENT); -// MatchElementDTO matchElementDTO = createMatchElementForNonBagFunctions( -// getFunctionId(functionOnActions), -// actions[0].trim(), PolicyEditorConstants.ACTION_CATEGORY_URI, actionId, actionDataType); -// Element matchElement= createMatchElement(matchElementDTO, doc); -// if(matchElement != null){ -// actionElement.appendChild(matchElement); -// } -// actionsElement.appendChild(actionElement); -// } else if(functionOnActions.contains("less") || functionOnActions.contains("greater")){ -// -// AttributeDesignatorDTO designatorDTO = new AttributeDesignatorDTO(); -// designatorDTO.setCategory(PolicyEditorConstants.ACTION_CATEGORY_URI); -// designatorDTO.setAttributeId(actionId); -// designatorDTO.setDataType(actionDataType); -// designatorDTO.setMustBePresent("true"); -// try { -// ApplyElementDTO elementDTO = PolicyEditorUtil. -// processGreaterLessThanFunctions(functionOnActions, actionDataType, -// actionNames, designatorDTO); -// applyElementDTO.setApplyElement(elementDTO); -// } catch (PolicyEditorException e) { -// //ignore TODO -// } -// } else if(functionOnActions.equals(EntitlementPolicyConstants.IS_IN)) { -// ApplyElementDTO elementDTO = createApplyElementForNonBagFunctions( -// getFunctionId(functionOnActions), -// PolicyEditorConstants.ACTION_CATEGORY_URI, actionId, actions[0].trim(), actionDataType); -// applyElementDTO.setApplyElement(elementDTO); -// } else { -// ApplyElementDTO elementDTO = createApplyElementForBagFunctions( -// getFunctionId(functionOnActions), -// EntitlementPolicyConstants.ACTION_ELEMENT, actionId, actions, actionDataType); -// applyElementDTO.setApplyElement(elementDTO); -// } -// } -// -// if(environmentNames != null && environmentNames.trim().length() > 0) { -// String[] environments = environmentNames.split(EntitlementPolicyConstants.ATTRIBUTE_SEPARATOR); -// if(environmentId == null || environmentId.trim().length() < 1){ -// environmentId = EntitlementPolicyConstants.ENVIRONMENT_ID; -// } -// if(functionOnEnvironment.equals(EntitlementPolicyConstants.EQUAL_TO) || -// functionOnEnvironment.equals(EntitlementPolicyConstants.REGEXP_MATCH)) { -// environmentsElement = doc.createElement(PolicyEditorConstants.ANY_OF_ELEMENT); -// Element environmentElement = doc.createElement(PolicyEditorConstants.ALL_OF_ELEMENT); -// MatchElementDTO matchElementDTO = createMatchElementForNonBagFunctions( -// getFunctionId(functionOnEnvironment), -// environments[0].trim(), PolicyEditorConstants.ENVIRONMENT_CATEGORY_URI, environmentId, environmentDataType); -// Element matchElement= createMatchElement(matchElementDTO, doc); -// if(matchElement != null){ -// environmentElement.appendChild(matchElement); -// } -// environmentsElement.appendChild(environmentElement); -// } else if(functionOnEnvironment.contains("less") || functionOnEnvironment.contains("greater")){ -// -// AttributeDesignatorDTO designatorDTO = new AttributeDesignatorDTO(); -// designatorDTO.setCategory(PolicyEditorConstants.ENVIRONMENT_CATEGORY_URI); -// designatorDTO.setAttributeId(environmentId); -// designatorDTO.setDataType(environmentDataType); -// designatorDTO.setMustBePresent("true"); -// try { -// ApplyElementDTO elementDTO = PolicyEditorUtil. -// processGreaterLessThanFunctions(functionOnEnvironment, environmentDataType, -// environmentNames, designatorDTO); -// applyElementDTO.setApplyElement(elementDTO); -// } catch (PolicyEditorException e) { -// //ignore TODO -// } -// } else if(functionOnEnvironment.equals(EntitlementPolicyConstants.IS_IN)) { -// ApplyElementDTO elementDTO = createApplyElementForNonBagFunctions( -// getFunctionId(functionOnEnvironment), -// PolicyEditorConstants.ENVIRONMENT_CATEGORY_URI, environmentId, environments[0].trim(), environmentDataType); -// applyElementDTO.setApplyElement(elementDTO); -// } else { -// ApplyElementDTO elementDTO = createApplyElementForBagFunctions( -// getFunctionId(functionOnEnvironment), -// PolicyEditorConstants.ENVIRONMENT_CATEGORY_URI, environmentId, environments, environmentDataType); -// applyElementDTO.setApplyElement(elementDTO); -// } -// } -// -// if(subjectNames != null && subjectNames.trim().length() > 0) { -// String[] subjects = subjectNames.split(EntitlementPolicyConstants.ATTRIBUTE_SEPARATOR); -// if(subjectId == null || subjectId.trim().length() < 1){ -// subjectId = EntitlementPolicyConstants.SUBJECT_ID_DEFAULT; -// } -// -// ApplyElementDTO elementDTO = null; -// if(functionOnSubjects.equals(EntitlementPolicyConstants.EQUAL_TO) || -// functionOnSubjects.equals(EntitlementPolicyConstants.REGEXP_MATCH)) { -// elementDTO = createApplyElementForNonBagFunctionsWithAnyOf( -// getFunctionId(functionOnSubjects), -// PolicyEditorConstants.SUBJECT_CATEGORY_URI,subjectId, subjects[0].trim()); -// -// } else if(functionOnSubjects.contains("less") || functionOnSubjects.contains("greater")){ -// -// AttributeDesignatorDTO designatorDTO = new AttributeDesignatorDTO(); -// designatorDTO.setCategory(PolicyEditorConstants.ACTION_CATEGORY_URI); -// designatorDTO.setAttributeId(subjectId); -// designatorDTO.setDataType(subjectDataType); -// designatorDTO.setMustBePresent("true"); -// try { -// elementDTO = PolicyEditorUtil. -// processGreaterLessThanFunctions(functionOnSubjects, subjectDataType, -// subjectNames, designatorDTO); -// applyElementDTO.setApplyElement(elementDTO); -// } catch (PolicyEditorException e) { -// //ignore TODO -// } -// } else if(functionOnSubjects.equals(EntitlementPolicyConstants.IS_IN)) { -// elementDTO = createApplyElementForNonBagFunctions( -// getFunctionId(functionOnSubjects), -// PolicyEditorConstants.SUBJECT_CATEGORY_URI, subjectId, subjects[0].trim(), subjectDataType); -// } else { -// elementDTO = createApplyElementForBagFunctions( -// getFunctionId(functionOnSubjects), -// PolicyEditorConstants.SUBJECT_CATEGORY_URI, subjectId, subjects, subjectDataType); -// } -// -// if(elementDTO != null){ -// applyElementDTO.setApplyElement(elementDTO); -// } -// } -// -// List applyElementDTOs = applyElementDTO.getApplyElements(); -// -// if(applyElementDTOs.size() > 1) { -// applyElementDTO.setFunctionId(EntitlementPolicyConstants.FUNCTION_AND); -// applyElement = createApplyElement(applyElementDTO, doc); -// } else if(applyElementDTOs.size() == 1){ -// applyElement = createApplyElement(applyElementDTOs.get(0), doc); -// } -// -// if(resourcesElement != null || actionsElement != null || subjectsElement != null || -// environmentsElement != null) { -// targetElement = doc.createElement(EntitlementPolicyConstants.TARGET_ELEMENT); -// if(resourcesElement != null) { -// targetElement.appendChild(resourcesElement); -// } -// if(actionsElement != null) { -// targetElement.appendChild(actionsElement); -// } -// if(subjectsElement != null) { -// targetElement.appendChild(subjectsElement); -// } -// -// if(environmentsElement != null){ -// targetElement.appendChild(environmentsElement); -// } -// } -// -// if(applyElement != null) { -// conditionElement = doc.createElement(EntitlementPolicyConstants.CONDITION_ELEMENT); -// conditionElement.appendChild(applyElement); -// } -// -// if(basicRuleDTO.getRuleId() != null && basicRuleDTO.getRuleId().trim().length() > 0 && -// basicRuleDTO.getRuleEffect() != null && basicRuleDTO.getRuleEffect(). -// trim().length() > 0){ -// -// ruleElement = doc.createElement(EntitlementPolicyConstants.RULE_ELEMENT); -// ruleElement.setAttribute(EntitlementPolicyConstants.RULE_ID, basicRuleDTO. -// getRuleId()); -// ruleElement.setAttribute(EntitlementPolicyConstants.RULE_EFFECT, -// basicRuleDTO.getRuleEffect()); -// -// if(basicRuleDTO.getRuleDescription() != null && basicRuleDTO. -// getRuleDescription().trim().length() > 0){ -// ruleElement.setAttribute(EntitlementPolicyConstants.RULE_DESCRIPTION, -// basicRuleDTO.getRuleDescription()); -// } -// -// if(targetElement != null) { -// ruleElement.appendChild(targetElement); -// } -// if(conditionElement != null) { -// ruleElement.appendChild(conditionElement); -// } -// } -// -// return ruleElement; -// -// } -// -// -// -// public static Element createBasicTargetElementDTO(BasicTargetDTO basicTargetDTO, -// Document doc) { -// -// //TODO -// String functionOnResources = basicTargetDTO.getFunctionOnResources(); -// String functionOnSubjects = basicTargetDTO.getFunctionOnSubjects(); -// String functionOnActions = basicTargetDTO.getFunctionOnActions(); -// String functionOnEnvironment = basicTargetDTO.getFunctionOnEnvironment(); -// String resourceNames = basicTargetDTO.getResourceList(); -// String actionNames = basicTargetDTO.getActionList(); -// String subjectNames = basicTargetDTO.getSubjectList(); -// String environmentNames = basicTargetDTO.getEnvironmentList(); -// String resourceId = basicTargetDTO.getResourceId(); -// String subjectId = basicTargetDTO.getSubjectId(); -// String actionId = basicTargetDTO.getActionId(); -// String environmentId = basicTargetDTO.getEnvironmentId(); -// String resourceDataType = basicTargetDTO.getResourceDataType(); -// String subjectDataType = basicTargetDTO.getSubjectDataType(); -// String actionDataType = basicTargetDTO.getActionDataType(); -// String environmentDataType = basicTargetDTO.getResourceDataType(); -// -// Element resourcesElement = null; -// Element actionsElement = null; -// Element subjectsElement = null; -// Element environmentsElement = null; -// Element targetElement = doc.createElement(EntitlementPolicyConstants.TARGET_ELEMENT); -// -// if(resourceNames != null && resourceNames.trim().length() > 0) { -// resourcesElement = doc.createElement(PolicyEditorConstants.ANY_OF_ELEMENT); -// Element resourceElement = doc.createElement(PolicyEditorConstants.ALL_OF_ELEMENT); -// String[] resources = resourceNames.split(EntitlementPolicyConstants.ATTRIBUTE_SEPARATOR); -// if(resourceId == null || resourceId.trim().length() < 1) { -// resourceId = EntitlementPolicyConstants.RESOURCE_ID; -// } -// if(functionOnResources.equals(EntitlementPolicyConstants.EQUAL_TO) || -// functionOnResources.equals(EntitlementPolicyConstants.REGEXP_MATCH) ) { -// MatchElementDTO matchElementDTO = createMatchElementForNonBagFunctions( -// getFunctionId(functionOnResources), -// resources[0].trim(), PolicyEditorConstants.RESOURCE_CATEGORY_URI, resourceId, resourceDataType); -// Element matchElement= createMatchElement(matchElementDTO, doc); -// if(matchElement != null){ -// resourceElement.appendChild(matchElement); -// } -// resourcesElement.appendChild(resourceElement); -// } else if(functionOnResources.equals(EntitlementPolicyConstants.AT_LEAST_ONE_MATCH)) { -// for(String resource : resources){ -// resource = resource.trim(); -// Element resourceEle = doc.createElement(PolicyEditorConstants.ALL_OF_ELEMENT); -// MatchElementDTO matchElementDTO = createMatchElementForNonBagFunctions( -// getFunctionId(EntitlementPolicyConstants.EQUAL_TO), -// resource, PolicyEditorConstants.RESOURCE_CATEGORY_URI, resourceId, resourceDataType); -// Element matchElement= createMatchElement(matchElementDTO, doc); -// if(matchElement != null){ -// resourceEle.appendChild(matchElement); -// } -// resourcesElement.appendChild(resourceEle); -// } -// } else if(functionOnResources.equals(EntitlementPolicyConstants.AT_LEAST_ONE_MATCH_REGEXP)) { -// for(String resource : resources){ -// resource = resource.trim(); -// Element resourceEle = doc.createElement(PolicyEditorConstants.ALL_OF_ELEMENT); -// MatchElementDTO matchElementDTO = createMatchElementForNonBagFunctions( -// getFunctionId(EntitlementPolicyConstants.REGEXP_MATCH), -// resource, PolicyEditorConstants.RESOURCE_CATEGORY_URI, resourceId, resourceDataType); -// Element matchElement= createMatchElement(matchElementDTO, doc); -// if(matchElement != null){ -// resourceEle.appendChild(matchElement); -// } -// resourcesElement.appendChild(resourceEle); -// } -// } else if(functionOnResources.equals(EntitlementPolicyConstants.MATCH_REGEXP_SET_OF)) { -// for(String resource : resources){ -// resource = resource.trim(); -// MatchElementDTO matchElementDTO = createMatchElementForNonBagFunctions( -// getFunctionId(EntitlementPolicyConstants.REGEXP_MATCH), -// resource, PolicyEditorConstants.RESOURCE_CATEGORY_URI, resourceId, resourceDataType); -// Element matchElement= createMatchElement(matchElementDTO, doc); -// if(matchElement != null){ -// resourceElement.appendChild(matchElement); -// } -// } -// resourcesElement.appendChild(resourceElement); -// }else if(functionOnResources.equals(EntitlementPolicyConstants.SET_OF)) { -// for(String resource : resources){ -// resource = resource.trim(); -// MatchElementDTO matchElementDTO = createMatchElementForNonBagFunctions( -// getFunctionId(EntitlementPolicyConstants.EQUAL_TO), -// resource, PolicyEditorConstants.RESOURCE_CATEGORY_URI, resourceId, resourceDataType); -// Element matchElement= createMatchElement(matchElementDTO, doc); -// if(matchElement != null){ -// resourceElement.appendChild(matchElement); -// } -// } -// resourcesElement.appendChild(resourceElement); -// } -// } -// -// if(actionNames != null && actionNames.trim().length() > 0) { -// actionsElement = doc.createElement(PolicyEditorConstants.ANY_OF_ELEMENT); -// Element actionElement = doc.createElement(PolicyEditorConstants.ALL_OF_ELEMENT); -// String[] actions = actionNames.split(","); -// if(actionId == null || actionId.trim().length() < 1) { -// actionId = EntitlementPolicyConstants.ACTION_ID; -// } -// if(functionOnActions.equals(EntitlementPolicyConstants.EQUAL_TO) || -// functionOnActions.equals(EntitlementPolicyConstants. REGEXP_MATCH)) { -// MatchElementDTO matchElementDTO = createMatchElementForNonBagFunctions( -// getFunctionId(functionOnActions), -// actions[0].trim(), PolicyEditorConstants.ACTION_CATEGORY_URI, actionId, actionDataType); -// Element matchElement= createMatchElement(matchElementDTO, doc); -// if(matchElement != null){ -// actionElement.appendChild(matchElement); -// } -// actionsElement.appendChild(actionElement); -// } else if(functionOnActions.equals(EntitlementPolicyConstants.AT_LEAST_ONE_MATCH)) { -// for(String action : actions){ -// action = action.trim(); -// Element actionEle = doc.createElement(PolicyEditorConstants.ALL_OF_ELEMENT); -// MatchElementDTO matchElementDTO = createMatchElementForNonBagFunctions( -// getFunctionId(EntitlementPolicyConstants.EQUAL_TO), -// action, PolicyEditorConstants.ACTION_CATEGORY_URI, actionId, actionDataType); -// Element matchElement= createMatchElement(matchElementDTO, doc); -// if(matchElement != null){ -// actionEle.appendChild(matchElement); -// } -// actionsElement.appendChild(actionEle); -// } -// } else if(functionOnActions.equals(EntitlementPolicyConstants.AT_LEAST_ONE_MATCH_REGEXP)) { -// for(String action : actions){ -// action = action.trim(); -// Element actionEle = doc.createElement(PolicyEditorConstants.ALL_OF_ELEMENT); -// MatchElementDTO matchElementDTO = createMatchElementForNonBagFunctions( -// getFunctionId(EntitlementPolicyConstants.REGEXP_MATCH), -// action, PolicyEditorConstants.ACTION_CATEGORY_URI, actionId, actionDataType); -// Element matchElement= createMatchElement(matchElementDTO, doc); -// if(matchElement != null){ -// actionEle.appendChild(matchElement); -// } -// actionsElement.appendChild(actionEle); -// } -// } else if(functionOnActions.equals(EntitlementPolicyConstants.MATCH_REGEXP_SET_OF)) { -// for(String action : actions){ -// action = action.trim(); -// MatchElementDTO matchElementDTO = createMatchElementForNonBagFunctions( -// getFunctionId(EntitlementPolicyConstants.REGEXP_MATCH), -// action, PolicyEditorConstants.ACTION_CATEGORY_URI, actionId, actionDataType); -// Element matchElement= createMatchElement(matchElementDTO, doc); -// if(matchElement != null){ -// actionElement.appendChild(matchElement); -// } -// } -// actionsElement.appendChild(actionElement); -// } else if(functionOnActions.equals(EntitlementPolicyConstants.SET_OF)) { -// for(String action : actions){ -// action = action.trim(); -// MatchElementDTO matchElementDTO = createMatchElementForNonBagFunctions( -// getFunctionId(EntitlementPolicyConstants.EQUAL_TO), -// action, PolicyEditorConstants.ACTION_CATEGORY_URI, actionId, actionDataType); -// Element matchElement= createMatchElement(matchElementDTO, doc); -// if(matchElement != null){ -// actionElement.appendChild(matchElement); -// } -// } -// actionsElement.appendChild(actionElement); -// } -// -// } -// -// if(environmentNames != null && environmentNames.trim().length() > 0) { -// environmentsElement = doc.createElement(PolicyEditorConstants.ANY_OF_ELEMENT); -// Element environmentElement = doc.createElement(PolicyEditorConstants.ALL_OF_ELEMENT); -// String[] environments = environmentNames.split(","); -// if(environmentId == null || environmentId.trim().length() < 1) { -// environmentId = EntitlementPolicyConstants.ENVIRONMENT_ID; -// } -// if(functionOnEnvironment.equals(EntitlementPolicyConstants.EQUAL_TO) || -// functionOnEnvironment.equals(EntitlementPolicyConstants.REGEXP_MATCH)) { -// MatchElementDTO matchElementDTO = createMatchElementForNonBagFunctions( -// getFunctionId(functionOnEnvironment), -// environments[0].trim(), PolicyEditorConstants.ENVIRONMENT_CATEGORY_URI, environmentId, environmentDataType); -// Element matchElement= createMatchElement(matchElementDTO, doc); -// if(matchElement != null){ -// environmentElement.appendChild(matchElement); -// } -// environmentsElement.appendChild(environmentElement); -// } else if(functionOnEnvironment.equals(EntitlementPolicyConstants.AT_LEAST_ONE_MATCH)) { -// for(String environment : environments){ -// environment = environment.trim(); -// Element environmentEle = doc.createElement(PolicyEditorConstants.ALL_OF_ELEMENT); -// MatchElementDTO matchElementDTO = createMatchElementForNonBagFunctions( -// getFunctionId(EntitlementPolicyConstants.EQUAL_TO), -// environment, PolicyEditorConstants.ENVIRONMENT_CATEGORY_URI, environmentId, environmentDataType); -// Element matchElement= createMatchElement(matchElementDTO, doc); -// if(matchElement != null){ -// environmentEle.appendChild(matchElement); -// } -// environmentsElement.appendChild(environmentEle); -// } -// } else if(functionOnEnvironment.equals(EntitlementPolicyConstants.AT_LEAST_ONE_MATCH_REGEXP)) { -// for(String environment : environments){ -// environment = environment.trim(); -// Element environmentEle = doc.createElement(PolicyEditorConstants.ALL_OF_ELEMENT); -// MatchElementDTO matchElementDTO = createMatchElementForNonBagFunctions( -// getFunctionId(EntitlementPolicyConstants.REGEXP_MATCH), -// environment, PolicyEditorConstants.ENVIRONMENT_CATEGORY_URI, environmentId, environmentDataType); -// Element matchElement= createMatchElement(matchElementDTO, doc); -// if(matchElement != null){ -// environmentEle.appendChild(matchElement); -// } -// environmentsElement.appendChild(environmentEle); -// } -// }else if(functionOnEnvironment.equals(EntitlementPolicyConstants.MATCH_REGEXP_SET_OF)) { -// for(String environment : environments){ -// environment = environment.trim(); -// MatchElementDTO matchElementDTO = createMatchElementForNonBagFunctions( -// getFunctionId(EntitlementPolicyConstants.REGEXP_MATCH), -// environment, PolicyEditorConstants.ENVIRONMENT_CATEGORY_URI, environmentId, environmentDataType); -// Element matchElement= createMatchElement(matchElementDTO, doc); -// if(matchElement != null){ -// environmentElement.appendChild(matchElement); -// } -// } -// environmentsElement.appendChild(environmentElement); -// }else if(functionOnEnvironment.equals(EntitlementPolicyConstants.SET_OF)) { -// for(String environment : environments){ -// environment = environment.trim(); -// MatchElementDTO matchElementDTO = createMatchElementForNonBagFunctions( -// getFunctionId(EntitlementPolicyConstants.EQUAL_TO), -// environment, PolicyEditorConstants.ENVIRONMENT_CATEGORY_URI, environmentId, environmentDataType); -// Element matchElement= createMatchElement(matchElementDTO, doc); -// if(matchElement != null){ -// environmentElement.appendChild(matchElement); -// } -// } -// environmentsElement.appendChild(environmentElement); -// } -// } -// -// if(subjectNames != null && subjectNames.trim().length() > 0) { -// subjectsElement = doc.createElement(PolicyEditorConstants.ANY_OF_ELEMENT); -// Element subjectElement = doc.createElement(PolicyEditorConstants.ALL_OF_ELEMENT); -// String[] subjects = subjectNames.split(","); -// if(subjectId == null || subjectId.trim().length() < 1){ -// subjectId = EntitlementPolicyConstants.SUBJECT_ID_DEFAULT; -// } -// -// if(EntitlementPolicyConstants.EQUAL_TO.equals(functionOnSubjects) || -// EntitlementPolicyConstants.REGEXP_MATCH.equals(functionOnSubjects)) { -// MatchElementDTO matchElementDTO = createMatchElementForNonBagFunctions( -// getFunctionId(functionOnSubjects), -// subjects[0].trim(), PolicyEditorConstants.SUBJECT_CATEGORY_URI, subjectId, subjectDataType); -// Element matchElement= createMatchElement(matchElementDTO, doc); -// if(matchElement != null){ -// subjectElement.appendChild(matchElement); -// } -// subjectsElement.appendChild(subjectElement); -// } else if(EntitlementPolicyConstants.AT_LEAST_ONE_MATCH.equals(functionOnSubjects)){ -// for(String subject : subjects){ -// subject = subject.trim(); -// Element subjectEle = doc.createElement(PolicyEditorConstants.ALL_OF_ELEMENT); -// MatchElementDTO matchElementDTO = createMatchElementForNonBagFunctions( -// getFunctionId(EntitlementPolicyConstants.EQUAL_TO), -// subject, PolicyEditorConstants.SUBJECT_CATEGORY_URI, subjectId, subjectDataType); -// Element matchElement= createMatchElement(matchElementDTO, doc); -// if(matchElement != null){ -// subjectEle.appendChild(matchElement); -// } -// subjectsElement.appendChild(subjectEle); -// } -// } else if(EntitlementPolicyConstants.AT_LEAST_ONE_MATCH_REGEXP.equals(functionOnSubjects)){ -// for(String subject : subjects){ -// subject = subject.trim(); -// Element subjectEle = doc.createElement(PolicyEditorConstants.ALL_OF_ELEMENT); -// MatchElementDTO matchElementDTO = createMatchElementForNonBagFunctions( -// getFunctionId(EntitlementPolicyConstants.REGEXP_MATCH), -// subject, PolicyEditorConstants.SUBJECT_CATEGORY_URI, subjectId, subjectDataType); -// Element matchElement= createMatchElement(matchElementDTO, doc); -// if(matchElement != null){ -// subjectEle.appendChild(matchElement); -// } -// subjectsElement.appendChild(subjectEle); -// } -// } else if(EntitlementPolicyConstants.SET_OF.equals(functionOnSubjects)){ -// for(String subject : subjects){ -// subject = subject.trim(); -// MatchElementDTO matchElementDTO = createMatchElementForNonBagFunctions( -// getFunctionId(EntitlementPolicyConstants.EQUAL_TO), -// subject, PolicyEditorConstants.SUBJECT_CATEGORY_URI, subjectId, subjectDataType); -// Element matchElement= createMatchElement(matchElementDTO, doc); -// if(matchElement != null){ -// subjectElement.appendChild(matchElement); -// } -// } -// subjectsElement.appendChild(subjectElement); -// } else if(EntitlementPolicyConstants.MATCH_REGEXP_SET_OF.equals(functionOnSubjects)){ -// for(String subject : subjects){ -// subject = subject.trim(); -// MatchElementDTO matchElementDTO = createMatchElementForNonBagFunctions( -// getFunctionId(EntitlementPolicyConstants.REGEXP_MATCH), -// subject, PolicyEditorConstants.SUBJECT_CATEGORY_URI, subjectId, subjectDataType); -// Element matchElement= createMatchElement(matchElementDTO, doc); -// if(matchElement != null){ -// subjectElement.appendChild(matchElement); -// } -// } -// subjectsElement.appendChild(subjectElement); -// } -// } -// -// if(resourcesElement != null) { -// targetElement.appendChild(resourcesElement); -// } -// if(actionsElement != null) { -// targetElement.appendChild(actionsElement); -// } -// if(subjectsElement != null) { -// targetElement.appendChild(subjectsElement); -// } -// -// if(environmentsElement != null){ -// targetElement.appendChild(environmentsElement); -// } -// -// return targetElement; -// } -// - - /** - * Creates XML request from RequestDTO object - * - * @param requestDTO - * @return - */ - public static RequestElementDTO createRequestElementDTO(RequestDTO requestDTO) { - - RequestElementDTO requestElement = new RequestElementDTO(); - - List rowDTOs = requestDTO.getRowDTOs(); - if (rowDTOs == null || rowDTOs.size() < 1) { - return requestElement; - } - - Map dtoMap = new HashMap(); - List dtoList = new ArrayList(); - - for (RowDTO rowDTO : rowDTOs) { - String category = rowDTO.getCategory(); - String value = rowDTO.getAttributeValue(); - String attributeId = rowDTO.getAttributeId(); - if (category != null && category.trim().length() > 0 && value != null && - value.trim().length() > 0 && attributeId != null && attributeId.trim().length() > 0) { - - if (requestDTO.isMultipleRequest()) { - String[] values = value.split(EntitlementPolicyConstants.ATTRIBUTE_SEPARATOR); - for (String attributeValue : values) { - AttributesElementDTO attributesElementDTO = new AttributesElementDTO(); - attributesElementDTO.setCategory(category); - - AttributeElementDTO attributeElementDTO = new AttributeElementDTO(); - attributeElementDTO.addAttributeValue(attributeValue); - attributeElementDTO.setAttributeId(attributeId); - attributeElementDTO.setIncludeInResult(rowDTO.isNotCompleted()); - attributesElementDTO.addAttributeElementDTO(attributeElementDTO); - if (rowDTO.getAttributeDataType() != null && rowDTO. - getAttributeDataType().trim().length() > 0) { - attributeElementDTO.setDataType(rowDTO.getAttributeDataType()); - } else { - attributeElementDTO.setDataType(EntitlementPolicyConstants.STRING_DATA_TYPE); - } - dtoList.add(attributesElementDTO); - } - - } else { - AttributesElementDTO attributesElementDTO = dtoMap.get(category); - if (attributesElementDTO == null) { - attributesElementDTO = new AttributesElementDTO(); - attributesElementDTO.setCategory(category); - } - - String[] values = value.split(EntitlementPolicyConstants.ATTRIBUTE_SEPARATOR); - AttributeElementDTO attributeElementDTO = new AttributeElementDTO(); - attributeElementDTO.setAttributeValues(Arrays.asList(values)); - attributeElementDTO.setAttributeId(attributeId); - attributeElementDTO.setIncludeInResult(rowDTO.isNotCompleted()); - attributesElementDTO.addAttributeElementDTO(attributeElementDTO); - if (rowDTO.getAttributeDataType() != null && rowDTO. - getAttributeDataType().trim().length() > 0) { - attributeElementDTO.setDataType(rowDTO.getAttributeDataType()); - } else { - attributeElementDTO.setDataType(EntitlementPolicyConstants.STRING_DATA_TYPE); - } - dtoMap.put(category, attributesElementDTO); - } - } - } - - requestElement.setMultipleRequest(requestDTO.isMultipleRequest()); - requestElement.setCombinedDecision(requestDTO.isCombinedDecision()); - requestElement.setReturnPolicyIdList(requestDTO.isReturnPolicyIdList()); - if (!requestDTO.isMultipleRequest()) { - dtoList = new ArrayList(); - for (Map.Entry entry : dtoMap.entrySet()) { - dtoList.add(entry.getValue()); - } - } - requestElement.setAttributesElementDTOs(dtoList); - return requestElement; - } - - -// public static TargetElementDTO createTargetElementDTOs(String policy) -// throws EntitlementPolicyCreationException { -// -// TargetElementDTO targetElementDTO = null; -// OMElement omElement; -// try { -// omElement = AXIOMUtil.stringToOM(policy); -// } catch (XMLStreamException e) { -// throw new EntitlementPolicyCreationException("Policy can not be converted to OMElement"); -// } -// -// if (omElement != null) { -// Iterator iterator = omElement.getChildrenWithLocalName(EntitlementPolicyConstants. -// TARGET_ELEMENT); -// while(iterator.hasNext()){ -// OMElement targetElement = (OMElement)iterator.next(); -// targetElementDTO = createTargetElementDTO(targetElement, null); -// } -// } -// return targetElementDTO; -// } - - -// -// -// -// public static PolicySetDTO createPolicySetDTO(String policySet) -// throws EntitlementPolicyCreationException { -// PolicySetDTO policySetDTO = new PolicySetDTO(); -// OMElement omElement; -// try { -// omElement = AXIOMUtil.stringToOM(policySet); -// } catch (XMLStreamException e) { -// throw new EntitlementPolicyCreationException("Policy can not be converted to OMElement"); -// } -// -// if(omElement != null){ -// policySetDTO.setPolicySetId(omElement. -// getAttributeValue(new QName(EntitlementPolicyConstants.POLICY_SET_ID))); -// -// String policyCombiningAlgorithm = omElement. -// getAttributeValue(new QName(EntitlementPolicyConstants.POLICY_ALGORITHM)); -// //TODO -// -// if(policyCombiningAlgorithm.contains(PolicyEditorConstants.POLICY_ALGORITHM_IDENTIFIER_1)){ -// policySetDTO.setPolicyCombiningAlgId(policyCombiningAlgorithm. -// split(PolicyEditorConstants.POLICY_ALGORITHM_IDENTIFIER_1)[1]); -// } else { -// policySetDTO.setPolicyCombiningAlgId(policyCombiningAlgorithm. -// split(PolicyEditorConstants.POLICY_ALGORITHM_IDENTIFIER_3)[1]); -// } -// -// Iterator iterator1 = omElement.getChildrenWithLocalName(EntitlementPolicyConstants. -// DESCRIPTION_ELEMENT); -// -// if(iterator1.hasNext()){ -// OMElement descriptionElement = (OMElement) iterator1.next(); -// if(descriptionElement != null && descriptionElement.getText() != null){ -// policySetDTO.setDescription(descriptionElement.getText().trim()); -// } -// } -// -// -// Iterator iterator2 = omElement.getChildrenWithLocalName(EntitlementPolicyConstants. -// POLICY_ELEMENT); -// while(iterator2.hasNext()){ -// OMElement policyElement = (OMElement)iterator2.next(); -// if(policyElement != null){ -// policySetDTO.setPolicyIds(policyElement. -// getAttributeValue(new QName(EntitlementPolicyConstants.POLICY_ID))); -// } -// } -// -// Iterator iterator3 = omElement.getChildrenWithLocalName(EntitlementPolicyConstants. -// POLICY_SET_ELEMENT); -// while(iterator3.hasNext()){ -// OMElement policySetElement = (OMElement)iterator3.next(); -// if(policySetElement != null){ -// policySetDTO.setPolicyIds(policySetElement. -// getAttributeValue(new QName(EntitlementPolicyConstants.POLICY_SET_ID))); -// } -// } -// -// Iterator iterator4 = omElement.getChildrenWithLocalName(EntitlementPolicyConstants. -// POLICY_SET_REFERENCE); -// while(iterator4.hasNext()){ -// OMElement policySetReferenceElement = (OMElement)iterator4.next(); -// if(policySetReferenceElement != null){ -// policySetDTO.setPolicyIds(policySetReferenceElement.getText().trim()); -// } -// } -// -// Iterator iterator5 = omElement.getChildrenWithLocalName(EntitlementPolicyConstants. -// POLICY_REFERENCE); -// while(iterator5.hasNext()){ -// OMElement policyReferenceElement = (OMElement)iterator5.next(); -// if(policyReferenceElement != null){ -// policySetDTO.setPolicyIds(policyReferenceElement.getText().trim()); -// } -// } -// -// } -// -// return policySetDTO; -// } -// - -// -// public static ConditionElementDT0 createConditionElementDT0(OMElement omElement){ -// ConditionElementDT0 conditionElementDT0 = new ConditionElementDT0(); -// if(omElement != null){ -// Iterator iterator = omElement.getChildrenWithLocalName(EntitlementPolicyConstants. -// APPLY_ELEMENT); -// while(iterator.hasNext()){ -// OMElement applyElement = (OMElement)iterator.next(); -// ApplyElementDTO applyElementDTO = new ApplyElementDTO(); -// conditionElementDT0.setApplyElement(createApplyElementDTO(applyElementDTO, -// applyElement, 0, 0, "")); -// } -// } -// return conditionElementDT0; -// } -// -// public static ApplyElementDTO createApplyElementDTO(ApplyElementDTO applyElementDTO, -// OMElement omElement , int applyElementNo, -// int addApplyElementNo, String applyElementId){ -// if(applyElementDTO == null){ -// applyElementDTO = new ApplyElementDTO(); -// } -// if(omElement != null){ -// applyElementNo ++; -// -// applyElementId = applyElementId + "/" + applyElementNo; -// applyElementDTO.setApplyElementNumber(applyElementNo); -//// applyElementDTO.setAddApplyElementPageNumber(addApplyElementNo); -// applyElementDTO.setApplyElementId(applyElementId); -// applyElementDTO.setFunctionId(omElement. -// getAttributeValue(new QName(EntitlementPolicyConstants.FUNCTION_ID))); -// Iterator iterator1 = omElement.getChildrenWithLocalName(EntitlementPolicyConstants. -// APPLY_ELEMENT); -// while(iterator1.hasNext()){ -// OMElement applyElement = (OMElement)iterator1.next(); -// ApplyElementDTO elementDTO = createApplyElementDTO(null, applyElement,applyElementNo, -// addApplyElementNo, applyElementId); -// applyElementNo = elementDTO.getApplyElementNumber() + 1; -// applyElementDTO.setApplyElement(elementDTO); -// } -// -// Iterator iterator2 = omElement.getChildrenWithLocalName(EntitlementPolicyConstants. -// SUBJECT_ELEMENT + EntitlementPolicyConstants.ATTRIBUTE_DESIGNATOR); -// int attributeDesignatorElementNo = 0; -// while(iterator2.hasNext()){ -// OMElement attributeDesignatorElement = (OMElement)iterator2.next(); -// applyElementDTO.setAttributeDesignators(createAttributeDesignatorDTO( -// attributeDesignatorElement, addApplyElementNo, -// EntitlementPolicyConstants.SUBJECT_ELEMENT, attributeDesignatorElementNo, applyElementId)); -// attributeDesignatorElementNo ++; -// } -// -// Iterator iterator3 = omElement.getChildrenWithLocalName(EntitlementPolicyConstants. -// RESOURCE_ELEMENT + EntitlementPolicyConstants.ATTRIBUTE_DESIGNATOR); -// -// while(iterator3.hasNext()){ -// OMElement attributeDesignatorElement = (OMElement)iterator3.next(); -// applyElementDTO.setAttributeDesignators(createAttributeDesignatorDTO( -// attributeDesignatorElement, addApplyElementNo, -// EntitlementPolicyConstants.RESOURCE_ELEMENT, 0, applyElementId)); -// attributeDesignatorElementNo ++; -// } -// -// Iterator iterator4 = omElement.getChildrenWithLocalName(EntitlementPolicyConstants. -// ACTION_ELEMENT + EntitlementPolicyConstants.ATTRIBUTE_DESIGNATOR); -// -// while(iterator4.hasNext()){ -// OMElement attributeDesignatorElement = (OMElement)iterator4.next(); -// applyElementDTO.setAttributeDesignators(createAttributeDesignatorDTO( -// attributeDesignatorElement, addApplyElementNo, -// EntitlementPolicyConstants.ACTION_ELEMENT, 0, applyElementId)); -// attributeDesignatorElementNo ++; -// } -// -// Iterator iterator5 = omElement.getChildrenWithLocalName(EntitlementPolicyConstants. -// ENVIRONMENT_ELEMENT + EntitlementPolicyConstants.ATTRIBUTE_DESIGNATOR); -// -// while(iterator5.hasNext()){ -// OMElement attributeDesignatorElement = (OMElement)iterator5.next(); -// applyElementDTO.setAttributeDesignators(createAttributeDesignatorDTO( -// attributeDesignatorElement, addApplyElementNo, -// EntitlementPolicyConstants.ENVIRONMENT_ELEMENT, 0, applyElementId)); -// attributeDesignatorElementNo ++; -// } -// -// Iterator iterator6 = omElement.getChildrenWithLocalName(EntitlementPolicyConstants. -// ATTRIBUTE_VALUE); -// int attributeValueElementNo = 0; -// while(iterator6.hasNext()){ -// AttributeValueElementDTO attributeValueElementDTO = new AttributeValueElementDTO(); -// OMElement attributeValueElement = (OMElement)iterator6.next(); -// attributeValueElementDTO.setAttributeDataType(attributeValueElement. -// getAttributeValue(new QName(EntitlementPolicyConstants.DATA_TYPE))); -// attributeValueElementDTO.setAttributeValue(attributeValueElement.getText()); -// attributeValueElementDTO.setApplyElementNumber(addApplyElementNo); -// attributeValueElementDTO.setApplyElementId(applyElementId); -// attributeValueElementDTO.setElementId(attributeValueElementNo); -// applyElementDTO.setAttributeValueElementDTO(attributeValueElementDTO); -// attributeValueElementNo ++; -// } -// -// Iterator iterator7 = omElement.getChildrenWithLocalName(EntitlementPolicyConstants. -// FUNCTION); -// -// while(iterator7.hasNext()){ -// OMElement functionElement = (OMElement)iterator7.next(); -// applyElementDTO.setFunctionFunctionId(functionElement. -// getAttributeValue(new QName(EntitlementPolicyConstants.FUNCTION_ID))); -// } -// -// Iterator iterator8 = omElement.getChildrenWithLocalName(EntitlementPolicyConstants. -// ENVIRONMENT_ELEMENT + EntitlementPolicyConstants.ATTRIBUTE_SELECTOR); -// int attributeSelectorElementNo = 0; -// while(iterator8.hasNext()){ -// OMElement attributeSelectorElement = (OMElement)iterator8.next(); -// applyElementDTO.setAttributeSelectors(createAttributeSelectorDTO( -// attributeSelectorElement, addApplyElementNo, attributeSelectorElementNo, applyElementId)); -// attributeSelectorElementNo ++; -// } -// -// applyElementDTO.setAttributeValueElementCount(attributeValueElementNo); -// applyElementDTO.setAttributeDesignatorsElementCount(attributeDesignatorElementNo); -// applyElementDTO.setAttributeSelectorElementCount(attributeSelectorElementNo); -// } -// return applyElementDTO; -// } -// -// public static TargetElementDTO createTargetElementDTO(OMElement omElement, String ruleId){ -// -// TargetElementDTO targetElementDTO = new TargetElementDTO(); -// List subElementDTOs = new ArrayList(); -// int subElementId = 0; -// -// if(omElement != null){ -// if(omElement.getChildrenWithLocalName(EntitlementPolicyConstants.RESOURCE_ELEMENT + "s"). -// hasNext()){ -// OMElement element = (OMElement) omElement.getChildrenWithLocalName( -// EntitlementPolicyConstants.RESOURCE_ELEMENT + "s").next(); -// Iterator iterator1 = element.getChildrenWithLocalName(EntitlementPolicyConstants. -// RESOURCE_ELEMENT); -// while(iterator1.hasNext()){ -// OMElement resourceElement = (OMElement)iterator1.next(); -// subElementDTOs.add(createSubElementDTO(resourceElement, ruleId, -// EntitlementPolicyConstants.RESOURCE_ELEMENT, subElementId)); -// subElementId ++; -// } -// } -// -// if(omElement.getChildrenWithLocalName(EntitlementPolicyConstants.SUBJECT_ELEMENT + "s"). -// hasNext()){ -// OMElement element = (OMElement) omElement.getChildrenWithLocalName( -// EntitlementPolicyConstants.SUBJECT_ELEMENT + "s").next(); -// Iterator iterator2 = element.getChildrenWithLocalName(EntitlementPolicyConstants. -// SUBJECT_ELEMENT); -// while(iterator2.hasNext()){ -// OMElement resourceElement = (OMElement)iterator2.next(); -// subElementDTOs.add(createSubElementDTO(resourceElement,ruleId, -// EntitlementPolicyConstants.SUBJECT_ELEMENT, subElementId)); -// subElementId ++; -// } -// } -// -// if(omElement.getChildrenWithLocalName(EntitlementPolicyConstants.ACTION_ELEMENT + "s"). -// hasNext()){ -// OMElement element = (OMElement) omElement.getChildrenWithLocalName( -// EntitlementPolicyConstants.ACTION_ELEMENT + "s").next(); -// Iterator iterator3 = element.getChildrenWithLocalName(EntitlementPolicyConstants. -// ACTION_ELEMENT); -// while(iterator3.hasNext()){ -// OMElement resourceElement = (OMElement)iterator3.next(); -// subElementDTOs.add(createSubElementDTO(resourceElement,ruleId, -// EntitlementPolicyConstants.ACTION_ELEMENT, subElementId)); -// subElementId ++; -// } -// } -// -// if(omElement.getChildrenWithLocalName(EntitlementPolicyConstants.SUBJECT_ELEMENT + "s"). -// hasNext()){ -// OMElement element = (OMElement) omElement.getChildrenWithLocalName( -// EntitlementPolicyConstants.SUBJECT_ELEMENT + "s").next(); -// Iterator iterator4 = element.getChildrenWithLocalName(EntitlementPolicyConstants. -// ENVIRONMENT_ELEMENT); -// while(iterator4.hasNext()){ -// OMElement resourceElement = (OMElement)iterator4.next(); -// subElementDTOs.add(createSubElementDTO(resourceElement,ruleId, -// EntitlementPolicyConstants.ENVIRONMENT_ELEMENT, subElementId)); -// subElementId ++; -// } -// } -// } -// -// targetElementDTO.setSubElementDTOs(subElementDTOs); -// targetElementDTO.setSubElementCount(subElementId); -// -// return targetElementDTO; -// } -// -// public static SubElementDTO createSubElementDTO(OMElement omElement, String ruleId, -// String subElementName, int subElementId){ -// -// SubElementDTO subElementDTO = new SubElementDTO(); -// subElementDTO.setElementName(subElementName); -// subElementDTO.setElementId(subElementId); -// subElementDTO.setRuleId(ruleId); -// int matchElementId = 0; -// if(omElement != null){ -// Iterator iterator1 = omElement.getChildrenWithLocalName(subElementName + -// EntitlementPolicyConstants.MATCH_ELEMENT); -// -// while(iterator1.hasNext()){ -// MatchElementDTO matchElementDTO = new MatchElementDTO(); -// OMElement matchElement = (OMElement)iterator1.next(); -// matchElementDTO.setMatchElementName(subElementName); -// matchElementDTO.setElementId(matchElementId); -// matchElementDTO.setRuleElementName(ruleId); -// matchElementDTO.setMatchId(matchElement. -// getAttributeValue(new QName(EntitlementPolicyConstants.MATCH_ID))); -// -// Iterator iterator2 = matchElement.getChildrenWithLocalName(subElementName + -// EntitlementPolicyConstants.ATTRIBUTE_DESIGNATOR); -// -// while(iterator2.hasNext()){ -// OMElement attributeDesignatorElement = (OMElement)iterator2.next(); -// matchElementDTO.setAttributeDesignatorDTO(createAttributeDesignatorDTO( -// attributeDesignatorElement, 0, subElementName, 0, "")); -// } -// -// Iterator iterator3 = matchElement.getChildrenWithLocalName(EntitlementPolicyConstants. -// ATTRIBUTE_VALUE); -// -// while(iterator3.hasNext()){ -// AttributeValueElementDTO attributeValueElementDTO = new AttributeValueElementDTO(); -// OMElement attributeValueElement = (OMElement)iterator3.next(); -// attributeValueElementDTO.setAttributeDataType(attributeValueElement. -// getAttributeValue(new QName(EntitlementPolicyConstants.DATA_TYPE))); -// attributeValueElementDTO.setAttributeValue(attributeValueElement.getText()); -// matchElementDTO.setAttributeValueElementDTO(attributeValueElementDTO); -// } -// -// Iterator iterator4 = matchElement.getChildrenWithLocalName(subElementName + -// EntitlementPolicyConstants.ATTRIBUTE_SELECTOR); -// while(iterator4.hasNext()){ -// OMElement attributeSelectorElement = (OMElement)iterator4.next(); -// matchElementDTO.setAttributeSelectorDTO(createAttributeSelectorDTO( -// attributeSelectorElement, 0, 0, "")); -// } -// matchElementId ++; -// subElementDTO.setMatchElementDTOs(matchElementDTO); -// } -// } -// subElementDTO.setMatchElementCount(matchElementId); -// -// return subElementDTO; -// } -// -// /** -// * This method creates the AttributeDesignatorDTO object using matchElement -// * @param omElement attributeDesignator OMElement -// * @param applyElementNo if attributeDesignator element is embed in a apply element, its number -// * @param elementName attributeSelectorElement number to uniquely identification -// * @param matchElementId match element id to identity the element -// * @param applyElementId apply element id to identity the element -// * @return AttributeDesignatorDTO object -// */ -// public static AttributeDesignatorDTO createAttributeDesignatorDTO(OMElement omElement, -// int applyElementNo, -// String elementName, -// int matchElementId, -// String applyElementId){ -// AttributeDesignatorDTO attributeDesignatorDTO = new AttributeDesignatorDTO(); -// -// if(omElement != null){ -// attributeDesignatorDTO.setAttributeId(omElement. -// getAttributeValue(new QName(EntitlementPolicyConstants.ATTRIBUTE_ID))); -// attributeDesignatorDTO.setDataType(omElement. -// getAttributeValue(new QName(EntitlementPolicyConstants.DATA_TYPE))); -// attributeDesignatorDTO.setIssuer(omElement. -// getAttributeValue(new QName(EntitlementPolicyConstants.ISSUER))); -// attributeDesignatorDTO.setMustBePresent(omElement. -// getAttributeValue(new QName(EntitlementPolicyConstants.MUST_BE_PRESENT))); -// attributeDesignatorDTO.setApplyElementNumber(applyElementNo); -// attributeDesignatorDTO.setElementName(elementName); -// attributeDesignatorDTO.setElementId(matchElementId); -// attributeDesignatorDTO.setApplyElementId(applyElementId); -// } -// return attributeDesignatorDTO; -// } -// -// /** -// * This method creates the AttributeSelectorDTO object using matchElement -// * @param omElement attributeSelector OMElement -// * @param applyElementNo if attributeSelector element is embed in a apply element, its number -// * @param attributeSelectorElementNo attributeSelectorElement number to uniquely identification -// * @param applyElementId apply element id to identity the element -// * @return AttributeSelectorDTO object -// */ -// public static AttributeSelectorDTO createAttributeSelectorDTO(OMElement omElement, -// int applyElementNo, -// int attributeSelectorElementNo, -// String applyElementId){ -// AttributeSelectorDTO attributeSelectorDTO = new AttributeSelectorDTO(); -// -// if(omElement != null){ -// attributeSelectorDTO.setAttributeSelectorDataType(omElement. -// getAttributeValue(new QName(EntitlementPolicyConstants.DATA_TYPE))); -// attributeSelectorDTO.setAttributeSelectorRequestContextPath(omElement. -// getAttributeValue(new QName(EntitlementPolicyConstants.REQUEST_CONTEXT_PATH))); -// attributeSelectorDTO.setAttributeSelectorMustBePresent(omElement. -// getAttributeValue(new QName(EntitlementPolicyConstants.MUST_BE_PRESENT))); -// attributeSelectorDTO.setApplyElementNumber(applyElementNo); -// attributeSelectorDTO.setElementNumber(attributeSelectorElementNo); -// attributeSelectorDTO.setApplyElementId(applyElementId); -// } -// return attributeSelectorDTO; -// } -// -// /** -// * -// * @param applyElementDTO -// * @param attributeValueElementNumber -// * @return -// */ -// public static int getAttributeValueElementCount(ApplyElementDTO applyElementDTO, -// int attributeValueElementNumber){ -// attributeValueElementNumber = applyElementDTO.getAttributeValueElementCount(); -// List applyElementDTOs = applyElementDTO.getApplyElements(); -// for(ApplyElementDTO elementDTO : applyElementDTOs){ -// attributeValueElementNumber = attributeValueElementNumber + -// getAttributeValueElementCount(elementDTO, attributeValueElementNumber); -// } -// return attributeValueElementNumber; -// } -// -// public static int getAttributeDesignatorElementCount(ApplyElementDTO applyElementDTO, -// int attributeDesignatorElementNumber){ -// attributeDesignatorElementNumber = attributeDesignatorElementNumber + applyElementDTO. -// getAttributeDesignatorsElementCount(); -// List applyElementDTOs = applyElementDTO.getApplyElements(); -// for(ApplyElementDTO elementDTO : applyElementDTOs){ -// attributeDesignatorElementNumber = attributeDesignatorElementNumber + -// getAttributeDesignatorElementCount(elementDTO, attributeDesignatorElementNumber); -// } -// return attributeDesignatorElementNumber; -// } -// -// public static int getAttributeSelectorElementCount(ApplyElementDTO applyElementDTO, -// int attributeSelectorElementNumber){ -// attributeSelectorElementNumber = attributeSelectorElementNumber + applyElementDTO. -// getAttributeSelectorElementCount(); -// List applyElementDTOs = applyElementDTO.getApplyElements(); -// for(ApplyElementDTO elementDTO : applyElementDTOs){ -// attributeSelectorElementNumber = attributeSelectorElementNumber + -// getAttributeSelectorElementCount(elementDTO, attributeSelectorElementNumber); -// } -// return attributeSelectorElementNumber; -// } -// -// /** -// * This method creates policy set element -// * @param policySetDTO PolicySetDTO -// * @param doc Document -// * @return DOM Element of Policy Set -// * @throws EntitlementPolicyCreationException throw exception -// */ -// public static Element createPolicySetElement(PolicySetDTO policySetDTO, Document doc) -// throws EntitlementPolicyCreationException { -// -// Element policySetElement = doc.createElement(EntitlementPolicyConstants.POLICY_SET_ELEMENT); -// Element targetElement = null; -// policySetElement.setAttribute("xmlns", EntitlementPolicyConstants.XACML3_POLICY_NAMESPACE); -// -// if(policySetDTO.getPolicySetId() != null && policySetDTO.getPolicySetId().trim().length() > 0) { -// policySetElement.setAttribute(EntitlementPolicyConstants.POLICY_SET_ID, policySetDTO. -// getPolicySetId()); -// } -// -// String combiningAlgId = policySetDTO.getPolicyCombiningAlgId(); -// if(combiningAlgId != null && combiningAlgId.trim().length() > 0) { -// -// if(PolicyEditorConstants.CombiningAlog.ONLY_ONE_APPLICABLE_ID.equals(combiningAlgId) || -// PolicyEditorConstants.CombiningAlog.FIRST_APPLICABLE_ID.equals(combiningAlgId)){ -// policySetElement.setAttribute(EntitlementPolicyConstants.POLICY_ALGORITHM, -// PolicyEditorConstants.POLICY_ALGORITHM_IDENTIFIER_1 + combiningAlgId); -// } else { -// policySetElement.setAttribute(EntitlementPolicyConstants.POLICY_ALGORITHM, -// PolicyEditorConstants.POLICY_ALGORITHM_IDENTIFIER_3 + combiningAlgId); -// } -// } -// -// if(policySetDTO.getVersion() != null && policySetDTO.getVersion().trim().length() > 0){ -// policySetElement.setAttribute(EntitlementPolicyConstants.POLICY_VERSION, -// policySetDTO.getVersion()); -// } else { -// // policy version is handled by wso2 registry. therefore we can ignore it, although it -// // is a required attribute -// policySetElement.setAttribute(EntitlementPolicyConstants.POLICY_VERSION, "1.0"); -// } -// -// -// Element descriptionElement = doc.createElement(EntitlementPolicyConstants. -// DESCRIPTION_ELEMENT); -// if(policySetDTO.getDescription() != null && policySetDTO. -// getDescription().trim().length() > 0) { -// descriptionElement.setTextContent(policySetDTO.getDescription()); -// policySetElement.appendChild(descriptionElement); -// } else { -// String description = "This is " + policySetDTO.getPolicySetId() + " policy set"; -// descriptionElement.setTextContent(description); -// policySetElement.appendChild(descriptionElement); -// } -// -//// if(policySetDTO.getTargetElementDTO() != null && // TODO -//// policySetDTO.getTargetElementDTO().getSubElementDTOs() != null){ -//// if(policySetDTO.getTargetElementDTO().getSubElementDTOs().size() > 0){ -//// targetElement = PolicyEditorUtil.createTargetElement(policySetDTO.getTargetElementDTO(). -//// getSubElementDTOs(), doc); -//// } -//// } else if(policySetDTO.getBasicTargetDTO() != null){ -//// targetElement = createBasicTargetElementDTO(policySetDTO.getBasicTargetDTO(), doc); -//// } -// -// if(targetElement != null){ -// policySetElement.appendChild(targetElement); -// } else { -// targetElement = doc.createElement(EntitlementPolicyConstants.TARGET_ELEMENT); -// policySetElement.appendChild(targetElement); -// } -// -// if(policySetDTO.getPolicyIdReferences() != null && policySetDTO.getPolicyIdReferences().size() > 0){ -// for(String policeReferences : policySetDTO.getPolicyIdReferences()){ -// Element policeReferencesElement = doc. -// createElement(EntitlementPolicyConstants.POLICY_REFERENCE); -// policeReferencesElement.setTextContent(policeReferences); -// policySetElement.appendChild(policeReferencesElement); -// } -// } -// -// if(policySetDTO.getPolicySetIdReferences() != null && policySetDTO.getPolicySetIdReferences().size() > 0){ -// for(String policeSetReferences : policySetDTO.getPolicySetIdReferences()){ -// Element policeSetReferencesElement = doc. -// createElement(EntitlementPolicyConstants.POLICY_SET_REFERENCE); -// policeSetReferencesElement.setTextContent(policeSetReferences); -// policySetElement.appendChild(policeSetReferencesElement); -// } -// } -// return policySetElement; -// } -// -// /** -// * Convert XACML policy Document element to a String object -// * @param doc Document element -// * @return String XACML policy -// * @throws EntitlementPolicyCreationException throws when transform fails -// */ -// public static String getStringFromDocument(Document doc) throws EntitlementPolicyCreationException { -// try { -// -// DOMSource domSource = new DOMSource(doc); -// StringWriter writer = new StringWriter(); -// StreamResult result = new StreamResult(writer); -// TransformerFactory transformerFactory = TransformerFactory.newInstance(); -// Transformer transformer = transformerFactory.newTransformer(); -// transformer.transform(domSource, result); -// return writer.toString().substring(writer.toString().indexOf('>') + 1); -// -// } catch(TransformerException e){ -// throw new EntitlementPolicyCreationException("While transforming policy element to String", e); -// } -// } -// -// /** -// * Select relavent function ID for given function name -// * @param functionName function name as String argument -// * @return returns function ID -// */ -// private static String getFunctionId(String functionName){ -// -// String functionId; -// -// if(functionName.equals(EntitlementPolicyConstants.REGEXP_MATCH)){ -// functionId = EntitlementPolicyConstants.FUNCTION_REGEXP; -// } else if(functionName.equals(EntitlementPolicyConstants.IS_IN)){ -// functionId = EntitlementPolicyConstants.FUNCTION_IS_IN; -// } else if(functionName.equals(EntitlementPolicyConstants.SET_OF)){ -// functionId = EntitlementPolicyConstants.FUNCTION_SET_EQUAL; -// } else if(functionName.equals(EntitlementPolicyConstants.SUBSET_OF)){ -// functionId = EntitlementPolicyConstants.FUNCTION_SUBSET; -// } else if(functionName.equals(EntitlementPolicyConstants.AT_LEAST)){ -// functionId = EntitlementPolicyConstants.FUNCTION_AT_LEAST; -// } else { -// functionId = EntitlementPolicyConstants.FUNCTION_EQUAL; -// } -// -// return functionId; -// } -// -// -//// /** -//// * create policy meta data that helps to edit the policy using basic editor -//// * @param order of the rule element are decided by this -//// * @return String Array to dent to back end -//// */ -//// public static String[] generateBasicPolicyEditorData(TargetDTO basicTargetDTO, -//// List ruleDTOs, -//// String ruleElementOrder){ -//// -//// List policyMetaDataList = new ArrayList(); -//// -//// if(basicTargetDTO != null){ -//// List rowDTOs = basicTargetDTO.getRowDTOList(); -//// for(RowDTO rowDTO : rowDTOs){ -//// createMetaDataFromRowDTO("target", rowDTO, policyMetaDataList); -//// } -//// } -//// -//// if(ruleDTOs != null && ruleDTOs.size() > 0){ -//// if(ruleElementOrder != null && ruleElementOrder.trim().length() > 0){ -//// String[] ruleIds = ruleElementOrder. -//// split(EntitlementPolicyConstants.ATTRIBUTE_SEPARATOR); -//// for(String ruleId : ruleIds){ -//// for(RuleDTO ruleDTO : ruleDTOs) { -//// if(ruleId.trim().equals(ruleDTO.getRuleId())){ -//// List rowDTOs = ruleDTO.getRowDTOList(); -//// if(rowDTOs != null && rowDTOs.size() > 0){ -//// for(RowDTO rowDTO : rowDTOs){ -//// createMetaDataFromRowDTO("rule" + ruleId, rowDTO, -//// policyMetaDataList); -//// } -//// } -//// -//// if(ruleDTO.getTargetDTO() != null && -//// ruleDTO.getTargetDTO().getRowDTOList() != null){ -//// for(RowDTO rowDTO : ruleDTO.getTargetDTO().getRowDTOList()){ -//// createMetaDataFromRowDTO("ruleTarget" + ruleId, rowDTO, -//// policyMetaDataList); -//// } -//// } -//// } -//// } -//// } -//// } else { -//// for(RuleDTO ruleDTO : ruleDTOs) { -//// List rowDTOs = ruleDTO.getRowDTOList(); -//// if(rowDTOs != null && rowDTOs.size() > 0){ -//// for(RowDTO rowDTO : rowDTOs){ -//// createMetaDataFromRowDTO("rule" + ruleDTO.getRuleId(), rowDTO, -//// policyMetaDataList); -//// } -//// } -//// -//// if(ruleDTO.getTargetDTO() != null && -//// ruleDTO.getTargetDTO().getRowDTOList() != null){ -//// for(RowDTO rowDTO : ruleDTO.getTargetDTO().getRowDTOList()){ -//// createMetaDataFromRowDTO("ruleTarget" + ruleDTO.getRuleId(), rowDTO, -//// policyMetaDataList); -//// } -//// } -//// } -//// } -//// } -//// -//// return policyMetaDataList.toArray(new String[policyMetaDataList.size()]); -//// } -// -// -// private static void createMetaDataFromRowDTO(String prefix, RowDTO rowDTO, List metaDataList){ -// -// if(metaDataList != null){ -// metaDataList.add(prefix + "|" + rowDTO.getCategory()); -// metaDataList.add(prefix + "|" + rowDTO.getPreFunction()); -// metaDataList.add(prefix + "|" + rowDTO.getFunction()); -// metaDataList.add(prefix + "|" + rowDTO.getAttributeValue()); -// metaDataList.add(prefix + "|" + rowDTO.getAttributeId()); -// metaDataList.add(prefix + "|" + rowDTO.getAttributeDataType()); -// metaDataList.add(prefix + "|" + rowDTO.getCombineFunction()); -// } -// } - -} \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/util/PolicyEditorUtil.java b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/util/PolicyEditorUtil.java deleted file mode 100644 index 5234a1cb0fb7..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/java/org/wso2/carbon/identity/entitlement/ui/util/PolicyEditorUtil.java +++ /dev/null @@ -1,3025 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.ui.util; - -import org.apache.axiom.om.OMElement; -import org.apache.axiom.om.util.AXIOMUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.wso2.balana.utils.Constants.PolicyConstants; -import org.wso2.balana.utils.exception.PolicyBuilderException; -import org.wso2.balana.utils.policy.PolicyBuilder; -import org.wso2.balana.utils.policy.dto.AllOfElementDTO; -import org.wso2.balana.utils.policy.dto.AnyOfElementDTO; -import org.wso2.balana.utils.policy.dto.ApplyElementDTO; -import org.wso2.balana.utils.policy.dto.AttributeAssignmentElementDTO; -import org.wso2.balana.utils.policy.dto.AttributeDesignatorDTO; -import org.wso2.balana.utils.policy.dto.AttributeSelectorDTO; -import org.wso2.balana.utils.policy.dto.AttributeValueElementDTO; -import org.wso2.balana.utils.policy.dto.BasicPolicyDTO; -import org.wso2.balana.utils.policy.dto.BasicRuleDTO; -import org.wso2.balana.utils.policy.dto.BasicTargetDTO; -import org.wso2.balana.utils.policy.dto.ConditionElementDT0; -import org.wso2.balana.utils.policy.dto.MatchElementDTO; -import org.wso2.balana.utils.policy.dto.ObligationElementDTO; -import org.wso2.balana.utils.policy.dto.PolicyElementDTO; -import org.wso2.balana.utils.policy.dto.RuleElementDTO; -import org.wso2.balana.utils.policy.dto.TargetElementDTO; -import org.wso2.carbon.identity.entitlement.common.EntitlementConstants; -import org.wso2.carbon.identity.entitlement.common.PolicyEditorEngine; -import org.wso2.carbon.identity.entitlement.common.PolicyEditorException; -import org.wso2.carbon.identity.entitlement.common.dto.PolicyEditorDataHolder; -import org.wso2.carbon.identity.entitlement.ui.EntitlementPolicyConstants; -import org.wso2.carbon.identity.entitlement.ui.EntitlementPolicyCreationException; -import org.wso2.carbon.identity.entitlement.ui.PolicyEditorConstants; -import org.wso2.carbon.identity.entitlement.ui.dto.ExtendAttributeDTO; -import org.wso2.carbon.identity.entitlement.ui.dto.ObligationDTO; -import org.wso2.carbon.identity.entitlement.ui.dto.PolicyDTO; -import org.wso2.carbon.identity.entitlement.ui.dto.PolicyRefIdDTO; -import org.wso2.carbon.identity.entitlement.ui.dto.PolicySetDTO; -import org.wso2.carbon.identity.entitlement.ui.dto.RowDTO; -import org.wso2.carbon.identity.entitlement.ui.dto.RuleDTO; -import org.wso2.carbon.identity.entitlement.ui.dto.SimplePolicyEditorDTO; -import org.wso2.carbon.identity.entitlement.ui.dto.SimplePolicyEditorElementDTO; -import org.wso2.carbon.identity.entitlement.ui.dto.TargetDTO; - -import javax.xml.namespace.QName; -import javax.xml.stream.XMLStreamException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -/** - * Util class that helps to create the XACML policy which is defined by the XACML basic policy editor - */ - -/** - * @deprecated As this moved to org.wso2.carbon.identity.entitlement.common - */ -@Deprecated -public class PolicyEditorUtil { - - private static Log log = LogFactory.getLog(PolicyEditorUtil.class); - - /** - * map of apply element w.r.t identifier - */ - private static Map applyElementMap = new HashMap(); - - /** - * Create XACML policy with the simplest input attributes - * - * @param policyEditorDTO - * @return - * @throws PolicyEditorException - */ - public static String createSOAPolicy(SimplePolicyEditorDTO policyEditorDTO) throws PolicyEditorException { - - BasicPolicyDTO basicPolicyDTO = new BasicPolicyDTO(); - BasicTargetDTO basicTargetDTO = null; - List ruleElementDTOs = new ArrayList(); - - PolicyEditorDataHolder holder = PolicyEditorEngine.getInstance(). - getPolicyEditorData(EntitlementConstants.PolicyEditor.RBAC); - - //create policy element - basicPolicyDTO.setPolicyId(policyEditorDTO.getPolicyId()); - // setting rule combining algorithm - basicPolicyDTO.setRuleAlgorithm(PolicyConstants.RuleCombiningAlog.FIRST_APPLICABLE_ID); - basicPolicyDTO.setDescription(policyEditorDTO.getDescription()); - - if (PolicyEditorConstants.SOA_CATEGORY_USER.equals(policyEditorDTO.getAppliedCategory())) { - - if (policyEditorDTO.getUserAttributeValue() != null && - !PolicyEditorConstants.FunctionIdentifier.ANY. - equals(policyEditorDTO.getUserAttributeValue().trim())) { - - basicTargetDTO = new BasicTargetDTO(); - String selectedDataType = null; - - if (policyEditorDTO.getUserAttributeId() == null) { - basicTargetDTO.setSubjectId(PolicyEditorConstants.SUBJECT_ID_DEFAULT); - } else { - basicTargetDTO.setSubjectId(holder.getAttributeIdUri(policyEditorDTO.getUserAttributeId())); - if ((selectedDataType = holder.getDataTypeUriForAttribute(policyEditorDTO.getUserAttributeId())) != null) { - basicTargetDTO.setSubjectDataType(selectedDataType); - } - } - - if (basicTargetDTO.getSubjectDataType() == null) { - basicTargetDTO.setSubjectDataType(PolicyConstants.DataType.STRING); - } - - String function = findFunction(policyEditorDTO.getUserAttributeValue(), - basicTargetDTO.getSubjectDataType()); - String value = findAttributeValue(policyEditorDTO.getUserAttributeValue()); - basicTargetDTO.setSubjectList(value); - basicTargetDTO.setFunctionOnSubjects(function); - } - - List elementDTOs = policyEditorDTO.getSimplePolicyEditorElementDTOs(); - - if (elementDTOs != null) { - int ruleNo = 1; - for (SimplePolicyEditorElementDTO dto : elementDTOs) { - BasicRuleDTO ruleElementDTO = new BasicRuleDTO(); - - if (dto.getResourceValue() != null && dto.getResourceValue().trim().length() > 0 && - !PolicyEditorConstants.FunctionIdentifier.ANY.equals(dto.getResourceValue().trim())) { - addResourceElement(ruleElementDTO, dto); - } - - if (dto.getActionValue() != null && dto.getActionValue().trim().length() > 0 && - !PolicyEditorConstants.FunctionIdentifier.ANY.equals(dto.getActionValue().trim())) { - addActionElement(ruleElementDTO, dto); - } - - if (dto.getEnvironmentValue() != null && dto.getEnvironmentValue().trim().length() > 0 && - !PolicyEditorConstants.FunctionIdentifier.ANY.equals(dto.getEnvironmentValue().trim())) { - addEnvironmentElement(ruleElementDTO, dto); - } - - ruleElementDTO.setRuleEffect(PolicyEditorConstants.RULE_EFFECT_PERMIT); - ruleElementDTO.setRuleId("Rule-" + ruleNo); - ruleElementDTOs.add(ruleElementDTO); - ruleNo++; - } - - BasicRuleDTO ruleElementDTO = new BasicRuleDTO(); - ruleElementDTO.setRuleId("Deny-Rule"); - ruleElementDTO.setRuleEffect(PolicyEditorConstants.RULE_EFFECT_DENY); - ruleElementDTOs.add(ruleElementDTO); - } - } else if (PolicyEditorConstants.SOA_CATEGORY_RESOURCE.equals(policyEditorDTO.getAppliedCategory())) { - - if (policyEditorDTO.getResourceValue() != null && - !PolicyEditorConstants.FunctionIdentifier.ANY.equals(policyEditorDTO.getResourceValue().trim())) { - basicTargetDTO = new BasicTargetDTO(); - - basicTargetDTO.setResourceId(PolicyEditorConstants.RESOURCE_ID_DEFAULT); - basicTargetDTO.setResourceDataType(PolicyConstants.DataType.STRING); - - String function = findFunction(policyEditorDTO.getResourceValue(), - basicTargetDTO.getResourceDataType()); - String value = findAttributeValue(policyEditorDTO.getResourceValue()); - basicTargetDTO.setResourceList(value); - basicTargetDTO.setFunctionOnResources(function); - } - - List elementDTOs = policyEditorDTO.getSimplePolicyEditorElementDTOs(); - - if (elementDTOs != null) { - int ruleNo = 1; - for (SimplePolicyEditorElementDTO dto : elementDTOs) { - BasicRuleDTO ruleElementDTO = new BasicRuleDTO(); - - if (dto.getResourceValue() != null && dto.getResourceValue().trim().length() > 0 && - !PolicyEditorConstants.FunctionIdentifier.ANY.equals(dto.getResourceValue().trim())) { - - addResourceElement(ruleElementDTO, dto); - } - - if (dto.getUserAttributeValue() != null && dto.getUserAttributeValue().trim().length() > 0 && - !PolicyEditorConstants.FunctionIdentifier.ANY.equals(dto.getUserAttributeValue().trim())) { - - addSubjectElement(ruleElementDTO, dto); - } - - if (dto.getActionValue() != null && dto.getActionValue().trim().length() > 0 && - !PolicyEditorConstants.FunctionIdentifier.ANY.equals(dto.getActionValue().trim())) { - - addActionElement(ruleElementDTO, dto); - } - - if (dto.getEnvironmentValue() != null && dto.getEnvironmentValue().trim().length() > 0 && - !PolicyEditorConstants.FunctionIdentifier.ANY.equals(dto.getEnvironmentValue().trim())) { - - addEnvironmentElement(ruleElementDTO, dto); - } - - ruleElementDTO.setRuleEffect(PolicyEditorConstants.RULE_EFFECT_PERMIT); - ruleElementDTO.setRuleId("Rule-" + ruleNo); - ruleElementDTOs.add(ruleElementDTO); - ruleNo++; - } - - BasicRuleDTO ruleElementDTO = new BasicRuleDTO(); - ruleElementDTO.setRuleId("Deny-Rule"); - ruleElementDTO.setRuleEffect(PolicyEditorConstants.RULE_EFFECT_DENY); - ruleElementDTOs.add(ruleElementDTO); - } - } else if (PolicyEditorConstants.SOA_CATEGORY_ACTION.equals(policyEditorDTO.getAppliedCategory())) { - - if (policyEditorDTO.getActionValue() != null && - !PolicyEditorConstants.FunctionIdentifier.ANY.equals(policyEditorDTO.getActionValue().trim())) { - - basicTargetDTO = new BasicTargetDTO(); - - basicTargetDTO.setActionId(PolicyEditorConstants.ACTION_ID_DEFAULT); - basicTargetDTO.setActionDataType(PolicyConstants.DataType.STRING); - - String function = findFunction(policyEditorDTO.getActionValue(), - basicTargetDTO.getActionDataType()); - String value = findAttributeValue(policyEditorDTO.getActionValue()); - basicTargetDTO.setActionList(value); - basicTargetDTO.setFunctionOnActions(function); - - } - List elementDTOs = policyEditorDTO.getSimplePolicyEditorElementDTOs(); - - if (elementDTOs != null) { - int ruleNo = 1; - for (SimplePolicyEditorElementDTO dto : elementDTOs) { - BasicRuleDTO ruleElementDTO = new BasicRuleDTO(); - - if (dto.getResourceValue() != null && dto.getResourceValue().trim().length() > 0 && - !PolicyEditorConstants.FunctionIdentifier.ANY.equals(dto.getResourceValue().trim())) { - addResourceElement(ruleElementDTO, dto); - } - - if (dto.getUserAttributeValue() != null && dto.getUserAttributeValue().trim().length() > 0 && - !PolicyEditorConstants.FunctionIdentifier.ANY.equals(dto.getUserAttributeValue().trim())) { - addSubjectElement(ruleElementDTO, dto); - } - - if (dto.getEnvironmentValue() != null && dto.getEnvironmentValue().trim().length() > 0 && - !PolicyEditorConstants.FunctionIdentifier.ANY.equals(dto.getEnvironmentValue().trim())) { - addEnvironmentElement(ruleElementDTO, dto); - } - - ruleElementDTO.setRuleEffect(PolicyEditorConstants.RULE_EFFECT_PERMIT); - ruleElementDTO.setRuleId("Rule-" + ruleNo); - ruleElementDTOs.add(ruleElementDTO); - ruleNo++; - } - - BasicRuleDTO ruleElementDTO = new BasicRuleDTO(); - ruleElementDTO.setRuleId("Deny-Rule"); - ruleElementDTO.setRuleEffect(PolicyEditorConstants.RULE_EFFECT_DENY); - ruleElementDTOs.add(ruleElementDTO); - } - } else if (PolicyEditorConstants.SOA_CATEGORY_ENVIRONMENT.equals(policyEditorDTO.getAppliedCategory())) { - - if (policyEditorDTO.getEnvironmentValue() != null && - !PolicyEditorConstants.FunctionIdentifier.ANY.equals(policyEditorDTO.getEnvironmentValue().trim())) { - - basicTargetDTO = new BasicTargetDTO(); - - String selectedDataType = null; - - if (policyEditorDTO.getEnvironmentId() == null) { - basicTargetDTO.setEnvironmentId(PolicyEditorConstants.ENVIRONMENT_ID_DEFAULT); - } else { - basicTargetDTO.setEnvironmentId(holder.getAttributeIdUri(policyEditorDTO.getEnvironmentId())); - if ((selectedDataType = holder.getDataTypeUriForAttribute(policyEditorDTO.getEnvironmentId())) != null) { - basicTargetDTO.setEnvironmentDataType(selectedDataType); - } - } - - if (basicTargetDTO.getEnvironmentDataType() == null) { - basicTargetDTO.setEnvironmentDataType(PolicyConstants.DataType.STRING); - } - - - String function = findFunction(policyEditorDTO.getEnvironmentValue(), - basicTargetDTO.getEnvironmentDataType()); - String value = findAttributeValue(policyEditorDTO.getEnvironmentValue()); - basicTargetDTO.setEnvironmentList(value); - basicTargetDTO.setFunctionOnEnvironment(function); - - } - List elementDTOs = policyEditorDTO.getSimplePolicyEditorElementDTOs(); - - if (elementDTOs != null) { - int ruleNo = 1; - for (SimplePolicyEditorElementDTO dto : elementDTOs) { - BasicRuleDTO ruleElementDTO = new BasicRuleDTO(); - - if (dto.getResourceValue() != null && dto.getResourceValue().trim().length() > 0 && - !PolicyEditorConstants.FunctionIdentifier.ANY.equals(dto.getResourceValue().trim())) { - addResourceElement(ruleElementDTO, dto); - } - - if (dto.getUserAttributeValue() != null && dto.getUserAttributeValue().trim().length() > 0 && - !PolicyEditorConstants.FunctionIdentifier.ANY.equals(dto.getUserAttributeValue().trim())) { - addSubjectElement(ruleElementDTO, dto); - } - - if (dto.getActionValue() != null && dto.getActionValue().trim().length() > 0 && - !PolicyEditorConstants.FunctionIdentifier.ANY.equals(dto.getActionValue().trim())) { - addActionElement(ruleElementDTO, dto); - } - - ruleElementDTO.setRuleEffect(PolicyEditorConstants.RULE_EFFECT_PERMIT); - ruleElementDTO.setRuleId("Rule-" + ruleNo); - ruleElementDTOs.add(ruleElementDTO); - ruleNo++; - } - - BasicRuleDTO ruleElementDTO = new BasicRuleDTO(); - ruleElementDTO.setRuleId("Deny-Rule"); - ruleElementDTO.setRuleEffect(PolicyEditorConstants.RULE_EFFECT_DENY); - ruleElementDTOs.add(ruleElementDTO); - } - } - - if (basicTargetDTO != null) { - basicPolicyDTO.setTargetDTO(basicTargetDTO); - } - - if (ruleElementDTOs.size() > 0) { - basicPolicyDTO.setBasicRuleDTOs(ruleElementDTOs); - } - - try { - return PolicyBuilder.getInstance().build(basicPolicyDTO); - } catch (PolicyBuilderException e) { - log.error(e); - throw new PolicyEditorException("Error while building policy"); - } - } - - /** - * Helper method to create SOA policy - * - * @param ruleElementDTO - * @param editorElementDTO - */ - private static void addResourceElement(BasicRuleDTO ruleElementDTO, - SimplePolicyEditorElementDTO editorElementDTO) { - - - ruleElementDTO.setResourceId(PolicyEditorConstants.RESOURCE_ID_DEFAULT); - ruleElementDTO.setResourceDataType(PolicyConstants.DataType.STRING); - String function = findFunction(editorElementDTO.getResourceValue(), - ruleElementDTO.getResourceDataType()); - String value = findAttributeValue(editorElementDTO.getResourceValue()); - ruleElementDTO.setResourceList(value); - ruleElementDTO.setFunctionOnResources(function); - } - - /** - * Helper method to create SOA policy - * - * @param ruleElementDTO - * @param editorElementDTO - */ - private static void addSubjectElement(BasicRuleDTO ruleElementDTO, - SimplePolicyEditorElementDTO editorElementDTO) { - - String selectedDataType = null; - PolicyEditorDataHolder holder = PolicyEditorEngine.getInstance(). - getPolicyEditorData(EntitlementConstants.PolicyEditor.RBAC); - - if (editorElementDTO.getUserAttributeId() == null) { - ruleElementDTO.setSubjectId(PolicyEditorConstants.SUBJECT_ID_DEFAULT); - } else { - ruleElementDTO.setSubjectId(holder.getAttributeIdUri(editorElementDTO.getUserAttributeId())); - if ((selectedDataType = holder.getDataTypeUriForAttribute(editorElementDTO.getUserAttributeId())) != null) { - ruleElementDTO.setSubjectDataType(selectedDataType); - } - } - - if (ruleElementDTO.getSubjectDataType() == null) { - ruleElementDTO.setSubjectDataType(PolicyConstants.DataType.STRING); - } - String function = findFunction(editorElementDTO.getUserAttributeValue(), - ruleElementDTO.getSubjectDataType()); - String value = findAttributeValue(editorElementDTO.getUserAttributeValue()); - ruleElementDTO.setSubjectList(value); - ruleElementDTO.setFunctionOnSubjects(function); - } - - /** - * Helper method to create SOA policy - * - * @param ruleElementDTO - * @param editorElementDTO - */ - private static void addActionElement(BasicRuleDTO ruleElementDTO, - SimplePolicyEditorElementDTO editorElementDTO) { - - ruleElementDTO.setActionId(PolicyEditorConstants.ACTION_ID_DEFAULT); - ruleElementDTO.setActionDataType(PolicyConstants.DataType.STRING); - - String function = findFunction(editorElementDTO.getActionValue(), - ruleElementDTO.getActionDataType()); - String value = findAttributeValue(editorElementDTO.getActionValue()); - ruleElementDTO.setActionList(value); - ruleElementDTO.setFunctionOnActions(function); - } - - /** - * Helper method to create SOA policy - * - * @param ruleElementDTO - * @param editorElementDTO - */ - private static void addEnvironmentElement(BasicRuleDTO ruleElementDTO, - SimplePolicyEditorElementDTO editorElementDTO) { - - String selectedDataType = null; - PolicyEditorDataHolder holder = PolicyEditorEngine.getInstance(). - getPolicyEditorData(EntitlementConstants.PolicyEditor.RBAC); - if (editorElementDTO.getEnvironmentId() == null) { - ruleElementDTO.setEnvironmentId(PolicyEditorConstants.ENVIRONMENT_ID_DEFAULT); - } else { - ruleElementDTO.setEnvironmentId(holder.getAttributeIdUri(editorElementDTO.getEnvironmentId())); - if ((selectedDataType = holder.getDataTypeUriForAttribute(editorElementDTO.getEnvironmentId())) != null) { - ruleElementDTO.setEnvironmentDataType(selectedDataType); - } - } - - if (ruleElementDTO.getEnvironmentDataType() == null) { - ruleElementDTO.setEnvironmentDataType(PolicyConstants.DataType.STRING); - } - - String function = findFunction(editorElementDTO.getEnvironmentValue(), - ruleElementDTO.getEnvironmentDataType()); - String value = findAttributeValue(editorElementDTO.getEnvironmentValue()); - ruleElementDTO.setEnvironmentDataType(ruleElementDTO.getEnvironmentDataType()); - ruleElementDTO.setEnvironmentList(value); - ruleElementDTO.setFunctionOnEnvironment(function); - - } - - /** - * Helper method to create SOA policy - * - * @param value - * @param dataType - * @return - */ - private static String findFunction(String value, String dataType) { - - if (value == null) { - return PolicyConstants.Functions.FUNCTION_EQUAL; - } - - value = value.replace(">", ">"); - value = value.replace("<", "<"); - - // only time range finction are valid for following data types - if (PolicyConstants.DataType.DATE.equals(dataType) || - PolicyConstants.DataType.INT.equals(dataType) || - PolicyConstants.DataType.TIME.equals(dataType) || - PolicyConstants.DataType.DATE_TIME.equals(dataType) || - PolicyConstants.DataType.DOUBLE.equals(dataType) || - PolicyConstants.DataType.STRING.equals(dataType)) { - - if (value.startsWith(PolicyEditorConstants.FunctionIdentifier.EQUAL_RANGE)) { - if (value.contains(PolicyEditorConstants.FunctionIdentifier.RANGE_CLOSE)) { - return PolicyConstants.Functions.FUNCTION_GREATER_EQUAL_AND_LESS; - } else { - return PolicyConstants.Functions.FUNCTION_GREATER_EQUAL_AND_LESS_EQUAL; - } - } - - if (value.startsWith(PolicyEditorConstants.FunctionIdentifier.RANGE)) { - if (value.contains(PolicyEditorConstants.FunctionIdentifier.EQUAL_RANGE_CLOSE)) { - return PolicyConstants.Functions.FUNCTION_GREATER_AND_LESS_EQUAL; - } else { - return PolicyConstants.Functions.FUNCTION_GREATER_AND_LESS; - } - } - - if (value.startsWith(PolicyEditorConstants.FunctionIdentifier.GREATER)) { - return PolicyConstants.Functions.FUNCTION_GREATER; - } else if (value.startsWith(PolicyEditorConstants.FunctionIdentifier.GREATER_EQUAL)) { - return PolicyConstants.Functions.FUNCTION_GREATER_EQUAL; - } else if (value.startsWith(PolicyEditorConstants.FunctionIdentifier.LESS)) { - return PolicyConstants.Functions.FUNCTION_LESS; - } else if (value.startsWith(PolicyEditorConstants.FunctionIdentifier.LESS_EQUAL)) { - return PolicyConstants.Functions.FUNCTION_LESS_EQUAL; - } - } - - if (value.startsWith(PolicyEditorConstants.FunctionIdentifier.REGEX)) { - return PolicyConstants.Functions.FUNCTION_EQUAL_MATCH_REGEXP; - } - - if (value.contains(PolicyEditorConstants.FunctionIdentifier.OR)) { - return PolicyConstants.Functions.FUNCTION_AT_LEAST_ONE; - } - - if (value.contains(PolicyEditorConstants.FunctionIdentifier.AND)) { - return PolicyConstants.Functions.FUNCTION_SET_EQUALS; - } - - return PolicyConstants.Functions.FUNCTION_EQUAL; - } - - /** - * Helper method to create SOA policy - * - * @param value - * @return - */ - private static String findAttributeValue(String value) { - - if (value == null) { - return null; - } - - value = value.replace(">", ">"); - value = value.replace("<", "<"); - - if (value.startsWith(PolicyEditorConstants.FunctionIdentifier.EQUAL_RANGE) || - value.startsWith(PolicyEditorConstants.FunctionIdentifier.RANGE) || - value.startsWith(PolicyEditorConstants.FunctionIdentifier.REGEX)) { - - return value.substring(1, value.length() - 1).trim(); - - } else if (value.startsWith(PolicyEditorConstants.FunctionIdentifier.GREATER) || - value.startsWith(PolicyEditorConstants.FunctionIdentifier.LESS)) { - return value.substring(1).trim(); - } else if (value.startsWith(PolicyEditorConstants.FunctionIdentifier.GREATER_EQUAL) || - value.startsWith(PolicyEditorConstants.FunctionIdentifier.LESS_EQUAL)) { - return value.substring(2).trim(); - } - - if (value.contains(PolicyEditorConstants.FunctionIdentifier.AND)) { - value = value.replace(PolicyEditorConstants.FunctionIdentifier.AND, - PolicyEditorConstants.ATTRIBUTE_SEPARATOR); - } - - if (value.contains(PolicyEditorConstants.FunctionIdentifier.OR)) { - value = value.replace(PolicyEditorConstants.FunctionIdentifier.OR, - PolicyEditorConstants.ATTRIBUTE_SEPARATOR); - } - - return value.trim(); - } - - -// TODO for what? -// public static String createRules(List elementDTOs, Document doc) -// throws PolicyEditorException { -// -// List ruleElementDTOs = new ArrayList(); -// if(elementDTOs != null){ -// int ruleNo = 1; -// for(SimplePolicyEditorElementDTO dto : elementDTOs){ -// BasicRuleDTO ruleElementDTO = new BasicRuleDTO(); -// -// if(dto.getResourceValue() != null && dto.getResourceValue().trim().length() > 0 && -// !PolicyEditorConstants.FunctionIdentifier.ANY.equals(dto.getResourceValue().trim())){ -// ruleElementDTO.setResourceDataType(PolicyEditorConstants.DataType.STRING); -// ruleElementDTO.setResourceId(PolicyEditorConstants.RESOURCE_ID_DEFAULT); -// ruleElementDTO.setResourceList(dto.getResourceValue()); -// ruleElementDTO.setFunctionOnResources(getBasicPolicyEditorFunction(dto. -// getFunctionOnResources())); -// } -// -// if(dto.getUserAttributeValue() != null && dto.getUserAttributeValue().trim().length() > 0 && -// !PolicyEditorConstants.FunctionIdentifier.ANY.equals(dto.getUserAttributeValue().trim())){ -// ruleElementDTO.setSubjectDataType(PolicyEditorConstants.DataType.STRING); -// ruleElementDTO.setSubjectId(dto.getUserAttributeId()); -// ruleElementDTO.setSubjectList(dto.getUserAttributeValue()); -// ruleElementDTO.setFunctionOnSubjects(getBasicPolicyEditorFunction(dto. -// getFunctionOnUsers())); -// } -// -// if(dto.getActionValue() != null && dto.getActionValue().trim().length() > 0 && -// !PolicyEditorConstants.FunctionIdentifier.ANY.equals(dto.getActionValue().trim())){ -// ruleElementDTO.setActionDataType(PolicyEditorConstants.DataType.STRING); -// ruleElementDTO.setActionList(dto.getActionValue()); -// ruleElementDTO.setActionId(PolicyEditorConstants.ACTION_ID_DEFAULT); -// ruleElementDTO.setFunctionOnActions(getBasicPolicyEditorFunction(dto. -// getFunctionOnActions())); -// } -// -// if(dto.getEnvironmentValue() != null && dto.getEnvironmentValue().trim().length() > 0 && -// !PolicyEditorConstants.FunctionIdentifier.ANY.equals(dto.getEnvironmentValue().trim())){ -// ruleElementDTO.setEnvironmentId(dto.getEnvironmentId()); -// ruleElementDTO.setEnvironmentList(dto.getEnvironmentValue()); -// ruleElementDTO.setEnvironmentDataType(PolicyEditorConstants.DataType.STRING); -// ruleElementDTO.setFunctionOnEnvironment(getBasicPolicyEditorFunction(dto. -// getFunctionOnEnvironments())); -// } -// -// if(dto.getOperationType() != null && PolicyEditorConstants.PreFunctions.CAN_DO. -// equals(dto.getOperationType().trim())){ -// ruleElementDTO.setRuleEffect(PolicyEditorConstants.RULE_EFFECT_PERMIT); -// } else { -// ruleElementDTO.setRuleEffect(PolicyEditorConstants.RULE_EFFECT_DENY); -// } -// ruleElementDTO.setRuleId("Rule-" + System.currentTimeMillis() + "-" + ruleNo); -// ruleElementDTOs.add(ruleElementDTO); -// ruleNo ++; -// } -// } -// -// if(ruleElementDTOs.size() > 0){ -// for(BasicRuleDTO dto : ruleElementDTOs){ -// Element rule = null; -// try { -// rule = BasicPolicyHelper.createRuleElement(dto, doc); -// } catch (PolicyBuilderException e) { -// throw new PolicyEditorException("Error while creating rule element"); -// } -// doc.appendChild(rule); -// } -// } -// -// return PolicyCreatorUtil.getStringFromDocument(doc); -// } - - - /** - * Creates DOM representation of the XACML rule element. - * - * @param ruleDTO RuleDTO - * @return - * @throws PolicyEditorException throws - */ - public static RuleElementDTO createRuleElementDTO(RuleDTO ruleDTO) throws PolicyEditorException { - - RuleElementDTO ruleElementDTO = new RuleElementDTO(); - - ruleElementDTO.setRuleId(ruleDTO.getRuleId()); - ruleElementDTO.setRuleEffect(ruleDTO.getRuleEffect()); - TargetDTO targetDTO = ruleDTO.getTargetDTO(); - List dynamicAttributeDTOs = ruleDTO.getAttributeDTOs(); - List obligationDTOs = ruleDTO.getObligationDTOs(); - - if (dynamicAttributeDTOs != null && dynamicAttributeDTOs.size() > 0) { - Map dtoMap = new HashMap(); - //1st creating map of dynamic attribute elements - for (ExtendAttributeDTO dto : dynamicAttributeDTOs) { - dtoMap.put("${" + dto.getId().trim() + "}", dto); - } - //creating map of apply element with identifier - for (ExtendAttributeDTO dto : dynamicAttributeDTOs) { - ApplyElementDTO applyElementDTO = createApplyElement(dto, dtoMap); - if (applyElementDTO == null) { - continue; - } - applyElementMap.put("${" + dto.getId().trim() + "}", applyElementDTO); - } - } - - if (targetDTO != null && targetDTO.getRowDTOList() != null && targetDTO.getRowDTOList().size() > 0) { - TargetElementDTO targetElementDTO = createTargetElementDTO(ruleDTO.getTargetDTO()); - if (targetElementDTO != null) { - ruleElementDTO.setTargetElementDTO(targetElementDTO); - } - } - - if (ruleDTO.getRowDTOList() != null && ruleDTO.getRowDTOList().size() > 0) { - ConditionElementDT0 conditionElementDT0 = createConditionDTO(ruleDTO.getRowDTOList()); - if (conditionElementDT0 != null) { - ruleElementDTO.setConditionElementDT0(conditionElementDT0); - } - } - - if (obligationDTOs != null && obligationDTOs.size() > 0) { - for (ObligationDTO obligationDTO : obligationDTOs) { - ObligationElementDTO elementDTO = createObligationElement(obligationDTO); - if (elementDTO != null) { - ruleElementDTO.addObligationElementDTO(elementDTO); - } - } - } - - return ruleElementDTO; - } - - /** - * creates DOM representation of the XACML obligation/advice element. - * - * @param obligationDTOs List of ObligationDTO - * @return - * @throws PolicyEditorException throws - */ - public static List createObligation(List obligationDTOs) - throws PolicyEditorException { - - List obligationElementDTOs = new ArrayList(); - if (obligationDTOs != null) { - for (ObligationDTO obligationDTO : obligationDTOs) { - ObligationElementDTO elementDTO = createObligationElement(obligationDTO); - if (elementDTO != null) { - obligationElementDTOs.add(elementDTO); - } - } - } - - return obligationElementDTOs; - } - - - /** - * @param dynamicAttributeDTO - * @param map - * @return - */ - private static ApplyElementDTO createApplyElement(ExtendAttributeDTO dynamicAttributeDTO, - Map map) { - - if (PolicyEditorConstants.DYNAMIC_SELECTOR_CATEGORY.equals(dynamicAttributeDTO.getSelector())) { - - String category = dynamicAttributeDTO.getCategory(); - String attributeId = dynamicAttributeDTO.getAttributeId(); - String attributeDataType = dynamicAttributeDTO.getDataType(); - - if (category != null && category.trim().length() > 0 && attributeDataType != null && - attributeDataType.trim().length() > 0) { - AttributeDesignatorDTO designatorDTO = new AttributeDesignatorDTO(); - designatorDTO.setCategory(category); - designatorDTO.setAttributeId(attributeId); - designatorDTO.setDataType(attributeDataType); - designatorDTO.setMustBePresent("true"); - - ApplyElementDTO applyElementDTO = new ApplyElementDTO(); - applyElementDTO.setAttributeDesignators(designatorDTO); - applyElementDTO.setFunctionId(processFunction("bag", attributeDataType)); - return applyElementDTO; - } - - } else { - - String function = dynamicAttributeDTO.getFunction(); - String attributeValue = dynamicAttributeDTO.getAttributeValue(); - String attributeDataType = dynamicAttributeDTO.getDataType(); - - if (attributeValue != null && function != null) { - String[] values = attributeValue.split(","); - - if (values != null && values.length > 0) { - - if (function.contains("concatenate")) { - ApplyElementDTO applyElementDTO = new ApplyElementDTO(); - applyElementDTO.setFunctionId(processFunction(function, attributeDataType, "2.0")); - // there can be any number of inputs - for (String value : values) { - if (map.containsKey(value)) { - applyElementDTO.setApplyElement(createApplyElement(map.get(value), map)); - } else { - AttributeValueElementDTO valueElementDTO = new AttributeValueElementDTO(); - valueElementDTO.setAttributeDataType(attributeDataType); - valueElementDTO.setAttributeValue(value); - applyElementDTO.setAttributeValueElementDTO(valueElementDTO); - } - } - - return applyElementDTO; - } - } - } - } - - return null; - } - - - private static ObligationElementDTO createObligationElement(ObligationDTO obligationDTO) { - - String id = obligationDTO.getObligationId(); - String effect = obligationDTO.getEffect(); - String type = obligationDTO.getType(); - - if (id != null && id.trim().length() > 0 && effect != null) { - - ObligationElementDTO elementDTO = new ObligationElementDTO(); - elementDTO.setId(id); - elementDTO.setEffect(effect); - if ("Advice".equals(type)) { - elementDTO.setType(ObligationElementDTO.ADVICE); - } else { - elementDTO.setType(ObligationElementDTO.OBLIGATION); - } - - String attributeValue = obligationDTO.getAttributeValue(); - String attributeDataType = obligationDTO.getAttributeValueDataType(); - String resultingAttributeId = obligationDTO.getResultAttributeId(); - - if (attributeValue != null && attributeValue.trim().length() > 0 && - resultingAttributeId != null && resultingAttributeId.trim().length() > 0) { - - AttributeAssignmentElementDTO assignmentElementDTO = new - AttributeAssignmentElementDTO(); - assignmentElementDTO.setAttributeId(resultingAttributeId); - if (attributeValue.contains(",")) { - String[] values = attributeValue.split(","); - ApplyElementDTO applyElementDTO = new ApplyElementDTO(); - applyElementDTO.setFunctionId(processFunction("bag", attributeDataType)); - for (String value : values) { - if (applyElementMap.containsKey(value)) { - applyElementDTO.setApplyElement(applyElementMap.get(value)); - } else { - AttributeValueElementDTO valueElementDTO = new AttributeValueElementDTO(); - valueElementDTO.setAttributeDataType(attributeDataType); - valueElementDTO.setAttributeValue(value); - applyElementDTO.setAttributeValueElementDTO(valueElementDTO); - } - } - assignmentElementDTO.setApplyElementDTO(applyElementDTO); - } else { - if (applyElementMap.containsKey(attributeValue)) { - assignmentElementDTO.setApplyElementDTO(applyElementMap.get(attributeValue)); - } else { - AttributeValueElementDTO valueElementDTO = new AttributeValueElementDTO(); - valueElementDTO.setAttributeDataType(attributeDataType); - valueElementDTO.setAttributeValue(attributeValue); - assignmentElementDTO.setValueElementDTO(valueElementDTO); - } - } - - elementDTO.addAssignmentElementDTO(assignmentElementDTO); - } - - return elementDTO; - } - - return null; - } - - /** - * Creates ConditionElementDT0 Object that represents the XACML Condition element - * - * @param rowDTOs - * @return - * @throws PolicyEditorException - */ - public static ConditionElementDT0 createConditionDTO(List rowDTOs) throws PolicyEditorException { - - ConditionElementDT0 rootApplyDTO = new ConditionElementDT0(); - - ArrayList temp = new ArrayList(); - Set> listSet = new HashSet>(); - - for (int i = 0; i < rowDTOs.size(); i++) { - - if (i == 0) { - temp.add(rowDTOs.get(0)); - continue; - } - - String combineFunction = rowDTOs.get(i - 1).getCombineFunction(); - - if (PolicyEditorConstants.COMBINE_FUNCTION_AND.equals(combineFunction)) { - temp.add(rowDTOs.get(i)); - } - - if (PolicyEditorConstants.COMBINE_FUNCTION_OR.equals(combineFunction)) { - listSet.add(temp); - temp = new ArrayList(); - temp.add(rowDTOs.get(i)); - } - } - - listSet.add(temp); - - if (listSet.size() > 1) { - ApplyElementDTO orApplyDTO = new ApplyElementDTO(); - orApplyDTO.setFunctionId(processFunction("or")); - for (ArrayList rowDTOArrayList : listSet) { - if (rowDTOArrayList.size() > 1) { - ApplyElementDTO andApplyDTO = new ApplyElementDTO(); - andApplyDTO.setFunctionId(processFunction("and")); - for (RowDTO rowDTO : rowDTOArrayList) { - ApplyElementDTO applyElementDTO = createApplyElement(rowDTO); - andApplyDTO.setApplyElement(applyElementDTO); - } - orApplyDTO.setApplyElement(andApplyDTO); - - } else if (rowDTOArrayList.size() == 1) { - RowDTO rowDTO = rowDTOArrayList.get(0); - ApplyElementDTO andApplyDTO = createApplyElement(rowDTO); - orApplyDTO.setApplyElement(andApplyDTO); - } - } - rootApplyDTO.setApplyElement(orApplyDTO); - } else if (listSet.size() == 1) { - ArrayList rowDTOArrayList = listSet.iterator().next(); - if (rowDTOArrayList.size() > 1) { - ApplyElementDTO andApplyDTO = new ApplyElementDTO(); - andApplyDTO.setFunctionId(processFunction("and")); - for (RowDTO rowDTO : rowDTOArrayList) { - ApplyElementDTO applyElementDTO = createApplyElement(rowDTO); - andApplyDTO.setApplyElement(applyElementDTO); - } - rootApplyDTO.setApplyElement(andApplyDTO); - } else if (rowDTOArrayList.size() == 1) { - RowDTO rowDTO = rowDTOArrayList.get(0); - ApplyElementDTO andApplyDTO = createApplyElement(rowDTO); - rootApplyDTO.setApplyElement(andApplyDTO); - } - } - - return rootApplyDTO; - } - - /** - * Creates ApplyElementDTO Object that represents the XACML Apply element - * - * @param rowDTO - * @return - * @throws PolicyEditorException - */ - public static ApplyElementDTO createApplyElement(RowDTO rowDTO) throws PolicyEditorException { - - String preFunction = rowDTO.getPreFunction(); - String function = rowDTO.getFunction(); - String dataType = rowDTO.getAttributeDataType(); - String attributeValue = rowDTO.getAttributeValue(); - - if (function == null || function.trim().length() < 1) { - throw new PolicyEditorException("Can not create Apply element:" + - "Missing required function Id"); - } - - if (attributeValue == null || attributeValue.trim().length() < 1) { - throw new PolicyEditorException("Can not create Apply element:" + - "Missing required attribute value"); - } - - ApplyElementDTO applyElementDTO = null; - - AttributeDesignatorDTO designatorDTO = new AttributeDesignatorDTO(); - designatorDTO.setCategory(rowDTO.getCategory()); - designatorDTO.setAttributeId(rowDTO.getAttributeId()); - designatorDTO.setDataType(dataType); - designatorDTO.setMustBePresent("true"); - - - if (rowDTO.getFunction().contains("less") || rowDTO.getFunction().contains("greater")) { - applyElementDTO = processGreaterLessThanFunctions(function, dataType, attributeValue, - designatorDTO); - } else if (PolicyConstants.Functions.FUNCTION_EQUAL.equals(rowDTO.getFunction())) { - applyElementDTO = processEqualFunctions(function, dataType, attributeValue, designatorDTO); - } else if (PolicyConstants.Functions.FUNCTION_EQUAL_MATCH_REGEXP.equals(rowDTO.getFunction())) { - applyElementDTO = processRegexpFunctions(function, dataType, attributeValue, designatorDTO); - } else { - applyElementDTO = processBagFunction(function, dataType, attributeValue, designatorDTO); - } - - - if (PolicyConstants.PreFunctions.PRE_FUNCTION_NOT.equals(preFunction)) { - ApplyElementDTO notApplyElementDTO = new ApplyElementDTO(); - notApplyElementDTO.setFunctionId(processFunction("not")); - notApplyElementDTO.setApplyElement(applyElementDTO); - applyElementDTO = notApplyElementDTO; - } - - return applyElementDTO; - } - - /** - * Creates TargetElementDTO Object that represents the XACML Target element - * - * @param targetDTO - * @return - */ - public static TargetElementDTO createTargetElementDTO(TargetDTO targetDTO) { - - AllOfElementDTO allOfElementDTO = new AllOfElementDTO(); - AnyOfElementDTO anyOfElementDTO = new AnyOfElementDTO(); - TargetElementDTO targetElementDTO = new TargetElementDTO(); - - List rowDTOs = targetDTO.getRowDTOList(); - ArrayList tempRowDTOs = new ArrayList(); - - // pre function processing - for (RowDTO rowDTO : rowDTOs) { - if (PolicyEditorConstants.PreFunctions.PRE_FUNCTION_ARE.equals(rowDTO.getPreFunction())) { - String[] attributeValues = rowDTO.getAttributeValue().split(PolicyEditorConstants.ATTRIBUTE_SEPARATOR); - allOfElementDTO = new AllOfElementDTO(); - for (int j = 0; j < attributeValues.length; j++) { - RowDTO newDto = new RowDTO(rowDTO); - newDto.setAttributeValue(attributeValues[j]); - if (j != attributeValues.length - 1) { - newDto.setCombineFunction(PolicyEditorConstants.COMBINE_FUNCTION_AND); - } - tempRowDTOs.add(newDto); - } - } else { - tempRowDTOs.add(rowDTO); - } - } - - if (tempRowDTOs.size() > 0) { - for (int i = 0; i < tempRowDTOs.size(); i++) { - if (i == 0) { - MatchElementDTO matchElementDTO = createTargetMatch(tempRowDTOs.get(0)); - if (matchElementDTO != null) { - allOfElementDTO.addMatchElementDTO(matchElementDTO); - } - continue; - } - - String combineFunction = tempRowDTOs.get(i - 1).getCombineFunction(); - - if (PolicyEditorConstants.COMBINE_FUNCTION_AND.equals(combineFunction)) { - MatchElementDTO matchElementDTO = createTargetMatch(tempRowDTOs.get(i)); - if (matchElementDTO != null) { - allOfElementDTO.addMatchElementDTO(matchElementDTO); - } - - } - - if (PolicyEditorConstants.COMBINE_FUNCTION_OR.equals(combineFunction)) { - anyOfElementDTO.addAllOfElementDTO(allOfElementDTO); - allOfElementDTO = new AllOfElementDTO(); - MatchElementDTO matchElementDTO = createTargetMatch(tempRowDTOs.get(i)); - if (matchElementDTO != null) { - allOfElementDTO.addMatchElementDTO(matchElementDTO); - } - } - } - anyOfElementDTO.addAllOfElementDTO(allOfElementDTO); - targetElementDTO.addAnyOfElementDTO(anyOfElementDTO); - } - return targetElementDTO; - } - - - /** - * process Bag functions - * - * @param function - * @param dataType - * @param attributeValue - * @param designatorDTO - * @return - */ - public static ApplyElementDTO processBagFunction(String function, String dataType, - String attributeValue, AttributeDesignatorDTO designatorDTO) { - - if (PolicyConstants.Functions.FUNCTION_IS_IN.equals(function)) { - ApplyElementDTO applyElementDTO = new ApplyElementDTO(); - applyElementDTO.setFunctionId(processFunction("is-in", dataType)); - if (applyElementMap.containsKey(attributeValue)) { - applyElementDTO.setApplyElement(applyElementMap.get(attributeValue)); - } else { - AttributeValueElementDTO valueElementDTO = new AttributeValueElementDTO(); - valueElementDTO.setAttributeDataType(dataType); - valueElementDTO.setAttributeValue(attributeValue); - applyElementDTO.setAttributeValueElementDTO(valueElementDTO); - } - - applyElementDTO.setAttributeDesignators(designatorDTO); - return applyElementDTO; - - } else if (PolicyConstants.Functions.FUNCTION_AT_LEAST_ONE.equals(function) || - PolicyConstants.Functions.FUNCTION_SET_EQUALS.equals(function)) { - - ApplyElementDTO applyElementDTO = new ApplyElementDTO(); - if (PolicyConstants.Functions.FUNCTION_AT_LEAST_ONE.equals(function)) { - applyElementDTO.setFunctionId(processFunction("at-least-one-member-of", dataType)); - } else { - applyElementDTO.setFunctionId(processFunction("set-equals", dataType)); - } - - String[] values = attributeValue.split(PolicyEditorConstants.ATTRIBUTE_SEPARATOR); - - ApplyElementDTO applyBagElementDTO = new ApplyElementDTO(); - applyBagElementDTO.setFunctionId(processFunction("bag", dataType)); - for (String value : values) { - if (applyElementMap.containsKey(value)) { - applyBagElementDTO.setApplyElement(applyElementMap.get(value)); - } else { - AttributeValueElementDTO valueElementDTO = new AttributeValueElementDTO(); - valueElementDTO.setAttributeDataType(dataType); - valueElementDTO.setAttributeValue(value); - applyBagElementDTO.setAttributeValueElementDTO(valueElementDTO); - } - } - - applyElementDTO.setAttributeDesignators(designatorDTO); - applyElementDTO.setApplyElement(applyBagElementDTO); - - return applyElementDTO; - } - - return null; - } - - /** - * Process equal function - * - * @param function - * @param dataType - * @param attributeValue - * @param designatorDTO - * @return - */ - public static ApplyElementDTO processEqualFunctions(String function, String dataType, - String attributeValue, AttributeDesignatorDTO designatorDTO) { - - if (PolicyConstants.Functions.FUNCTION_EQUAL.equals(function)) { - - ApplyElementDTO applyElementDTO = new ApplyElementDTO(); - if (PolicyEditorConstants.DataType.DAY_TIME_DURATION.equals(dataType) || - PolicyEditorConstants.DataType.YEAR_MONTH_DURATION.equals(dataType)) { - applyElementDTO.setFunctionId(processFunction("equal", dataType, "3.0")); - } else { - applyElementDTO.setFunctionId(processFunction("equal", dataType)); - } - - ApplyElementDTO oneAndOnlyApplyElement = new ApplyElementDTO(); - oneAndOnlyApplyElement.setFunctionId(processFunction("one-and-only", dataType)); - oneAndOnlyApplyElement.setAttributeDesignators(designatorDTO); - - if (applyElementMap.containsKey(attributeValue)) { - applyElementDTO.setApplyElement(applyElementMap.get(attributeValue)); - } else { - AttributeValueElementDTO valueElementDTO = new AttributeValueElementDTO(); - valueElementDTO.setAttributeDataType(dataType); - valueElementDTO.setAttributeValue(attributeValue); - applyElementDTO.setAttributeValueElementDTO(valueElementDTO); - } - - applyElementDTO.setApplyElement(oneAndOnlyApplyElement); - - return applyElementDTO; - } - - return null; - } - - /** - * Process less than and greater than functions - * - * @param function - * @param dataType - * @param attributeValue - * @param designatorDTO - * @return - * @throws PolicyEditorException - */ - public static ApplyElementDTO processGreaterLessThanFunctions(String function, String dataType, - String attributeValue, AttributeDesignatorDTO designatorDTO) - throws PolicyEditorException { - - String[] values = attributeValue.split(PolicyEditorConstants.ATTRIBUTE_SEPARATOR); - - - if (PolicyConstants.Functions.FUNCTION_GREATER_EQUAL_AND_LESS_EQUAL.equals(function) || - PolicyConstants.Functions.FUNCTION_GREATER_AND_LESS_EQUAL.equals(function) || - PolicyConstants.Functions.FUNCTION_GREATER_EQUAL_AND_LESS.equals(function) || - PolicyConstants.Functions.FUNCTION_GREATER_AND_LESS.equals(function)) { - - String leftValue; - String rightValue; - - if (values.length == 2) { - leftValue = values[0].trim(); - rightValue = values[1].trim(); - } else { - throw new PolicyEditorException("Can not create Apply element:" + - "Missing required attribute values for function : " + function); - } - - ApplyElementDTO andApplyElement = new ApplyElementDTO(); - - andApplyElement.setFunctionId(processFunction("and")); - - ApplyElementDTO greaterThanApplyElement = new ApplyElementDTO(); - if (PolicyConstants.Functions.FUNCTION_GREATER_AND_LESS.equals(function) || - PolicyConstants.Functions.FUNCTION_GREATER_AND_LESS_EQUAL.equals(function)) { - greaterThanApplyElement.setFunctionId(processFunction("greater-than", dataType)); - } else { - greaterThanApplyElement.setFunctionId(processFunction("greater-than-or-equal", dataType)); - } - - - ApplyElementDTO lessThanApplyElement = new ApplyElementDTO(); - if (PolicyConstants.Functions.FUNCTION_GREATER_AND_LESS.equals(function) || - PolicyConstants.Functions.FUNCTION_GREATER_EQUAL_AND_LESS.equals(function)) { - lessThanApplyElement.setFunctionId(processFunction("less-than", dataType)); - } else { - lessThanApplyElement.setFunctionId(processFunction("less-than-or-equal", dataType)); - } - - ApplyElementDTO oneAndOnlyApplyElement = new ApplyElementDTO(); - oneAndOnlyApplyElement.setFunctionId(processFunction("one-and-only", dataType)); - oneAndOnlyApplyElement.setAttributeDesignators(designatorDTO); - - AttributeValueElementDTO leftValueElementDTO = new AttributeValueElementDTO(); - leftValueElementDTO.setAttributeDataType(dataType); - leftValueElementDTO.setAttributeValue(leftValue); - - AttributeValueElementDTO rightValueElementDTO = new AttributeValueElementDTO(); - rightValueElementDTO.setAttributeDataType(dataType); - rightValueElementDTO.setAttributeValue(rightValue); - - greaterThanApplyElement.setApplyElement(oneAndOnlyApplyElement); - greaterThanApplyElement.setAttributeValueElementDTO(leftValueElementDTO); - - lessThanApplyElement.setApplyElement(oneAndOnlyApplyElement); - lessThanApplyElement.setAttributeValueElementDTO(rightValueElementDTO); - - andApplyElement.setApplyElement(greaterThanApplyElement); - andApplyElement.setApplyElement(lessThanApplyElement); - - return andApplyElement; - - } else { - - ApplyElementDTO applyElementDTO = new ApplyElementDTO(); - - if (PolicyConstants.Functions.FUNCTION_GREATER.equals(function)) { - applyElementDTO.setFunctionId(processFunction("greater-than", dataType)); - } else if (PolicyConstants.Functions.FUNCTION_GREATER_EQUAL.equals(function)) { - applyElementDTO.setFunctionId(processFunction("greater-than-or-equal", dataType)); - } else if (PolicyConstants.Functions.FUNCTION_LESS.equals(function)) { - applyElementDTO.setFunctionId(processFunction("less-than", dataType)); - } else if (PolicyConstants.Functions.FUNCTION_LESS_EQUAL.equals(function)) { - applyElementDTO.setFunctionId(processFunction("less-than-or-equal", dataType)); - } else { - throw new PolicyEditorException("Can not create Apply element:" + - "Invalid function : " + function); - } - - ApplyElementDTO oneAndOnlyApplyElement = new ApplyElementDTO(); - oneAndOnlyApplyElement.setFunctionId(processFunction("one-and-only", dataType)); - oneAndOnlyApplyElement.setAttributeDesignators(designatorDTO); - - AttributeValueElementDTO valueElementDTO = new AttributeValueElementDTO(); - valueElementDTO.setAttributeDataType(dataType); - valueElementDTO.setAttributeValue(values[0]); - - applyElementDTO.setApplyElement(oneAndOnlyApplyElement); - applyElementDTO.setAttributeValueElementDTO(valueElementDTO); - - return applyElementDTO; - - } - } - - /** - * Process regexp-match functions. - * - * @param function Function name. - * @param dataType Data type. - * @param attributeValue Attribute Value. - * @param designatorDTO AttributeDesignator information. - * @return ApplyElementDTO. - */ - public static ApplyElementDTO processRegexpFunctions(String function, String dataType, String attributeValue, - AttributeDesignatorDTO designatorDTO) { - - if (PolicyConstants.Functions.FUNCTION_EQUAL_MATCH_REGEXP.equals(function)) { - ApplyElementDTO applyElementDTO = new ApplyElementDTO(); - applyElementDTO.setFunctionId(PolicyConstants.XACMLData.FUNCTION_ANY_OF); - if (applyElementMap.containsKey(attributeValue)) { - applyElementDTO.setApplyElement(applyElementMap.get(attributeValue)); - } else { - AttributeValueElementDTO valueElementDTO = new AttributeValueElementDTO(); - valueElementDTO.setAttributeDataType(dataType); - valueElementDTO.setAttributeValue(attributeValue); - applyElementDTO.setAttributeValueElementDTO(valueElementDTO); - } - applyElementDTO.setFunctionFunctionId( - processFunction(PolicyConstants.Functions.FUNCTION_EQUAL_MATCH_REGEXP, dataType)); - applyElementDTO.setAttributeDesignators(designatorDTO); - return applyElementDTO; - } - return null; - } - - /** - * Helper method to create full XACML function URI - * - * @param function - * @param type - * @param version - * @return - */ - private static String processFunction(String function, String type, String version) { - return "urn:oasis:names:tc:xacml:" + version + ":function:" + getDataTypePrefix(type) + - "-" + function; - } - - /** - * Helper method to create full XACML function URI - * - * @param function - * @return - */ - private static String processFunction(String function) { - return "urn:oasis:names:tc:xacml:1.0:function:" + function; - } - - /** - * Helper method to create full XACML function URI - * - * @param function - * @param type - * @return - */ - private static String processFunction(String function, String type) { - return "urn:oasis:names:tc:xacml:1.0:function:" + getDataTypePrefix(type) + "-" + function; - } -// -// /** -// * Helper method to check whether attribute value is pre-defined one -// * -// * @param value -// * @return -// */ -// private static boolean isPreDefinedValue(String value){ -// -// if(value != null && applyElementMap != null && applyElementMap.size() > 0){ -// value = value.trim(); -// if(value.startsWith("${") && value.endsWith("}")){ -// value = value.substring(value.indexOf("{") + 1, value.indexOf("}")); -// return applyElementMap.containsKey(value); -// } -// } -// -// return false; -// } -// -// /** -// * Helper method to check whether attribute value is pre-defined one -// * -// * @param value -// * @param map -// * @return -// */ -// private static boolean isPreDefinedValue(String value, Map map){ -// -// if(value != null && map != null && map.size() > 0){ -// value = value.trim(); -// if(value.startsWith("${") && value.endsWith("}")){ -// value = value.substring(value.indexOf("{") + 1, value.indexOf("}")); -// return map.containsKey(value); -// } -// } -// -// return false; -// } - - /** - * Helper method to create full XACML function URI - * - * @param dataTypeUri - * @return - */ - private static String getDataTypePrefix(String dataTypeUri) { - - if (dataTypeUri != null) { - if (dataTypeUri.contains("#")) { - return dataTypeUri.substring(dataTypeUri.indexOf("#") + 1); - } else if (dataTypeUri.contains(":")) { - String[] stringArray = dataTypeUri.split(":"); - if (stringArray != null && stringArray.length > 0) { - return stringArray[stringArray.length - 1]; - } - } - } - return dataTypeUri; - } - - /** - * Creates match element - * - * @param rowDTO - * @return - */ - public static MatchElementDTO createTargetMatch(RowDTO rowDTO) { - - - String category = rowDTO.getCategory(); - String functionId = rowDTO.getFunction(); - String attributeValue = rowDTO.getAttributeValue(); - String attributeId = rowDTO.getAttributeId(); - String dataType = rowDTO.getAttributeDataType(); - MatchElementDTO matchElementDTO; - - if (functionId != null && functionId.trim().length() > 0 && attributeValue != null && - attributeValue.trim().length() > 0 && category != null && - category.trim().length() > 0 && attributeId != null && - attributeId.trim().length() > 0 && dataType != null && - dataType.trim().length() > 0) { - - functionId = processFunction(functionId, dataType); - - matchElementDTO = new MatchElementDTO(); - - AttributeValueElementDTO attributeValueElementDTO = new AttributeValueElementDTO(); - attributeValueElementDTO.setAttributeDataType(dataType); - attributeValueElementDTO.setAttributeValue(attributeValue.trim()); - - AttributeDesignatorDTO attributeDesignatorDTO = new AttributeDesignatorDTO(); - attributeDesignatorDTO.setDataType(dataType); - attributeDesignatorDTO.setAttributeId(attributeId); - attributeDesignatorDTO.setCategory(category); - - matchElementDTO.setMatchId(functionId); - matchElementDTO.setAttributeValueElementDTO(attributeValueElementDTO); - matchElementDTO.setAttributeDesignatorDTO(attributeDesignatorDTO); - } else { - return null; // TODO - } - - return matchElementDTO; - } - - - /** - * This method creates a match element (such as subject,action,resource or environment) of the XACML policy - * - * @param matchElementDTO match element data object - * @param doc XML document - * @return match Element - * @throws PolicyEditorException if any error occurs - */ - public static Element createMatchElement(MatchElementDTO matchElementDTO, Document doc) - throws PolicyEditorException { - - Element matchElement; - - if (matchElementDTO.getMatchId() != null && matchElementDTO.getMatchId().trim().length() > 0) { - - matchElement = doc.createElement(PolicyEditorConstants.MATCH_ELEMENT); - - matchElement.setAttribute(PolicyEditorConstants.MATCH_ID, - matchElementDTO.getMatchId()); - - if (matchElementDTO.getAttributeValueElementDTO() != null) { - Element attributeValueElement = createAttributeValueElement(matchElementDTO. - getAttributeValueElementDTO(), doc); - matchElement.appendChild(attributeValueElement); - } - - if (matchElementDTO.getAttributeDesignatorDTO() != null) { - Element attributeDesignatorElement = createAttributeDesignatorElement(matchElementDTO. - getAttributeDesignatorDTO(), doc); - matchElement.appendChild(attributeDesignatorElement); - } else if (matchElementDTO.getAttributeSelectorDTO() != null) { - Element attributeSelectorElement = createAttributeSelectorElement(matchElementDTO. - getAttributeSelectorDTO(), doc); - matchElement.appendChild(attributeSelectorElement); - } - } else { - throw new PolicyEditorException("Can not create Match element:" + - " Required Attributes are missing"); - } - return matchElement; - } - - /** - * This method creates attribute value DOM element - * - * @param attributeValueElementDTO attribute value element data object - * @param doc XML document - * @return attribute value element as DOM - */ - public static Element createAttributeValueElement(AttributeValueElementDTO - attributeValueElementDTO, Document doc) { - - Element attributeValueElement = doc.createElement(EntitlementPolicyConstants.ATTRIBUTE_VALUE); - - if (attributeValueElementDTO.getAttributeValue() != null && attributeValueElementDTO. - getAttributeValue().trim().length() > 0) { - - attributeValueElement.setTextContent(attributeValueElementDTO.getAttributeValue().trim()); - - if (attributeValueElementDTO.getAttributeDataType() != null && attributeValueElementDTO. - getAttributeDataType().trim().length() > 0) { - attributeValueElement.setAttribute(EntitlementPolicyConstants.DATA_TYPE, - attributeValueElementDTO.getAttributeDataType()); - } else { - attributeValueElement.setAttribute(EntitlementPolicyConstants.DATA_TYPE, - EntitlementPolicyConstants.STRING_DATA_TYPE); - } - - } - - return attributeValueElement; - } - - /** - * This method creates attribute designator DOM element - * - * @param attributeDesignatorDTO attribute designator data object - * @param doc XML document - * @return attribute designator element as DOM - * @throws PolicyEditorException throws if missing required data - */ - public static Element createAttributeDesignatorElement(AttributeDesignatorDTO - attributeDesignatorDTO, Document doc) throws PolicyEditorException { - - Element attributeDesignatorElement; - - if (attributeDesignatorDTO != null && doc != null) { - - String category = attributeDesignatorDTO.getCategory(); - String attributeId = attributeDesignatorDTO.getAttributeId(); - String dataType = attributeDesignatorDTO.getDataType(); - String mustBe = attributeDesignatorDTO.getMustBePresent(); - - if (category != null && category.trim().length() > 0 && attributeId != null && - attributeId.trim().length() > 0 && dataType != null && dataType.trim().length() > 0 && - mustBe != null && mustBe.trim().length() > 0) { - - attributeDesignatorElement = doc. - createElement(PolicyEditorConstants.ATTRIBUTE_DESIGNATOR); - - attributeDesignatorElement.setAttribute(PolicyEditorConstants.ATTRIBUTE_ID, - attributeId); - - attributeDesignatorElement.setAttribute(PolicyEditorConstants.CATEGORY, category); - - attributeDesignatorElement.setAttribute(PolicyEditorConstants.DATA_TYPE, dataType); - - attributeDesignatorElement.setAttribute(PolicyEditorConstants.MUST_BE_PRESENT, mustBe); - - if (attributeDesignatorDTO.getIssuer() != null && attributeDesignatorDTO.getIssuer(). - trim().length() > 0) { - attributeDesignatorElement.setAttribute(EntitlementPolicyConstants.ISSUER, - attributeDesignatorDTO.getIssuer()); - } - } else { - throw new PolicyEditorException("Can not create AttributeDesignator element:" + - " Required Attributes are missing"); - } - } else { - throw new PolicyEditorException("Can not create AttributeDesignator element:" + - " A Null object is received"); - } - return attributeDesignatorElement; - } - - /** - * This method creates attribute selector DOM element - * - * @param attributeSelectorDTO attribute selector data object - * @param doc xML document - * @return attribute selector element as DOM - */ - public static Element createAttributeSelectorElement(AttributeSelectorDTO attributeSelectorDTO, - Document doc) { - - Element attributeSelectorElement = doc.createElement(EntitlementPolicyConstants. - ATTRIBUTE_SELECTOR); - - if (attributeSelectorDTO.getAttributeSelectorRequestContextPath() != null && - attributeSelectorDTO.getAttributeSelectorRequestContextPath().trim().length() > 0) { - - attributeSelectorElement.setAttribute(EntitlementPolicyConstants.REQUEST_CONTEXT_PATH, - EntitlementPolicyConstants.ATTRIBUTE_NAMESPACE + attributeSelectorDTO. - getAttributeSelectorRequestContextPath()); - - if (attributeSelectorDTO.getAttributeSelectorDataType() != null && - attributeSelectorDTO.getAttributeSelectorDataType().trim().length() > 0) { - attributeSelectorElement.setAttribute(EntitlementPolicyConstants.DATA_TYPE, - attributeSelectorDTO.getAttributeSelectorDataType()); - } else { - attributeSelectorElement.setAttribute(EntitlementPolicyConstants.DATA_TYPE, - EntitlementPolicyConstants.STRING_DATA_TYPE); - } - - if (attributeSelectorDTO.getAttributeSelectorMustBePresent() != null && - attributeSelectorDTO.getAttributeSelectorMustBePresent().trim().length() > 0) { - attributeSelectorElement.setAttribute(EntitlementPolicyConstants.MUST_BE_PRESENT, - attributeSelectorDTO.getAttributeSelectorMustBePresent()); - } - - } - - return attributeSelectorElement; - } - - /** - * Modifies the user data that are got from policy editor. If there are null values for required - * things, replace them with default values - */ - public static String[] processPolicySetData(PolicySetDTO policyDTO) { - - TargetDTO targetDTO = policyDTO.getTargetDTO(); - List obligationDTOs = policyDTO.getObligations(); - List policyRefIdDTOs = policyDTO.getPolicyRefIdDTOs(); - String policyOrder = policyDTO.getPolicyOrder(); - - - PolicyEditorDataHolder holder = PolicyEditorEngine.getInstance(). - getPolicyEditorData(EntitlementConstants.PolicyEditor.SET); - - List policyMetaDataList = new ArrayList(); - - List arrangedRefIdDTOs = new ArrayList(); - - if (policyOrder != null && policyOrder.trim().length() > 0) { - String[] ruleIds = policyOrder. - split(EntitlementPolicyConstants.ATTRIBUTE_SEPARATOR); - for (String ruleId : ruleIds) { - for (PolicyRefIdDTO dto : policyRefIdDTOs) { - if (ruleId.equals(dto.getId())) { - arrangedRefIdDTOs.add(dto); - } - } - } - policyRefIdDTOs = arrangedRefIdDTOs; - } - createMetaDataFromPolicySet("policy", policyDTO, policyMetaDataList); - String algorithm = policyDTO.getPolicyCombiningAlgId(); - if (algorithm != null && algorithm.trim().length() > 0) { - policyDTO.setPolicyCombiningAlgId(holder.getPolicyAlgorithmUri(algorithm)); - } else { - policyDTO.setPolicyCombiningAlgId(holder.getDefaultPolicyAlgorithm()); - } - - if (targetDTO != null && targetDTO.getRowDTOList() != null) { - List newRowDTOs = new ArrayList(); - for (RowDTO rowDTO : targetDTO.getRowDTOList()) { - createMetaDataFromRowDTO("target", rowDTO, policyMetaDataList); - String category = rowDTO.getCategory(); - - if (category == null) { - continue; - } - - String attributeValue = rowDTO.getAttributeValue(); - if (attributeValue == null || attributeValue.trim().length() < 1) { - continue; - } - rowDTO.setCategory(holder.getCategoryUri(category)); - - if (rowDTO.getAttributeDataType() == null || - rowDTO.getAttributeDataType().trim().length() < 1 || - rowDTO.getAttributeDataType().trim().equals("null")) { - - if (holder.getDefaultDataType() != null) { - rowDTO.setAttributeDataType(holder.getDefaultDataType()); - } else { - rowDTO.setAttributeDataType(PolicyEditorConstants.DataType.STRING); - } - } else { - if (holder.getDataTypeUri(rowDTO.getAttributeDataType()) != null) { - rowDTO.setAttributeDataType(holder.getDataTypeUri(rowDTO.getAttributeDataType())); - } - } - - String attributeId = rowDTO.getAttributeId(); - if (attributeId == null || attributeId.trim().length() < 1 || - attributeId.trim().equals("null")) { - attributeId = holder.getCategoryDefaultAttributeId(category); - } - rowDTO.setAttributeId(holder.getAttributeIdUri(attributeId)); - rowDTO.setFunction(holder.getFunctionUri(rowDTO.getFunction())); - rowDTO.setPreFunction(holder.getPreFunctionUri(rowDTO.getPreFunction())); - newRowDTOs.add(rowDTO); - } - targetDTO.setRowDTOList(newRowDTOs); - policyDTO.setTargetDTO(targetDTO); - } - - if (policyRefIdDTOs != null) { - policyDTO.setPolicyRefIdDTOs(policyRefIdDTOs); - for (PolicyRefIdDTO dto : policyRefIdDTOs) { - createMetaDataFromReference("reference", dto, policyMetaDataList); - } - } - - if (obligationDTOs != null) { - for (ObligationDTO dto : obligationDTOs) { - createMetaDataFromObligation("obligation", dto, policyMetaDataList); - if (dto.getAttributeValueDataType() == null || - dto.getAttributeValueDataType().trim().length() == 0 || - dto.getAttributeValueDataType().trim().equals("null")) { - dto.setAttributeValueDataType(PolicyEditorConstants.DataType.STRING); - } - if (dto.getResultAttributeId() == null || - dto.getResultAttributeId().trim().length() == 0 || - dto.getResultAttributeId().trim().equals("null")) { - // setting obligation id - dto.setResultAttributeId(dto.getObligationId()); - } - } - policyDTO.setObligations(obligationDTOs); - } - - return policyMetaDataList.toArray(new String[policyMetaDataList.size()]); - } - - - /** - * Modifies the user data that are got from policy editor. If there are null values for required - * things, replace them with default values - */ - public static String[] processPolicyData(PolicyDTO policyDTO) { - - TargetDTO targetDTO = policyDTO.getTargetDTO(); - List ruleDTOs = policyDTO.getRuleDTOs(); - List obligationDTOs = policyDTO.getObligationDTOs(); - String ruleElementOrder = policyDTO.getRuleOrder(); - - - PolicyEditorDataHolder holder = PolicyEditorEngine.getInstance(). - getPolicyEditorData(EntitlementConstants.PolicyEditor.STANDARD); - - List policyMetaDataList = new ArrayList(); - - List arrangedRules = new ArrayList(); - - if (ruleElementOrder != null && ruleElementOrder.trim().length() > 0) { - String[] ruleIds = ruleElementOrder. - split(EntitlementPolicyConstants.ATTRIBUTE_SEPARATOR); - for (String ruleId : ruleIds) { - for (RuleDTO ruleDTO : ruleDTOs) { - if (ruleId.equals(ruleDTO.getRuleId())) { - arrangedRules.add(ruleDTO); - } - } - } - ruleDTOs = arrangedRules; - } - createMetaDataFromPolicy("policy", policyDTO, policyMetaDataList); - String algorithm = policyDTO.getRuleAlgorithm(); - if (algorithm != null && algorithm.trim().length() > 0) { - policyDTO.setRuleAlgorithm(holder.getRuleAlgorithmUri(algorithm)); - } else { - policyDTO.setRuleAlgorithm(holder.getDefaultRuleAlgorithm()); - } - - if (targetDTO != null && targetDTO.getRowDTOList() != null) { - List newRowDTOs = new ArrayList(); - for (RowDTO rowDTO : targetDTO.getRowDTOList()) { - createMetaDataFromRowDTO("target", rowDTO, policyMetaDataList); - String category = rowDTO.getCategory(); - - if (category == null) { - continue; - } - - String attributeValue = rowDTO.getAttributeValue(); - if (attributeValue == null || attributeValue.trim().length() < 1) { - continue; - } - rowDTO.setCategory(holder.getCategoryUri(category)); - - if (rowDTO.getAttributeDataType() == null || - rowDTO.getAttributeDataType().trim().length() < 1 || - rowDTO.getAttributeDataType().trim().equals("null")) { - - if (holder.getDefaultDataType() != null) { - rowDTO.setAttributeDataType(holder.getDefaultDataType()); - } else { - rowDTO.setAttributeDataType(PolicyEditorConstants.DataType.STRING); - } - } else { - if (holder.getDataTypeUri(rowDTO.getAttributeDataType()) != null) { - rowDTO.setAttributeDataType(holder.getDataTypeUri(rowDTO.getAttributeDataType())); - } - } - - String attributeId = rowDTO.getAttributeId(); - if (attributeId == null || attributeId.trim().length() < 1 || - attributeId.trim().equals("null")) { - attributeId = holder.getCategoryDefaultAttributeId(category); - } - rowDTO.setAttributeId(holder.getAttributeIdUri(attributeId)); - rowDTO.setFunction(holder.getFunctionUri(rowDTO.getFunction())); - rowDTO.setPreFunction(holder.getPreFunctionUri(rowDTO.getPreFunction())); - newRowDTOs.add(rowDTO); - } - targetDTO.setRowDTOList(newRowDTOs); - policyDTO.setTargetDTO(targetDTO); - } - - if (ruleDTOs != null) { - for (RuleDTO ruleDTO : ruleDTOs) { - createMetaDataFromRule("rule", ruleDTO, policyMetaDataList); - List newRowDTOs = new ArrayList(); - for (RowDTO rowDTO : ruleDTO.getRowDTOList()) { - createMetaDataFromRowDTO("ruleRow" + ruleDTO.getRuleId(), rowDTO, policyMetaDataList); - String category = rowDTO.getCategory(); - - if (category == null) { - continue; - } - - String attributeValue = rowDTO.getAttributeValue(); - if (attributeValue == null || attributeValue.trim().length() < 1) { - continue; - } - rowDTO.setCategory(holder.getCategoryUri(category)); - - if (rowDTO.getAttributeDataType() == null || - rowDTO.getAttributeDataType().trim().length() < 1 || - rowDTO.getAttributeDataType().trim().equals("null")) { - - if (holder.getDefaultDataType() != null) { - rowDTO.setAttributeDataType(holder.getDefaultDataType()); - } else { - rowDTO.setAttributeDataType(PolicyEditorConstants.DataType.STRING); - } - } else { - if (holder.getDataTypeUri(rowDTO.getAttributeDataType()) != null) { - rowDTO.setAttributeDataType(holder.getDataTypeUri(rowDTO.getAttributeDataType())); - } - } - - String attributeId = rowDTO.getAttributeId(); - if (attributeId == null || attributeId.trim().length() < 1 || - attributeId.trim().equals("null")) { - attributeId = holder.getCategoryDefaultAttributeId(category); - } - rowDTO.setAttributeId(holder.getAttributeIdUri(attributeId)); - rowDTO.setFunction(holder.getFunctionUri(rowDTO.getFunction())); - rowDTO.setPreFunction(holder.getPreFunctionUri(rowDTO.getPreFunction())); - newRowDTOs.add(rowDTO); - } - - ruleDTO.setRowDTOList(newRowDTOs); - - TargetDTO ruleTargetDTO = ruleDTO.getTargetDTO(); - - if (ruleTargetDTO == null) { - continue; - } - - List newTargetRowDTOs = new ArrayList(); - - for (RowDTO rowDTO : ruleTargetDTO.getRowDTOList()) { - createMetaDataFromRowDTO("ruleTarget" + ruleDTO.getRuleId(), rowDTO, policyMetaDataList); - String category = rowDTO.getCategory(); - - if (category == null) { - continue; - } - - String attributeValue = rowDTO.getAttributeValue(); - if (attributeValue == null || attributeValue.trim().length() < 1) { - continue; - } - rowDTO.setCategory(holder.getCategoryUri(category)); - - if (rowDTO.getAttributeDataType() == null || - rowDTO.getAttributeDataType().trim().length() < 1 || - rowDTO.getAttributeDataType().trim().equals("null")) { - - if (holder.getDefaultDataType() != null) { - rowDTO.setAttributeDataType(holder.getDefaultDataType()); - } else { - rowDTO.setAttributeDataType(PolicyEditorConstants.DataType.STRING); - } - } else { - if (holder.getDataTypeUri(rowDTO.getAttributeDataType()) != null) { - rowDTO.setAttributeDataType(holder.getDataTypeUri(rowDTO.getAttributeDataType())); - } - } - - String attributeId = rowDTO.getAttributeId(); - if (attributeId == null || attributeId.trim().length() < 1 || - attributeId.trim().equals("null")) { - attributeId = holder.getCategoryDefaultAttributeId(category); - } - rowDTO.setAttributeId(holder.getAttributeIdUri(attributeId)); - rowDTO.setFunction(holder.getFunctionUri(rowDTO.getFunction())); - rowDTO.setPreFunction(holder.getPreFunctionUri(rowDTO.getPreFunction())); - newTargetRowDTOs.add(rowDTO); - } - - ruleTargetDTO.setRowDTOList(newTargetRowDTOs); - - List ruleObligationDTOs = ruleDTO.getObligationDTOs(); - - if (ruleObligationDTOs != null) { - for (ObligationDTO dto : ruleObligationDTOs) { - createMetaDataFromObligation("ruleObligation" + ruleDTO.getRuleId(), - dto, policyMetaDataList); - if (dto.getAttributeValueDataType() == null || - dto.getAttributeValueDataType().trim().length() < 1 || - dto.getAttributeValueDataType().trim().equals("null")) { - dto.setAttributeValueDataType(PolicyEditorConstants.DataType.STRING); - } - if (dto.getResultAttributeId() == null || - dto.getResultAttributeId().trim().length() == 0 || - dto.getResultAttributeId().trim().equals("null")) { - // setting obligation id - dto.setResultAttributeId(dto.getObligationId()); - } - } - ruleDTO.setObligationDTOs(ruleObligationDTOs); - } - - ruleDTO.setTargetDTO(ruleTargetDTO); - } - - policyDTO.setRuleDTOs(ruleDTOs); - } - - if (obligationDTOs != null) { - for (ObligationDTO dto : obligationDTOs) { - createMetaDataFromObligation("obligation", dto, policyMetaDataList); - if (dto.getAttributeValueDataType() == null || - dto.getAttributeValueDataType().trim().length() == 0 || - dto.getAttributeValueDataType().trim().equals("null")) { - dto.setAttributeValueDataType(PolicyEditorConstants.DataType.STRING); - } - if (dto.getResultAttributeId() == null || - dto.getResultAttributeId().trim().length() == 0 || - dto.getResultAttributeId().trim().equals("null")) { - // setting obligation id - dto.setResultAttributeId(dto.getObligationId()); - } - } - policyDTO.setObligationDTOs(obligationDTOs); - } - -// for(ExtendAttributeDTO attributeDTO : ruleDTO.getAttributeDTOs()){ -// -// String id = attributeDTO.getId(); -// String selector = attributeDTO.getSelector(); -// String category = null; -// String function = null; -// -// if(id == null){ -// continue; -// } -// -// if(PolicyEditorConstants.DYNAMIC_SELECTOR_FUNCTION.equals(selector)){ -// -// String attributeValue = attributeDTO.getAttributeValue(); -// if(attributeValue == null || attributeValue.trim().length() < 1){ -// continue; -// } -// function = attributeDTO.getFunction(); -// if(function != null){ -// function = function.replace(">", ">"); -// function = function.replace("<", "<"); -// -// if(ruleFunctionMap.get(function) != null){// TODO -// attributeDTO.setFunction(ruleFunctionMap.get(function)); -// } -// } -// -// if(attributeDTO.getDataType() == null || -// attributeDTO.getDataType().trim().length() < 1 || -// attributeDTO.getDataType().trim().equals("null")) { -// -// if(category != null && defaultDataTypeMap.get(category) != null){ -// attributeDTO.setDataType((defaultDataTypeMap. -// get(category).iterator().next())); -// } else { -// attributeDTO.setDataType(PolicyEditorConstants.DataType.STRING); -// } -// } -// -// } else { -// -// category = attributeDTO.getCategory(); -// -// if(category == null || category.trim().length() < 1){ -// continue; -// } -// -// if(categoryMap.get(category) != null){ -// attributeDTO.setCategory(categoryMap.get(category)); -// } -// -// if(attributeDTO.getDataType() == null || -// attributeDTO.getDataType().trim().length() < 1 || -// attributeDTO.getDataType().trim().equals("null")) { -// -// if(defaultDataTypeMap.get(category) != null){ -// attributeDTO.setDataType((defaultDataTypeMap. -// get(category).iterator().next())); -// } else { -// attributeDTO.setDataType(PolicyEditorConstants.DataType.STRING); -// } -// } -// -// if(attributeDTO.getAttributeId() == null || -// attributeDTO.getAttributeId().trim().length() < 1 || -// attributeDTO.getAttributeId().trim().equals("null")) { -// if(defaultAttributeIdMap.get(category) != null){ -// attributeDTO.setAttributeId((defaultAttributeIdMap. -// get(category).iterator().next())); -// } -// } -// } -// -// -// ExtendAttributeDTO odlRowDTO = new ExtendAttributeDTO(attributeDTO); -// odlRowDTO.setCategory(category); -// odlRowDTO.setFunction(function); -// createMetaDataFromDynamicAttribute("targetRule" + odlRowDTO.getId(), odlRowDTO, -// policyMetaDataList); -// //newDynamicAttributeDTOs.add(attributeDTO); -// } - - return policyMetaDataList.toArray(new String[policyMetaDataList.size()]); - } - - private static void createMetaDataFromPolicy(String prefix, PolicyDTO policyDTO, List metaDataList) { - if (metaDataList != null) { - metaDataList.add(prefix + "|" + policyDTO.getPolicyId()); - metaDataList.add(prefix + "|" + policyDTO.getRuleAlgorithm()); - if (policyDTO.getDescription() == null) { - policyDTO.setDescription(""); - } - metaDataList.add(prefix + "|" + policyDTO.getDescription()); - metaDataList.add(prefix + "|" + policyDTO.getVersion()); - } - } - - private static void createMetaDataFromPolicySet(String prefix, PolicySetDTO policyDTO, List metaDataList) { - if (metaDataList != null) { - metaDataList.add(prefix + "|" + policyDTO.getPolicySetId()); - metaDataList.add(prefix + "|" + policyDTO.getPolicyCombiningAlgId()); - if (policyDTO.getDescription() == null) { - policyDTO.setDescription(""); - } - metaDataList.add(prefix + "|" + policyDTO.getDescription()); - metaDataList.add(prefix + "|" + policyDTO.getVersion()); - } - } - - private static void createMetaDataFromRule(String prefix, RuleDTO ruleDTO, List metaDataList) { - if (metaDataList != null) { - metaDataList.add(prefix + "|" + ruleDTO.getRuleId()); - metaDataList.add(prefix + "|" + ruleDTO.getRuleEffect()); - metaDataList.add(prefix + "|" + ruleDTO.getRuleDescription()); - } - } - - private static void createMetaDataFromRowDTO(String prefix, RowDTO rowDTO, List metaDataList) { - - if (metaDataList != null) { - metaDataList.add(prefix + "|" + rowDTO.getCategory()); - metaDataList.add(prefix + "|" + rowDTO.getPreFunction()); - metaDataList.add(prefix + "|" + rowDTO.getFunction()); - metaDataList.add(prefix + "|" + rowDTO.getAttributeValue()); - metaDataList.add(prefix + "|" + rowDTO.getAttributeId()); - metaDataList.add(prefix + "|" + rowDTO.getAttributeDataType()); - metaDataList.add(prefix + "|" + rowDTO.getCombineFunction()); - } - } - - private static void createMetaDataFromDynamicAttribute(String prefix, ExtendAttributeDTO dto, - List metaDataList) { - - if (metaDataList != null) { - metaDataList.add(prefix + "|" + dto.getCategory()); - metaDataList.add(prefix + "|" + dto.getSelector()); - metaDataList.add(prefix + "|" + dto.getFunction()); - metaDataList.add(prefix + "|" + dto.getAttributeValue()); - metaDataList.add(prefix + "|" + dto.getAttributeId()); - metaDataList.add(prefix + "|" + dto.getDataType()); - metaDataList.add(prefix + "|" + dto.getId()); - } - } - - private static void createMetaDataFromObligation(String prefix, ObligationDTO dto, - List metaDataList) { - - if (metaDataList != null) { - metaDataList.add(prefix + "|" + dto.getType()); - metaDataList.add(prefix + "|" + dto.getObligationId()); - metaDataList.add(prefix + "|" + dto.getEffect()); - metaDataList.add(prefix + "|" + dto.getAttributeValue()); - metaDataList.add(prefix + "|" + dto.getResultAttributeId()); - metaDataList.add(prefix + "|" + dto.getAttributeValueDataType()); - } - } - - private static void createMetaDataFromReference(String prefix, PolicyRefIdDTO dto, - List metaDataList) { - if (metaDataList != null) { - metaDataList.add(prefix + "|" + dto.getId()); - metaDataList.add(prefix + "|" + dto.isPolicySet()); - metaDataList.add(prefix + "|" + dto.isReferenceOnly()); - } - } - - public static String[] createBasicPolicyData(SimplePolicyEditorDTO policyEditorDTO) { - - List metaDataList = new ArrayList(); - - metaDataList.add("policyId|" + policyEditorDTO.getPolicyId()); - metaDataList.add("category|" + policyEditorDTO.getAppliedCategory()); - metaDataList.add("policyDescription|" + policyEditorDTO.getDescription()); - metaDataList.add("userAttributeId|" + policyEditorDTO.getUserAttributeId()); - metaDataList.add("userAttributeValue|" + policyEditorDTO.getUserAttributeValue()); - metaDataList.add("function|" + policyEditorDTO.getFunction()); - metaDataList.add("actionValue|" + policyEditorDTO.getActionValue()); - metaDataList.add("resourceValue|" + policyEditorDTO.getResourceValue()); - metaDataList.add("category|" + policyEditorDTO.getAppliedCategory()); - metaDataList.add("environmentValue|" + policyEditorDTO.getEnvironmentValue()); - metaDataList.add("environmentId|" + policyEditorDTO.getEnvironmentId()); - - List elementDTOs = policyEditorDTO.getSimplePolicyEditorElementDTOs(); - - if (elementDTOs != null && elementDTOs.size() > 0) { - for (int i = 0; i < elementDTOs.size(); i++) { - SimplePolicyEditorElementDTO dto = elementDTOs.get(i); - if (dto.getResourceValue() != null) { - metaDataList.add("resourceValue" + i + "|" + dto.getResourceValue()); - } else { - metaDataList.add("resourceValue" + i); - } - if (dto.getEnvironmentValue() != null) { - metaDataList.add("environmentValue" + i + "|" + dto.getEnvironmentValue()); - } else { - metaDataList.add("environmentValue" + i); - } - if (dto.getActionValue() != null) { - metaDataList.add("actionValue" + i + "|" + dto.getActionValue()); - } else { - metaDataList.add("actionValue" + i); - } - if (dto.getOperationType() != null) { - metaDataList.add("operationValue" + i + "|" + dto.getOperationType()); - } else { - metaDataList.add("operationValue" + i); - } - if (dto.getUserAttributeId() != null) { - metaDataList.add("userAttributeId" + i + "|" + dto.getUserAttributeId()); - } else { - metaDataList.add("userAttributeId" + i); - } - if (dto.getUserAttributeValue() != null) { - metaDataList.add("userAttributeValue" + i + "|" + dto.getUserAttributeValue()); - } else { - metaDataList.add("userAttributeValue" + i); - } - if (dto.getEnvironmentId() != null) { - metaDataList.add("environmentId" + i + "|" + dto.getEnvironmentId()); - } else { - metaDataList.add("environmentId" + i); - } - if (dto.getFunctionOnResources() != null) { - metaDataList.add("functionOnResources" + i + "|" + dto.getFunctionOnResources()); - } else { - metaDataList.add("functionOnResources" + i); - } - if (dto.getFunctionOnActions() != null) { - metaDataList.add("functionOnActions" + i + "|" + dto.getFunctionOnActions()); - } else { - metaDataList.add("functionOnActions" + i); - } - if (dto.getFunctionOnUsers() != null) { - metaDataList.add("functionOnUsers" + i + "|" + dto.getFunctionOnUsers()); - } else { - metaDataList.add("functionOnUsers" + i); - } - if (dto.getFunctionOnEnvironments() != null) { - metaDataList.add("functionOnEnvironments" + i + "|" + dto.getFunctionOnEnvironments()); - } else { - metaDataList.add("functionOnEnvironments" + i); - } - - } - } - return metaDataList.toArray(new String[metaDataList.size()]); - } - -////////////////////////////////////// Simple Policy Editor data //////////////////////////////////// - - - public static SimplePolicyEditorDTO createSimplePolicyEditorDTO(String[] policyEditorData) { - - Map metaDataMap = new HashMap(); - List SimplePolicyEditorElementDTOs = new ArrayList(); - - int i = 0; - - if (policyEditorData != null) { - for (String data : policyEditorData) { - if (data.contains("|")) { - String identifier = data.substring(0, data.indexOf("|")); - String value = data.substring(data.indexOf("|") + 1); - metaDataMap.put(identifier, value); - } - i++; - } - } - - SimplePolicyEditorDTO policyEditorDTO = new SimplePolicyEditorDTO(); - policyEditorDTO.setPolicyId(metaDataMap.get("policyId")); - policyEditorDTO.setAppliedCategory(metaDataMap.get("policyId")); - policyEditorDTO.setFunction(metaDataMap.get("function")); - policyEditorDTO.setActionValue(metaDataMap.get("actionValue")); - policyEditorDTO.setDescription(metaDataMap.get("policyDescription")); - policyEditorDTO.setUserAttributeId(metaDataMap.get("userAttributeId")); - policyEditorDTO.setUserAttributeValue(metaDataMap.get("userAttributeValue")); - policyEditorDTO.setResourceValue(metaDataMap.get("resourceValue")); - policyEditorDTO.setEnvironmentValue(metaDataMap.get("environmentValue")); - policyEditorDTO.setEnvironmentId(metaDataMap.get("environmentId")); - policyEditorDTO.setAppliedCategory(metaDataMap.get("category")); - - i = (i - 11) / 11; - - for (int j = 0; j < i; j++) { - - SimplePolicyEditorElementDTO elementDTO = new SimplePolicyEditorElementDTO(); - - elementDTO.setResourceValue(metaDataMap.get("resourceValue" + j)); - elementDTO.setEnvironmentValue(metaDataMap.get("environmentValue" + j)); - if (metaDataMap.get("actionValue" + j) != null) { - elementDTO.setActionValue(metaDataMap.get("actionValue" + j)); - } - elementDTO.setOperationType(metaDataMap.get("operationValue" + j)); - elementDTO.setUserAttributeId(metaDataMap.get("userAttributeId" + j)); - elementDTO.setUserAttributeValue(metaDataMap.get("userAttributeValue" + j)); - elementDTO.setEnvironmentId(metaDataMap.get("environmentId" + j)); - elementDTO.setFunctionOnResources(metaDataMap.get("functionOnResources" + j)); - elementDTO.setFunctionOnActions(metaDataMap.get("functionOnActions" + j)); - elementDTO.setFunctionOnUsers(metaDataMap.get("functionOnUsers" + j)); - elementDTO.setFunctionOnEnvironments(metaDataMap.get("functionOnEnvironments" + j)); - - SimplePolicyEditorElementDTOs.add(elementDTO); - } - - if (SimplePolicyEditorElementDTOs.size() > 0) { - policyEditorDTO.setSimplePolicyEditorElementDTOs(SimplePolicyEditorElementDTOs); - } - - return policyEditorDTO; - } - - -///////////////////////////////// policy Set /////////////////////////////////////////////////////// - -// public static PolicyElementDTO createPolicySetElementDTO(String policy) -// throws EntitlementPolicyCreationException { -// -// PolicySetDTO policyElementDTO = new PolicySetDTO(); -// OMElement omElement; -// try { -// omElement = AXIOMUtil.stringToOM(policy); -// } catch (XMLStreamException e) { -// throw new EntitlementPolicyCreationException("Policy can not be converted to OMElement"); -// } -// -// if (omElement != null) { -// -// policyElementDTO.setPolicySetId(omElement. -// getAttributeValue(new QName(EntitlementPolicyConstants.POLICY_SET_ID))); -// -// String ruleCombiningAlgorithm = omElement. -// getAttributeValue(new QName(EntitlementPolicyConstants.POLICY_ALGORITHM)); -// -// try{ -// policyElementDTO.setRuleCombiningAlgorithms(ruleCombiningAlgorithm. -// split(PolicyEditorConstants.RULE_ALGORITHM_IDENTIFIER_3)[1]); -// } catch (Exception ignore){ -// policyElementDTO.setRuleCombiningAlgorithms(ruleCombiningAlgorithm. -// split(PolicyEditorConstants.RULE_ALGORITHM_IDENTIFIER_1)[1]); -// // if this is also fails, can not edit the policy -// } -// -// Iterator iterator = omElement.getChildrenWithLocalName(EntitlementPolicyConstants. -// DESCRIPTION_ELEMENT); -// -// if(iterator.hasNext()){ -// OMElement descriptionElement = (OMElement) iterator.next(); -// if(descriptionElement != null && descriptionElement.getText() != null){ -// policyElementDTO.setPolicyDescription(descriptionElement.getText().trim()); -// } -// } -// -// } -// return policyElementDTO; -// } - -//////////////////////////////// Standard policy editor///////////////////////////////////////////////////// - - public static PolicyElementDTO createPolicyElementDTO(String policy) - throws EntitlementPolicyCreationException { - - PolicyElementDTO policyElementDTO = new PolicyElementDTO(); - OMElement omElement; - try { - omElement = AXIOMUtil.stringToOM(policy); - } catch (XMLStreamException e) { - throw new EntitlementPolicyCreationException("Policy can not be converted to OMElement"); - } - - if (omElement != null) { - - policyElementDTO.setPolicyName(omElement. - getAttributeValue(new QName(EntitlementPolicyConstants.POLICY_ID))); - - String ruleCombiningAlgorithm = omElement. - getAttributeValue(new QName(EntitlementPolicyConstants.RULE_ALGORITHM)); - - try { - policyElementDTO.setRuleCombiningAlgorithms(ruleCombiningAlgorithm. - split(PolicyEditorConstants.RULE_ALGORITHM_IDENTIFIER_3)[1]); - } catch (Exception ignore) { - policyElementDTO.setRuleCombiningAlgorithms(ruleCombiningAlgorithm. - split(PolicyEditorConstants.RULE_ALGORITHM_IDENTIFIER_1)[1]); - // if this is also fails, can not edit the policy - } - - Iterator iterator = omElement.getChildrenWithLocalName(EntitlementPolicyConstants. - DESCRIPTION_ELEMENT); - - if (iterator.hasNext()) { - OMElement descriptionElement = (OMElement) iterator.next(); - if (descriptionElement != null && descriptionElement.getText() != null) { - policyElementDTO.setPolicyDescription(descriptionElement.getText().trim()); - } - } - - } - return policyElementDTO; - } - - public static List createRuleElementDTOs(String policy) - throws EntitlementPolicyCreationException { - - List ruleElementDTOs = new ArrayList(); - OMElement omElement; - try { - omElement = AXIOMUtil.stringToOM(policy); - } catch (XMLStreamException e) { - throw new EntitlementPolicyCreationException("Policy can not be converted to OMElement"); - } - - if (omElement != null) { - Iterator iterator2 = omElement.getChildrenWithLocalName(EntitlementPolicyConstants. - RULE_ELEMENT); - while (iterator2.hasNext()) { - OMElement ruleElement = (OMElement) iterator2.next(); - ruleElementDTOs.add(createRuleDTO(ruleElement)); - } - } - return ruleElementDTOs; - } - - - public static RuleElementDTO createRuleDTO(OMElement omElement) { - RuleElementDTO ruleElementDTO = new RuleElementDTO(); - - if (omElement != null) { - ruleElementDTO.setRuleId(omElement. - getAttributeValue(new QName(EntitlementPolicyConstants.RULE_ID)).trim()); - ruleElementDTO.setRuleEffect(omElement. - getAttributeValue(new QName(EntitlementPolicyConstants.RULE_EFFECT)).trim()); - - Iterator iterator1 = omElement. - getChildrenWithLocalName(EntitlementPolicyConstants.DESCRIPTION_ELEMENT); - - while (iterator1.hasNext()) { - OMElement descriptionElement = (OMElement) iterator1.next(); - if (descriptionElement != null && descriptionElement.getText() != null) { - ruleElementDTO.setRuleDescription(descriptionElement.getText().trim()); - } - } - } - - return ruleElementDTO; - } - - - public static void processRuleRowPolicyEditorData(List rules, String[] policyEditorData) { - - for (RuleDTO ruleDTO : rules) { - List ruleList = new ArrayList(); - List ruleTargetList = new ArrayList(); - List obligationList = new ArrayList(); - - for (String data : policyEditorData) { - if (data.contains("|")) { - String identifier = data.substring(0, data.indexOf("|")); - if (identifier.startsWith("ruleTarget")) { - String ruleId = identifier.substring(10); - if (ruleId != null && ruleId.contains(ruleDTO.getRuleId())) { - ruleTargetList.add(data.substring(data.indexOf("|") + 1)); - } - } else if (identifier.startsWith("ruleObligation")) { - String ruleId = identifier.substring(14); - if (ruleId != null && ruleId.equals(ruleDTO.getRuleId())) { - obligationList.add(data.substring(data.indexOf("|") + 1)); - } - } else if (identifier.startsWith("ruleRow")) { - String ruleId = identifier.substring(7); - if (ruleId != null && ruleId.equals(ruleDTO.getRuleId())) { - ruleList.add(data.substring(data.indexOf("|") + 1)); - } - } - } - } - - ruleDTO.setRowDTOList(createRowDTO(ruleList)); - ruleDTO.getTargetDTO().setRowDTOList(createRowDTO(ruleTargetList)); - ruleDTO.setObligationDTOs(createObligationDTO(obligationList)); - ruleDTO.setCompletedRule(true); - } - } - - public static void processTargetPolicyEditorData(TargetDTO targetDTO, String[] policyEditorData) { - - List targetList = new ArrayList(); - - if (policyEditorData != null) { - for (String data : policyEditorData) { - if (data.contains("|")) { - String identifier = data.substring(0, data.indexOf("|")); - if (("target").equals(identifier)) { - targetList.add(data.substring(data.indexOf("|") + 1)); - } - } - } - - targetDTO.setRowDTOList(createRowDTO(targetList)); - } - } - - public static void processPolicyEditorData(PolicyElementDTO policyElementDTO, String[] policyEditorData) { - - List targetList = new ArrayList(); - - if (policyEditorData != null) { - for (String data : policyEditorData) { - if (data.contains("|")) { - String identifier = data.substring(0, data.indexOf("|")); - if (("policy").equals(identifier)) { - targetList.add(data.substring(data.indexOf("|") + 1)); - } - } - } - - policyElementDTO.setPolicyName(targetList.get(0)); - policyElementDTO.setRuleCombiningAlgorithms(targetList.get(1)); - if (targetList.get(2) != null) { - policyElementDTO.setPolicyDescription(targetList.get(2)); - } - policyElementDTO.setVersion(targetList.get(3)); - } - } - - public static void processObligationPolicyEditorData(List obligationDTOs, - String[] policyEditorData) { - - List targetList = new ArrayList(); - - if (policyEditorData != null) { - for (String data : policyEditorData) { - if (data.contains("|")) { - String identifier = data.substring(0, data.indexOf("|")); - if (("obligation").equals(identifier)) { - targetList.add(data.substring(data.indexOf("|") + 1)); - } - } - } - - obligationDTOs.addAll(createObligationDTO(targetList)); - } - } - - public static void processRulePolicyEditorData(List ruleDTOs, - String[] policyEditorData) { - List targetList = new ArrayList(); - if (policyEditorData != null) { - for (String data : policyEditorData) { - if (data.contains("|")) { - String identifier = data.substring(0, data.indexOf("|")); - if (("rule").equals(identifier)) { - targetList.add(data.substring(data.indexOf("|") + 1)); - } - } - } - ruleDTOs.addAll(createRuleDTO(targetList)); - if (ruleDTOs.size() > 0) { - processRuleRowPolicyEditorData(ruleDTOs, policyEditorData); - } - } - } - - public static void processReferencePolicyEditorData(List policyRefIdDTOs, - String[] policyEditorData) { - - List targetList = new ArrayList(); - if (policyEditorData != null) { - for (String data : policyEditorData) { - if (data.contains("|")) { - String identifier = data.substring(0, data.indexOf("|")); - if (("reference").equals(identifier)) { - targetList.add(data.substring(data.indexOf("|") + 1)); - } - } - } - - policyRefIdDTOs.addAll(createReferenceDTO(targetList)); - } - } - - private static List createRowDTO(List list) { - List rowDTOs = new ArrayList(); - for (int i = 0; i < list.size(); i = i + 7) { - List newList = list.subList(i, i + 7); - if (newList != null) { - RowDTO rowDTO = new RowDTO(); - rowDTO.setCategory(newList.get(0)); - rowDTO.setPreFunction(newList.get(1)); - rowDTO.setFunction(newList.get(2)); - rowDTO.setAttributeValue(newList.get(3)); - rowDTO.setAttributeId(newList.get(4)); - rowDTO.setAttributeDataType(newList.get(5)); - rowDTO.setCombineFunction(newList.get(6)); - rowDTOs.add(rowDTO); - } - } - return rowDTOs; - } - - private static List createObligationDTO(List list) { - List rowDTOs = new ArrayList(); - for (int i = 0; i < list.size(); i = i + 6) { - List newList = list.subList(i, i + 6); - if (newList != null) { - ObligationDTO rowDTO = new ObligationDTO(); - rowDTO.setType(newList.get(0)); - rowDTO.setObligationId(newList.get(1)); - rowDTO.setEffect(newList.get(2)); - rowDTO.setAttributeValue(newList.get(3)); - rowDTO.setResultAttributeId(newList.get(4)); - rowDTO.setAttributeValueDataType(newList.get(5)); - rowDTOs.add(rowDTO); - } - } - return rowDTOs; - } - - private static List createRuleDTO(List list) { - List rowDTOs = new ArrayList(); - for (int i = 0; i < list.size(); i = i + 3) { - List newList = list.subList(i, i + 3); - if (newList != null) { - RuleDTO rowDTO = new RuleDTO(); - rowDTO.setRuleId(newList.get(0)); - rowDTO.setRuleEffect(newList.get(1)); - rowDTO.setRuleDescription(newList.get(2)); - rowDTOs.add(rowDTO); - } - } - return rowDTOs; - } - - private static List createReferenceDTO(List list) { - List rowDTOs = new ArrayList(); - for (int i = 0; i < list.size(); i = i + 3) { - List newList = list.subList(i, i + 3); - if (newList != null) { - PolicyRefIdDTO rowDTO = new PolicyRefIdDTO(); - rowDTO.setId(newList.get(0)); - rowDTO.setPolicySet(Boolean.parseBoolean(newList.get(1))); - rowDTO.setReferenceOnly(Boolean.parseBoolean(newList.get(2))); - rowDTOs.add(rowDTO); - } - } - return rowDTOs; - } - -///////////////////////////////////////// Basic Policy Editor /////////////////////////////////////// - - /** - * create policy meta data that helps to edit the policy using basic editor - * - * @param basicPolicyDTO BasicPolicyDTO - * @param ruleElementOrder String - * @return String Array to dent to back end - */ - public static String[] generateBasicPolicyEditorData(BasicPolicyDTO basicPolicyDTO, - String ruleElementOrder) { - - List basicRuleDTOs = basicPolicyDTO.getBasicRuleDTOs(); - BasicTargetDTO basicTargetDTO = basicPolicyDTO.getTargetDTO(); - - PolicyEditorDataHolder holder = PolicyEditorEngine.getInstance(). - getPolicyEditorData(EntitlementConstants.PolicyEditor.BASIC); - List arrangedRules = new ArrayList(); - - if (ruleElementOrder != null && ruleElementOrder.trim().length() > 0) { - String[] ruleIds = ruleElementOrder. - split(EntitlementPolicyConstants.ATTRIBUTE_SEPARATOR); - for (String ruleId : ruleIds) { - for (BasicRuleDTO ruleDTO : basicRuleDTOs) { - if (ruleId.equals(ruleDTO.getRuleId())) { - arrangedRules.add(ruleDTO); - } - } - } - basicRuleDTOs = arrangedRules; - } - - int ruleEditorDataConstant = EntitlementPolicyConstants.BASIC_POLICY_EDITOR_RULE_DATA_AMOUNT; - int targetEditorDataConstant = EntitlementPolicyConstants.BASIC_POLICY_EDITOR_TARGET_DATA_AMOUNT; - - int i = 0; - String selectedDataType; - String[] policyEditorData; - if (basicRuleDTOs != null) { - policyEditorData = new String[targetEditorDataConstant + - (basicRuleDTOs.size() * ruleEditorDataConstant)]; - } else { - policyEditorData = new String[targetEditorDataConstant]; - } - - policyEditorData[i++] = basicPolicyDTO.getPolicyId(); - policyEditorData[i++] = basicPolicyDTO.getRuleAlgorithm(); - String algorithm = basicPolicyDTO.getRuleAlgorithm(); - if (algorithm != null && algorithm.trim().length() > 0) { - basicPolicyDTO.setRuleAlgorithm(holder.getRuleAlgorithmUri(algorithm)); - } else { - basicPolicyDTO.setRuleAlgorithm(holder.getRuleAlgorithmUri(holder.getDefaultRuleAlgorithm())); - } - policyEditorData[i++] = basicPolicyDTO.getVersion(); - policyEditorData[i++] = basicPolicyDTO.getDescription(); - - policyEditorData[i++] = basicTargetDTO.getFunctionOnResources(); - policyEditorData[i++] = basicTargetDTO.getResourceList(); - policyEditorData[i++] = basicTargetDTO.getResourceId(); - String resourceId = basicTargetDTO.getResourceId(); - policyEditorData[i++] = basicTargetDTO.getResourceDataType(); - basicTargetDTO.setFunctionOnResources(holder.getFunctionUri(basicTargetDTO.getFunctionOnResources())); - basicTargetDTO.setResourceId(holder.getAttributeIdUri(resourceId)); - if ((selectedDataType = holder.getDataTypeUriForAttribute(resourceId)) != null) { - basicTargetDTO.setResourceDataType(selectedDataType); - } - - policyEditorData[i++] = basicTargetDTO.getFunctionOnSubjects(); - policyEditorData[i++] = basicTargetDTO.getSubjectList(); - policyEditorData[i++] = basicTargetDTO.getSubjectId(); - policyEditorData[i++] = basicTargetDTO.getSubjectDataType(); - String subjectId = basicTargetDTO.getSubjectId(); - basicTargetDTO.setFunctionOnSubjects(holder.getFunctionUri(basicTargetDTO.getFunctionOnSubjects())); - basicTargetDTO.setSubjectId(holder.getAttributeIdUri(subjectId)); - if ((selectedDataType = holder.getDataTypeUriForAttribute(subjectId)) != null) { - basicTargetDTO.setSubjectDataType(selectedDataType); - } - - policyEditorData[i++] = basicTargetDTO.getFunctionOnActions(); - policyEditorData[i++] = basicTargetDTO.getActionList(); - policyEditorData[i++] = basicTargetDTO.getActionId(); - String actionId = basicTargetDTO.getActionId(); - policyEditorData[i++] = basicTargetDTO.getActionDataType(); - basicTargetDTO.setFunctionOnActions(holder.getFunctionUri(basicTargetDTO.getFunctionOnActions())); - basicTargetDTO.setActionId(holder.getAttributeIdUri(actionId)); - if ((selectedDataType = holder.getDataTypeUriForAttribute(actionId)) != null) { - basicTargetDTO.setActionDataType(selectedDataType); - } - - policyEditorData[i++] = basicTargetDTO.getFunctionOnEnvironment(); - policyEditorData[i++] = basicTargetDTO.getEnvironmentList(); - policyEditorData[i++] = basicTargetDTO.getEnvironmentId(); - policyEditorData[i++] = basicTargetDTO.getEnvironmentDataType(); - String environmentId = basicTargetDTO.getEnvironmentId(); - basicTargetDTO.setFunctionOnEnvironment(holder.getFunctionUri(basicTargetDTO.getFunctionOnEnvironment())); - basicTargetDTO.setEnvironmentId(holder.getAttributeIdUri(environmentId)); - if ((selectedDataType = holder.getDataTypeUriForAttribute(environmentId)) != null) { - basicTargetDTO.setEnvironmentDataType(selectedDataType); - } - - - if (basicRuleDTOs != null && basicRuleDTOs.size() > 0) { - for (BasicRuleDTO basicRuleDTO : basicRuleDTOs) { - generateBasicPolicyEditorDataForRule(basicRuleDTO, policyEditorData, i); - i = i + ruleEditorDataConstant; - - if (basicRuleDTO.getRuleId() == null || basicRuleDTO.getRuleId().trim().length() == 0) { - basicRuleDTO.setRuleId(UUID.randomUUID().toString()); - } - - if (basicRuleDTO.getRuleEffect() == null || basicRuleDTO.getRuleEffect().trim().length() == 0) { - basicRuleDTO.setRuleEffect(holder.getDefaultEffect()); - } - } - } - - if (holder.isAddLastRule()) { - - if (basicRuleDTOs == null) { - basicRuleDTOs = new ArrayList(); - } - - BasicRuleDTO basicRuleDTO = new BasicRuleDTO(); - basicRuleDTO.setRuleId(UUID.randomUUID().toString()); - if (holder.getLastRuleEffect() != null) { - basicRuleDTO.setRuleEffect(holder.getLastRuleEffect()); - } else { - basicRuleDTO.setRuleEffect(holder.getDefaultEffect()); - } - basicRuleDTOs.add(basicRuleDTO); - } - - //as we have rearrage the rules - basicPolicyDTO.setBasicRuleDTOs(basicRuleDTOs); - - return policyEditorData; - } - - public static String[] generateBasicPolicyEditorDataForRule(BasicRuleDTO basicRuleDTO, - String[] policyEditorData, int currentArrayIndex) { - int i = currentArrayIndex; - String selectedDataType; - PolicyEditorDataHolder holder = PolicyEditorEngine.getInstance(). - getPolicyEditorData(EntitlementConstants.PolicyEditor.BASIC); - - policyEditorData[i++] = basicRuleDTO.getRuleId(); - policyEditorData[i++] = basicRuleDTO.getRuleEffect(); - policyEditorData[i++] = basicRuleDTO.getRuleDescription(); - basicRuleDTO.setRuleEffect(holder.getRuleEffectUri(basicRuleDTO.getRuleEffect())); - - policyEditorData[i++] = basicRuleDTO.getPreFunctionOnResources(); - policyEditorData[i++] = basicRuleDTO.getFunctionOnResources(); - policyEditorData[i++] = basicRuleDTO.getResourceList(); - policyEditorData[i++] = basicRuleDTO.getResourceId(); - String resourceId = basicRuleDTO.getResourceId(); - policyEditorData[i++] = basicRuleDTO.getResourceDataType(); - basicRuleDTO.setPreFunctionOnResources(holder.getPreFunctionUri(basicRuleDTO.getPreFunctionOnResources())); - basicRuleDTO.setFunctionOnResources(holder.getFunctionUri(basicRuleDTO.getFunctionOnResources())); - basicRuleDTO.setResourceId(holder.getAttributeIdUri(resourceId)); - if ((selectedDataType = holder.getDataTypeUriForAttribute(resourceId)) != null) { - basicRuleDTO.setResourceDataType(selectedDataType); - } - - policyEditorData[i++] = basicRuleDTO.getPreFunctionOnSubjects(); - policyEditorData[i++] = basicRuleDTO.getFunctionOnSubjects(); - policyEditorData[i++] = basicRuleDTO.getSubjectList(); - policyEditorData[i++] = basicRuleDTO.getSubjectId(); - policyEditorData[i++] = basicRuleDTO.getSubjectDataType(); - String subjectId = basicRuleDTO.getSubjectId(); - basicRuleDTO.setPreFunctionOnSubjects(holder.getPreFunctionUri(basicRuleDTO.getPreFunctionOnSubjects())); - basicRuleDTO.setFunctionOnSubjects(holder.getFunctionUri(basicRuleDTO.getFunctionOnSubjects())); - basicRuleDTO.setSubjectId(holder.getAttributeIdUri(subjectId)); - if ((selectedDataType = holder.getDataTypeUriForAttribute(subjectId)) != null) { - basicRuleDTO.setSubjectDataType(selectedDataType); - } - - policyEditorData[i++] = basicRuleDTO.getPreFunctionOnActions(); - policyEditorData[i++] = basicRuleDTO.getFunctionOnActions(); - policyEditorData[i++] = basicRuleDTO.getActionList(); - policyEditorData[i++] = basicRuleDTO.getActionId(); - String actionId = basicRuleDTO.getActionId(); - policyEditorData[i++] = basicRuleDTO.getActionDataType(); - basicRuleDTO.setPreFunctionOnActions(holder.getPreFunctionUri(basicRuleDTO.getPreFunctionOnActions())); - basicRuleDTO.setFunctionOnActions(holder.getFunctionUri(basicRuleDTO.getFunctionOnActions())); - basicRuleDTO.setActionId(holder.getAttributeIdUri(actionId)); - if ((selectedDataType = holder.getDataTypeUriForAttribute(actionId)) != null) { - basicRuleDTO.setActionDataType(selectedDataType); - } - - policyEditorData[i++] = basicRuleDTO.getPreFunctionOnEnvironment(); - policyEditorData[i++] = basicRuleDTO.getFunctionOnEnvironment(); - policyEditorData[i++] = basicRuleDTO.getEnvironmentList(); - policyEditorData[i++] = basicRuleDTO.getEnvironmentId(); - policyEditorData[i++] = basicRuleDTO.getEnvironmentDataType(); - String environmentId = basicRuleDTO.getSubjectId(); - basicRuleDTO.setPreFunctionOnEnvironment(holder.getPreFunctionUri(basicRuleDTO.getPreFunctionOnEnvironment())); - basicRuleDTO.setFunctionOnEnvironment(holder.getFunctionUri(basicRuleDTO.getFunctionOnEnvironment())); - basicRuleDTO.setEnvironmentId(holder.getAttributeIdUri(environmentId)); - if ((selectedDataType = holder.getDataTypeUriForAttribute(environmentId)) != null) { - basicRuleDTO.setEnvironmentDataType(selectedDataType); - } - - return policyEditorData; - } - - - public static BasicPolicyDTO createBasicPolicyDTO(String[] policyEditorData) { - - BasicPolicyDTO basicPolicyDTO = new BasicPolicyDTO(); - int i = 0; - - if (policyEditorData[i] != null) { - basicPolicyDTO.setPolicyId(policyEditorData[i]); - } - i++; - if (policyEditorData[i] != null) { - basicPolicyDTO.setRuleAlgorithm(policyEditorData[i]); - } - i++; - if (policyEditorData[i] != null) { - basicPolicyDTO.setVersion(policyEditorData[i]); - } - i++; - if (policyEditorData[i] != null) { - basicPolicyDTO.setDescription(policyEditorData[i]); - } - i++; - - BasicTargetDTO basicTargetDTO = new BasicTargetDTO(); - - if (policyEditorData[i] != null) { - basicTargetDTO.setFunctionOnResources(policyEditorData[i]); - } - i++; - if (policyEditorData[i] != null) { - basicTargetDTO.setResourceList(policyEditorData[i]); - } - i++; - if (policyEditorData[i] != null) { - basicTargetDTO.setResourceId(policyEditorData[i]); - } - i++; - if (policyEditorData[i] != null) { - basicTargetDTO.setResourceDataType(policyEditorData[i]); - } - i++; - - if (policyEditorData[i] != null) { - basicTargetDTO.setFunctionOnSubjects(policyEditorData[i]); - } - i++; - if (policyEditorData[i] != null) { - basicTargetDTO.setSubjectList(policyEditorData[i]); - } - i++; - if (policyEditorData[i] != null) { - basicTargetDTO.setSubjectId(policyEditorData[i]); - } - i++; - if (policyEditorData[i] != null) { - basicTargetDTO.setSubjectDataType(policyEditorData[i]); - } - i++; - - if (policyEditorData[i] != null) { - basicTargetDTO.setFunctionOnActions(policyEditorData[i]); - } - i++; - if (policyEditorData[i] != null) { - basicTargetDTO.setActionList(policyEditorData[i]); - } - i++; - if (policyEditorData[i] != null) { - basicTargetDTO.setActionId(policyEditorData[i]); - } - i++; - if (policyEditorData[i] != null) { - basicTargetDTO.setActionDataType(policyEditorData[i]); - } - i++; - - if (policyEditorData[i] != null) { - basicTargetDTO.setFunctionOnEnvironment(policyEditorData[i]); - } - i++; - if (policyEditorData[i] != null) { - basicTargetDTO.setEnvironmentList(policyEditorData[i]); - } - i++; - if (policyEditorData[i] != null) { - basicTargetDTO.setEnvironmentId(policyEditorData[i]); - } - i++; - if (policyEditorData[i] != null) { - basicTargetDTO.setEnvironmentDataType(policyEditorData[i]); - } - i++; - - basicPolicyDTO.setTargetDTO(basicTargetDTO); - List basicRuleDTOs = createBasicRuleDTOs(policyEditorData, i); - if (basicRuleDTOs != null && basicRuleDTOs.size() > 0) { - basicPolicyDTO.setBasicRuleDTOs(basicRuleDTOs); - } - - return basicPolicyDTO; - } - - public static List createBasicRuleDTOs(String[] policyEditorData, int nextIndex) { - - List basicRuleDTOs = new ArrayList(); - if (policyEditorData != null) { - while (true) { - if (policyEditorData.length == nextIndex) { - break; - } - BasicRuleDTO basicRuleDTO = createBasicRuleDTO(policyEditorData, nextIndex); - nextIndex = nextIndex + EntitlementPolicyConstants.BASIC_POLICY_EDITOR_RULE_DATA_AMOUNT; - basicRuleDTO.setCompletedRule(true); - basicRuleDTOs.add(basicRuleDTO); - } - } - return basicRuleDTOs; - } - - public static BasicRuleDTO createBasicRuleDTO(String[] policyEditorDataForRule, int nextIndex) { - - BasicRuleDTO basicRuleDTO = new BasicRuleDTO(); - int i = nextIndex; - - if (policyEditorDataForRule[i] != null) { - basicRuleDTO.setRuleId(policyEditorDataForRule[i]); - } - i++; - if (policyEditorDataForRule[i] != null) { - basicRuleDTO.setRuleEffect(policyEditorDataForRule[i]); - } - i++; - if (policyEditorDataForRule[i] != null) { - basicRuleDTO.setRuleDescription(policyEditorDataForRule[i]); - } - i++; - - if (policyEditorDataForRule[i] != null) { - basicRuleDTO.setPreFunctionOnResources(policyEditorDataForRule[i]); - } - i++; - if (policyEditorDataForRule[i] != null) { - basicRuleDTO.setFunctionOnResources(policyEditorDataForRule[i]); - } - i++; - if (policyEditorDataForRule[i] != null) { - basicRuleDTO.setResourceList(policyEditorDataForRule[i]); - } - i++; - if (policyEditorDataForRule[i] != null) { - basicRuleDTO.setResourceId(policyEditorDataForRule[i]); - } - i++; - if (policyEditorDataForRule[i] != null) { - basicRuleDTO.setResourceDataType(policyEditorDataForRule[i]); - } - i++; - - if (policyEditorDataForRule[i] != null) { - basicRuleDTO.setPreFunctionOnSubjects(policyEditorDataForRule[i]); - } - i++; - if (policyEditorDataForRule[i] != null) { - basicRuleDTO.setFunctionOnSubjects(policyEditorDataForRule[i]); - } - i++; - if (policyEditorDataForRule[i] != null) { - basicRuleDTO.setSubjectList(policyEditorDataForRule[i]); - } - i++; - if (policyEditorDataForRule[i] != null) { - basicRuleDTO.setSubjectId(policyEditorDataForRule[i]); - } - i++; - if (policyEditorDataForRule[i] != null) { - basicRuleDTO.setSubjectDataType(policyEditorDataForRule[i]); - } - i++; - - - if (policyEditorDataForRule[i] != null) { - basicRuleDTO.setPreFunctionOnActions(policyEditorDataForRule[i]); - } - i++; - if (policyEditorDataForRule[i] != null) { - basicRuleDTO.setFunctionOnActions(policyEditorDataForRule[i]); - } - i++; - if (policyEditorDataForRule[i] != null) { - basicRuleDTO.setActionList(policyEditorDataForRule[i]); - } - i++; - if (policyEditorDataForRule[i] != null) { - basicRuleDTO.setActionId(policyEditorDataForRule[i]); - } - i++; - if (policyEditorDataForRule[i] != null) { - basicRuleDTO.setActionDataType(policyEditorDataForRule[i]); - } - i++; - - if (policyEditorDataForRule[i] != null) { - basicRuleDTO.setPreFunctionOnEnvironment(policyEditorDataForRule[i]); - } - i++; - if (policyEditorDataForRule[i] != null) { - basicRuleDTO.setFunctionOnEnvironment(policyEditorDataForRule[i]); - } - i++; - if (policyEditorDataForRule[i] != null) { - basicRuleDTO.setEnvironmentList(policyEditorDataForRule[i]); - } - i++; - if (policyEditorDataForRule[i] != null) { - basicRuleDTO.setEnvironmentId(policyEditorDataForRule[i]); - } - i++; - if (policyEditorDataForRule[i] != null) { - basicRuleDTO.setEnvironmentDataType(policyEditorDataForRule[i]); - } - - return basicRuleDTO; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/META-INF/component.xml b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/META-INF/component.xml deleted file mode 100644 index d4d53ef11466..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/META-INF/component.xml +++ /dev/null @@ -1,145 +0,0 @@ - - - - - - my_pap_menu - my.pap - org.wso2.carbon.identity.entitlement.ui.i18n.Resources - identity_entitlement_menu - # - region1 - 60 - manage - ../entitlement/images/policy.gif - /permission/admin/manage/identity/entitlement/pap/policy/view - - - policy_pap_menu - my.pap.policy - org.wso2.carbon.identity.entitlement.ui.i18n.Resources - my_pap_menu - ../entitlement/index.jsp - region1 - 5 - manage - ../entitlement/images/policies.gif - /permission/admin/manage/identity/entitlement/pap/policy/view - - - policy_publish_menu - identity.policy.publish - org.wso2.carbon.identity.entitlement.ui.i18n.Resources - my_pap_menu - ../entitlement/policy-publish.jsp - region1 - 9 - manage - ../entitlement/images/publish.gif - /permission/admin/manage/identity/entitlement/pap/subscriber - - - - - my_pdp_menu - my.pdp - org.wso2.carbon.identity.entitlement.ui.i18n.Resources - identity_entitlement_menu - # - region1 - 70 - manage - ../entitlement/images/policy.gif - /permission/admin/manage/identity/entitlement/pdp/view - - - pdp_policy_menu - my.pdp.policies - org.wso2.carbon.identity.entitlement.ui.i18n.Resources - my_pdp_menu - ../entitlement/my-pdp.jsp - region1 - 6 - manage - ../entitlement/images/policies.gif - /permission/admin/manage/identity/entitlement/pdp/view - - - pdp_config_menu - my.pdp.extension - org.wso2.carbon.identity.entitlement.ui.i18n.Resources - my_pdp_menu - ../entitlement/pdp-manage.jsp - region1 - 7 - manage - ../entitlement/images/config.gif - /permission/admin/manage/identity/entitlement/pdp/view - - - policy_search_menu - identity.policy.search - org.wso2.carbon.identity.entitlement.ui.i18n.Resources - my_pdp_menu - ../entitlement/advance-search.jsp - region1 - 10 - manage - ../entitlement/images/search-top.png - /permission/admin/manage/identity/entitlement/pdp - - - - - my_pep_menu - xacml - org.wso2.carbon.identity.entitlement.ui.i18n.Resources - tools_menu - # - region5 - 4 - tools - ../entitlement/images/policy.gif - /permission/admin/manage/identity/entitlement/pep - - - policy_tryit_menu - identity.policy.tryit - org.wso2.carbon.identity.entitlement.ui.i18n.Resources - my_pep_menu - ../entitlement/create-evaluation-request.jsp - region5 - 5 - tools - ../entitlement/images/evaluate.png - /permission/admin/manage/identity/entitlement/pep - - - - - - - - entitlement-policy - - org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyUploadExecutor - - - - diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/org/wso2/carbon/identity/entitlement/ui/i18n/Resources.properties b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/org/wso2/carbon/identity/entitlement/ui/i18n/Resources.properties deleted file mode 100644 index 766dc0074362..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/org/wso2/carbon/identity/entitlement/ui/i18n/Resources.properties +++ /dev/null @@ -1,469 +0,0 @@ -identity.entitlement=Policies -identity.pap=Administration -identity.pdp.config=Configuration -identity.pdp.policy=Policy -identity.policy.tryit=TryIt -try.this = Try -xacml=XACML -next=Next -back=Back -prev=prev -my.pdp=PDP -my.pap=PAP -my.pep=PEP -my.pap.policy=Policy Administration -my.pdp.policy=PDP Policy View -my.pdp.policies=Policy View -my.pdp.extension=Extension -eval.policy=Evaluate Policy -eval.ent.policy=Evaluate Entitlement Policy -eval.ent.policy.for.policyId=Evaluation is done with one policy which policy id is -ent.eval.policy.request=Entitlement Policy Evaluation Request [XACML] -ent.eval.policy.response=Entitlement Policy Response [XACML] -evaluate=Evaluate -test.evaluate=Test Evaluate -pdp.evaluate=Evaluate With PDP -back.evaluate=Back To Evaluate -cancel=Cancel -clear=Clear -order=Edit Order -import.policy=Import Policy -import.new.ent.policy=Import New Entitlement Policy -ent.clear.cache=Clear Decision Cache -import.ent.policy=Import Entitlement Policy -ent.policy=Entitlement Policy -upload=Upload -ent.policies=Entitlement Policies -user.ent=User Entitlement -add.new.ent.policy=Add New Entitlement Policy -eval.ent.policies=Evaluate Entitlement Policies -create.ent.policy=Create New Entitlement Policy -available.ent.policies=Available Entitlement Policies -no.policies.defined=No policies defined -no.policies.reference.defined=No policies references are defined -remove.policy=Remove Policy -edit.policy=Edit Policy -versions=Versions -ent.policy.added.successfully=Entitlement policy is added to PAP policy store successfully. -error.while.retreiving.policies=Error while retrieving policy from the backend. Error is {0} -invalid.request=Invalid entitlement policy request -empty.form=At least one of the 4 fields should be non-empty -empty.request=Entitlement policy request cannot be empty -imported.successfuly=Entitlement policy imported successfully -select.policy.to.upload=Please select a policy to upload -error.while.loading.policy=Error while loading entitlement policies. -error.while.loading.policy.resource=Error while loading entitlement policy resource -error.while.performing.advance.search=Error while performing Advance Search -error.while.publishing.policies=Error while publishing policies -error.while.ordering.invalid.policy.value=Error while ordering entitlement policies. Please enter a valid value. -error.while.ordering.policy=Error while ordering entitlement policies. Error is : -cannot.order.policies=Can not re-order policies. You are not authorize for all the policies in PDP -policy.could.not.be.deleted=Policy could not be deleted. Error is : -subscriber.could.not.be.deleted=Subscriber could not be deleted. Error is : -policy.could.not.be.rollback=Policy could not be rollback. Error is : -policy.pdp.deleted.successfully=Entitlement Policies will be de-promoted from PDP. Please Refresh the page after few seconds to check the new status. -policy.deleted.successfully=Entitlement policies are deleted successfully. -policy.rollbacked.successfully=Entitlement is rollbacked successfully. -updated.successfully=Entitlement policy is updated successfully. -ordered.successfully=Entitlement policy will be ordered. Please Refresh the page after few seconds to check the new status. -policy.enabled.successfully=Entitlement Policy will be enabled. Please Refresh the page after few seconds to check the new status. -policy.disable.successfully=Entitlement Policy will be disabled. Please Refresh the page after few seconds to check the new status. -error.while.enabling.policy=Policy could not be enabled or disabled. Error is : -invalid.policy.not.updated=Entitlement policy is not updated. Error is : -delete=Delete -cache.clear.message=You are about to clear decision cache. Do you want to proceed? -attribute.cache.clear.message=You are about to clear attribute cache. Do you want to proceed? -refresh.finder=You are about to re-initialize the finder. Do you want to proceed? -remove.message1=You are about to remove -remove.message2=. Do you want to proceed? -entitlement.policy.creation=Entitlement Policy Creation Wizard -add.policy.element =Add Policy Element -edit.policy.element =Edit Policy Element -policy.name=Entitlement Policy Name -policy.description=Entitlement Policy Description -policy.based.on=This policy is based on -policy.create= Create -policy.name.is.required=Policy Name is required -policy.name.is.conformance=Policy Name is invalid -policy.name.with.space=Spaces is not allowed in Policy Name -policy.name.with.special-character=Special character is not allowed in Policy Name -policy.description.is.required=Policy Description is required -add=Add -rule.combining.algorithm=Rule Combining Algorithm -finish=Finish -match.id=Match Id -attribute.data.type=Attribute Data Type -attribute.value=Attribute Value -attribute.designator.data.type=Attribute Designator Data Type -attribute.id=Attribute Id -issuer=Issuer -must.present=Must Be Present -subject.category=Subject Category -edit=Edit -view=View -save=Save -view.status=View Status -refresh=Refresh -rollback=RollBack -add.new.subject.element=Add New Subject Element -add.new.action.element=Add New Action Element -add.new.resource.element=Add New Resource Element -add.new.environment.element=Add New Environment Element -add.subject.element=Add Subject Element -add.action.element=Add Action Element -add.resource.element=Add Resource Element -add.environment.element=Add Environment Element -edit.subject.element=Edit Subject Element -edit.action.element=Edit Action Element -edit.resource.element=Edit Resource Element -edit.environment.element=Edit Environment Element -add.match.element=Add Match Element -rule.id=Rule Id -rule.effect=Rule Effect -rule.description=Rule Description -rule.id.is.required=Rule id is required -rule.id.is.existing=Rule id can not be duplicated. -policy.id.is.existing=Policy id can not be duplicated. -rule.id.is.not.conformance=Rule id is not valid. -rule.effect.is.required=Rule effect is required -add.target.element=Add Target Element -add.condition.element=Add Condition Element -expression.element=Select Expression -add.new.rule.element=Add New Rule Element -add.expression=Add Expression Element -add.apply.element=Add Apply Element -add.apply.match.element=Add New Apply Element -edit.apply.match.element=Edit Apply Element -add.new.action.match=Add New Action Match -add.new.resource.match=Add New Resource Match -add.new.environment.match=Add New Environment Match -function.id=Function Name -add.attribute.value.element=Add Attribute Value Element -attribute.value.element=Attribute Value Element -functionId.is.required=Function Id is required -edit.apply.element=Edit Apply Element -edit.attribute.value.element=Edit Attribute Value Element -add.rule.element=Add Rule Element -add.rule.elements=Add Rule Elements -edit.rule.element=Edit Rule Element -edit.rule.elements=Edit Rule Elements -edit.target.element=Edit Target Element -edit.condition.element=Edit Condition Element -attribute.designator.element=Attribute Designator Element -attribute.selector.element=Attribute Selector Element -attribute.selector.data.type=Attribute Selector Data Type -request.context.path=Request Context Path -attribute.value.is.required=Attribute Value is required -add.policy.Element=Add Policy Element -add.subject.attribute.designator.element=Add Subject Attribute Designator Element -add.action.attribute.designator.element=Add Action Attribute Designator Element -add.resource.attribute.designator.element=Add Resource Attribute Designator Element -add.environment.attribute.designator.element=Add Environment Attribute Designator Element -attribute.id.is.required=Attribute ID is required -error.while.creating.policy=Error while creating entitlement policy using policy editor. -error.while.adding.policy=Error while adding entitlement policy. -permit=Permit -deny=Deny -delete.this.row=Delete This Row -resource.name=Resource Name -parent.resource.name=Parent Resource Name -resource.names=Resource Names -child.resource.names=Child Resource Names -subject.names=Subject Names -environment.names=Environment Name -roles.users=User's -access.name=Access -delete.rule=Delete -add.new.entry=Add New Rule Entry -select.roles=Select Roles -select.resource=Select Resource -resource=Resource -resources=Resources -subject=Subject -action=Action -environment=Environment -effect=Effect -select.resources.registry=Select Resources From Registry -conf.registry=Configuration Registry -gov.registry=Governance Registry -select.resources.discovery=Select Resources From Discovery Proxy -function.on.resources=Function Apply On Resources -function.on.subjects=Function Apply On Subjects -function.on.actions=Function Apply On Actions -select.subjects=Select Subjects -no.subjects.filtered=No Matching Subjects Found -select.subject.type=Select Subject Type -list.subjects=List Subject Names -subject.search=Search -select.all=Select All -unSelect.all=UnSelect All -select.discovery.resources=Select Discovery Resources -configure.wsdiscovery=Configure WS-Discovery By Visiting WS-Discovery Control Panel -create.basic.ent.policy=Create Basic Entitlement Policy -function.on.environment=Function Apply On Environment -add.new.entitlement.rule=Define Entitlement Rule(s) -add.new.obligations=Define Policy Obligations or Advices -add.new.policy.references=Define Policy references -add.extend.attribute=Define Extend Attribute Values -rule.name=Rule Name -user.attribute=User Attribute -update=Update -rollaback=RollBack -reset=Reset -policy.apply.to=This Policy is going to evaluated, Only when followings are matched.... -policy.set.apply.to=The Policy Set Applies To -import.entitlement.policy.from=Import Entitlement Policy From -function.element.value=Function Element Value -subject.match=Subject Match -resource.match=Resource Match -action.match=Action Match -environment.match=Environment Match -attributeValue.element.id=Attribute Value Element Id -select.attribute.designator.type=Select Attribute Designator Type -not.attribute.value.element.defined=No attribute Value elements defined yet -not.attribute.designator.element.defined=No attribute Designator elements defined yet -not.attribute.selector.element.defined=No attribute Selector elements defined yet -attribute.designator.element.id=Attribute Designator Element Id -attribute.selector.element.id=Attribute Selector Element Id -no.subject.match.define=No subject match elements defined yet -no.action.match.define=No action match elements defined yet -no.resource.match.define=No resource match elements defined yet -no.environment.match.define=No environment match elements defined yet -no.subject.define=No subject elements defined yet -no.action.define=No action elements defined yet -no.resource.define=No resource elements defined yet -no.environment.define=No environment elements defined yet -attribute.designator.selector.element.is.required=Attribute designator or selector element is required -no.rule.element.define=No rules defined yet -match.element.id=Match Element Id -function.element=Function Element -no.apply.element.define=No apply elements defined yet -apply.element.id=Apply Element Id -apply.element=Apply Element -resource.names.are=Resource -action.name=Action -action.names=Action Name -subject.name=Subject Name -subject.attribute=Subject Attribute Name -subject.attribute.value=Subject Attribute Value -create.request.using.editor=Create Request Using Editor -policy.could.not.be.edited=Policy could not be edited using policy editor wizard -policy.could.not.be.edited.with.basic=Policy could not be edited using Basic policy editor wizard. Please use the advanced wizard -subject.element.name=Subject Element Name -action.element.name=Action Element Name -resource.element.name=Resource Element Name -environment.element.name=Environment Element Name -create.policy=Create XACML Policy -edit.xacml.policy=Edit XACML Policy -create.policy.set=Create XACML Policy Set -edit.xacml.policy.set=Edit XACML Policy Set -select.registry.resource=Select Registry Resource -create.request=Create Request -create.evaluation.request=Create Evaluation Request -enable.policy=Enable -disable.policy=Disable -policy.order=Order -policy.order.header=Policy Order -promote.policy=Promote To PDP -sync.policy=Sync With PDP -not.promote.policy=Remove From PDP -cache.clear.error=Error occurred while clearing decision cache. -use.advance.view=Use Advanced View -use.xml.view=Use XML View -policy.set.name=Policy Set Name -policy.combining.algorithm=Policy Combining Algorithm -policy.set.description=Policy Set Description -add.new.policy.set=Add New Policy Set -select.polices=Select Policies -select.policy.set=Select Policy Sets -list.policy.set=List Policy Set -no.policy.set.filtered=No Matching policy Sets Founded -list.policies=List Policies -no.policies.filtered=No Matching policies Founded -error.while.creating.policy.set=Error while creating entitlement policy Set. -select.policies.policySets=Select Already Defined Policies or Policy Sets -selected.policies=Selected Policies -no.selected.policy=No policies are selected -create.entitlement.policy.set=Create Entitlement Policy Set -create.entitlement.policy=Create Entitlement Policy -create.simple.entitlement.policy=Create Simple Policy -all=ALL -policy.type=Policy Type -policy.status.type=Policy Status Type -search.policy=Search Policy -search.status.by.user=Search Status by user -search.status.by.policy=Search Status by policy -search=Search -enter.subscriber.search=Enter subscriber search pattern -select.policies.to.be.deleted=Please select the policies to be deleted. -select.subscribers.to.be.deleted=Please select the subscribers to be deleted. -delete.all.policies.prompt=Do you want to delete all policies? -delete.all.subscribers.prompt=Do you want to delete all subscribers? -de.promote.policy.message=Do you want to de-promote this policy from PDP? This would completely remove policy from PDP. You can disable policy, if you only want to make it unavailable for PDP evaluation. Do you want to continue? -disable.policy.message=Do you want to disable this policy? After disabling policy would not be available for PDP evaluation. -enable.policy.message=Do you want to enable this policy? After enabling policy would be available for PDP evaluation. -delete.services.on.page.prompt=Do you want to delete the selected policies? -delete.subscribers.on.page.prompt=Do you want to delete the selected subscribers? -select.policies.to.be.published=Please select the policies to be published. -publish.all.policies.prompt=Do you want to publish all policies? -publish.services.on.page.prompt=Do you want to publish the selected polices? -select.subscriber.to.be.published=Please select subscriber to publish -no.subscriber.to.be.published=No subscribersList are configured -publish.to.all.subscribersList.prompt=Do you want to publish to all subscribers? -publish.selected.subscriber.prompt=Do you want to publish to the selected subscribers? -publish.pdp.subscriber.prompt=You are going to publish to PDP. Do you want to continue? -publish.to.all.subscribers.prompt=Do you want to publish to all subscribers? -selectAllInPage=Select all in this page -selectAll=Select all in all pages -no.subscribers.found=No matching subscribers are found -error.loading.subscribers=Error while loading subscribers. Error is : -selectNone=Select none -no.rule.defined=No rules defined yet -no.subscribersList.defined=No subscribersList defined yet -no.status.defined=No status can be found -search.results=Search Results -advance.search=Advanced Search -entitled.data.search=Search Entitled Data -attribute.type=Attribute Type -subject.type=Subject Type -attribute.dataType=Attribute Data Type -policy.id=Policy Id -id=Id -type=Type -actions=Actions -entitlement.policy.id=Entitlement Policy Id -policy.version=Entitlement Policy Version -policy.version.created.time=Entitlement Policy Version Created Time -policy.version.created.user=Entitlement Policy Version Created User -policy.version.view=Policy View -policy.viewer=Policy Viewer -policy.reference=Policy Reference -policy.version.manage=Manage Policy Version -policy.action=Policy Action -policy.user=Performed By -target=Target -target.action=Target Action -no.result.found=No Result is found -policy.search=Policy Search -attribute.search=Attribute Search -identity.policy.search=Search -advance.search.message1=This search finds the resources that given subject can access -subject.id=Subject Id -user.role=User / Role Name -enter.attribute.search.pattern=Enter attribute search pattern -ent.clear.attribute.cache=Clear Attribute Cache -define.policy.policy.sets=Define Policies and Policy Sets -add.to.policy.set=Add to Policy Set -subject.name.is.required=User or Role name is required -select.attribute.values=Select Attribute Values -select.meta.data.finder=Select Meta Data Finder Module -tree.of.attribute.values=Tree Of Attribute Values -select=Select -order.not.null=Policy Order can not be empty -order.not.integer=Policy Order can be Integer -selected.attribute.values=Selected Attribute Values -select.attribute.dataType=Select Attribute DataType -select.attribute.id=Select Attribute Id -enable.child.search=Enable search through child resources -error.while.retrieving.attribute.values=Error retrieving attribute values -no.entitlement.data.defined=No entitlement data is found for this category -no.entitlement.data.finder.defined=No entitlement data finder module is defined for this category -attribute.finder.module=Entitlement Data module -select.attribute.data=Select Entitlement Data -attribute.values=Attribute Values -rule.target= Rule's conditions are evaluated Only when followings are matched.... -rule.condition=Define your conditions by using followings.... -rule.obligation=Define your obligations or advices for sending back to PEP... -error.while.creating.request=Error while creating XACML request. -identity.policy.publish=Policy Publish -policy.publisher=Policy Publisher -publish.policy=Publish Policy -select.policy.publisher=Select Policy Publisher -select.publish.data=Select Publish Data -add.new.policy=Add New Policy -add.new.policy.description=Add New Policy -add.new.policy.method=Policy creation methods -add.new.policy.simple=Simple Policy Editor -add.new.policy.simple.description=You can define simple access control rules using this editor. Then you can convert these rules in to XACML 3.0 policy. Categories are limited to Resource, Action, Subject and Environment. Attribute Id and Data Types are configurable. You can do it from -add.new.policy.basic=Basic Policy Editor -add.new.policy.basic.description= You can create a basic XACML 3.0 policy. Categories are limited to Resource, Action, Subject and Environment. This editor is configurable. You can do it from -add.new.policy.editor=Standard Policy Editor -add.new.policy.editor.description= You can create a normal XACML 3.0 policy. Here you can define custom categories, attributeIs and DataTypes. Also you can add Obligations and Advices in to your rules and policy. This editor is configurable. You can do it from -add.new.policy.set.editor=Policy Set Editor -add.new.policy.set.editor.description= You can create a XACML 3.0 policy sets. Here you can define Policy Set Target, Obligations, Advices and References to already defined policies or policy sets. This editor is configurable. You can do it from -add.new.policy.import=Import Existing Policy -add.new.policy.import.description= You can import existing XACML policy from file system or from carbon registry -add.new.policy.write=Write Policy in XML -add.new.policy.write.description= You can write XACML policy using XML editor -here=here -policy.status=Policy Status -select.publish.actions= Select policy publishing action -select.publish.version= Select policy version -select.publish.order= Select policy order -select.publish.enable.disable= Select policy Enable/Disable -select.publish.enable.disable.policies= Select Enable/Disable of Policies -select.subscriber= Select Subscriber -select.publish.version.current= Use current policy version -select.publish.version.older= Use older policy version -select.publish.order.default= Use default policy order -select.publish.enable=Publish As Enabled Policy -select.publish.disable=Publish As Disabled Policy -select.publish.enable.policies=Publish as Enabled Policies -select.publish.disable.policies=Publish as Disabled Policies -select.publish.order.custom= Define policy order -select.publish.actions.add= Add Policy -select.publish.actions.update= Update Policy -select.publish.actions.delete= Delete Policy -select.publish.actions.enable= Enable Policy -select.publish.actions.disable= Disable Policy -select.publish.actions.order= Order Policy -select.publish.actions.add.policies= Add Selected Policies -select.publish.actions.update.policies= Update Selected Policies -select.publish.actions.delete.policies= Delete Selected Policies -select.publish.actions.enable.policies= Enable Selected Policies -select.publish.actions.disable.policies= Disable Selected Policies -select.publish.actions.promote= Promote Policy -select.publish.version.no=As multiple policies are published. Latest version of the policies are used to publish. -subscriber.list=Policy Subscribers -subscriber.name= Subscriber Name -status=Status -details=Details -time.stamp=Time Stamp -status.success=Succeed -status.fail=Failed -back.to.subscribersList=<< Back to Subscriber List -back.to.policies=<< Back to Policy List -subscriber.id=Subscriber Id -subscriber.url=Subscriber Url -authentication=Authentication Scheme -subscriber.username=Subscriber User Name -subscriber.password=Subscriber Password -subscriber.clientKey=Key for subscriber -subscriber.clientSecret=Secret for subscriber -subscriber.accessToken=Access token for subscriber -no.policy.editor.data=Policy Editor data can not loaded. Please check with policy editor configurations -add.subscriber=Add Subscriber -show.subscriber=Subscriber Details -subscriber.configurations=Subscriber Configurations -subscriber.status=Subscriber Status -subscriber.id.is.required=Subscriber id is required -subscriber.url.is.required=Subscriber url is required -policy.editor.config.can.not.update=Policy editor config could not be updated. Error is : -policy.editor.config.update=Policy editor config is updated successfully -publish=Publish -publish.to.pdp=Publish To My PDP -publish.selected=Publish -publish.to.all=Publish To all -publish.all.policies=Publish All -select.module=Select Module -add.new.subscriber=Add Subscriber -pdp.configuration=PDP Configurations -policy.administration=Policy Administration -policy.editor.config=Policy Editor Configuration -policy.finder=Policy Finder Extensions -attribute.finer=Attribute Finder Extensions -resource.finder=Resource Finder Extensions -view.finder=Extension Details -back.to.pdp.config=<< Back to PDP Configurations -configure.authorization=Configure Authorization -unsafe.char.validation.msg=For security measures following characters are restricted < > ` \\\" diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/add-policy.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/add-policy.jsp deleted file mode 100644 index e73d741be8df..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/add-policy.jsp +++ /dev/null @@ -1,131 +0,0 @@ - -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> -<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" - prefix="carbon"%> -<%@ page import="org.wso2.carbon.identity.entitlement.common.EntitlementConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.common.PolicyEditorEngine" %> -<%@ page import="org.wso2.carbon.identity.entitlement.common.PolicyEditorException" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIMessage" %> -<%@ page import="java.util.ResourceBundle" %> -<%@ page import="org.owasp.encoder.Encode" %> -<% - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - String type = request.getParameter("type"); - if(request.getParameter("editorConfig") != null){ - try { - PolicyEditorEngine.getInstance().persistConfig(type, request.getParameter("editorConfig")); - String message = resourceBundle.getString("policy.editor.config.update"); - %> - - <% - } catch (PolicyEditorException e) { - String message = resourceBundle. - getString("policy.editor.config.can.not.update") + e.getMessage(); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.ERROR, request); - %> - - - <% - } - } -%> - - -
-

-
- <%--

--%> - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - -
- - - -
- - - -
- - - - -
- -
- -
-
-
-
- \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/add-subscriber.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/add-subscriber.jsp deleted file mode 100644 index fc3105a8b6ac..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/add-subscriber.jsp +++ /dev/null @@ -1,340 +0,0 @@ - -<%@page import="org.apache.axis2.context.ConfigurationContext"%> -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> -<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" - prefix="carbon"%> -<%@ page import="org.wso2.carbon.CarbonConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.PublisherDataHolder" %> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.PublisherPropertyDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.EntitlementPolicyConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.PropertyDTOComparator" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIMessage" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %> -<%@ page import="org.wso2.carbon.utils.ServerConstants" %> -<%@ page import="java.util.ResourceBundle" %> -<%@ page import="org.owasp.encoder.Encode" %> - -<% - String subscriberId; - PublisherDataHolder subscriber = null; - PublisherDataHolder[] dataHolders; - PublisherPropertyDTO[] propertyDTOs = null; - String selectedModule = null; - String forwardTo = null; - boolean view = false; - String paginationValue = "" ; - - EntitlementPolicyAdminServiceClient client = null; - - - int numberOfPages = 0; - String isPaginatedString = request.getParameter("isPaginated"); - if (isPaginatedString != null && isPaginatedString.equals("true")) { - client = (EntitlementPolicyAdminServiceClient) session.getAttribute(EntitlementPolicyConstants.ENTITLEMENT_SUBSCRIBER_CLIENT); - } - - - - String pageNumber = request.getParameter("pageNumber"); - if (pageNumber == null) { - pageNumber = "0"; - } - int pageNumberInt = 0; - try { - pageNumberInt = Integer.parseInt(pageNumber); - } catch (NumberFormatException ignored) { - } - - - selectedModule = request.getParameter("selectedModule"); - String viewString = request.getParameter("view"); - subscriberId = request.getParameter("subscriberId"); - dataHolders = (PublisherDataHolder[]) session. - getAttribute(EntitlementPolicyConstants.ENTITLEMENT_PUBLISHER_MODULE); - - if((viewString != null)){ - view = Boolean.parseBoolean(viewString); - } - - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = - (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants. - CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - - try { - - if (client == null) { - - client = new EntitlementPolicyAdminServiceClient(cookie, - serverURL, configContext); - session.setAttribute(EntitlementPolicyConstants.ENTITLEMENT_SUBSCRIBER_CLIENT, client); - } - - if(subscriberId != null){ - subscriber = client.getSubscriber(subscriberId); - if(subscriber != null){ - propertyDTOs = subscriber.getPropertyDTOs(); - selectedModule = subscriber.getModuleName(); - dataHolders = new PublisherDataHolder[]{subscriber}; - } - } else { - if(dataHolders == null){ - dataHolders = client.getPublisherModuleData(); - } - if(dataHolders != null){ - session.setAttribute(EntitlementPolicyConstants.ENTITLEMENT_PUBLISHER_MODULE, dataHolders); - if(selectedModule != null){ - for(PublisherDataHolder holder : dataHolders){ - if(selectedModule.equals(holder.getModuleName())){ - propertyDTOs = holder.getPropertyDTOs(); - break; - } - } - } - } - } - if(propertyDTOs != null){ - session.setAttribute(EntitlementPolicyConstants.ENTITLEMENT_PUBLISHER_PROPERTY, propertyDTOs); - java.util.Arrays.sort(propertyDTOs , new PropertyDTOComparator()); - } - - paginationValue = "isPaginated=true&view="+viewString+"&subscriberId="+subscriberId; - } catch (Exception e) { - String message = resourceBundle.getString("error.while.performing.advance.search"); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.ERROR, request); - forwardTo = "../admin/error.jsp"; -%> - - - -<% - } -%> - - - - - - - - - - - - - - - -
- <% - if(view){ - %> -

- <% - } else { - %> -

- <% - } - %> -
- <% - if(view){ - %> -
- -
- <% - } - %> -
- <% - if(view){ - %> -
- - <% - if(propertyDTOs != null){ - for(PublisherPropertyDTO dto : propertyDTOs){ - if(dto.getSecret()){ - continue; - } - if(dto.getDisplayName() != null && dto.getValue() != null){ - %> - - - - - <% - } - } - } - %> -
<%=Encode.forHtmlContent(dto.getDisplayName())%><%=Encode.forHtmlContent(dto.getValue())%>
-
- -
-
-
- <% - } else { - %> - - - - - - - <% - if(propertyDTOs != null){ - for (PublisherPropertyDTO dto : propertyDTOs) { - if(dto.getDisplayName() == null){ - continue; - } - String inputType = "text"; - if (dto.getSecret()) { - inputType = "password"; - } - %> - - - - - <% - } - } - %> - - - -
* - -
<%=Encode.forHtmlContent(dto.getDisplayName())%> - <% - if(dto.getRequired()){ - %> - * - <% - } - %> - - <% if(dto.getValue() != null) {%> - readonly='readonly' <% } %> /> - <% - } else { - %> - autocomplete="off" <% } %>/> - <% - } - %> -
- value="" onclick="doUpdate();" <%} else { %> - value="" onclick="doAdd();" <% } %> /> - -
- <% - } - %> -
-
-
-
diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/advance-search.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/advance-search.jsp deleted file mode 100644 index a1ef9ab30c2e..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/advance-search.jsp +++ /dev/null @@ -1,358 +0,0 @@ - -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> -<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" - prefix="carbon"%> -<%@ page import="org.apache.axis2.context.ConfigurationContext"%> -<%@ page import="org.wso2.carbon.CarbonConstants"%> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.EntitledAttributesDTO"%> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.EntitledResultSetDTO"%> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.EntitlementPolicyConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementServiceClient" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIMessage"%> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %> -<%@ page import="org.wso2.carbon.utils.ServerConstants" %> -<%@ page import="java.util.HashSet" %> -<%@ page import="java.util.ResourceBundle" %> -<%@ page import="java.util.Set" %> -<%@ page import="org.owasp.encoder.Encode" %> -<% - String subjectType = ""; - String action = ""; - String subjectName = ""; - String subjectId = ""; - String resourceName = ""; - String enableChildSearchParameter; - boolean enableChildSearch; - String[] subjectTypes = new String[]{"Role","User"}; - EntitledResultSetDTO results = null; - EntitledAttributesDTO[] entitledAttributes = null; - String forwardTo; - - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = - (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants. - CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - subjectType = (String)request.getParameter("subjectType"); - if("Role".equals(subjectType)) { - subjectId = EntitlementPolicyConstants.SUBJECT_ID_ROLE; - } else { - subjectType = "User"; - subjectId = EntitlementPolicyConstants.SUBJECT_ID_DEFAULT; - } - - String userSelectedSubjectId = (String)request.getParameter("subjectId"); - if(userSelectedSubjectId != null && !"".equals(userSelectedSubjectId)){ - subjectId = userSelectedSubjectId; - } - subjectName = (String)request.getParameter("subjectName"); - resourceName = (String) request.getParameter("resourceName"); - action = (String)request.getParameter("action"); - enableChildSearchParameter = (String)request.getParameter("enableChildSearch"); - if("true".equals(enableChildSearchParameter)){ - enableChildSearch = true; - } else { - enableChildSearch =false; - } - - try { - if (subjectName != null) { - EntitlementServiceClient client = new EntitlementServiceClient(cookie, - serverURL, configContext); - results = client.getEntitledAttributes(subjectName, resourceName, subjectId, action, - enableChildSearch); - - if(EntitlementPolicyConstants.SEARCH_ERROR.equals(results.getMessageType())){ -%> - - - -<% - } else { - entitledAttributes = results.getEntitledAttributesDTOs(); - } - } - } catch (Exception e) { - String message = resourceBundle.getString("error.while.performing.advance.search"); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.ERROR, request); - forwardTo = "../admin/error.jsp"; -%> - - - -<% - } -%> - - - - - - - - - - - - - -
-

- <% - if (CarbonUIUtil.isUserAuthorized(request, "/permission/admin/manage/identity/entitlement/pdp")) { - %> -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* - -
* - <% - if (subjectName != null && !subjectName.equals("")) { - %> - - <% - } else { - %> - - <% - } - %> -
* - -
- <% - if (action != null && !action.equals("")) { - %> - - <% - } else { - %> - - <% - } - %> -
- <% - if (resourceName != null && !resourceName.equals("")) { - %> - - <% - } else { - %> - - <% - } - %> -
- checked="checked" <%}%> type="checkbox" name="enableChildSearch" value="true" /> -
- -
-
- - - - - <% - if(action == null || action.trim().length() < 1){ - %> - - - <% - } else { - %> - - <% - } - %> - - - - - <% - if(entitledAttributes != null && entitledAttributes.length > 0) { - Set resourceSet = new HashSet (); - for(EntitledAttributesDTO result : entitledAttributes){ - if(result.getAllResources()){ - resourceSet.add("ANY"); - } else { - resourceSet.add(result.getResourceName()); - } - } - for(String resource : resourceSet){ - %> - - - <% - - if(action == null || action.trim().length() < 1){ - Set actionSet = new HashSet(); - String actionNames = ""; - for(EntitledAttributesDTO result : entitledAttributes){ - if(result.getAllResources()){ - if(result.getAllActions()){ - actionSet.add("ANY"); - } else { - actionSet.add(result.getAction()); - } - } else if(resource.equals(result.getResourceName())){ - if(result.getAllActions()){ - actionSet.add("ANY"); - } else { - actionSet.add(result.getAction()); - } - } - } - - for(String actionName : actionSet){ - if("".equals(actionNames)){ - actionNames = actionName; - } else { - actionNames = actionNames + " , " + actionName; - } - } - %> - - <% - } - %> - - <% - } - } else { - %> - - - - - <% - } - %> - -
<%=Encode.forHtmlContent(resource)%><%=Encode.forHtmlContent(actionNames)%>
No Result is found
-
- <% - } - %> -
-
diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/attribute-search.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/attribute-search.jsp deleted file mode 100644 index ca423a8834b4..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/attribute-search.jsp +++ /dev/null @@ -1,267 +0,0 @@ - -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> -<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" - prefix="carbon"%> -<%@ page import="org.apache.axis2.context.ConfigurationContext"%> -<%@ page import="org.wso2.carbon.CarbonConstants"%> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.AttributeDTO"%> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.EntitlementPolicyConstants"%> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIMessage" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %> -<%@page import="org.wso2.carbon.utils.ServerConstants"%> -<%@ page import="java.util.ArrayList" %> -<%@ page import="java.util.List" %> -<%@ page import="java.util.ResourceBundle" %> -<%@ page import="org.owasp.encoder.Encode" %> - -<% - String policyId = ""; - String attributeType = ""; - String attributeId = ""; - String attributeDataType = ""; - String [] results = null; - String[] policyIds = null; - String[] attributeTypes = new String[] {EntitlementPolicyConstants.RESOURCE_ELEMENT, - EntitlementPolicyConstants.SUBJECT_ELEMENT, - EntitlementPolicyConstants.ACTION_ELEMENT, - EntitlementPolicyConstants.ENVIRONMENT_ELEMENT}; - String forwardTo; - - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = - (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants. - CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - - policyId = (String)request.getParameter("policyId"); - attributeType = (String)request.getParameter("attributeType"); - attributeId = (String)request.getParameter("attributeId"); - attributeDataType = (String)request.getParameter("attributeDataType"); - - List attributeValueDTOs = new ArrayList(); - - if(policyId != null && !"".equals(policyId)){ - AttributeDTO attributeValueDTO = new AttributeDTO(); - attributeValueDTO.setPolicyId(policyId); - if(!EntitlementPolicyConstants.COMBO_BOX_ANY_VALUE.equals(attributeType)){ - attributeValueDTO.setAttributeType(attributeType); - } - attributeValueDTO.setAttributeDataType(attributeDataType); - attributeValueDTO.setAttributeId(attributeId); - attributeValueDTOs.add(attributeValueDTO); - } - - try { - EntitlementPolicyAdminServiceClient client = new EntitlementPolicyAdminServiceClient(cookie, - serverURL, configContext); - policyIds = client.getAllPolicyIds(); - if(attributeValueDTOs.size() > 0){ - results = client.getAdvanceSearchResult(attributeValueDTOs.toArray(new AttributeDTO[attributeValueDTOs.size()])); - } - - } catch (Exception e) { - String message = resourceBundle.getString("error.while.loading.policy.resource"); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.ERROR, request); - forwardTo = "../admin/error.jsp"; -%> - - - -<% - } -%> - - - - - - - - - - - - - -
-

-
-
- - - - - - - - - - - - - - - - - - - - - - - - -
- -
- -
- <% - if (attributeId != null && !attributeId.equals("")) { - %> - - <% - } else { - %> - - <% - } - %> -
- <% - if (attributeDataType != null && !attributeDataType.equals("")) { - %> - - <% - } else { - %> - - <% - } - %> -
- -
-
-

- - - - - - - - - - <% - if(results != null && results.length > 0) { - for(String result : results){ - %> - - <% - String[] resultData = result.split(","); - for(String data : resultData){ - %> - - <% - } - %> - - <% - } - } else { - %> - - - - <% - } - %> - -
<%=data%>
-
-
-
diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/authorization-add.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/authorization-add.jsp deleted file mode 100644 index 9cbc424e0907..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/authorization-add.jsp +++ /dev/null @@ -1,117 +0,0 @@ - -<%@ page import="org.apache.axis2.context.ConfigurationContext"%> -<%@ page import="org.wso2.carbon.CarbonConstants"%> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO"%> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.EntitlementPolicyCreator"%> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.PolicyEditorConstants"%> - -<%@page - import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient"%> -<%@page import="org.wso2.carbon.identity.entitlement.ui.dto.SimplePolicyEditorElementDTO"%> -<%@ page import="org.wso2.carbon.ui.CarbonUIMessage" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %> -<%@ page import="org.wso2.carbon.utils.ServerConstants" %> -<%@ page import="java.util.ArrayList" %> -<%@ page import="java.util.List" %> -<%@ page import="java.util.ResourceBundle" %> -<% - String serverURL = CarbonUIUtil.getServerURL(config - .getServletContext(), session); - ConfigurationContext configContext = (ConfigurationContext) config - .getServletContext().getAttribute( - CarbonConstants.CONFIGURATION_CONTEXT); - String cookie = (String) session - .getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String forwardTo = null; - String action = request.getParameter("rule"); - String policyid = request.getParameter("policyid"); - String type = request.getParameter("type"); - String value = request.getParameter("value"); - PolicyDTO dto = null; - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - - if ((request.getParameter("policyid") != null)) { - - try { - EntitlementPolicyAdminServiceClient client = - new EntitlementPolicyAdminServiceClient(cookie, serverURL, configContext); - int i = 0; - dto = client.getPolicy(policyid, false); - String[] data = dto.getBasicPolicyEditorMetaData(); - - if(data != null){ - i = (data.length -11)/11; - } - List elementDTOs = new ArrayList(); - SimplePolicyEditorElementDTO elementDTO = new SimplePolicyEditorElementDTO(); - if("permit".equals(action)){ - elementDTO.setOperationType(PolicyEditorConstants.PreFunctions.CAN_DO); - } - elementDTO.setResourceValue(PolicyEditorConstants.ANY); - elementDTO.setActionValue(PolicyEditorConstants.ANY); - elementDTO.setEnvironmentValue(PolicyEditorConstants.ANY); - elementDTO.setUserAttributeValue(value); - if("role".equals(type)){ - elementDTO.setUserAttributeId(PolicyEditorConstants.SUBJECT_ID_ROLE); - } - elementDTOs.add(elementDTO); - EntitlementPolicyCreator creator = new EntitlementPolicyCreator(); - String policy = creator.addNewRules(dto.getPolicy(),elementDTOs); - if(PolicyEditorConstants.SOA_POLICY_EDITOR.equals(dto.getPolicyEditor())){ - List metaDataList = new ArrayList(); - metaDataList.add("resourceValue" + i + "|" + "*"); - metaDataList.add("actionValue" + i + "|" + "*"); - metaDataList.add("userAttributeValue" + i + "|" + value); - if("role".equals(type)){ - metaDataList.add("userAttributeValue" + i + "|" + value); - } - metaDataList.add("environmentValue" + i + "|" + "*"); - metaDataList.add("operationValue" + i + "|" + PolicyEditorConstants.PreFunctions.CAN_DO); - metaDataList.add("update"); - dto.setBasicPolicyEditorMetaData(metaDataList.toArray(new String[metaDataList.size()])); - } - - if(policy != null){ - dto.setPolicy(policy); - client.updatePolicy(dto); - } - //session.setAttribute("entitlementpolicy", dto.getPolicy()); - forwardTo = "index.jsp?region=region1&item=policy_menu"; - } catch (Exception e) { - String message = resourceBundle.getString("invalid.policy.not.updated"); - //session.setAttribute("entitlementpolicy", dto.getPolicy()); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.ERROR, request); - forwardTo = "index.jsp?region=region1&item=policy_menu"; - } - } else { - forwardTo = "index.jsp?region=region1&item=policy_menu"; - } -%> - - - - \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/authorization-index.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/authorization-index.jsp deleted file mode 100644 index a80ff345658b..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/authorization-index.jsp +++ /dev/null @@ -1,281 +0,0 @@ - -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> -<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %> -<%@ page import="org.apache.axis2.context.ConfigurationContext" %> -<%@ page import="org.wso2.carbon.CarbonConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.PaginatedPolicySetDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIMessage" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil"%> -<%@ page import="org.wso2.carbon.utils.ServerConstants" %> -<%@ page import="java.util.ResourceBundle" %> -<%@ page import="org.owasp.encoder.Encode" %> - - - -<% - entitlementPolicyBean.cleanEntitlementPolicyBean(); - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = - (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String forwardTo = null; - PaginatedPolicySetDTO paginatedPolicySetDTO = null; - PolicyDTO[] policies = null; - String[] policyTypes = new String[] {"Policy", "PolicySet", "Active" , "Promoted"}; - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - - String type = "role"; - String userName = request.getParameter("userName"); - String value = request.getParameter("roleName"); - if(userName != null && userName.trim().length() > 0 ) { - type = "user"; - value = userName; - } - - int numberOfPages = 0; - String pageNumber = request.getParameter("pageNumber"); - if (pageNumber == null) { - pageNumber = "0"; - } - int pageNumberInt = 0; - try { - pageNumberInt = Integer.parseInt(pageNumber); - } catch (NumberFormatException ignored) { - } - - String policyTypeFilter = request.getParameter("policyTypeFilter"); - if (policyTypeFilter == null || "".equals(policyTypeFilter)) { - policyTypeFilter = "ALL"; - } - String policySearchString = request.getParameter("policySearchString"); - if (policySearchString == null) { - policySearchString = ""; - } else { - policySearchString = policySearchString.trim(); - } - - String paginationValue = "policyTypeFilter=" + policyTypeFilter + - "&policySearchString=" + policySearchString; - - try { - EntitlementPolicyAdminServiceClient client = new EntitlementPolicyAdminServiceClient(cookie, serverURL, configContext); - paginatedPolicySetDTO = client.getAllPolicies(policyTypeFilter, policySearchString, pageNumberInt, false); - policies = paginatedPolicySetDTO.getPolicySet(); - numberOfPages = paginatedPolicySetDTO.getNumberOfPages(); - - } catch (Exception e) { - String message = resourceBundle.getString("error.while.loading.policy"); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.ERROR, request, e); - forwardTo = "../admin/error.jsp"; -%> - - - - -<% - } -%> - - - - - - - - - -
-

-
- - - - - -
-
- -
-
- - -
- - - - -
- - - - - - - - "> - - -
- - - -     - - "/>  - - - "> -
-
-
- - -
- - - - - - - - <% - if (policies != null) { - for (int i = 0; i < policies.length; i++) { - if(policies[i] != null){ - if(!"Policy".equals(policies[i].getPolicyType())){ - continue; - } - - boolean edit = policies[i].getPolicyEditable(); - boolean delete = policies[i].getPolicyCanDelete(); - %> - - - - - - - - - - <%} } - } else { %> - - - - <%}%> - -
- , - <%=numberOfPages%>)" style="background-image:url(../admin/images/up-arrow.gif)"> - , - <%=numberOfPages%>)" style="background-image:url(../admin/images/down-arrow.gif)"> - - - disabled="disabled"<% } %>/> - - href="policy-view.jsp?policyid=<%=Encode.forUriComponent(policies[i].getPolicyId())%>" <% } %>> - <%=Encode.forHtmlContent(policies[i].getPolicyId())%> - - -
-
- -
-
-
diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/basic-policy-editor.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/basic-policy-editor.jsp deleted file mode 100644 index 549e073651e8..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/basic-policy-editor.jsp +++ /dev/null @@ -1,1467 +0,0 @@ - -<%@ page import="org.owasp.encoder.Encode" %> -<%@ page import="org.wso2.balana.utils.policy.dto.BasicRuleDTO" %> -<%@ page import="org.wso2.balana.utils.policy.dto.BasicTargetDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.common.EntitlementConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.common.PolicyEditorEngine" %> -<%@ page import="org.wso2.carbon.identity.entitlement.common.dto.PolicyEditorDataHolder" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.EntitlementPolicyConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.PolicyEditorConstants" %> -<%@ page import="java.util.ArrayList" %> -<%@ page import="java.util.List" %> -<%@ page import="java.util.Set" %> -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> -<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %> - - - -<% - BasicRuleDTO basicRuleDTO = null; - PolicyEditorDataHolder holder = PolicyEditorEngine.getInstance(). - getPolicyEditorData(EntitlementConstants.PolicyEditor.BASIC); - Set functionIds = holder.getRuleFunctions(); - Set preFunctionIds = holder.getPreFunctionMap().keySet(); - Set targetFunctionIds = holder.getTargetFunctions(); - Set ruleEffects = holder.getRuleEffectMap().keySet(); - Set subjectIds = holder.getCategoryAttributeIdMap().get(PolicyEditorConstants.SOA_CATEGORY_SUBJECT); - Set environmentIds = holder.getCategoryAttributeIdMap().get(PolicyEditorConstants.SOA_CATEGORY_ENVIRONMENT); - Set algorithmNames = holder.getRuleCombiningAlgorithms().keySet(); - Set availableCategories = holder.getCategoryMap().keySet(); - - List basicRuleDTOs = entitlementPolicyBean.getBasicRuleDTOs(); - BasicTargetDTO basicTargetDTO = entitlementPolicyBean.getBasicTargetDTO(); - - String selectedAttributeDataType = request.getParameter("selectedAttributeDataType"); - String selectedAttributeId = request.getParameter("selectedAttributeId"); - String category = request.getParameter("category"); - - String ruleId = Encode.forHtml(request.getParameter("ruleId")); - if(ruleId != null && ruleId.trim().length() > 0 && !ruleId.trim().equals("null") ) { - basicRuleDTO = entitlementPolicyBean.getBasicRuleElement(ruleId); - } - - // Why null TODO - if("null".equals(selectedAttributeId)){ - selectedAttributeId = null; - } - - if("null".equals(selectedAttributeDataType)){ - selectedAttributeDataType = null; - } - - String selectedAttributeNames = ""; - - String selectedSubjectNames = ""; - String selectedResourceNames = ""; - String selectedActionNames = ""; - String selectedEnvironmentNames = ""; - String selectedResourceId=""; - String selectedResourceDataType=""; - String selectedSubjectId=""; - String selectedSubjectDataType=""; - String selectedActionId=""; - String selectedActionDataType=""; - String selectedEnvironmentId=""; - String selectedEnvironmentDataType=""; - - String resourceNames = ""; - String environmentNames = ""; - String subjectNames = ""; - String actionNames = ""; - String functionOnResources = ""; - String functionOnSubjects = ""; - String functionOnActions = ""; - String functionOnEnvironment = ""; - String preFunctionOnResources = ""; - String preFunctionOnSubjects = ""; - String preFunctionOnActions = ""; - String preFunctionOnEnvironment = ""; - String resourceDataType = ""; - String subjectDataType = ""; - String actionDataType = ""; - String environmentDataType = ""; - String resourceId= ""; - String subjectId = ""; - String actionId = ""; - String environmentId = ""; - String ruleDescription = ""; - String ruleEffect = ""; - - String resourceNamesTarget = ""; - String environmentNamesTarget = ""; - String subjectNamesTarget = ""; - String actionNamesTarget = ""; - - String functionOnResourcesTarget = ""; - String functionOnSubjectsTarget = ""; - String functionOnActionsTarget = ""; - String functionOnEnvironmentTarget = ""; - - String preFunctionOnSubjectsTarget = ""; - String preFunctionOnActionsTarget = ""; - String preFunctionOnEnvironmentTarget = ""; - String preFunctionOnResourcesTarget = ""; - - String resourceDataTypeTarget = ""; - String subjectDataTypeTarget = ""; - String actionDataTypeTarget = ""; - String environmentDataTypeTarget = ""; - - String resourceIdTarget = ""; - String subjectIdTarget = ""; - String actionIdTarget = ""; - String environmentIdTarget = ""; - - int noOfSelectedAttributes = 1; - /** - * Get posted resources from jsp pages and put then in to a String object - */ - while(true) { - String attributeName = request.getParameter("attributeValue" + noOfSelectedAttributes); - if (attributeName == null || attributeName.trim().length() < 1) { - break; - } - if(selectedAttributeNames.equals("")) { - selectedAttributeNames = attributeName.trim(); - } else { - selectedAttributeNames = selectedAttributeNames + "," + attributeName.trim(); - } - noOfSelectedAttributes ++; - } - - - if(category != null){ - if (EntitlementPolicyConstants.RESOURCE_ELEMENT.equals(category)){ - selectedResourceNames = selectedAttributeNames; - selectedResourceId = selectedAttributeId; - selectedResourceDataType = selectedAttributeDataType; - } else if (EntitlementPolicyConstants.SUBJECT_ELEMENT.equals(category)){ - selectedSubjectNames = selectedAttributeNames; - selectedSubjectId = selectedAttributeId; - selectedSubjectDataType = selectedAttributeDataType; - } else if (EntitlementPolicyConstants.ACTION_ELEMENT.equals(category)){ - selectedActionNames = selectedAttributeNames; - selectedActionId = selectedAttributeId; - selectedActionDataType = selectedAttributeDataType; - } else if (EntitlementPolicyConstants.ENVIRONMENT_ELEMENT.equals(category)){ - selectedEnvironmentNames = selectedAttributeNames; - selectedEnvironmentId = selectedAttributeId; - selectedEnvironmentDataType = selectedAttributeDataType; - } - } - /** - * Assign current BasicRule Object Values to variables to show on UI - */ - if(basicRuleDTO != null){ - - ruleEffect = basicRuleDTO.getRuleEffect(); - ruleId = basicRuleDTO.getRuleId(); - ruleDescription = basicRuleDTO.getRuleDescription(); - - resourceNames = basicRuleDTO.getResourceList(); - subjectNames = basicRuleDTO.getSubjectList(); - actionNames = basicRuleDTO.getActionList(); - environmentNames = basicRuleDTO.getEnvironmentList(); - - functionOnActions = basicRuleDTO.getFunctionOnActions(); - functionOnResources = basicRuleDTO.getFunctionOnResources(); - functionOnSubjects = basicRuleDTO.getFunctionOnSubjects(); - functionOnEnvironment = basicRuleDTO.getFunctionOnEnvironment(); - - preFunctionOnActions = basicRuleDTO.getPreFunctionOnActions(); - preFunctionOnResources = basicRuleDTO.getPreFunctionOnResources(); - preFunctionOnSubjects = basicRuleDTO.getPreFunctionOnSubjects(); - preFunctionOnEnvironment = basicRuleDTO.getPreFunctionOnEnvironment(); - - if(selectedResourceDataType != null && selectedResourceDataType.trim().length() > 0){ - resourceDataType = selectedResourceDataType; - } else { - resourceDataType = basicRuleDTO.getResourceDataType(); - } - - if(selectedSubjectDataType != null && selectedSubjectDataType.trim().length() > 0){ - subjectDataType = selectedSubjectDataType; - } else { - subjectDataType = basicRuleDTO.getSubjectDataType(); - } - - if(selectedActionDataType != null && selectedActionDataType.trim().length() > 0){ - actionDataType = selectedActionDataType; - } else { - actionDataType = basicRuleDTO.getActionDataType(); - } - - if(selectedEnvironmentDataType != null && selectedEnvironmentDataType.trim().length() > 0){ - environmentDataType = selectedEnvironmentDataType; - } else { - environmentDataType = basicRuleDTO.getEnvironmentDataType(); - } - - if(selectedResourceId != null && selectedResourceId.trim().length() > 0){ - resourceId = selectedResourceId; - } else { - resourceId = basicRuleDTO.getResourceId(); - } - - if(selectedSubjectId != null && selectedSubjectId.trim().length() > 0){ - subjectId = selectedSubjectId; - } else { - subjectId = basicRuleDTO.getSubjectId(); - } - - if(selectedActionId != null && selectedActionId.trim().length() > 0){ - actionId = selectedActionId; - } else { - actionId = basicRuleDTO.getActionId(); - } - - if(selectedEnvironmentId != null && selectedEnvironmentId.trim().length() > 0){ - environmentId = selectedEnvironmentId; - } else { - environmentId = basicRuleDTO.getEnvironmentId(); - } - - if(selectedResourceNames != null && selectedResourceNames.trim().length() > 0){ - if(resourceNames != null && resourceNames.trim().length() > 0){ - resourceNames = resourceNames + "," + selectedResourceNames; - } else { - resourceNames = selectedResourceNames; - } - } - - if(selectedSubjectNames != null && selectedSubjectNames.trim().length() > 0){ - if(subjectNames != null && subjectNames.trim().length() > 0){ - subjectNames = subjectNames + "," + selectedSubjectNames; - } else { - subjectNames = selectedSubjectNames; - } - } - - if(selectedActionNames != null && selectedActionNames.trim().length() > 0){ - if(actionNames != null && actionNames.trim().length() > 0){ - actionNames = actionNames + "," + selectedActionNames; - } else { - actionNames = selectedActionNames; - } - } - - if(selectedEnvironmentNames != null && selectedEnvironmentNames.trim().length() > 0){ - if(environmentNames != null && environmentNames.trim().length() > 0){ - environmentNames = environmentNames + "," + selectedEnvironmentNames; - } else { - environmentNames = selectedEnvironmentNames; - } - } - - } - - /** - * Assign current BasicTarget Object Values to variables to show on UI. - */ - if(basicTargetDTO != null){ - - resourceNamesTarget = basicTargetDTO.getResourceList(); - subjectNamesTarget = basicTargetDTO.getSubjectList(); - actionNamesTarget = basicTargetDTO.getActionList(); - environmentNamesTarget = basicTargetDTO.getEnvironmentList(); - - functionOnActionsTarget = basicTargetDTO.getFunctionOnActions(); - functionOnResourcesTarget = basicTargetDTO.getFunctionOnResources(); - functionOnSubjectsTarget = basicTargetDTO.getFunctionOnSubjects(); - functionOnEnvironmentTarget = basicTargetDTO.getFunctionOnEnvironment(); - - resourceDataTypeTarget = basicTargetDTO.getResourceDataType(); - subjectDataTypeTarget = basicTargetDTO.getSubjectDataType(); - actionDataTypeTarget = basicTargetDTO.getActionDataType(); - environmentDataTypeTarget = basicTargetDTO.getEnvironmentDataType(); - - resourceIdTarget = basicTargetDTO.getResourceId(); - subjectIdTarget = basicTargetDTO.getSubjectId(); - actionIdTarget = basicTargetDTO.getActionId(); - environmentIdTarget = basicTargetDTO.getEnvironmentId(); - - if(basicRuleDTO == null) { - if(selectedResourceNames != null && selectedResourceNames.trim().length() > 0){ - if(resourceNamesTarget != null && resourceNamesTarget.trim().length() > 0){ - resourceNamesTarget = resourceNamesTarget + "," + selectedResourceNames; - } else { - resourceNamesTarget = selectedResourceNames; - } - } - - if(selectedSubjectNames != null && selectedSubjectNames.trim().length() > 0){ - if(subjectNamesTarget != null && subjectNamesTarget.trim().length() > 0){ - subjectNamesTarget = subjectNamesTarget + "," + selectedSubjectNames; - } else { - subjectNamesTarget = selectedSubjectNames; - } - } - - if(selectedActionNames != null && selectedActionNames.trim().length() > 0){ - if(actionNamesTarget != null && actionNamesTarget.trim().length() > 0){ - actionNamesTarget = actionNamesTarget + "," + selectedActionNames; - } else { - actionNamesTarget = selectedActionNames; - } - } - - if(selectedEnvironmentNames != null && selectedEnvironmentNames.trim().length() > 0){ - if(environmentNamesTarget != null && environmentNamesTarget.trim().length() > 0){ - environmentNamesTarget = environmentNamesTarget + "," + selectedEnvironmentNames; - } else { - environmentNamesTarget = selectedEnvironmentNames; - } - } - - if(selectedResourceDataType != null && selectedResourceDataType.trim().length() > 0){ - resourceDataTypeTarget = selectedResourceDataType; - } - - if(selectedSubjectDataType != null && selectedSubjectDataType.trim().length() > 0){ - subjectDataTypeTarget = selectedSubjectDataType; - } - - if(selectedActionDataType != null && selectedActionDataType.trim().length() > 0){ - actionDataTypeTarget = selectedActionDataType; - } - - if(selectedEnvironmentDataType != null && selectedEnvironmentDataType.trim().length() > 0){ - environmentDataTypeTarget = selectedEnvironmentDataType; - } - - if(selectedResourceId != null && selectedResourceId.trim().length() > 0){ - resourceIdTarget = selectedResourceId; - } - - if(selectedSubjectId != null && selectedSubjectId.trim().length() > 0){ - subjectIdTarget = selectedSubjectId; - } - - if(selectedActionId != null && selectedActionId.trim().length() > 0){ - actionIdTarget = selectedActionId; - } - - if(selectedEnvironmentId != null && selectedEnvironmentId.trim().length() > 0){ - environmentIdTarget = selectedEnvironmentId; - } - } - } - -%> - - - - -<% if(entitlementPolicyBean.isEditPolicy()){%> - -<% } else { %> - -<%}%> - - - - - - - - - - - - - -
-<%if(entitlementPolicyBean.isEditPolicy()){%> -

-<%} else {%>

<%}%> -
-
- - - - - <% - if(entitlementPolicyBean.getPolicyName() != null) { - %> - - <% - } else { - %> - - <% - } - %> - - - <% - if(holder.isShowRuleAlgorithms() && algorithmNames != null){ - %> - - - - - <% - } - %> - <% - if(holder.isShowPolicyDescription()){ - %> - - - <% - if(entitlementPolicyBean.getPolicyDescription() != null) { - %> - - <% - } else { - %> - - <% - } - %> - - <% - } - %> - - - - - - - - - - - - - - - - -
*
- -
-

-
- - - - - - - - - - - - - - - - - - -
- - - - - - - -
- - - <% - if (resourceNamesTarget != null && resourceNamesTarget.trim().length() > 0) { - - %> - - <% - } else { - %> - - - <% - } - %> - - - - -
-
- - - - - - - -
- - - - - <% - if (subjectNamesTarget != null && subjectNamesTarget.trim().length() > 0) { - %> - - <% - } else { - %> - - <% - } - %> - - -
-
- - - - - - - - -
- - - <% - if (actionNamesTarget != null && actionNamesTarget.trim().length() > 0) { - - %> - - <% - } else { - %> - - - <% - } - %> - - - - -
-
- - - - - - - -
- - - - - <% - if (environmentNamesTarget != null && environmentNamesTarget.trim().length() > 0) { - - %> - - <% - } else { - %> - - - <% - } - %> - - -
-
-
-
-

-
- - - - - - - - - - -
- - <% - if(holder.isShowRuleId()){ - %> - - - - - <% - } - %> - - <% - if(holder.isShowRuleEffect()){ - %> - - - - - <% - } - %> - - <% - if(holder.isShowRuleDescription()){ - %> - - - <% - if(ruleDescription != null) { - %> - - <% - } else { - %> - - <% - } - %> - - <% - } - %> - - - - - - - - - - - - - - - - - - - - - -
* - - <% - if (ruleId != null && ruleId.trim().length() > 0 && !ruleId.trim().equals("null")) { - %> - - <% - } else { - %> - - <% - } - %> -
- -
- - - - - - - - - - -
- - - - - <% - if (resourceNames != null && !resourceNames.equals("")) { - - %> - - <% - } else { - %> - - - <% - } - %> - - - - - - -
-
- - - - - - - - - - -
- - - - - - - <% - if (subjectNames != null && !subjectNames.equals("")) { - - %> - - <% - } else { - %> - - - <% - } - %> - - - - -
-
- - - - - - - - - - - -
- - - - - <% - if (actionNames != null && !actionNames.equals("")) { - - %> - - <% - } else { - %> - - - <% - } - %> - - - - - - -
-
- - - - - - - - - - -
- - - - - - - <% - if (environmentNames != null && !environmentNames.equals("")) { - - %> - - <% - } else { - %> - - - <% - } - %> - - - - -
-
-
- <% - if (basicRuleDTO != null && basicRuleDTO.isCompletedRule()) { - %> - - - - - <% - } else { - %> - - - <% - } - %> -
-
-
- - - - - - - - - <% - if (basicRuleDTOs != null && basicRuleDTOs.size() > 0) { - List orderedBasicRuleDTOs = new ArrayList(); - String ruleElementOrder = entitlementPolicyBean.getRuleElementOrder(); - if(ruleElementOrder != null){ - String[] orderedRuleIds = ruleElementOrder.split(EntitlementPolicyConstants.ATTRIBUTE_SEPARATOR); - for(String orderedRuleId : orderedRuleIds){ - for(BasicRuleDTO orderedBasicRuleElementDTO : basicRuleDTOs) { - if(orderedRuleId.trim().equals(orderedBasicRuleElementDTO.getRuleId())){ - orderedBasicRuleDTOs.add(orderedBasicRuleElementDTO); - } - } - } - } - - if(orderedBasicRuleDTOs.size() < 1){ - orderedBasicRuleDTOs = basicRuleDTOs; - } - for (BasicRuleDTO ruleElementDTO : orderedBasicRuleDTOs) { - if(ruleElementDTO.isCompletedRule()){ - %> - - - - - - - <% - } - } - } else { - %> - - - - <% - } - %> -
- - - - <%=Encode.forHtml(ruleElementDTO.getRuleId())%> - <%=ruleElementDTO.getRuleEffect()%> - - -

-
- " class="button"/> - " class="button"/> -
-
-
-
-
diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/basic-policy-finish.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/basic-policy-finish.jsp deleted file mode 100644 index 5d2e9c957c75..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/basic-policy-finish.jsp +++ /dev/null @@ -1,139 +0,0 @@ - -<%@ page import="org.apache.axis2.context.ConfigurationContext"%> -<%@ page import="org.wso2.balana.utils.policy.dto.BasicPolicyDTO"%> -<%@ page import="org.wso2.balana.utils.policy.dto.BasicRuleDTO"%> -<%@ page import="org.wso2.balana.utils.policy.dto.BasicTargetDTO"%> -<%@ page import="org.wso2.carbon.CarbonConstants"%> -<%@ page import="org.wso2.carbon.identity.entitlement.common.EntitlementConstants"%> -<%@ page import="org.wso2.carbon.identity.entitlement.common.PolicyEditorException"%> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.EntitlementPolicyCreator" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.util.PolicyEditorUtil" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIMessage" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %> -<%@ page import="org.wso2.carbon.utils.ServerConstants" %> -<%@ page import="java.util.List" %> -<%@ page import="java.util.ResourceBundle" %> - - -<% - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = - (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants. - CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String forwardTo = null; - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - - String policy = ""; - PolicyDTO policyDTO = null; - BasicPolicyDTO basicPolicyDTO = new BasicPolicyDTO(); - EntitlementPolicyCreator policyCreator = new EntitlementPolicyCreator(); - - String ruleElementOrder = request.getParameter("ruleElementOrder"); - if(ruleElementOrder != null && ruleElementOrder.trim().length() > 0){ - entitlementPolicyBean.setRuleElementOrder(ruleElementOrder.trim()); - } else { - ruleElementOrder = entitlementPolicyBean.getRuleElementOrder(); - } - - List basicRuleDTOs = entitlementPolicyBean.getBasicRuleDTOs(); - BasicTargetDTO basicTargetDTO = entitlementPolicyBean.getBasicTargetDTO(); - - String policyName = entitlementPolicyBean.getPolicyName(); - String algorithmName = entitlementPolicyBean.getAlgorithmName(); - String policyDescription = entitlementPolicyBean.getPolicyDescription(); - - String[] policyEditorData = null; - - try { - - if(policyName != null && policyName.trim().length() > 0) { - - basicPolicyDTO.setPolicyId(policyName); - basicPolicyDTO.setRuleAlgorithm(algorithmName); - basicPolicyDTO.setDescription(policyDescription); - basicPolicyDTO.setBasicRuleDTOs(basicRuleDTOs); - basicPolicyDTO.setTargetDTO(basicTargetDTO); - - if(basicRuleDTOs != null && basicTargetDTO != null){ - policyEditorData = PolicyEditorUtil.generateBasicPolicyEditorData(basicPolicyDTO, ruleElementOrder); - policy = policyCreator.createBasicPolicy(basicPolicyDTO); - } - - EntitlementPolicyAdminServiceClient client = new EntitlementPolicyAdminServiceClient(cookie, - serverURL, configContext); - - String message = null; - if(entitlementPolicyBean.isEditPolicy()){ - try{ - policyDTO = client.getPolicy(policyName, false); - } catch (Exception e){ - //ignore - } - - if(policyDTO == null){ - policyDTO = new PolicyDTO(); - } - - policyDTO.setPolicy(policy); - policyDTO.setPolicyEditor(EntitlementConstants.PolicyEditor.BASIC); - if(policyEditorData != null){ - policyDTO.setPolicyEditorData(policyEditorData); - } - client.updatePolicy(policyDTO); - message = resourceBundle.getString("updated.successfully"); - } else { - policyDTO = new PolicyDTO(); - policyDTO.setPolicyId(policyName); - policyDTO.setPolicy(policy); - policyDTO.setPolicyEditor(EntitlementConstants.PolicyEditor.BASIC); - if(policyEditorData != null){ - policyDTO.setPolicyEditorData(policyEditorData); - } - client.addPolicy(policyDTO); - message = resourceBundle.getString("ent.policy.added.successfully"); - } - entitlementPolicyBean.cleanEntitlementPolicyBean(); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.INFO, request); - forwardTo = "index.jsp?"; - } - } catch (PolicyEditorException e) { - String message = resourceBundle.getString("error.while.creating.policy"); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.ERROR, request); - forwardTo = "index.jsp?"; - } catch (Exception e) { - String message = resourceBundle.getString("error.while.adding.policy") + " " + e.getMessage(); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.ERROR, request); - forwardTo = "index.jsp?"; - } -%> - - - \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/basic-policy-update.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/basic-policy-update.jsp deleted file mode 100644 index 24cd530548ad..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/basic-policy-update.jsp +++ /dev/null @@ -1,314 +0,0 @@ - -<%@ page import="org.wso2.balana.utils.policy.dto.BasicRuleDTO" %> -<%@ page import="org.wso2.balana.utils.policy.dto.BasicTargetDTO" %> -<%@ page import="org.owasp.encoder.Encode" %> - - - - -<% - BasicRuleDTO basicRuleDTO = new BasicRuleDTO(); - BasicTargetDTO basicTargetDTO = new BasicTargetDTO(); - entitlementPolicyBean.setRuleElementOrder(null); - - String action = request.getParameter("action"); - - String category = request.getParameter("category"); - String ruleElementOrder = request.getParameter("ruleElementOrder"); - String updateRule = request.getParameter("updateRule"); - // rules - String ruleId = request.getParameter("ruleId"); - String ruleEffect = request.getParameter("ruleEffect"); - String ruleDescription = request.getParameter("ruleDescription"); - String completedRule = request.getParameter("completedRule"); - String editRule = request.getParameter("editRule"); - - String resourceNames = request.getParameter("resourceNames"); - String functionOnResources = request.getParameter("functionOnResources"); - String resourceDataType = request.getParameter("resourceDataType"); - String preFunctionOnResources = request.getParameter("preFunctionOnResources"); - String resourceId = request.getParameter("resourceId"); - - String subjectNames = request.getParameter("subjectNames"); - String functionOnSubjects = request.getParameter("functionOnSubjects"); - String subjectDataType = request.getParameter("subjectDataType"); - String subjectId = request.getParameter("subjectId"); - String preFunctionOnSubjects = request.getParameter("preFunctionOnSubjects"); - - String actionNames = request.getParameter("actionNames"); - String functionOnActions = request.getParameter("functionOnActions"); - String actionDataType = request.getParameter("actionDataType"); - String actionId = request.getParameter("actionId"); - String preFunctionOnActions = request.getParameter("preFunctionOnActions"); - - String environmentNames = request.getParameter("environmentNames"); - String functionOnEnvironment = request.getParameter("functionOnEnvironment"); - String environmentDataType = request.getParameter("environmentDataType"); - String environmentId = request.getParameter("environmentId"); - String preFunctionOnEnvironment = request.getParameter("preFunctionOnEnvironment"); - - // targets - String resourceNamesTarget = request.getParameter("resourceNamesTarget"); - String functionOnResourcesTarget = request.getParameter("functionOnResourcesTarget"); - String resourceDataTypeTarget = request.getParameter("resourceDataTypeTarget"); - String resourceIdTarget = request.getParameter("resourceIdTarget"); - String preFunctionOnResourcesTarget = request.getParameter("preFunctionOnResourcesTarget"); - - String subjectNamesTarget = request.getParameter("subjectNamesTarget"); - String functionOnSubjectsTarget = request.getParameter("functionOnSubjectsTarget"); - String subjectDataTypeTarget = request.getParameter("subjectDataTypeTarget"); - String subjectIdTarget = request.getParameter("subjectIdTarget"); - String preFunctionOnSubjectsTarget = request.getParameter("preFunctionOnSubjectsTarget"); - - String actionNamesTarget = request.getParameter("actionNamesTarget"); - String functionOnActionsTarget = request.getParameter("functionOnActionsTarget"); - String actionDataTypeTarget = request.getParameter("actionDataTypeTarget"); - String actionIdTarget = request.getParameter("actionIdTarget"); - String preFunctionOnActionsTarget = request.getParameter("preFunctionOnActionsTarget"); - - String environmentNamesTarget = request.getParameter("environmentNamesTarget"); - String functionOnEnvironmentTarget = request.getParameter("functionOnEnvironmentTarget"); - String preFunctionOnEnvironmentTarget = request.getParameter("preFunctionOnEnvironmentTarget"); - String environmentDataTypeTarget = request.getParameter("environmentDataTypeTarget"); - String environmentIdTarget = request.getParameter("environmentIdTarget"); - -// String attributeIdTarget = request.getParameter("attributeIdTarget"); -// String functionOnAttributesTarget = request.getParameter("functionOnAttributesTarget"); -// String userAttributeValueTarget = request.getParameter("userAttributeValueTarget"); - - - if(ruleId != null && ruleId.trim().length() > 0 && !ruleId.trim().equals("null") && editRule == null ) { - - basicRuleDTO.setRuleId(ruleId); - basicRuleDTO.setRuleEffect(ruleEffect); - - if(ruleDescription != null && ruleDescription.trim().length() > 0 ){ - basicRuleDTO.setRuleDescription(ruleDescription); - } - - if(resourceNames != null && !resourceNames.equals("")){ - basicRuleDTO.setResourceList(resourceNames); - } - - if(functionOnResources != null && !functionOnResources.equals("")){ - basicRuleDTO.setFunctionOnResources(functionOnResources); - } - - if(resourceDataType != null && resourceDataType.trim().length() > 0 && - !resourceDataType.trim().equals("null")){ - basicRuleDTO.setResourceDataType(resourceDataType); - } - - if(resourceId != null && resourceId.trim().length() > 0 && !resourceId.trim().equals("null")){ - basicRuleDTO.setResourceId(resourceId); - } - - if(preFunctionOnResources != null && preFunctionOnResources.trim().length() > 0){ - basicRuleDTO.setPreFunctionOnResources(preFunctionOnResources); - } - - if(subjectNames != null && !subjectNames.equals("")){ - basicRuleDTO.setSubjectList(subjectNames); - } - - if(subjectNames != null && !functionOnSubjects.equals("")){ - basicRuleDTO.setFunctionOnSubjects(functionOnSubjects); - } - - if(subjectDataType != null && subjectDataType.trim().length() > 0 && - !subjectDataType.trim().equals("null")) { - basicRuleDTO.setSubjectDataType(subjectDataType); - } - - if(subjectId != null && subjectId.trim().length() > 0 && !subjectId.trim().equals("null")){ - basicRuleDTO.setSubjectId(subjectId); - } - - if(preFunctionOnSubjects != null && preFunctionOnSubjects.trim().length() > 0){ - basicRuleDTO.setPreFunctionOnSubjects(preFunctionOnSubjects); - } - - if(actionNames != null && !actionNames.equals("")){ - basicRuleDTO.setActionList(actionNames); - } - - if(functionOnActions != null && !functionOnActions.equals("")){ - basicRuleDTO.setFunctionOnActions(functionOnActions); - } - - if(actionDataType != null && actionDataType.trim().length() > 0 && - !actionDataType.trim().equals("null")){ - basicRuleDTO.setActionDataType(actionDataType); - } - - if(actionId != null && actionId.trim().length() > 0 && !actionId.trim().equals("null")){ - basicRuleDTO.setActionId(actionId); - } - - if(preFunctionOnActions != null && preFunctionOnActions.trim().length() > 0){ - basicRuleDTO.setPreFunctionOnActions(preFunctionOnActions); - } - - if(environmentNames != null && !environmentNames.equals("")){ - basicRuleDTO.setEnvironmentList(environmentNames); - } - - if(functionOnEnvironment != null && !functionOnEnvironment.equals("")){ - basicRuleDTO.setFunctionOnEnvironment(functionOnEnvironment); - } - - if(environmentDataType != null && environmentDataType.trim().length() > 0 && - !environmentDataType.trim().equals("null")){ - basicRuleDTO.setEnvironmentDataType(environmentDataType); - } - - if(environmentId != null && environmentId.trim().length() > 0 && - !environmentId.trim().equals("null")){ - basicRuleDTO.setEnvironmentId(environmentId); - } - - if(preFunctionOnEnvironment != null && preFunctionOnEnvironment.trim().length() > 0){ - basicRuleDTO.setPreFunctionOnEnvironment(preFunctionOnEnvironment); - } - - if(completedRule != null && completedRule.equals("true")){ - basicRuleDTO.setCompletedRule(true); - } - - entitlementPolicyBean.setBasicRuleElementDTOs(basicRuleDTO); - } - - if(resourceNamesTarget != null && !resourceNamesTarget.equals("")){ - basicTargetDTO.setResourceList(resourceNamesTarget); - } - - if(functionOnResourcesTarget != null && !functionOnResourcesTarget.equals("")){ - basicTargetDTO.setFunctionOnResources(functionOnResourcesTarget); - } - - if(resourceDataTypeTarget != null && resourceDataTypeTarget.trim().length() > 0 && - !resourceDataTypeTarget.trim().equals("null")){ - basicTargetDTO.setResourceDataType(resourceDataTypeTarget); - } - - if(resourceIdTarget != null && resourceIdTarget.trim().length() > 0 && - !resourceIdTarget.trim().equals("null")){ - basicTargetDTO.setResourceId(resourceIdTarget); - } - - if(subjectNamesTarget != null && !subjectNamesTarget.equals("")){ - basicTargetDTO.setSubjectList(subjectNamesTarget); - } - - if(functionOnSubjectsTarget != null && !functionOnSubjectsTarget.equals("")){ - basicTargetDTO.setFunctionOnSubjects(functionOnSubjectsTarget); - } - - if(subjectDataTypeTarget != null && subjectDataTypeTarget.trim().length() > 0 && - !subjectDataTypeTarget.trim().equals("null")){ - basicTargetDTO.setSubjectDataType(subjectDataTypeTarget); - } - - if(subjectIdTarget != null && subjectIdTarget.trim().length() > 0 && - !subjectIdTarget.trim().equals("null")){ - basicTargetDTO.setSubjectId(subjectIdTarget); - } - - if(actionNamesTarget != null && !actionNamesTarget.equals("")){ - basicTargetDTO.setActionList(actionNamesTarget); - } - - if(functionOnActionsTarget != null && !functionOnActionsTarget.equals("")){ - basicTargetDTO.setFunctionOnActions(functionOnActionsTarget); - } - - if(actionDataTypeTarget != null && actionDataTypeTarget.trim().length() > 0 && - !actionDataTypeTarget.trim().equals("null")){ - basicTargetDTO.setActionDataType(actionDataTypeTarget); - } - - if(actionIdTarget != null && actionIdTarget.trim().length() > 0 && - !actionIdTarget.trim().equals("null")){ - basicTargetDTO.setActionId(actionIdTarget); - } - - if(environmentNamesTarget != null && !environmentNamesTarget.equals("")){ - basicTargetDTO.setEnvironmentList(environmentNamesTarget); - } - - if(functionOnEnvironmentTarget != null && !functionOnEnvironmentTarget.equals("")){ - basicTargetDTO.setFunctionOnEnvironment(functionOnEnvironmentTarget); - } - - if(environmentDataTypeTarget != null && environmentDataTypeTarget.trim().length() > 0 && - !environmentDataTypeTarget.trim().equals("null")){ - basicTargetDTO.setEnvironmentDataType(environmentDataTypeTarget); - } - - if(environmentIdTarget != null && environmentIdTarget.trim().length() > 0 && - !environmentIdTarget.trim().equals("null")){ - basicTargetDTO.setEnvironmentId(environmentIdTarget); - } - - entitlementPolicyBean.setBasicTargetDTO(basicTargetDTO); - - if(ruleElementOrder != null && ruleElementOrder.trim().length() > 0){ - if(basicRuleDTO.isCompletedRule() && !"true".equals(updateRule)){ - entitlementPolicyBean.setRuleElementOrder(ruleElementOrder.trim() + ", " + - basicRuleDTO.getRuleId()); - } else{ - entitlementPolicyBean.setRuleElementOrder(ruleElementOrder.trim()); - } - } - - String forwardTo = "basic-policy-editor.jsp"; - if ("completePolicy".equals(action)) { - forwardTo = "basic-policy-finish.jsp"; - } else if ("updateRule".equals(action) || "addRule".equals(action) || "cancelRule".equals(action) || - "editRule".equals(action)) { - forwardTo = "basic-policy-editor.jsp"; - } else if ("deleteRule".equals(action)) { - forwardTo = "delete-rule-entry.jsp"; - } else if ("selectAttributes".equals(action)) { - forwardTo = "select-attribute-values.jsp"; - } - - if (completedRule == null || !Boolean.parseBoolean(completedRule)) { - forwardTo = forwardTo + "?ruleId=" + Encode.forUriComponent(ruleId); - if (category != null && category.trim().length() > 0) { - forwardTo = forwardTo + "&category=" + Encode.forUriComponent(category); - } - - if ("deleteRule".equals(action)) { - forwardTo = forwardTo + "&initiatedFrom=basic-policy-editor"; - } - } - -%> - - - - diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/clear-attribute-cache-ajaxprocessor.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/clear-attribute-cache-ajaxprocessor.jsp deleted file mode 100644 index d4e7ed85b261..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/clear-attribute-cache-ajaxprocessor.jsp +++ /dev/null @@ -1,59 +0,0 @@ - -<%@ page import="org.apache.axis2.context.ConfigurationContext"%> -<%@ page import="org.wso2.carbon.CarbonConstants"%> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementAdminServiceClient"%> -<%@ page import="org.wso2.carbon.ui.CarbonUIMessage"%> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil"%> - -<% - String serverURL = CarbonUIUtil.getServerURL(config - .getServletContext(), session); - ConfigurationContext configContext = (ConfigurationContext) config - .getServletContext().getAttribute( - CarbonConstants.CONFIGURATION_CONTEXT); - String cookie = (String) session - .getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String forwardTo = null; - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - - try { - EntitlementAdminServiceClient client = new EntitlementAdminServiceClient(cookie, serverURL, configContext); - client.clearAttributeCache(); - forwardTo = "pdp-manage.jsp?region=region1&item=policy_menu"; - } catch (Exception e) { - String message = resourceBundle.getString("cache.clear.error"); - CarbonUIMessage.sendCarbonUIMessage(message,CarbonUIMessage.ERROR, request); - forwardTo = "pdp-manage.jsp?region=region1&item=policy_menu"; - } - -%> - -<%@page import="org.wso2.carbon.utils.ServerConstants"%> -<%@ page import="java.util.ResourceBundle" %> - - - \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/clear-cache-ajaxprocessor.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/clear-cache-ajaxprocessor.jsp deleted file mode 100644 index c4df09dbece4..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/clear-cache-ajaxprocessor.jsp +++ /dev/null @@ -1,65 +0,0 @@ - -<%@ page import="org.apache.axis2.context.ConfigurationContext"%> -<%@ page import="org.wso2.carbon.CarbonConstants"%> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementAdminServiceClient"%> -<%@ page import="org.wso2.carbon.ui.CarbonUIMessage"%> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil"%> - -<% - String httpMethod = request.getMethod(); - if (!"post".equalsIgnoreCase(httpMethod)) { - response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); - return; - } - - String serverURL = CarbonUIUtil.getServerURL(config - .getServletContext(), session); - ConfigurationContext configContext = (ConfigurationContext) config - .getServletContext().getAttribute( - CarbonConstants.CONFIGURATION_CONTEXT); - String cookie = (String) session - .getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String forwardTo = null; - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - - try { - EntitlementAdminServiceClient client = new EntitlementAdminServiceClient(cookie, serverURL, configContext); - client.clearDecisionCache(); - forwardTo = "pdp-manage.jsp?region=region1&item=policy_menu"; - } catch (Exception e) { - String message = resourceBundle.getString("cache.clear.error"); - CarbonUIMessage.sendCarbonUIMessage(message,CarbonUIMessage.ERROR, request); - forwardTo = "pdp-manage.jsp?region=region1&item=policy_menu"; - } - -%> - -<%@page import="org.wso2.carbon.utils.ServerConstants"%> -<%@ page import="java.util.ResourceBundle" %> - - - \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/create-evaluation-request.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/create-evaluation-request.jsp deleted file mode 100644 index 0330e33a5447..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/create-evaluation-request.jsp +++ /dev/null @@ -1,292 +0,0 @@ -<%@ page import="org.owasp.encoder.Encode" %> - - -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> -<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %> - - -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> -<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" - prefix="carbon"%> - - -<% - String resourceNames; - String subjectNames; - String actionNames; - String environmentNames; - String multipleRequest; - String returnPolicyList; - String resourceNamesInclude; - String subjectNamesInclude; - String actionNamesInclude; - String environmentNamesInclude; - - String clearAttributes = request.getParameter("clearAttributes"); - if("true".equals(clearAttributes)){ - session.removeAttribute("resourceNames"); - session.removeAttribute("subjectNames"); - session.removeAttribute("attributeId"); - session.removeAttribute("environmentNames"); - session.removeAttribute("actionNames"); - session.removeAttribute("resourceNamesInclude"); - session.removeAttribute("subjectNamesInclude"); - session.removeAttribute("actionNamesInclude"); - session.removeAttribute("environmentNamesInclude"); - session.removeAttribute("multipleRequest"); - session.removeAttribute("returnPolicyList"); - } - - // remove request and response from session - session.removeAttribute("txtRequest"); - session.removeAttribute("txtResponse"); - - - String policyId = request.getParameter("policyId"); - if(policyId != null && policyId.trim().length() > 0){ - session.setAttribute("policyId", policyId); - } else { - policyId = (String)session.getAttribute("policyId"); - } - - resourceNames = (String)session.getAttribute("resourceNames"); - subjectNames = (String)session.getAttribute("subjectNames"); - actionNames = (String)session.getAttribute("actionNames"); - environmentNames = (String)session.getAttribute("environmentNames"); - - multipleRequest = (String)session.getAttribute("multipleRequest"); - returnPolicyList = (String)session.getAttribute("returnPolicyList"); - - resourceNamesInclude = (String)session.getAttribute("resourceNamesInclude"); - subjectNamesInclude = (String)session.getAttribute("subjectNamesInclude"); - actionNamesInclude = (String)session.getAttribute("actionNamesInclude"); - environmentNamesInclude = (String)session.getAttribute("environmentNamesInclude"); -%> - - - - - - - - - - - - - - - -
-

-
-
- -
-
- - - <% - if(policyId != null){ - %> - - - - <% - } - %> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
<%=Encode.forHtmlContent(policyId)%>
- - - -
- <% - if (resourceNames != null && resourceNames.trim().length() > 0) { - %> - - <% - } else { - %> - - <% - } - %> - - -
- <% - if (subjectNames != null && subjectNames.trim().length() > 0) { - %> - - <% - } else { - %> - - <% - } - %> - - -
- <% - if (actionNames != null && actionNames.trim().length() > 0) { - %> - - <% - } else { - %> - - <% - } - %> - - -
- <% - if (environmentNames != null && environmentNames.trim().length() > 0) { - %> - - <% - } else { - %> - - <% - } - %> - - -
- <% - if(policyId != null){ - %> - " class="button"/> - <% - } else { - %> - " class="button"/> - <% - } - %> - " class="button"/> - " class="button"/> - - <% - if(policyId != null){ - %> - " class="button"/> - <% - } - %> - -
-
-
-
-
diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/create-policy-set.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/create-policy-set.jsp deleted file mode 100644 index 1b7a0a5d2002..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/create-policy-set.jsp +++ /dev/null @@ -1,1008 +0,0 @@ - - -<%@ page import="org.apache.axis2.context.ConfigurationContext" %> -<%@ page import="org.owasp.encoder.Encode" %> -<%@ page import="org.wso2.balana.utils.Constants.PolicyConstants" %> -<%@ page import="org.wso2.carbon.CarbonConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.common.EntitlementConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.common.PolicyEditorEngine" %> -<%@ page import="org.wso2.carbon.identity.entitlement.common.dto.PolicyEditorDataHolder" %> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.PaginatedPolicySetDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.EntitlementPolicyConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.PolicyEditorConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.ObligationDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.PolicyRefIdDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.RowDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.TargetDTO" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %> -<%@ page import="org.wso2.carbon.utils.ServerConstants" %> -<%@ page import="java.util.ArrayList" %> -<%@ page import="java.util.List" %> -<%@ page import="java.util.ResourceBundle" %> -<%@ page import="java.util.Set" %> -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> -<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %> - - - - -<% - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - PolicyEditorDataHolder holder = PolicyEditorEngine.getInstance(). - getPolicyEditorData(EntitlementConstants.PolicyEditor.SET); - if(holder == null){ - //String message = MessageFormat.format(resourceBundle.getString("no.policy.editor.data")); - String message = "Policy Editor data can not loaded. Please check with policy editor configurations"; -%> - -<% - } - - String currentCategory = null; - String currentPreFunction = null; - String currentFunction = null; - String currentAttributeValue = null; - String currentAttributeId = null; - String currentAttributeDataType = null; - String currentCombineFunction = null; - - String currentObligationId = null; - String currentObligationEffect = null; - String currentObligationType = null; - String currentObligationAttributeValue = null; - String currentObligationAttributeId = null; - - String selectedAttributeNames = ""; - - String[] ruleEffects = PolicyConstants.RuleEffect.effect; - - String[] combineFunctions = new String[] {PolicyEditorConstants.COMBINE_FUNCTION_END, - PolicyEditorConstants.COMBINE_FUNCTION_AND, PolicyEditorConstants.COMBINE_FUNCTION_OR}; - - Set policyCombingAlgorithm = holder.getPolicyCombiningAlgorithms().keySet(); - - String[] obligationTypes = new String[]{"Obligation", "Advice"}; - - String selectedAttributeDataType = request.getParameter("selectedAttributeDataType"); - String selectedAttributeId = request.getParameter("selectedAttributeId"); - - // These are pass as hidden values. So can contain null value ... - if ("null".equals(selectedAttributeId)) { - selectedAttributeId = null; - } - - if ("null".equals(selectedAttributeDataType)) { - selectedAttributeDataType = null; - } - - int noOfSelectedAttributes = 1; - /** - * Get posted resources from jsp pages and put then in to a String object - */ - while(true) { - String attributeName = request.getParameter("attributeValue" + noOfSelectedAttributes); - if (attributeName == null || attributeName.trim().length() < 1) { - break; - } - if(selectedAttributeNames.equals("")) { - selectedAttributeNames = attributeName.trim(); - } else { - selectedAttributeNames = selectedAttributeNames + "," + attributeName.trim(); - } - noOfSelectedAttributes ++; - } - - - Set categories = holder.getCategoryMap().keySet(); - String[] targetPreFunctions = new String[]{"is"}; - Set targetFunctions = holder.getTargetFunctions(); - - List policyIds = entitlementPolicyBean.getPolicyRefIds(); - TargetDTO targetDTO = entitlementPolicyBean.getTargetDTO(); - List obligationDTOs = entitlementPolicyBean.getObligationDTOs(); - - int numberOfPages = 0; - int pageNumberInt = 0; - String pageNumber = request.getParameter("pageNumber"); - if (pageNumber == null) { - pageNumber = "0"; - } - try { - pageNumberInt = Integer.parseInt(pageNumber); - } catch (NumberFormatException ignored) { - } - - String policyTypeFilter = request.getParameter("policyTypeFilter"); - if (policyTypeFilter == null || "".equals(policyTypeFilter)) { - policyTypeFilter = "ALL"; - } - String policySearchString = request.getParameter("policySearchString"); - if (policySearchString == null) { - policySearchString = "*"; - } else { - policySearchString = policySearchString.trim(); - } - - String paginationValue = "policyTypeFilter=" + policyTypeFilter + - "&policySearchString=" + policySearchString; - - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = - (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String forwardTo = null; - PaginatedPolicySetDTO paginatedPolicySetDTO = null; - org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO[] policies = null; - try { - EntitlementPolicyAdminServiceClient client = - new EntitlementPolicyAdminServiceClient(cookie, serverURL, configContext); - paginatedPolicySetDTO = client. - getAllPolicies(policyTypeFilter, policySearchString, pageNumberInt, false); - policies = paginatedPolicySetDTO.getPolicySet(); - numberOfPages = paginatedPolicySetDTO.getNumberOfPages(); - } catch (Exception e){ - //ignore - } -%> - - - -<% - if(targetDTO != null){ - List rowDTOs = targetDTO.getRowDTOList(); - if(rowDTOs != null && rowDTOs.size() > 0){ - RowDTO rowDTO = rowDTOs.get(0); - currentCategory = rowDTO.getCategory(); - currentPreFunction = rowDTO.getPreFunction(); - currentFunction = rowDTO.getFunction(); - if(rowDTO.isNotCompleted()){ - if(rowDTO.getAttributeValue() != null && rowDTO.getAttributeValue().trim().length() > 0){ - if(selectedAttributeNames != null && selectedAttributeNames.trim().length() > 0){ - currentAttributeValue = rowDTO.getAttributeValue() + "," + selectedAttributeNames; - } else { - currentAttributeValue = rowDTO.getAttributeValue(); - } - } else { - currentAttributeValue = selectedAttributeNames; - } - currentAttributeId = selectedAttributeId; - currentAttributeDataType = selectedAttributeDataType; - } else { - currentAttributeValue = rowDTO.getAttributeValue(); - currentAttributeId = rowDTO.getAttributeId(); - currentAttributeDataType = rowDTO.getAttributeDataType(); - } - currentCombineFunction = rowDTO.getCombineFunction(); - } - } - - - if(obligationDTOs != null && obligationDTOs.size() > 0){ - ObligationDTO dto = obligationDTOs.get(0); - currentObligationType = dto.getType(); - currentObligationId = dto.getObligationId(); - currentObligationEffect = dto.getEffect(); - currentObligationAttributeValue = dto.getAttributeValue(); - currentObligationAttributeId = dto.getResultAttributeId(); - } else { - obligationDTOs = null; - } - -%> - - -<% if(entitlementPolicyBean.isEditPolicy()){%> - -<% } else { %> - -<%}%> - - - - - - - - - -
-<%if(entitlementPolicyBean.isEditPolicy()){%> -

-<%} else {%>

<%}%> -
-
- - - - <% - if (entitlementPolicyBean.getPolicyName() != null) { - %> - - <% - } else { - %> - - <% - } - %> - - - - - - - - - - <% - if (entitlementPolicyBean.getPolicyDescription() != null) { - %> - - <% - } else { - %> - - <% - } - %> - - - - - - - - - - - - - - - - - - - - - - - -
*
- -
- -

- -
- - - - - -
- - - - - - - - - - - - - - - - - - - - -
- - - - - - - <% - if (currentAttributeValue != null && !"".equals(currentAttributeValue)) { - - %> - - <% - } else { - %> - - - <% - } - %> - - - - - - - - -
-
- <% - if(targetDTO != null){ - List rowDTOs = targetDTO.getRowDTOList(); - if(rowDTOs != null && rowDTOs.size() > 0){ - //rowDTOs.remove(0); - for(int i = 1; i < rowDTOs.size(); i ++){ - RowDTO rowDTO = rowDTOs.get(i); - currentCategory = rowDTO.getCategory(); - currentPreFunction = rowDTO.getPreFunction(); - currentFunction = rowDTO.getFunction(); - if(rowDTO.isNotCompleted()){ - if(rowDTO.getAttributeValue() != null && rowDTO.getAttributeValue().trim().length() > 0){ - if(selectedAttributeNames != null && selectedAttributeNames.trim().length() > 0){ - currentAttributeValue = rowDTO.getAttributeValue() + "," + selectedAttributeNames; - } else { - currentAttributeValue = rowDTO.getAttributeValue(); - } - } else { - currentAttributeValue = selectedAttributeNames; - } - currentAttributeId = selectedAttributeId; - currentAttributeDataType = selectedAttributeDataType; - } else { - currentAttributeValue = rowDTO.getAttributeValue(); - currentAttributeId = rowDTO.getAttributeId(); - currentAttributeDataType = rowDTO.getAttributeDataType(); - } - currentCombineFunction = rowDTO.getCombineFunction(); - - %> - - <% - } - } - } - %> -
-
-

-
- - - - - - -
Obligation TypeIdEffect Attribute Value
- - - - - - - - - - - <% - if(obligationDTOs != null && obligationDTOs.size() > 0){ - //obligationDTOs.remove(0); - for(int i = 1; i < obligationDTOs.size(); i++){ - ObligationDTO dto = obligationDTOs.get(i); - currentObligationType = dto.getType(); - currentObligationId = dto.getObligationId(); - currentObligationEffect = dto.getEffect(); - currentObligationAttributeValue = dto.getAttributeValue(); - currentObligationAttributeId = dto.getResultAttributeId(); - %> - - <% - } - } - %> -
- - - <% - if (currentObligationId != null && currentObligationId.trim().length() > 0) { - %> - - <% - } else { - %> - - <% - } - %> - - - - <% - if (currentObligationAttributeValue != null && currentObligationAttributeValue.trim().length() > 0) { - %> - - <% - } else { - %> - - <% - } - %> - -
-
-
-

-
- - - - -
- - - - - - - -
- - - "/>  - - - "> -
-
- - - - <% - if (policies != null) { - for (int i = 0; i < policies.length; i++) { - if(policies[i] != null){ - %> - - - - - <% } - } - } else { %> - - - - <%}%> - -
- <%=Encode.forHtmlContent(policies[i].getPolicyId())%> - - - -
- -
-
- - - - - - - - - <% - if (policyIds != null && policyIds.size() > 0) { - List orderedPolicyDTOs = new ArrayList(); - String policyReferenceOrder = entitlementPolicyBean.getPolicyReferenceOrder(); - if (policyReferenceOrder != null) { - String[] orderedRuleIds = policyReferenceOrder.split(EntitlementPolicyConstants.ATTRIBUTE_SEPARATOR); - for (String orderedRuleId : orderedRuleIds) { - for (PolicyRefIdDTO dto : policyIds) { - if (orderedRuleId.trim().equals(dto.getId())) { - orderedPolicyDTOs.add(dto); - } - } - } - } - - if (orderedPolicyDTOs.size() < 1) { - orderedPolicyDTOs = policyIds; - } - for (PolicyRefIdDTO orderedRuleDTO : orderedPolicyDTOs) { - %> - - - - - - - <% - } - } else { - %> - - - - <% - } - %> -
- - - - <%=Encode.forHtml(orderedRuleDTO.getId())%> - <%=orderedRuleDTO.isReferenceOnly()%> - - -

-
- " - class="button"/> - " - class="button"/> -
-
-
-
-
diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/css/entitlement.css b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/css/entitlement.css deleted file mode 100644 index aa5f41b7b460..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/css/entitlement.css +++ /dev/null @@ -1,91 +0,0 @@ -.arrowUp { - background-image: url(../images/up.gif) !important; -} - -.arrowDown { - background-image: url(../images/down.gif) !important; -} - -#middle { - line-height: 30px; -} - -.noRuleBox { - color: #999; - border: solid 1px #ccc; - padding: 5px; - font-style: italic; -} - -.text-box-big { - width: 320px !important; -} - -.defaultText { - color: #666666; - font-style: italic; -} - -.goToAdvance { - border: solid 1px #ccc; - background-color: #e3f2db; - padding: 5px; - margin-bottom: 10px; -} - -.formTableTabed{ - margin:10px; -} - -.formTableTabed td{ - padding:10px; -} - -table#main-table table.oneline-listing td { - padding: 0 5px !important; - line-height: 15px; -} -table#main-table table.oneline-listing { - border-left: 1px solid #CCCCCC; - border-right: 1px solid #CCCCCC; - border-bottom: 1px solid #CCCCCC; - border-top: 5px solid #CCCCCC; - margin-top: 3px; - padding: 8px; -} - - -table#main-table table.oneline-listing-alt td { - padding: 0 5px !important; - line-height: 15px; -} -table#main-table table.oneline-listing-alt { - margin-top: 3px; - padding: 8px; -} - -#middle div.sectionSeperator, #middle div.sectionHelp{ - line-height:10px; -} -#middle div.sectionHelp{ - margin-top:10px; -} -.sectionSubShifter{ - margin-top:-25px; -} -.leftCol-vsmall{ - width:50px; -} -div#workArea table.styledLeft tbody tr td table.ob-table{ - line-height:20px; -} -div#workArea table.styledLeft tbody tr td table.ob-table td{ - height:auto; - padding:0 !important; -} -#obligationRuleTable,#obligationTable{ - margin-top:-10px; -} -.heading_A{ - padding-top:20px; -} \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/css/tree-styles.css b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/css/tree-styles.css deleted file mode 100644 index d20769b238fb..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/css/tree-styles.css +++ /dev/null @@ -1,86 +0,0 @@ -.treeControl{ - height: 300px; - overflow: auto; - width: 500px; -} -.treeControl ul{ - padding:0px; - margin:0px; -} - -.treeControl ul li{ - list-style:none; - padding-left:15px; - padding-top:5px; - white-space:nowrap; -} -.treeControl ul li a.plus{ - background-image:url(../images/plus.gif); - background-repeat:no-repeat; - background-position:0px 2px; - padding-left:15px; - cursor:pointer; -} -.treeControl ul li a.minus{ - background-image:url(../images/minus.gif); - background-repeat:no-repeat; - background-position:0px 2px; - padding-left:15px; - cursor:pointer; -} -.treeControl ul li a.nodata{ - background-image:url(../images/nodata.gif); - background-repeat:no-repeat; - background-position:0px 2px; - padding-left:15px; - cursor:pointer; -} -.treeControl ul li a.treeNode{ - cursor:pointer; - color:#4c99c3; - padding:3px; -} -.treeControl ul li a.selected{ - background-color: #666666; - color:#fff; -} -.button-dif, .button-dif:visited { - width:30px; - background-image: -webkit-gradient(linear, left top, left bottom, from(#eeeeee), to(#ffffff)); /* mozilla - FF3.6+ */ - background-image: -moz-linear-gradient(top, #eeeeee 0%, #ffffff 100%); /* IE 5.5 - 7 */ - filter: progid:DXImageTransform.Microsoft.gradient(gradientType = 0, startColorStr = #eeeeee, endColorStr = #ffffff); /* IE8 */ - -ms-filter: progid: DXImageTransform.Microsoft.gradient(gradientType = 0, startColorStr = #eeeeee, endColoStr = #ffffff); - display: inline-block; - padding: 5px 5px 6px; - color: #000; - text-decoration: none; - -moz-border-radius: 6px; - -webkit-border-radius: 6px; - -moz-box-shadow: 0 1px 3px rgba(0,0,0,0.6); - -webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.6); - text-shadow: 0 -1px 1px rgba(0,0,0,0.25); - border-bottom: 1px solid rgba(0,0,0,0.25); - position: relative; - cursor: pointer -} -.treeTable td{ - padding:10px; - vertical-align:top; - border:solid 1px #ccc; -} -.listViewItem{ - width:auto; -} - -.listViewItemDel { - cursor: pointer; - float: left; - display: block; - width: 15%; - padding-top: 5px; -} - -.listViewItemContent { - float: left; - width: 85% -} \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/delete-policy-entry.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/delete-policy-entry.jsp deleted file mode 100644 index 8ff3b710a2cb..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/delete-policy-entry.jsp +++ /dev/null @@ -1,38 +0,0 @@ - - - - -<% - String forwardTo = "create-policy-set.jsp"; - String policyId = request.getParameter("policyRefId"); - if(policyId != null && policyId.trim().length() > 0){ - entitlementPolicyBean.removePolicyRefId(policyId); - } -%> - - - - \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/delete-rule-entry.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/delete-rule-entry.jsp deleted file mode 100644 index ef3264aae757..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/delete-rule-entry.jsp +++ /dev/null @@ -1,48 +0,0 @@ -<%@ page import="org.apache.commons.lang.StringUtils" %> - - - - -<% - String forwardTo = null; - String ruleId = request.getParameter("ruleId"); - String initiatedPage = request.getParameter("initiatedFrom"); - if(StringUtils.equals("basic-policy-editor", initiatedPage)){ - if(ruleId != null && ruleId.trim().length() > 0){ - entitlementPolicyBean.removeBasicRuleElement(ruleId); - } - forwardTo = "basic-policy-editor.jsp"; - } else { - if(ruleId != null && ruleId.trim().length() > 0){ - entitlementPolicyBean.removeRuleDTO(ruleId); - } - forwardTo = "policy-editor.jsp"; - } -%> - - - - \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/edit-policy.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/edit-policy.jsp deleted file mode 100644 index 5b58d78325c5..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/edit-policy.jsp +++ /dev/null @@ -1,134 +0,0 @@ - -<%@ page import="org.apache.axis2.context.ConfigurationContext"%> -<%@ page import="org.wso2.balana.utils.policy.dto.BasicPolicyDTO"%> -<%@ page import="org.wso2.balana.utils.policy.dto.PolicyElementDTO"%> -<%@ page import="org.wso2.carbon.CarbonConstants"%> - - -<% - entitlementPolicyBean.cleanEntitlementPolicyBean(); - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = - (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String forwardTo = null; - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - EntitlementPolicyAdminServiceClient client = new EntitlementPolicyAdminServiceClient(cookie, serverURL, configContext); - String policyId = request.getParameter("policyid"); - PolicyDTO policyDTO = client.getPolicy(policyId, false); - String[] policyEditorData = policyDTO.getPolicyEditorData(); - - try { - if(EntitlementConstants.PolicyEditor.SET.equals(policyDTO.getPolicyEditor())){ - TargetDTO targetDTO = new TargetDTO(); - List obligationDTOs = new ArrayList(); - List policyRefIdDTOs = new ArrayList(); - PolicyElementDTO elementDTO = new PolicyElementDTO(); - - PolicyEditorUtil.processPolicyEditorData(elementDTO, policyEditorData); - PolicyEditorUtil.processTargetPolicyEditorData(targetDTO, policyEditorData); - PolicyEditorUtil.processObligationPolicyEditorData(obligationDTOs, policyEditorData); - PolicyEditorUtil.processReferencePolicyEditorData(policyRefIdDTOs, policyEditorData); - - entitlementPolicyBean.setPolicyName(elementDTO.getPolicyName()); - entitlementPolicyBean.setAlgorithmName(elementDTO.getRuleCombiningAlgorithms()); - entitlementPolicyBean.setPolicyDescription(elementDTO.getPolicyDescription()); - - entitlementPolicyBean.setTargetDTO(targetDTO); - entitlementPolicyBean.setObligationDTOs(obligationDTOs); - entitlementPolicyBean.setPolicyRefIds(policyRefIdDTOs); - entitlementPolicyBean.setEditPolicy(true); - forwardTo="create-policy-set.jsp"; - } else { - if(EntitlementConstants.PolicyEditor.BASIC.equals(policyDTO.getPolicyEditor())){ - BasicPolicyDTO basicPolicyDTO = PolicyEditorUtil.createBasicPolicyDTO(policyEditorData); - - entitlementPolicyBean.setPolicyName(basicPolicyDTO.getPolicyId()); - entitlementPolicyBean.setAlgorithmName(basicPolicyDTO.getRuleAlgorithm()); - entitlementPolicyBean.setPolicyDescription(basicPolicyDTO.getDescription()); - - entitlementPolicyBean.setBasicTargetDTO(basicPolicyDTO.getTargetDTO()); - entitlementPolicyBean.setBasicRuleDTOs(basicPolicyDTO.getBasicRuleDTOs()); - entitlementPolicyBean.setEditPolicy(true); - forwardTo="basic-policy-editor.jsp"; - - } else if(EntitlementConstants.PolicyEditor.STANDARD.equals(policyDTO.getPolicyEditor())){ - - TargetDTO targetDTO = new TargetDTO(); - List ruleDTOs = new ArrayList(); - List obligationDTOs = new ArrayList(); - PolicyElementDTO elementDTO = new PolicyElementDTO(); - - PolicyEditorUtil.processPolicyEditorData(elementDTO, policyEditorData); - PolicyEditorUtil.processRulePolicyEditorData(ruleDTOs, policyEditorData); - PolicyEditorUtil.processTargetPolicyEditorData(targetDTO, policyEditorData); - PolicyEditorUtil.processObligationPolicyEditorData(obligationDTOs, policyEditorData); - - entitlementPolicyBean.setPolicyName(elementDTO.getPolicyName()); - entitlementPolicyBean.setAlgorithmName(elementDTO.getRuleCombiningAlgorithms()); - entitlementPolicyBean.setPolicyDescription(elementDTO.getPolicyDescription()); - - entitlementPolicyBean.setTargetDTO(targetDTO); - entitlementPolicyBean.setRuleDTOs(ruleDTOs); - entitlementPolicyBean.setObligationDTOs(obligationDTOs); - entitlementPolicyBean.setEditPolicy(true); - forwardTo="policy-editor.jsp"; - - } else if (EntitlementConstants.PolicyEditor.RBAC.equals(policyDTO.getPolicyEditor())) { - SimplePolicyEditorDTO editorDTO = PolicyEditorUtil.createSimplePolicyEditorDTO(policyEditorData); - entitlementPolicyBean.setSimplePolicyEditorDTO(editorDTO); - entitlementPolicyBean.setEditPolicy(true); - forwardTo="simple-policy-editor.jsp"; - } else { - session.setAttribute("policy", policyDTO.getPolicy()); - forwardTo="policy-view.jsp?policyid=" + Encode.forUriComponent(policyId); - } - } - } catch (Exception e) { - session.setAttribute("policy", policyDTO.getPolicy()); - forwardTo="policy-view.jsp?policyid=" + Encode.forUriComponent(policyId); - } -%> - -<%@page import="org.wso2.carbon.identity.entitlement.common.EntitlementConstants"%> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.ObligationDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.PolicyRefIdDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.RuleDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.SimplePolicyEditorDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.TargetDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.util.PolicyEditorUtil" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %> -<%@ page import="org.wso2.carbon.utils.ServerConstants" %> -<%@ page import="java.util.ArrayList" %> -<%@ page import="java.util.List" %> -<%@ page import="org.owasp.encoder.Encode" %> - - - - \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/enable-disable-policy-ajaxprocessor.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/enable-disable-policy-ajaxprocessor.jsp deleted file mode 100644 index c53c886aa5c3..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/enable-disable-policy-ajaxprocessor.jsp +++ /dev/null @@ -1,75 +0,0 @@ - -<%@ page import="org.apache.axis2.context.ConfigurationContext"%> -<%@ page import="org.wso2.carbon.CarbonConstants"%> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient"%> -<%@ page import="org.wso2.carbon.ui.CarbonUIMessage"%> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil"%> - -<%@page import="org.wso2.carbon.utils.ServerConstants"%> -<%@page import="java.util.ResourceBundle"%> -<% - String httpMethod = request.getMethod(); - if (!"post".equalsIgnoreCase(httpMethod)) { - response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); - return; - } - - String serverURL = CarbonUIUtil.getServerURL(config - .getServletContext(), session); - ConfigurationContext configContext = (ConfigurationContext) config - .getServletContext().getAttribute( - CarbonConstants.CONFIGURATION_CONTEXT); - String cookie = (String) session - .getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String forwardTo = "my-pdp.jsp"; - String action = request.getParameter("action"); - String policyid = request.getParameter("policyid"); - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - - if ((request.getParameter("policyid") != null)) { - try { - EntitlementPolicyAdminServiceClient client = - new EntitlementPolicyAdminServiceClient(cookie, serverURL, configContext); - if ("enable".equals(action)){ - client.enableDisablePolicy(policyid, true); - String message = resourceBundle.getString("policy.enabled.successfully"); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.INFO, request); - } else if("disable".equals(action)) { - client.enableDisablePolicy(policyid, false); - String message = resourceBundle.getString("policy.disable.successfully"); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.INFO, request); - } - } catch (Exception e) { - String message = resourceBundle.getString("error.while.enabling.policy") + e.getMessage(); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.ERROR, request); - } - } -%> - - - - \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/eval-policy-submit.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/eval-policy-submit.jsp deleted file mode 100644 index b35e18cfe2a0..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/eval-policy-submit.jsp +++ /dev/null @@ -1,170 +0,0 @@ - -<%@ page import="org.apache.axis2.context.ConfigurationContext"%> -<%@ page import="org.wso2.carbon.CarbonConstants"%> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.EntitlementPolicyConstants"%> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.EntitlementPolicyCreator"%> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementAdminServiceClient"%> - -<% - boolean evaluatedWithPDP = false; - String requestString = request.getParameter("txtRequest"); - String withPDP = request.getParameter("withPDP"); - if("true".equals(withPDP)){ - evaluatedWithPDP = true; - } - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = - (ConfigurationContext) config.getServletContext(). - getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String resp = null; - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - - List rowDTOs = new ArrayList(); - String resourceNames = request.getParameter("resourceNames"); - String subjectNames = request.getParameter("subjectNames"); - String actionNames = request.getParameter("actionNames"); - String environmentNames = request.getParameter("environmentNames"); - String multipleRequest = request.getParameter("multipleRequest"); - String returnPolicyList = request.getParameter("returnPolicyList"); - - if (resourceNames != null && resourceNames.trim().length() > 0){ - RowDTO rowDTO = new RowDTO(); - rowDTO.setAttributeValue(resourceNames); - rowDTO.setAttributeDataType(EntitlementPolicyConstants.STRING_DATA_TYPE); - rowDTO.setAttributeId("urn:oasis:names:tc:xacml:1.0:resource:resource-id"); - rowDTO.setCategory("urn:oasis:names:tc:xacml:3.0:attribute-category:resource"); - String resourceNamesInclude = request.getParameter("resourceNamesInclude"); - if(resourceNamesInclude != null){ - rowDTO.setNotCompleted(Boolean.parseBoolean(resourceNamesInclude)); - session.setAttribute("resourceNamesInclude",resourceNamesInclude); - } - rowDTOs.add(rowDTO); - session.setAttribute("resourceNames",resourceNames); - } - if (subjectNames != null && subjectNames.trim().length() > 0){ - RowDTO rowDTO = new RowDTO(); - rowDTO.setAttributeValue(subjectNames); - rowDTO.setAttributeDataType(EntitlementPolicyConstants.STRING_DATA_TYPE); - rowDTO.setAttributeId("urn:oasis:names:tc:xacml:1.0:subject:subject-id"); - rowDTO.setCategory("urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"); - String subjectNamesInclude = request.getParameter("subjectNamesInclude"); - if(subjectNamesInclude != null){ - rowDTO.setNotCompleted(Boolean.parseBoolean(subjectNamesInclude)); - session.setAttribute("subjectNamesInclude",subjectNamesInclude); - } - rowDTOs.add(rowDTO); - session.setAttribute("subjectNames",subjectNames); - } - if (actionNames != null && actionNames.trim().length() > 0){ - RowDTO rowDTO = new RowDTO(); - rowDTO.setAttributeValue(actionNames); - rowDTO.setAttributeDataType(EntitlementPolicyConstants.STRING_DATA_TYPE); - rowDTO.setAttributeId("urn:oasis:names:tc:xacml:1.0:action:action-id"); - rowDTO.setCategory("urn:oasis:names:tc:xacml:3.0:attribute-category:action"); - String actionNamesInclude = request.getParameter("actionNamesInclude"); - if(actionNamesInclude != null){ - rowDTO.setNotCompleted(Boolean.parseBoolean(actionNamesInclude)); - session.setAttribute("actionNamesInclude",actionNamesInclude); - } - rowDTOs.add(rowDTO); - session.setAttribute("actionNames",actionNames); - } - if (environmentNames != null && environmentNames.trim().length() > 0){ - RowDTO rowDTO = new RowDTO(); - rowDTO.setAttributeValue(environmentNames); - rowDTO.setAttributeDataType(EntitlementPolicyConstants.STRING_DATA_TYPE); - rowDTO.setAttributeId("urn:oasis:names:tc:xacml:1.0:environment:environment-id"); - rowDTO.setCategory("urn:oasis:names:tc:xacml:3.0:attribute-category:environment"); - rowDTOs.add(rowDTO); - String environmentNamesInclude = request.getParameter("environmentNamesInclude"); - if(environmentNamesInclude != null){ - rowDTO.setNotCompleted(Boolean.parseBoolean(environmentNamesInclude)); - session.setAttribute("actionNamesInclude",environmentNamesInclude); - } - session.setAttribute("environmentNames", environmentNames); - } - - RequestDTO requestDTO = new RequestDTO(); - if(multipleRequest != null){ - requestDTO.setMultipleRequest(Boolean.parseBoolean(multipleRequest)); - session.setAttribute("multipleRequest", multipleRequest); - } - if(returnPolicyList != null){ - requestDTO.setReturnPolicyIdList(Boolean.parseBoolean(returnPolicyList)); - session.setAttribute("returnPolicyList", returnPolicyList); - } - requestDTO.setRowDTOs(rowDTOs); - - EntitlementPolicyCreator entitlementPolicyCreator = new EntitlementPolicyCreator(); - - try { - EntitlementAdminServiceClient adminClient = - new EntitlementAdminServiceClient(cookie, serverURL, configContext); - EntitlementServiceClient client = new EntitlementServiceClient(cookie, serverURL, configContext); - if(requestString == null || requestString.trim().length() < 1){ - String createdRequest = entitlementPolicyCreator.createBasicRequest(requestDTO); - if(createdRequest != null && createdRequest.trim().length() > 0){ - requestString = createdRequest.trim().replaceAll("><", ">\n<"); - } - } - if(evaluatedWithPDP){ - resp = client.getDecision(requestString); - } else { - String policyId = (String) session.getAttribute("policyId"); - if(policyId != null){ - resp = adminClient.getDecision(requestString, new String[]{policyId}); - } else { - resp = adminClient.getDecision(requestString); - } - } - - String responseValue = ClientUtil.getStatus(resp); - - session.setAttribute("txtRequest", requestString); - session.setAttribute("txtResponse", resp); - - CarbonUIMessage.sendCarbonUIMessage(responseValue, CarbonUIMessage.INFO, request); - } catch (Exception e) { - String message = resourceBundle.getString("invalid.request"); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.ERROR, request); - } -%> - -<%@page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementServiceClient"%> -<%@page import="org.wso2.carbon.identity.entitlement.ui.dto.RequestDTO"%> -<%@page import="org.wso2.carbon.identity.entitlement.ui.dto.RowDTO" %> -<%@page import="org.wso2.carbon.identity.entitlement.ui.util.ClientUtil" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIMessage" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %> -<%@ page import="org.wso2.carbon.utils.ServerConstants" %> -<%@ page import="java.util.ArrayList" %> -<%@ page import="java.util.List" %> -<%@ page import="java.util.ResourceBundle" %> - - - \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/eval-policy.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/eval-policy.jsp deleted file mode 100644 index a8ba968fd855..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/eval-policy.jsp +++ /dev/null @@ -1,273 +0,0 @@ - - -<%@ page import="org.wso2.carbon.identity.entitlement.ui.EntitlementPolicyConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.EntitlementPolicyCreator" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.RequestDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.RowDTO" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIMessage" %> -<%@ page import="java.util.ArrayList" %> -<%@ page import="java.util.List" %> -<%@ page import="org.owasp.encoder.Encode" %> - -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> -<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" - prefix="carbon"%> - - - -<% - String forwardTo = null; - boolean showResponse = false; - String requestString = (String)session.getAttribute("txtRequest"); - String responseString = (String)session.getAttribute("txtResponse"); - String policyId = (String)session.getAttribute("policyId"); - String isResponse = request.getParameter("isResponse"); - if(isResponse != null && isResponse.trim().length() > 0){ - showResponse = true; - } - if(responseString != null){ - responseString = responseString.trim().replaceAll("><", ">\n<"); - } else { - responseString = ""; - } - if(!showResponse){ - List rowDTOs = new ArrayList(); - String multipleRequest = request.getParameter("multipleRequest"); - String returnPolicyList = request.getParameter("returnPolicyList"); - String resourceNames = request.getParameter("resourceNames"); - String subjectNames = request.getParameter("subjectNames"); - String actionNames = request.getParameter("actionNames"); - String environmentNames = request.getParameter("environmentNames"); - - if (resourceNames != null && !resourceNames.trim().equals("")){ - RowDTO rowDTO = new RowDTO(); - rowDTO.setAttributeValue(resourceNames); - rowDTO.setAttributeDataType(EntitlementPolicyConstants.STRING_DATA_TYPE); - rowDTO.setAttributeId("urn:oasis:names:tc:xacml:1.0:resource:resource-id"); - rowDTO.setCategory("urn:oasis:names:tc:xacml:3.0:attribute-category:resource"); - String resourceNamesInclude = request.getParameter("resourceNamesInclude"); - if(resourceNamesInclude != null){ - rowDTO.setNotCompleted(Boolean.parseBoolean(resourceNamesInclude)); - session.setAttribute("resourceNamesInclude",resourceNamesInclude); - } - rowDTOs.add(rowDTO); - session.setAttribute("resourceNames",resourceNames); - } - if (subjectNames != null && !subjectNames.trim().equals("")){ - RowDTO rowDTO = new RowDTO(); - rowDTO.setAttributeValue(subjectNames); - rowDTO.setAttributeDataType(EntitlementPolicyConstants.STRING_DATA_TYPE); - rowDTO.setAttributeId("urn:oasis:names:tc:xacml:1.0:subject:subject-id"); - rowDTO.setCategory("urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"); - String subjectNamesInclude = request.getParameter("subjectNamesInclude"); - if(subjectNamesInclude != null){ - rowDTO.setNotCompleted(Boolean.parseBoolean(subjectNamesInclude)); - session.setAttribute("subjectNamesInclude",subjectNamesInclude); - } - rowDTOs.add(rowDTO); - session.setAttribute("subjectNames",subjectNames); - } - if (actionNames != null && !actionNames.trim().equals("")){ - RowDTO rowDTO = new RowDTO(); - rowDTO.setAttributeValue(actionNames); - rowDTO.setAttributeDataType(EntitlementPolicyConstants.STRING_DATA_TYPE); - rowDTO.setAttributeId("urn:oasis:names:tc:xacml:1.0:action:action-id"); - rowDTO.setCategory("urn:oasis:names:tc:xacml:3.0:attribute-category:action"); - String actionNamesInclude = request.getParameter("actionNamesInclude"); - if(actionNamesInclude != null){ - rowDTO.setNotCompleted(Boolean.parseBoolean(actionNamesInclude)); - session.setAttribute("actionNamesInclude",actionNamesInclude); - } - rowDTOs.add(rowDTO); - session.setAttribute("actionNames",actionNames); - } - if (environmentNames != null && !environmentNames.trim().equals("")){ - RowDTO rowDTO = new RowDTO(); - rowDTO.setAttributeValue(environmentNames); - rowDTO.setAttributeDataType(EntitlementPolicyConstants.STRING_DATA_TYPE); - rowDTO.setAttributeId("urn:oasis:names:tc:xacml:1.0:environment:environment-id"); - rowDTO.setCategory("urn:oasis:names:tc:xacml:3.0:attribute-category:environment"); - String environmentNamesInclude = request.getParameter("environmentNamesInclude"); - if(environmentNamesInclude != null){ - rowDTO.setNotCompleted(Boolean.parseBoolean(environmentNamesInclude)); - session.setAttribute("actionNamesInclude",environmentNamesInclude); - } - rowDTOs.add(rowDTO); - session.setAttribute("environmentNames",environmentNames); - } - - RequestDTO requestDTO = new RequestDTO(); - if(multipleRequest != null){ - requestDTO.setMultipleRequest(Boolean.parseBoolean(multipleRequest)); - session.setAttribute("multipleRequest", multipleRequest); - } - if(returnPolicyList != null){ - requestDTO.setReturnPolicyIdList(Boolean.parseBoolean(returnPolicyList)); - session.setAttribute("returnPolicyList", returnPolicyList); - } - requestDTO.setRowDTOs(rowDTOs); - - EntitlementPolicyCreator entitlementPolicyCreator = new EntitlementPolicyCreator(); - try { - if(requestString != null && requestString.trim().length() > 0){ - requestString = requestString.trim().replaceAll("><", ">\n<"); - } else if(!requestDTO.getRowDTOs().isEmpty()){ - String createdRequest = entitlementPolicyCreator.createBasicRequest(requestDTO); - if(createdRequest != null && createdRequest.trim().length() > 0){ - requestString = createdRequest.trim().replaceAll("><", ">\n<"); - } - } else { - requestString = ""; - } - } catch (Exception e) { - CarbonUIMessage.sendCarbonUIMessage(e.getMessage(), CarbonUIMessage.ERROR, request); - forwardTo = "../admin/error.jsp"; - %> - - <% - } - } -%> - - - - - - - - - - - - - -
-

-
-
- - - - - - - - - - - - - - - -
- <% - if(showResponse){ - %> - - <% - } else { - %> - - <% - } - %> -
-
- - - -
-
- <% - if(showResponse){ - %> - - <% - } else { - %> - <% - if(policyId != null){ - %> - - <% - }else { - %> - - <% - } - %> - - - <% - } - %> -
-
-
-
-
diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/finish-policy-set.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/finish-policy-set.jsp deleted file mode 100644 index bdc6e697e2ce..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/finish-policy-set.jsp +++ /dev/null @@ -1,127 +0,0 @@ - -<%@ page import="org.apache.axis2.context.ConfigurationContext"%> -<%@ page import="org.wso2.carbon.CarbonConstants"%> -<%@ page import="org.wso2.carbon.identity.entitlement.common.EntitlementConstants"%> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO"%> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.EntitlementPolicyCreator"%> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient"%> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.ObligationDTO"%> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.PolicyRefIdDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.PolicySetDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.TargetDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.util.PolicyEditorUtil" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIMessage" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %> -<%@ page import="org.wso2.carbon.utils.ServerConstants" %> -<%@ page import="java.util.List" %> -<%@ page import="java.util.ResourceBundle" %> - - -<% - - String policyOrderOrder = entitlementPolicyBean.getPolicyReferenceOrder(); - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = - (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants. - CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String forwardTo = null; - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - - String policyName = entitlementPolicyBean.getPolicyName(); - String algorithmName = entitlementPolicyBean.getAlgorithmName(); - String policyDescription = entitlementPolicyBean.getPolicyDescription(); - - TargetDTO targetDTO = entitlementPolicyBean.getTargetDTO(); - List obligationDTOs = entitlementPolicyBean.getObligationDTOs(); - List policyRefIdDTOs = entitlementPolicyBean.getPolicyRefIds(); - - PolicySetDTO policySetDTO = new PolicySetDTO(); - org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO policyDTO = null; - String message = null; - try { - if(policyName != null && policyName.trim().length() > 0 && algorithmName != null - && algorithmName.trim().length() > 0) { - policySetDTO.setPolicySetId(policyName); - policySetDTO.setPolicyCombiningAlgId(algorithmName); - policySetDTO.setDescription(policyDescription); - policySetDTO.setPolicyOrder(policyOrderOrder); - policySetDTO.setTargetDTO(targetDTO); - policySetDTO.setObligations(obligationDTOs); - policySetDTO.setPolicyRefIdDTOs(policyRefIdDTOs); - EntitlementPolicyAdminServiceClient client = new EntitlementPolicyAdminServiceClient(cookie, - serverURL, configContext); - EntitlementPolicyCreator policyCreator = new EntitlementPolicyCreator(); - - String[] policyEditorData = PolicyEditorUtil.processPolicySetData(policySetDTO); - String policyString = policyCreator.createPolicySet(policySetDTO, client); - - if(entitlementPolicyBean.isEditPolicy()){ - try{ - policyDTO = client.getPolicy(policyName, false); - } catch (Exception e){ - //ignore - } - - if(policyDTO == null){ - policyDTO = new PolicyDTO(); - } - - policyDTO.setPolicy(policyString); - policyDTO.setPolicyEditor(EntitlementConstants.PolicyEditor.SET); - if(policyEditorData != null){ - policyDTO.setPolicyEditorData(policyEditorData); - } - client.updatePolicy(policyDTO); - message = resourceBundle.getString("updated.successfully"); - } else { - policyDTO = new PolicyDTO(); - policyDTO.setPolicyId(policyName); - policyDTO.setPolicy(policyString); - policyDTO.setPolicyEditor(EntitlementConstants.PolicyEditor.SET); - if(policyEditorData != null){ - policyDTO.setPolicyEditorData(policyEditorData); - } - client.addPolicy(policyDTO); - message = resourceBundle.getString("ent.policy.added.successfully"); - } - entitlementPolicyBean.cleanEntitlementPolicyBean(); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.INFO, request); - } - entitlementPolicyBean.cleanEntitlementPolicyBean(); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.INFO, request); - forwardTo = "index.jsp?"; - } catch (Exception e) { - message = resourceBundle.getString("error.while.adding.policy") + " " + e.getMessage(); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.ERROR, request); - forwardTo = "index.jsp?"; - } -%> - - - \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/finish.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/finish.jsp deleted file mode 100644 index da6bea9594f1..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/finish.jsp +++ /dev/null @@ -1,129 +0,0 @@ - -<%@ page import="org.apache.axis2.context.ConfigurationContext"%> -<%@ page import="org.wso2.carbon.CarbonConstants"%> -<%@ page import="org.wso2.carbon.identity.entitlement.common.EntitlementConstants"%> -<%@ page import="org.wso2.carbon.identity.entitlement.common.PolicyEditorException"%> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.EntitlementPolicyCreator"%> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient"%> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.ObligationDTO"%> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.PolicyDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.RuleDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.TargetDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.util.PolicyEditorUtil" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIMessage" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %> -<%@ page import="org.wso2.carbon.utils.ServerConstants" %> -<%@ page import="java.util.List" %> -<%@ page import="java.util.ResourceBundle" %> - - -<% - - String ruleElementOrder = entitlementPolicyBean.getRuleElementOrder(); - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = - (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants. - CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String forwardTo = null; - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - - org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO policy = null; - String policyName = entitlementPolicyBean.getPolicyName(); - String algorithmName = entitlementPolicyBean.getAlgorithmName(); - String policyDescription = entitlementPolicyBean.getPolicyDescription(); - - List ruleDTOs = entitlementPolicyBean.getRuleDTOs(); - TargetDTO targetDTO = entitlementPolicyBean.getTargetDTO(); - List obligationDTOs = entitlementPolicyBean.getObligationDTOs(); - String message = ""; - try { - - if(policyName != null && policyName.trim().length() > 0 && algorithmName != null - && algorithmName.trim().length() > 0) { - PolicyDTO policyDTO = new PolicyDTO(); - policyDTO.setPolicyId(policyName); - policyDTO.setRuleAlgorithm(algorithmName); - policyDTO.setDescription(policyDescription); - policyDTO.setRuleOrder(ruleElementOrder); - policyDTO.setRuleDTOs(ruleDTOs); - policyDTO.setTargetDTO(targetDTO); - policyDTO.setObligationDTOs(obligationDTOs); - EntitlementPolicyAdminServiceClient client = new EntitlementPolicyAdminServiceClient(cookie, - serverURL, configContext); - EntitlementPolicyCreator policyCreator = new EntitlementPolicyCreator(); - String[] policyEditorData = PolicyEditorUtil.processPolicyData(policyDTO); - String policyString = policyCreator.createPolicy(policyDTO); - - if(entitlementPolicyBean.isEditPolicy()){ - try{ - policy = client.getPolicy(policyName, false); - } catch (Exception e){ - //ignore - } - - if(policy == null){ - policy = new org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO(); - } - policy.setPolicyEditor(EntitlementConstants.PolicyEditor.STANDARD); - if(policyEditorData != null){ - policy.setPolicyEditorData(policyEditorData); - } - policy.setPolicyId(policyName); - policy.setPolicy(policyString); - client.updatePolicy(policy); - message = resourceBundle.getString("updated.successfully"); - } else { - policy = new org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO(); - if(policyEditorData != null){ - policy.setPolicyEditorData(policyEditorData); - } - policy.setPolicyId(policyName); - policy.setPolicy(policyString); - policy.setPolicyEditor(EntitlementConstants.PolicyEditor.STANDARD); - client.addPolicy(policy); - message = resourceBundle.getString("ent.policy.added.successfully"); - } - - entitlementPolicyBean.cleanEntitlementPolicyBean(); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.INFO, request); - forwardTo = "index.jsp?"; - } - } catch (PolicyEditorException e) { - message = resourceBundle.getString("error.while.creating.policy"); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.ERROR, request); - forwardTo = "index.jsp?"; - } catch (Exception e) { - message = resourceBundle.getString("error.while.adding.policy") + " " + e.getMessage(); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.ERROR, request); - forwardTo = "index.jsp?"; - } -%> - - - \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/Policy-type.gif b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/Policy-type.gif deleted file mode 100644 index f07a5202980f..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/Policy-type.gif and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/PolicySet-type.gif b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/PolicySet-type.gif deleted file mode 100644 index 638d8ab6ea9d..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/PolicySet-type.gif and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/actions.png b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/actions.png deleted file mode 100644 index b59bf13c1e47..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/actions.png and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/add-new-policy.png b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/add-new-policy.png deleted file mode 100644 index 05d899d0b134..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/add-new-policy.png and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/add-policy.png b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/add-policy.png deleted file mode 100644 index 78a34601e828..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/add-policy.png and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/add.gif b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/add.gif deleted file mode 100644 index 4bfdd7983ecb..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/add.gif and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/advance-search.png b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/advance-search.png deleted file mode 100644 index 01248fbecbce..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/advance-search.png and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/advanceview.png b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/advanceview.png deleted file mode 100644 index fbe8bdc00d07..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/advanceview.png and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/basic-pap.png b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/basic-pap.png deleted file mode 100644 index 88e0b76b5afe..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/basic-pap.png and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/basic-policy-editor.png b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/basic-policy-editor.png deleted file mode 100644 index ac3c3a2b544d..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/basic-policy-editor.png and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/calendar.jpg b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/calendar.jpg deleted file mode 100644 index b609c898c5a6..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/calendar.jpg and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/cancel.gif b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/cancel.gif deleted file mode 100644 index 6c71ebcea6cb..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/cancel.gif and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/cleanCache.png b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/cleanCache.png deleted file mode 100644 index 5e856431860a..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/cleanCache.png and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/close.png b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/close.png deleted file mode 100644 index fb619131025c..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/close.png and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/config.gif b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/config.gif deleted file mode 100644 index c493a1253a15..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/config.gif and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/delete.gif b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/delete.gif deleted file mode 100644 index 471f55c15f6d..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/delete.gif and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/disable.gif b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/disable.gif deleted file mode 100644 index 46c2b6d41fe3..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/disable.gif and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/down.gif b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/down.gif deleted file mode 100644 index 3cc181abda97..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/down.gif and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/down.png b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/down.png deleted file mode 100644 index 38f94be3c387..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/down.png and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/edit.gif b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/edit.gif deleted file mode 100644 index 90bd4dce695d..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/edit.gif and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/enable.gif b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/enable.gif deleted file mode 100644 index 1b86800383fb..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/enable.gif and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/ent-options.png b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/ent-options.png deleted file mode 100644 index 9cc9ea2b35c8..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/ent-options.png and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/entitlement.png b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/entitlement.png deleted file mode 100644 index 13e5ae06ff21..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/entitlement.png and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/evaluate.png b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/evaluate.png deleted file mode 100644 index 2e2a31747542..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/evaluate.png and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/evaluation-request.png b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/evaluation-request.png deleted file mode 100644 index 56b3c7156a88..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/evaluation-request.png and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/icon-refresh.gif b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/icon-refresh.gif deleted file mode 100644 index dafc8b36215a..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/icon-refresh.gif and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/import-policy.png b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/import-policy.png deleted file mode 100644 index 9bd6f5ecdcd3..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/import-policy.png and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/import.gif b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/import.gif deleted file mode 100644 index c9fb1df14b31..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/import.gif and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/minus.gif b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/minus.gif deleted file mode 100644 index 55445a2b9f42..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/minus.gif and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/nodata.gif b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/nodata.gif deleted file mode 100644 index c6276a35bb34..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/nodata.gif and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/pdp-config.png b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/pdp-config.png deleted file mode 100644 index d22e05622545..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/pdp-config.png and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/pdp-policy.png b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/pdp-policy.png deleted file mode 100644 index 881387a01194..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/pdp-policy.png and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/plus.gif b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/plus.gif deleted file mode 100644 index 9b1b474823f7..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/plus.gif and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/policies.gif b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/policies.gif deleted file mode 100644 index f07a5202980f..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/policies.gif and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/policy-admin.png b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/policy-admin.png deleted file mode 100644 index f2683afbbde1..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/policy-admin.png and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/policy-pub.png b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/policy-pub.png deleted file mode 100644 index 8938075e8aa7..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/policy-pub.png and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/policy-set-pap.png b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/policy-set-pap.png deleted file mode 100644 index f20375c27c6d..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/policy-set-pap.png and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/policy-set.png b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/policy-set.png deleted file mode 100644 index 9628fadb2f7e..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/policy-set.png and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/policy.gif b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/policy.gif deleted file mode 100644 index f9c58f5f82c1..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/policy.gif and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/publish-all.gif b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/publish-all.gif deleted file mode 100644 index dafc3d0002cb..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/publish-all.gif and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/publish-pdp.gif b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/publish-pdp.gif deleted file mode 100644 index ca5ae022f445..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/publish-pdp.gif and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/publish.gif b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/publish.gif deleted file mode 100644 index eabe987da78e..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/publish.gif and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/registry.gif b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/registry.gif deleted file mode 100644 index b6375199aa1b..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/registry.gif and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/save-button.gif b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/save-button.gif deleted file mode 100644 index a90f5933546b..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/save-button.gif and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/save.gif b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/save.gif deleted file mode 100644 index 2777bebfe7c6..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/save.gif and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/search-attribute.png b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/search-attribute.png deleted file mode 100644 index ae951e88a25a..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/search-attribute.png and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/search-policy.gif b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/search-policy.gif deleted file mode 100644 index b6375199aa1b..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/search-policy.gif and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/search-top.png b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/search-top.png deleted file mode 100644 index c288eafd7cd8..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/search-top.png and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/search.gif b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/search.gif deleted file mode 100644 index cfe76b5d5b06..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/search.gif and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/simple-pap.png b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/simple-pap.png deleted file mode 100644 index 7afe5d4a5de3..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/simple-pap.png and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/standard-pap.png b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/standard-pap.png deleted file mode 100644 index 46ab3fb6f640..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/standard-pap.png and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/sync.png b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/sync.png deleted file mode 100644 index 8bbb3d1f5cde..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/sync.png and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/try-pdp.png b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/try-pdp.png deleted file mode 100644 index 6d440d62866b..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/try-pdp.png and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/up.gif b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/up.gif deleted file mode 100644 index a856a8e04d8e..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/up.gif and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/up.png b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/up.png deleted file mode 100644 index e3e9d2518d80..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/up.png and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/user-store.gif b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/user-store.gif deleted file mode 100644 index cc3745ed9695..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/user-store.gif and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/view.gif b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/view.gif deleted file mode 100644 index 9a1c6e23304a..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/view.gif and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/view.png b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/view.png deleted file mode 100644 index a5cb652ace3f..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/view.png and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/wsdiscovery.gif b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/wsdiscovery.gif deleted file mode 100644 index a9a9549021d9..000000000000 Binary files a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/images/wsdiscovery.gif and /dev/null differ diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/import-policy-submit-ajaxprocessor.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/import-policy-submit-ajaxprocessor.jsp deleted file mode 100644 index d5d8bd67220b..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/import-policy-submit-ajaxprocessor.jsp +++ /dev/null @@ -1,68 +0,0 @@ - -<%@ page import="org.apache.axis2.context.ConfigurationContext"%> -<%@ page import="org.wso2.carbon.CarbonConstants"%> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient"%> -<%@ page import="org.wso2.carbon.ui.CarbonUIMessage"%> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil"%> - -<% - String httpMethod = request.getMethod(); - if (!"post".equalsIgnoreCase(httpMethod)) { - response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); - return; - } - - String policyFromRegistry = request.getParameter("policyFromRegistry"); - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = - (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String forwardTo = null; - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - - try { - EntitlementPolicyAdminServiceClient client = new EntitlementPolicyAdminServiceClient(cookie, serverURL, configContext); - if(policyFromRegistry != null && !policyFromRegistry.trim().equals("")){ - client.importPolicyFromRegistry(policyFromRegistry.trim()); - String message = resourceBundle.getString("imported.successfuly"); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.INFO, request); - forwardTo="index.jsp?region=region1&item=policy_menu"; - } else { - forwardTo = "import-policy.jsp"; - CarbonUIMessage.sendCarbonUIMessage("Registry path can not be empty", CarbonUIMessage.ERROR, request); - } - } catch (Exception e) { - forwardTo = "import-policy.jsp"; - CarbonUIMessage.sendCarbonUIMessage(e.getMessage(), CarbonUIMessage.ERROR, request); - } -%> - -<%@page import="org.wso2.carbon.utils.ServerConstants"%> -<%@page import="java.util.ResourceBundle"%> - - - - diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/import-policy.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/import-policy.jsp deleted file mode 100644 index 8a1d90171943..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/import-policy.jsp +++ /dev/null @@ -1,184 +0,0 @@ - -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> -<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" - prefix="carbon"%> -<%@ taglib uri="http://www.owasp.org/index.php/Category:OWASP_CSRFGuard_Project/Owasp.CsrfGuard.tld" prefix="csrf" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.EntitlementPolicyConstants" %> -<%@ page import="org.owasp.encoder.Encode" %> - - -<% - String importFrom = (String)request.getParameter("importFrom"); - String[] importingMethods = new String[]{EntitlementPolicyConstants.IMPORT_POLICY_REGISTRY, - EntitlementPolicyConstants.IMPORT_POLICY_FILE_SYSTEM}; - if(importFrom == null || importFrom.trim().length() == 0){ - importFrom = EntitlementPolicyConstants.IMPORT_POLICY_FILE_SYSTEM; - } -%> - - - - - - - - - - - - - - - - -
-

- -
- - - - - - - - - - - - - - - - <% - } else { - %> - - - - - <% - } - %> - - - - - - -
- - -
-
- enctype="multipart/form-data" - <% - } - %> - > - <% - if(importFrom.equals(EntitlementPolicyConstants.IMPORT_POLICY_FILE_SYSTEM)){ - %> -
-
- - - - - - - -
- - - - -
-
- - -
-
-
-
diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/index.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/index.jsp deleted file mode 100644 index fe3c25e72ee2..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/index.jsp +++ /dev/null @@ -1,526 +0,0 @@ - -<%@page import="org.apache.axis2.context.ConfigurationContext"%> -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> -<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %> -<%@ page import="org.wso2.carbon.CarbonConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.EntitlementFinderDataHolder" %> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.PaginatedPolicySetDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.EntitlementPolicyConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIMessage"%> - -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %> -<%@ page import="org.wso2.carbon.utils.ServerConstants" %> -<%@ page import="java.util.ResourceBundle" %> -<%@ page import="org.owasp.encoder.Encode" %> - - - - -<% - // remove session attributes - entitlementPolicyBean.cleanEntitlementPolicyBean(); - session.removeAttribute("publishAction"); - session.removeAttribute("policyVersion"); - session.removeAttribute("policyOrder"); - session.removeAttribute("publishAllPolicies"); - session.removeAttribute("selectedPolicies"); - session.removeAttribute("subscriberIds"); - session.removeAttribute("policyId"); - - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = - (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String forwardTo = null; - PaginatedPolicySetDTO paginatedPolicySetDTO = null; - - PolicyDTO[] policies = null; - String[] policyTypes = new String[] {"Policy", "PolicySet"}; - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - session.removeAttribute("publishAllPolicies"); - session.removeAttribute("selectedPolicies"); - session.removeAttribute(EntitlementPolicyConstants.ENTITLEMENT_PUBLISHER_MODULE); - - int numberOfPages = 0; - int pageNumberInt = 0; - String pageNumber = request.getParameter("pageNumber"); - if (pageNumber == null) { - pageNumber = "0"; - } - try { - pageNumberInt = Integer.parseInt(pageNumber); - } catch (NumberFormatException ignored) { - } - - String policyTypeFilter = request.getParameter("policyTypeFilter"); - if (policyTypeFilter == null || "".equals(policyTypeFilter)) { - policyTypeFilter = "ALL"; - } - String policySearchString = request.getParameter("policySearchString"); - if (policySearchString == null) { - policySearchString = "*"; - } else { - policySearchString = policySearchString.trim(); - } - - String paginationValue = "policyTypeFilter=" + policyTypeFilter + - "&policySearchString=" + policySearchString; - - try { - EntitlementPolicyAdminServiceClient client = - new EntitlementPolicyAdminServiceClient(cookie, serverURL, configContext); - paginatedPolicySetDTO = client. - getAllPolicies(policyTypeFilter, policySearchString, pageNumberInt, false); - EntitlementFinderDataHolder [] entitlementFinders = client.getEntitlementDataModules(); - if(entitlementFinders != null){ - for(EntitlementFinderDataHolder holder : entitlementFinders){ - entitlementPolicyBean.getEntitlementFinders().put(holder.getName(), holder); - } - } - policies = paginatedPolicySetDTO.getPolicySet(); - numberOfPages = paginatedPolicySetDTO.getNumberOfPages(); - - } catch (Exception e) { - String message = resourceBundle.getString("error.while.loading.policy")+ " " + e.getMessage(); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.ERROR, request); - forwardTo = "../admin/error.jsp"; -%> - - - - -<% - } -%> - - - - - - - - - -
-

-
- - <% - if (CarbonUIUtil.isUserAuthorized(request, "/permission/admin/manage/identity/entitlement/pap/policy/create")) { - %> - - - - <%-- --%> - <%----%> - -
-
- -
-
--%> - <%----%> - <%----%> - <%----%> - <%--
- <% - } - %> - -
- - - - -
- - - - - - - -
- - - -     - - "/>  - - - "> -
-
-
- - - - - - - <% - if (CarbonUIUtil.isUserAuthorized(request, "/permission/admin/manage/identity/entitlement/pap/policy/delete")) { - %> - - <% - } - if (CarbonUIUtil.isUserAuthorized(request, "/permission/admin/manage/identity/entitlement/pap/policy/publish")) { - %> - - <% - } - if (CarbonUIUtil.isUserAuthorized(request, "/permission/admin/manage/identity/entitlement/pap/policy/publish")) { - %> - - <% - } - %> - - - -
- -   |   -   - - - - - -  
- -
- - - - - - - - <% - if (policies != null) { - for (int i = 0; i < policies.length; i++) { - if(policies[i] != null){ - %> - - - - - - - - <% - boolean canEdit = CarbonUIUtil.isUserAuthorized(request, "/permission/admin/manage/identity/entitlement/pap/policy/update"); - boolean canViewVersions = CarbonUIUtil.isUserAuthorized(request, "/permission/admin/manage/identity/entitlement/pap/policy/view"); - boolean canPublish = CarbonUIUtil.isUserAuthorized(request, "/permission/admin/manage/identity/entitlement/pap/policy/publish"); - boolean canTryIt = CarbonUIUtil.isUserAuthorized(request, "/permission/admin/manage/identity/entitlement/pdp/test"); - boolean canViewStatus = CarbonUIUtil.isUserAuthorized(request, "/permission/admin/manage/identity/entitlement/pap/policy/view"); - %> - - - - - <%} } } else { %> - - - - <%}%> - -
- - - <%=Encode.forHtmlContent(policies[i].getPolicyId())%> - - <% - if(policies[i].getPolicyType() == null || "".equals(policies[i].getPolicyType())){ - policies[i].setPolicyType("Policy"); - } - %> - - <%=Encode.forHtmlAttribute(policies[i].getPolicyType())%> - <%=Encode.forHtmlContent(policies[i].getPolicyType())%> - - - <% - if (canEdit) { - %> - - - <% - } - if (canViewVersions) { - %> - - - <% - } - if (canPublish) { - %> - - - <% - } - if (canTryIt) { - %> - - - <% - } - if (canViewStatus) { - %> - - - <% - } - %> -
-
- -
-
-
diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/js/animation-min/animation-min.js b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/js/animation-min/animation-min.js deleted file mode 100644 index 0510b556c703..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/js/animation-min/animation-min.js +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright (c) 2010, Yahoo! Inc. All rights reserved. -Code licensed under the BSD License: -http://developer.yahoo.com/yui/license.html -version: 2.8.1 -*/ -(function(){var B=YAHOO.util;var A=function(D,C,E,F){if(!D){}this.init(D,C,E,F);};A.NAME="Anim";A.prototype={toString:function(){var C=this.getEl()||{};var D=C.id||C.tagName;return(this.constructor.NAME+": "+D);},patterns:{noNegatives:/width|height|opacity|padding/i,offsetAttribute:/^((width|height)|(top|left))$/,defaultUnit:/width|height|top$|bottom$|left$|right$/i,offsetUnit:/\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i},doMethod:function(C,E,D){return this.method(this.currentFrame,E,D-E,this.totalFrames);},setAttribute:function(C,F,E){var D=this.getEl();if(this.patterns.noNegatives.test(C)){F=(F>0)?F:0;}if(C in D&&!("style" in D&&C in D.style)){D[C]=F;}else{B.Dom.setStyle(D,C,F+E);}},getAttribute:function(C){var E=this.getEl();var G=B.Dom.getStyle(E,C);if(G!=="auto"&&!this.patterns.offsetUnit.test(G)){return parseFloat(G);}var D=this.patterns.offsetAttribute.exec(C)||[];var H=!!(D[3]);var F=!!(D[2]);if("style" in E){if(F||(B.Dom.getStyle(E,"position")=="absolute"&&H)){G=E["offset"+D[0].charAt(0).toUpperCase()+D[0].substr(1)];}else{G=0;}}else{if(C in E){G=E[C];}}return G;},getDefaultUnit:function(C){if(this.patterns.defaultUnit.test(C)){return"px";}return"";},setRuntimeAttribute:function(D){var I;var E;var F=this.attributes;this.runtimeAttributes[D]={};var H=function(J){return(typeof J!=="undefined");};if(!H(F[D]["to"])&&!H(F[D]["by"])){return false;}I=(H(F[D]["from"]))?F[D]["from"]:this.getAttribute(D);if(H(F[D]["to"])){E=F[D]["to"];}else{if(H(F[D]["by"])){if(I.constructor==Array){E=[];for(var G=0,C=I.length;G0&&isFinite(K)){if(G.currentFrame+K>=J){K=J-(I+1);}G.currentFrame+=K;}};this._queue=B;this._getIndex=E;};YAHOO.util.Bezier=new function(){this.getPosition=function(E,D){var F=E.length;var C=[];for(var B=0;B0&&!(L[0] instanceof Array)){L=[L];}else{var K=[];for(M=0,O=L.length;M0){this.runtimeAttributes[P]=this.runtimeAttributes[P].concat(L);}this.runtimeAttributes[P][this.runtimeAttributes[P].length]=I;}else{F.setRuntimeAttribute.call(this,P);}};var B=function(G,I){var H=E.Dom.getXY(this.getEl());G=[G[0]-H[0]+I[0],G[1]-H[1]+I[1]];return G;};var D=function(G){return(typeof G!=="undefined");};E.Motion=A;})();(function(){var D=function(F,E,G,H){if(F){D.superclass.constructor.call(this,F,E,G,H);}};D.NAME="Scroll";var B=YAHOO.util;YAHOO.extend(D,B.ColorAnim);var C=D.superclass;var A=D.prototype;A.doMethod=function(E,H,F){var G=null;if(E=="scroll"){G=[this.method(this.currentFrame,H[0],F[0]-H[0],this.totalFrames),this.method(this.currentFrame,H[1],F[1]-H[1],this.totalFrames)];}else{G=C.doMethod.call(this,E,H,F);}return G;};A.getAttribute=function(E){var G=null;var F=this.getEl();if(E=="scroll"){G=[F.scrollLeft,F.scrollTop];}else{G=C.getAttribute.call(this,E);}return G;};A.setAttribute=function(E,H,G){var F=this.getEl();if(E=="scroll"){F.scrollLeft=H[0];F.scrollTop=H[1];}else{C.setAttribute.call(this,E,H,G);}};B.Scroll=D;})();YAHOO.register("animation",YAHOO.util.Anim,{version:"2.8.1",build:"19"}); diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/js/create-basic-policy.js b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/js/create-basic-policy.js deleted file mode 100644 index 6418bf09d0d4..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/js/create-basic-policy.js +++ /dev/null @@ -1,48 +0,0 @@ -function showNewRuleBox(link) { - link.style.display = "none"; - var rowToHide = document.getElementById(link.id + "Row"); - if (rowToHide.style.display == "none") { - rowToHide.style.display = ""; - } else { - rowToHide.style.display = "none"; - } -} -function showHideRow(link) { - var rowToHide = document.getElementById(link.id + "Row"); - if (rowToHide.style.display == "none") { - rowToHide.style.display = ""; - link.className = "icon-link arrowUp"; - } else { - rowToHide.style.display = "none"; - link.className = "icon-link arrowDown"; - } -} -function handleFocus(obj, txt) { - if (obj.value == txt) { - obj.value = ''; - YAHOO.util.Dom.removeClass(obj, 'defaultText'); - - } -} -function handleBlur(obj, txt) { - if (obj.value == '') { - obj.value = txt; - YAHOO.util.Dom.addClass(obj, 'defaultText'); - } -} -YAHOO.util.Event.onDOMReady( - function() { - /*if (document.getElementById("resourceNamesTarget").value == "") { - document.getElementById("resourceNamesTarget").value = "Pick resource name"; - } - if (document.getElementById("subjectNamesTarget").value == "") { - document.getElementById("subjectNamesTarget").value = "Pick role name"; - } - if (document.getElementById("userAttributeValueTarget").value == "") { - document.getElementById("userAttributeValueTarget").value = "User attribute"; - } - if (document.getElementById("actionNamesTarget").value == "") { - document.getElementById("actionNamesTarget").value = "Action"; - }*/ - } - ); \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/js/popup.js b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/js/popup.js deleted file mode 100644 index 30b1d0dac408..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/js/popup.js +++ /dev/null @@ -1,51 +0,0 @@ -function customPopupDialog(message, title, windowHight, okButton, callback, windowWidth) { - var strDialog = "
" + message + "
"; - var requiredWidth = 750; - if (windowWidth) { - requiredWidth = windowWidth; - } - var func = function() { - jQuery("#dcontainer").html(strDialog); - if (okButton) { - jQuery("#dialog").dialog({ - close:function() { - jQuery(this).dialog('destroy').remove(); - jQuery("#dcontainer").empty(); - return false; - }, - buttons:{ - "OK":function() { - if (callback && typeof callback == "function") - callback(); - jQuery(this).dialog("destroy").remove(); - jQuery("#dcontainer").empty(); - return false; - } - }, - height:windowHight, - width:requiredWidth, - minHeight:windowHight, - minWidth:requiredWidth, - modal:true - }); - } else { - jQuery("#dialog").dialog({ - close:function() { - jQuery(this).dialog('destroy').remove(); - jQuery("#dcontainer").empty(); - return false; - }, - height:windowHight, - width:requiredWidth, - minHeight:windowHight, - minWidth:requiredWidth, - modal:true - }); - } - }; - if (!pageLoaded) { - jQuery(document).ready(func); - } else { - func(); - } -}; diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/js/treecontrol.js b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/js/treecontrol.js deleted file mode 100644 index 84d7b28bb9e2..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/js/treecontrol.js +++ /dev/null @@ -1,126 +0,0 @@ -function treeColapse(icon) { - var parentNode = icon.parentNode; - var allChildren = parentNode.childNodes; - var todoOther = ""; - var attributes = ""; - //Do minimizing for the rest of the nodes - for (var i = 0; i < allChildren.length; i++) { - if (allChildren[i].nodeName == "UL") { - - if (allChildren[i].style.display == "none") { - attributes = { - opacity: { to: 1 } - }; - var anim = new YAHOO.util.Anim(allChildren[i], attributes); - anim.animate(); - allChildren[i].style.display = ""; - if (YAHOO.util.Dom.hasClass(icon, "plus") || YAHOO.util.Dom.hasClass(icon, "minus")) { - YAHOO.util.Dom.removeClass(icon, "plus"); - YAHOO.util.Dom.addClass(icon, "minus"); - } - todoOther = "show"; - parentNode.style.height = "auto"; - } - else { - attributes = { - opacity: { to: 0 } - }; - anim = new YAHOO.util.Anim(allChildren[i], attributes); - anim.duration = 0.3; - anim.onComplete.subscribe(hideTreeItem, allChildren[i]); - - anim.animate(); - if (YAHOO.util.Dom.hasClass(icon, "plus") || YAHOO.util.Dom.hasClass(icon, "minus")) { - YAHOO.util.Dom.removeClass(icon, "minus"); - YAHOO.util.Dom.addClass(icon, "plus"); - } - todoOther = "hide"; - //parentNode.style.height = "50px"; - } - } - } -} -function hideTreeItem(state,opts,item){ - item.style.display = "none"; -} -function selectMe(obj){ - if(YAHOO.util.Dom.hasClass(obj, 'selected')){ - YAHOO.util.Dom.removeClass(obj, 'selected'); - } else { - YAHOO.util.Dom.addClass(obj, 'selected'); - } -} -var paths = new Array(); -function pickNames(fullPath){ - var nameLinks = YAHOO.util.Dom.getElementsByClassName('selected', 'a'); - var listView = document.getElementById('listView'); - var displayNodeValue; - for(var i=0;i' + delLink; - listView.appendChild(newNode); - } - - } - return; -} -function getTreePathFromNode(node,path){ - var hasParent = false; - if(node.nodeName == "A"){ - var parentOnTree = node.parentNode.parentNode.parentNode; - if(parentOnTree.nodeName == "DIV"){ - return path; - } - var allChildren = parentOnTree.childNodes; - var nodeNumber = 0; - for(var i=0;i0)?B.dump(I[K],N-1):Q);}else{P.push(I[K]);}P.push(O);}if(P.length>1){P.pop();}P.push("]");}else{P.push("{");for(K in I){if(B.hasOwnProperty(I,K)){P.push(K+L);if(B.isObject(I[K])){P.push((N>0)?B.dump(I[K],N-1):Q);}else{P.push(I[K]);}P.push(O);}}if(P.length>1){P.pop();}P.push("}");}return P.join("");},substitute:function(Y,J,R){var N,M,L,U,V,X,T=[],K,O="dump",S=" ",I="{",W="}",Q,P;for(;;){N=Y.lastIndexOf(I);if(N<0){break;}M=Y.indexOf(W,N);if(N+1>=M){break;}K=Y.substring(N+1,M);U=K;X=null;L=U.indexOf(S);if(L>-1){X=U.substring(L+1);U=U.substring(0,L);}V=J[U];if(R){V=R(U,V,X);}if(B.isObject(V)){if(B.isArray(V)){V=B.dump(V,parseInt(X,10));}else{X=X||"";Q=X.indexOf(O);if(Q>-1){X=X.substring(4);}P=V.toString();if(P===G||Q>-1){V=B.dump(V,parseInt(X,10));}else{V=P;}}}else{if(!B.isString(V)&&!B.isNumber(V)){V="~-"+T.length+"-~";T[T.length]=K;}}Y=Y.substring(0,N)+V+Y.substring(M+1);}for(N=T.length-1;N>=0;N=N-1){Y=Y.replace(new RegExp("~-"+N+"-~"),"{"+T[N]+"}","g");}return Y;},trim:function(I){try{return I.replace(/^\s+|\s+$/g,"");}catch(J){return I;}},merge:function(){var L={},J=arguments,I=J.length,K;for(K=0;K519)?true:false);while((G=G[u])){z[0]+=G[b];z[1]+=G[P];if(AC){z=E.Dom._calcBorders(G,z);}}if(E.Dom._getStyle(y,p)!==f){G=y;while((G=G[Z])&&G[C]){AA=G[i];AB=G[O];if(H&&(E.Dom._getStyle(G,"overflow")!=="visible")){z=E.Dom._calcBorders(G,z);}if(AA||AB){z[0]-=AB;z[1]-=AA;}}z[0]+=x;z[1]+=Y;}else{if(D){z[0]-=x;z[1]-=Y;}else{if(I||H){z[0]+=x;z[1]+=Y;}}}z[0]=Math.floor(z[0]);z[1]=Math.floor(z[1]);}else{}return z;};}}(),getX:function(G){var Y=function(x){return E.Dom.getXY(x)[0];};return E.Dom.batch(G,Y,E.Dom,true);},getY:function(G){var Y=function(x){return E.Dom.getXY(x)[1];};return E.Dom.batch(G,Y,E.Dom,true);},setXY:function(G,x,Y){E.Dom.batch(G,E.Dom._setXY,{pos:x,noRetry:Y});},_setXY:function(G,z){var AA=E.Dom._getStyle(G,p),y=E.Dom.setStyle,AD=z.pos,Y=z.noRetry,AB=[parseInt(E.Dom.getComputedStyle(G,j),10),parseInt(E.Dom.getComputedStyle(G,o),10)],AC,x;if(AA=="static"){AA=V;y(G,p,AA);}AC=E.Dom._getXY(G);if(!AD||AC===false){return false;}if(isNaN(AB[0])){AB[0]=(AA==V)?0:G[b];}if(isNaN(AB[1])){AB[1]=(AA==V)?0:G[P];}if(AD[0]!==null){y(G,j,AD[0]-AC[0]+AB[0]+"px");}if(AD[1]!==null){y(G,o,AD[1]-AC[1]+AB[1]+"px");}if(!Y){x=E.Dom._getXY(G);if((AD[0]!==null&&x[0]!=AD[0])||(AD[1]!==null&&x[1]!=AD[1])){E.Dom._setXY(G,{pos:AD,noRetry:true});}}},setX:function(Y,G){E.Dom.setXY(Y,[G,null]);},setY:function(G,Y){E.Dom.setXY(G,[null,Y]);},getRegion:function(G){var Y=function(x){var y=false;if(E.Dom._canPosition(x)){y=E.Region.getRegion(x);}else{}return y;};return E.Dom.batch(G,Y,E.Dom,true);},getClientWidth:function(){return E.Dom.getViewportWidth();},getClientHeight:function(){return E.Dom.getViewportHeight();},getElementsByClassName:function(AB,AF,AC,AE,x,AD){AF=AF||"*";AC=(AC)?E.Dom.get(AC):null||K;if(!AC){return[];}var Y=[],G=AC.getElementsByTagName(AF),z=E.Dom.hasClass;for(var y=0,AA=G.length;y-1;}}else{}return G;},addClass:function(Y,G){return E.Dom.batch(Y,E.Dom._addClass,G);},_addClass:function(x,Y){var G=false,y;if(x&&Y){y=E.Dom._getAttribute(x,F)||J;if(!E.Dom._hasClass(x,Y)){E.Dom.setAttribute(x,F,A(y+B+Y));G=true;}}else{}return G;},removeClass:function(Y,G){return E.Dom.batch(Y,E.Dom._removeClass,G);},_removeClass:function(y,x){var Y=false,AA,z,G;if(y&&x){AA=E.Dom._getAttribute(y,F)||J;E.Dom.setAttribute(y,F,AA.replace(E.Dom._getClassRegex(x),J));z=E.Dom._getAttribute(y,F);if(AA!==z){E.Dom.setAttribute(y,F,A(z));Y=true;if(E.Dom._getAttribute(y,F)===""){G=(y.hasAttribute&&y.hasAttribute(g))?g:F; -y.removeAttribute(G);}}}else{}return Y;},replaceClass:function(x,Y,G){return E.Dom.batch(x,E.Dom._replaceClass,{from:Y,to:G});},_replaceClass:function(y,x){var Y,AB,AA,G=false,z;if(y&&x){AB=x.from;AA=x.to;if(!AA){G=false;}else{if(!AB){G=E.Dom._addClass(y,x.to);}else{if(AB!==AA){z=E.Dom._getAttribute(y,F)||J;Y=(B+z.replace(E.Dom._getClassRegex(AB),B+AA)).split(E.Dom._getClassRegex(AA));Y.splice(1,0,B+AA);E.Dom.setAttribute(y,F,A(Y.join(J)));G=true;}}}}else{}return G;},generateId:function(G,x){x=x||"yui-gen";var Y=function(y){if(y&&y.id){return y.id;}var z=x+YAHOO.env._id_counter++;if(y){if(y[e]&&y[e].getElementById(z)){return E.Dom.generateId(y,z+x);}y.id=z;}return z;};return E.Dom.batch(G,Y,E.Dom,true)||Y.apply(E.Dom,arguments);},isAncestor:function(Y,x){Y=E.Dom.get(Y);x=E.Dom.get(x);var G=false;if((Y&&x)&&(Y[l]&&x[l])){if(Y.contains&&Y!==x){G=Y.contains(x);}else{if(Y.compareDocumentPosition){G=!!(Y.compareDocumentPosition(x)&16);}}}else{}return G;},inDocument:function(G,Y){return E.Dom._inDoc(E.Dom.get(G),Y);},_inDoc:function(Y,x){var G=false;if(Y&&Y[C]){x=x||Y[e];G=E.Dom.isAncestor(x[v],Y);}else{}return G;},getElementsBy:function(Y,AF,AB,AD,y,AC,AE){AF=AF||"*";AB=(AB)?E.Dom.get(AB):null||K;if(!AB){return[];}var x=[],G=AB.getElementsByTagName(AF);for(var z=0,AA=G.length;z=8&&K.documentElement.hasAttribute){E.Dom.DOT_ATTRIBUTES.type=true;}})();YAHOO.util.Region=function(C,D,A,B){this.top=C;this.y=C;this[1]=C;this.right=D;this.bottom=A;this.left=B;this.x=B;this[0]=B; -this.width=this.right-this.left;this.height=this.bottom-this.top;};YAHOO.util.Region.prototype.contains=function(A){return(A.left>=this.left&&A.right<=this.right&&A.top>=this.top&&A.bottom<=this.bottom);};YAHOO.util.Region.prototype.getArea=function(){return((this.bottom-this.top)*(this.right-this.left));};YAHOO.util.Region.prototype.intersect=function(E){var C=Math.max(this.top,E.top),D=Math.min(this.right,E.right),A=Math.min(this.bottom,E.bottom),B=Math.max(this.left,E.left);if(A>=C&&D>=B){return new YAHOO.util.Region(C,D,A,B);}else{return null;}};YAHOO.util.Region.prototype.union=function(E){var C=Math.min(this.top,E.top),D=Math.max(this.right,E.right),A=Math.max(this.bottom,E.bottom),B=Math.min(this.left,E.left);return new YAHOO.util.Region(C,D,A,B);};YAHOO.util.Region.prototype.toString=function(){return("Region {"+"top: "+this.top+", right: "+this.right+", bottom: "+this.bottom+", left: "+this.left+", height: "+this.height+", width: "+this.width+"}");};YAHOO.util.Region.getRegion=function(D){var F=YAHOO.util.Dom.getXY(D),C=F[1],E=F[0]+D.offsetWidth,A=F[1]+D.offsetHeight,B=F[0];return new YAHOO.util.Region(C,E,A,B);};YAHOO.util.Point=function(A,B){if(YAHOO.lang.isArray(A)){B=A[1];A=A[0];}YAHOO.util.Point.superclass.constructor.call(this,B,A,B,A);};YAHOO.extend(YAHOO.util.Point,YAHOO.util.Region);(function(){var B=YAHOO.util,A="clientTop",F="clientLeft",J="parentNode",K="right",W="hasLayout",I="px",U="opacity",L="auto",D="borderLeftWidth",G="borderTopWidth",P="borderRightWidth",V="borderBottomWidth",S="visible",Q="transparent",N="height",E="width",H="style",T="currentStyle",R=/^width|height$/,O=/^(\d[.\d]*)+(em|ex|px|gd|rem|vw|vh|vm|ch|mm|cm|in|pt|pc|deg|rad|ms|s|hz|khz|%){1}?/i,M={get:function(X,Z){var Y="",a=X[T][Z];if(Z===U){Y=B.Dom.getStyle(X,U);}else{if(!a||(a.indexOf&&a.indexOf(I)>-1)){Y=a;}else{if(B.Dom.IE_COMPUTED[Z]){Y=B.Dom.IE_COMPUTED[Z](X,Z);}else{if(O.test(a)){Y=B.Dom.IE.ComputedStyle.getPixel(X,Z);}else{Y=a;}}}}return Y;},getOffset:function(Z,e){var b=Z[T][e],X=e.charAt(0).toUpperCase()+e.substr(1),c="offset"+X,Y="pixel"+X,a="",d;if(b==L){d=Z[c];if(d===undefined){a=0;}a=d;if(R.test(e)){Z[H][e]=d;if(Z[c]>d){a=d-(Z[c]-d);}Z[H][e]=L;}}else{if(!Z[H][Y]&&!Z[H][e]){Z[H][e]=b;}a=Z[H][Y];}return a+I;},getBorderWidth:function(X,Z){var Y=null;if(!X[T][W]){X[H].zoom=1;}switch(Z){case G:Y=X[A];break;case V:Y=X.offsetHeight-X.clientHeight-X[A];break;case D:Y=X[F];break;case P:Y=X.offsetWidth-X.clientWidth-X[F];break;}return Y+I;},getPixel:function(Y,X){var a=null,b=Y[T][K],Z=Y[T][X];Y[H][K]=Z;a=Y[H].pixelRight;Y[H][K]=b;return a+I;},getMargin:function(Y,X){var Z;if(Y[T][X]==L){Z=0+I;}else{Z=B.Dom.IE.ComputedStyle.getPixel(Y,X);}return Z;},getVisibility:function(Y,X){var Z;while((Z=Y[T])&&Z[X]=="inherit"){Y=Y[J];}return(Z)?Z[X]:S;},getColor:function(Y,X){return B.Dom.Color.toRGB(Y[T][X])||Q;},getBorderColor:function(Y,X){var Z=Y[T],a=Z[X]||Z.color;return B.Dom.Color.toRGB(B.Dom.Color.toHex(a));}},C={};C.top=C.right=C.bottom=C.left=C[E]=C[N]=M.getOffset;C.color=M.getColor;C[G]=C[P]=C[V]=C[D]=M.getBorderWidth;C.marginTop=C.marginRight=C.marginBottom=C.marginLeft=M.getMargin;C.visibility=M.getVisibility;C.borderColor=C.borderTopColor=C.borderRightColor=C.borderBottomColor=C.borderLeftColor=M.getBorderColor;B.Dom.IE_COMPUTED=C;B.Dom.IE_ComputedStyle=M;})();(function(){var C="toString",A=parseInt,B=RegExp,D=YAHOO.util;D.Dom.Color={KEYWORDS:{black:"000",silver:"c0c0c0",gray:"808080",white:"fff",maroon:"800000",red:"f00",purple:"800080",fuchsia:"f0f",green:"008000",lime:"0f0",olive:"808000",yellow:"ff0",navy:"000080",blue:"00f",teal:"008080",aqua:"0ff"},re_RGB:/^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i,re_hex:/^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i,re_hex3:/([0-9A-F])/gi,toRGB:function(E){if(!D.Dom.Color.re_RGB.test(E)){E=D.Dom.Color.toHex(E);}if(D.Dom.Color.re_hex.exec(E)){E="rgb("+[A(B.$1,16),A(B.$2,16),A(B.$3,16)].join(", ")+")";}return E;},toHex:function(H){H=D.Dom.Color.KEYWORDS[H]||H;if(D.Dom.Color.re_RGB.exec(H)){var G=(B.$1.length===1)?"0"+B.$1:Number(B.$1),F=(B.$2.length===1)?"0"+B.$2:Number(B.$2),E=(B.$3.length===1)?"0"+B.$3:Number(B.$3);H=[G[C](16),F[C](16),E[C](16)].join("");}if(H.length<6){H=H.replace(D.Dom.Color.re_hex3,"$1$1");}if(H!=="transparent"&&H.indexOf("#")<0){H="#"+H;}return H.toLowerCase();}};}());YAHOO.register("dom",YAHOO.util.Dom,{version:"2.8.1",build:"19"});YAHOO.util.CustomEvent=function(D,C,B,A,E){this.type=D;this.scope=C||window;this.silent=B;this.fireOnce=E;this.fired=false;this.firedWith=null;this.signature=A||YAHOO.util.CustomEvent.LIST;this.subscribers=[];if(!this.silent){}var F="_YUICEOnSubscribe";if(D!==F){this.subscribeEvent=new YAHOO.util.CustomEvent(F,this,true);}this.lastError=null;};YAHOO.util.CustomEvent.LIST=0;YAHOO.util.CustomEvent.FLAT=1;YAHOO.util.CustomEvent.prototype={subscribe:function(B,C,D){if(!B){throw new Error("Invalid callback for subscriber to '"+this.type+"'");}if(this.subscribeEvent){this.subscribeEvent.fire(B,C,D);}var A=new YAHOO.util.Subscriber(B,C,D);if(this.fireOnce&&this.fired){this.notify(A,this.firedWith);}else{this.subscribers.push(A);}},unsubscribe:function(D,F){if(!D){return this.unsubscribeAll();}var E=false;for(var B=0,A=this.subscribers.length;B0){H=C[0];}try{B=F.fn.call(E,H,F.obj);}catch(G){this.lastError=G;if(A){throw G;}}}else{try{B=F.fn.call(E,this.type,C,F.obj);}catch(D){this.lastError=D;if(A){throw D;}}}return B;},unsubscribeAll:function(){var A=this.subscribers.length,B;for(B=A-1;B>-1;B--){this._delete(B);}this.subscribers=[];return A;},_delete:function(A){var B=this.subscribers[A];if(B){delete B.fn;delete B.obj;}this.subscribers.splice(A,1);},toString:function(){return"CustomEvent: "+"'"+this.type+"', "+"context: "+this.scope;}};YAHOO.util.Subscriber=function(A,B,C){this.fn=A;this.obj=YAHOO.lang.isUndefined(B)?null:B;this.overrideContext=C;};YAHOO.util.Subscriber.prototype.getScope=function(A){if(this.overrideContext){if(this.overrideContext===true){return this.obj;}else{return this.overrideContext;}}return A;};YAHOO.util.Subscriber.prototype.contains=function(A,B){if(B){return(this.fn==A&&this.obj==B);}else{return(this.fn==A);}};YAHOO.util.Subscriber.prototype.toString=function(){return"Subscriber { obj: "+this.obj+", overrideContext: "+(this.overrideContext||"no")+" }";};if(!YAHOO.util.Event){YAHOO.util.Event=function(){var G=false,H=[],J=[],A=0,E=[],B=0,C={63232:38,63233:40,63234:37,63235:39,63276:33,63277:34,25:9},D=YAHOO.env.ua.ie,F="focusin",I="focusout";return{POLL_RETRYS:500,POLL_INTERVAL:40,EL:0,TYPE:1,FN:2,WFN:3,UNLOAD_OBJ:3,ADJ_SCOPE:4,OBJ:5,OVERRIDE:6,CAPTURE:7,lastError:null,isSafari:YAHOO.env.ua.webkit,webkit:YAHOO.env.ua.webkit,isIE:D,_interval:null,_dri:null,_specialTypes:{focusin:(D?"focusin":"focus"),focusout:(D?"focusout":"blur")},DOMReady:false,throwErrors:false,startInterval:function(){if(!this._interval){this._interval=YAHOO.lang.later(this.POLL_INTERVAL,this,this._tryPreloadAttach,null,true);}},onAvailable:function(Q,M,O,P,N){var K=(YAHOO.lang.isString(Q))?[Q]:Q;for(var L=0;L-1;M--){S=(this.removeListener(L[M],K,R)&&S);}return S;}}if(!R||!R.call){return this.purgeElement(L,false,K);}if("unload"==K){for(M=J.length-1;M>-1;M--){U=J[M];if(U&&U[0]==L&&U[1]==K&&U[2]==R){J.splice(M,1);return true;}}return false;}var N=null;var O=arguments[3];if("undefined"===typeof O){O=this._getCacheIndex(H,L,K,R);}if(O>=0){N=H[O];}if(!L||!N){return false;}var T=N[this.CAPTURE]===true?true:false;try{this._simpleRemove(L,K,N[this.WFN],T);}catch(Q){this.lastError=Q;return false;}delete H[O][this.WFN];delete H[O][this.FN];H.splice(O,1);return true;},getTarget:function(M,L){var K=M.target||M.srcElement;return this.resolveTextNode(K);},resolveTextNode:function(L){try{if(L&&3==L.nodeType){return L.parentNode;}}catch(K){}return L;},getPageX:function(L){var K=L.pageX;if(!K&&0!==K){K=L.clientX||0;if(this.isIE){K+=this._getScrollLeft();}}return K;},getPageY:function(K){var L=K.pageY;if(!L&&0!==L){L=K.clientY||0;if(this.isIE){L+=this._getScrollTop();}}return L;},getXY:function(K){return[this.getPageX(K),this.getPageY(K)];},getRelatedTarget:function(L){var K=L.relatedTarget;if(!K){if(L.type=="mouseout"){K=L.toElement; -}else{if(L.type=="mouseover"){K=L.fromElement;}}}return this.resolveTextNode(K);},getTime:function(M){if(!M.time){var L=new Date().getTime();try{M.time=L;}catch(K){this.lastError=K;return L;}}return M.time;},stopEvent:function(K){this.stopPropagation(K);this.preventDefault(K);},stopPropagation:function(K){if(K.stopPropagation){K.stopPropagation();}else{K.cancelBubble=true;}},preventDefault:function(K){if(K.preventDefault){K.preventDefault();}else{K.returnValue=false;}},getEvent:function(M,K){var L=M||window.event;if(!L){var N=this.getEvent.caller;while(N){L=N.arguments[0];if(L&&Event==L.constructor){break;}N=N.caller;}}return L;},getCharCode:function(L){var K=L.keyCode||L.charCode||0;if(YAHOO.env.ua.webkit&&(K in C)){K=C[K];}return K;},_getCacheIndex:function(M,P,Q,O){for(var N=0,L=M.length;N0&&E.length>0);}var P=[];var R=function(T,U){var S=T;if(U.overrideContext){if(U.overrideContext===true){S=U.obj;}else{S=U.overrideContext;}}U.fn.call(S,U.obj);};var L,K,O,N,M=[];for(L=0,K=E.length;L-1;L--){O=E[L];if(!O||!O.id){E.splice(L,1);}}this.startInterval();}else{if(this._interval){this._interval.cancel();this._interval=null;}}this.locked=false;},purgeElement:function(O,P,R){var M=(YAHOO.lang.isString(O))?this.getEl(O):O;var Q=this.getListeners(M,R),N,K;if(Q){for(N=Q.length-1;N>-1;N--){var L=Q[N];this.removeListener(M,L.type,L.fn);}}if(P&&M&&M.childNodes){for(N=0,K=M.childNodes.length;N-1;N--){M=H[N];if(M){L.removeListener(M[L.EL],M[L.TYPE],M[L.FN],N);}}M=null;}L._simpleRemove(window,"unload",L._unload);},_getScrollLeft:function(){return this._getScroll()[1];},_getScrollTop:function(){return this._getScroll()[0];},_getScroll:function(){var K=document.documentElement,L=document.body;if(K&&(K.scrollTop||K.scrollLeft)){return[K.scrollTop,K.scrollLeft];}else{if(L){return[L.scrollTop,L.scrollLeft];}else{return[0,0];}}},regCE:function(){},_simpleAdd:function(){if(window.addEventListener){return function(M,N,L,K){M.addEventListener(N,L,(K));};}else{if(window.attachEvent){return function(M,N,L,K){M.attachEvent("on"+N,L);};}else{return function(){};}}}(),_simpleRemove:function(){if(window.removeEventListener){return function(M,N,L,K){M.removeEventListener(N,L,(K));};}else{if(window.detachEvent){return function(L,M,K){L.detachEvent("on"+M,K);};}else{return function(){};}}}()};}();(function(){var EU=YAHOO.util.Event;EU.on=EU.addListener;EU.onFocus=EU.addFocusListener;EU.onBlur=EU.addBlurListener; -/* DOMReady: based on work by: Dean Edwards/John Resig/Matthias Miller/Diego Perini */ -if(EU.isIE){if(self!==self.top){document.onreadystatechange=function(){if(document.readyState=="complete"){document.onreadystatechange=null;EU._ready();}};}else{YAHOO.util.Event.onDOMReady(YAHOO.util.Event._tryPreloadAttach,YAHOO.util.Event,true);var n=document.createElement("p");EU._dri=setInterval(function(){try{n.doScroll("left");clearInterval(EU._dri);EU._dri=null;EU._ready();n=null;}catch(ex){}},EU.POLL_INTERVAL);}}else{if(EU.webkit&&EU.webkit<525){EU._dri=setInterval(function(){var rs=document.readyState;if("loaded"==rs||"complete"==rs){clearInterval(EU._dri);EU._dri=null;EU._ready();}},EU.POLL_INTERVAL);}else{EU._simpleAdd(document,"DOMContentLoaded",EU._ready);}}EU._simpleAdd(window,"load",EU._load);EU._simpleAdd(window,"unload",EU._unload);EU._tryPreloadAttach();})();}YAHOO.util.EventProvider=function(){};YAHOO.util.EventProvider.prototype={__yui_events:null,__yui_subscribers:null,subscribe:function(A,C,F,E){this.__yui_events=this.__yui_events||{};var D=this.__yui_events[A];if(D){D.subscribe(C,F,E);}else{this.__yui_subscribers=this.__yui_subscribers||{};var B=this.__yui_subscribers;if(!B[A]){B[A]=[];}B[A].push({fn:C,obj:F,overrideContext:E});}},unsubscribe:function(C,E,G){this.__yui_events=this.__yui_events||{};var A=this.__yui_events;if(C){var F=A[C];if(F){return F.unsubscribe(E,G);}}else{var B=true;for(var D in A){if(YAHOO.lang.hasOwnProperty(A,D)){B=B&&A[D].unsubscribe(E,G);}}return B;}return false;},unsubscribeAll:function(A){return this.unsubscribe(A); -},createEvent:function(B,G){this.__yui_events=this.__yui_events||{};var E=G||{},D=this.__yui_events,F;if(D[B]){}else{F=new YAHOO.util.CustomEvent(B,E.scope||this,E.silent,YAHOO.util.CustomEvent.FLAT,E.fireOnce);D[B]=F;if(E.onSubscribeCallback){F.subscribeEvent.subscribe(E.onSubscribeCallback);}this.__yui_subscribers=this.__yui_subscribers||{};var A=this.__yui_subscribers[B];if(A){for(var C=0;C -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> -<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %> -<%@ page import="org.apache.axis2.context.ConfigurationContext" %> -<%@ page import="org.wso2.carbon.CarbonConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.PaginatedPolicySetDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.PolicyEditorConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementAdminServiceClient" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient"%> - -<%@ page import="org.wso2.carbon.ui.CarbonUIMessage" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %> -<%@ page import="org.wso2.carbon.utils.ServerConstants" %> -<%@ page import="java.util.ResourceBundle" %> -<%@ page import="org.owasp.encoder.Encode" %> - - -<% - - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = - (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String forwardTo = null; - PaginatedPolicySetDTO paginatedPolicySetDTO = null; - String globalPolicyCombiningAlgorithm = null; - String [] policyCombiningAlgorithms = new String[]{PolicyEditorConstants.CombiningAlog.DENY_OVERRIDE_ID, - PolicyEditorConstants.CombiningAlog.PERMIT_OVERRIDE_ID, - PolicyEditorConstants.CombiningAlog.FIRST_APPLICABLE_ID, - PolicyEditorConstants.CombiningAlog.PERMIT_UNLESS_DENY_ID, - PolicyEditorConstants.CombiningAlog.DENY_UNLESS_PERMIT_ID, - PolicyEditorConstants.CombiningAlog.ORDER_PERMIT_OVERRIDE_ID, - PolicyEditorConstants.CombiningAlog.ORDER_DENY_OVERRIDE_ID, - PolicyEditorConstants.CombiningAlog.ONLY_ONE_APPLICABLE_ID}; - - PolicyDTO[] policies = null; - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - globalPolicyCombiningAlgorithm = request.getParameter("globalAlgorithmName"); - - int numberOfPages = 0; - String pageNumber = request.getParameter("pageNumber"); - if (pageNumber == null) { - pageNumber = "0"; - } - int pageNumberInt = 0; - try { - pageNumberInt = Integer.parseInt(pageNumber); - } catch (NumberFormatException ignored) { - } - - String policyTypeFilter = request.getParameter("policyTypeFilter"); - if (policyTypeFilter == null || "".equals(policyTypeFilter)) { - policyTypeFilter = "ALL"; - } - String policySearchString = request.getParameter("policySearchString"); - if (policySearchString == null) { - policySearchString = ""; - } else { - policySearchString = policySearchString.trim(); - } - - String paginationValue = "policyTypeFilter=" + policyTypeFilter + - "&policySearchString=" + policySearchString; - - try { - EntitlementPolicyAdminServiceClient client = - new EntitlementPolicyAdminServiceClient(cookie, serverURL, configContext); - EntitlementAdminServiceClient adminClient = - new EntitlementAdminServiceClient(cookie, serverURL, configContext); - paginatedPolicySetDTO = client. - getAllPolicies(policyTypeFilter, policySearchString, pageNumberInt, true); - policies = paginatedPolicySetDTO.getPolicySet(); - numberOfPages = paginatedPolicySetDTO.getNumberOfPages(); - if(globalPolicyCombiningAlgorithm != null && globalPolicyCombiningAlgorithm.trim().length() > 0){ - adminClient.setGlobalPolicyAlgorithm(globalPolicyCombiningAlgorithm); - } else { - globalPolicyCombiningAlgorithm = adminClient.getGlobalPolicyAlgorithm(); - } - - } catch (Exception e) { - String message = resourceBundle.getString("error.while.loading.policy")+ " " + e.getMessage(); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.ERROR, request); - forwardTo = "../admin/error.jsp"; -%> - - - - -<% - } -%> - - - - - - - - - -
-

-
- - <% - if (CarbonUIUtil.isUserAuthorized(request, "/permission/admin/manage/identity/entitlement/pap/policy/view")) { - %> - - - - -
- - - - - <% - if (CarbonUIUtil.isUserAuthorized(request, "/permission/admin/manage/identity/entitlement/pdp/manage")) { - %> - - <% - } - %> - -
- - - -
-
- <% - } - %> - -
- - - - -
- - - - - - - -
- - - "/>  - - - "> -
-
-
- - <%----%> - <%----%> - <%----%> - <%----%> - <%----%> - <%----%> - <%----%> - <%----%> - <%--
--%> - <%----%> - <%--  |  --%> - <%-- --%> - <%-- - <%--style="background-image: url(images/delete.gif);" >--%> - <%--
--%> - -
- - - - - - - - - - - <% - if (policies != null) { - for (int i = 0; i < policies.length; i++) { - if(policies[i] != null){ - %> - - - - - - <% - boolean canEnable = CarbonUIUtil.isUserAuthorized(request, "/permission/admin/manage/identity/entitlement/pap/policy/enable"); - boolean canDemote = CarbonUIUtil.isUserAuthorized(request, "/permission/admin/manage/identity/entitlement/pap/policy/demote"); - boolean canOrder = CarbonUIUtil.isUserAuthorized(request, "/permission/admin/manage/identity/entitlement/pap/policy/order"); - %> - - - - <%} } - } else { %> - - - - <%}%> - -
- <%=policies[i].getPolicyOrder()%> - - - <%=Encode.forUriComponent(policies[i].getPolicyId())%> - - <% - if(policies[i].getPolicyType() == null || "".equals(policies[i].getPolicyType())){ - policies[i].setPolicyType("Policy"); - } - %> - - <%=Encode.forHtmlAttribute(policies[i].getPolicyType())%> - <%=Encode.forHtmlContent(policies[i].getPolicyType())%> - - - <% - if (canEnable) { - if (policies[i].getActive()) { - %> - - - <% - } else { - %> - - - <% - } - } - if (canDemote) { - %> - - - <% - } - if (canOrder) { - %> - <%--
--%> - -   -   -   - - -   -   - - - - <%--
--%> - <% - } - %> -
-
- -
-
-
diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/pdp-manage.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/pdp-manage.jsp deleted file mode 100644 index 916fe071b2a4..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/pdp-manage.jsp +++ /dev/null @@ -1,273 +0,0 @@ - -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> -<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" - prefix="carbon"%> -<%@ page import="org.apache.axis2.context.ConfigurationContext"%> -<%@ page import="org.wso2.carbon.CarbonConstants"%> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.PDPDataHolder"%> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementAdminServiceClient" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %> -<%@page import="org.wso2.carbon.utils.ServerConstants"%> -<%@ page import="java.util.ResourceBundle" %> - -<% - - PDPDataHolder pdpDataHolder = null; - String[] pipAttributeFinders = null; - String[] pipResourceFinders = null; - String[] policyFinders = null; - String forwardTo; - - - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = - (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants. - CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - try { - EntitlementAdminServiceClient client = new EntitlementAdminServiceClient(cookie, - serverURL, configContext); - - pdpDataHolder = client.getPDPData(); - if(pdpDataHolder != null){ - pipAttributeFinders = pdpDataHolder.getPipAttributeFinders(); - pipResourceFinders = pdpDataHolder.getPipResourceFinders(); - policyFinders = pdpDataHolder.getPolicyFinders(); - } - } catch (Exception e) { -%> - -<% - } -%> - - - - - - - - - - - - - -
-

-
- <% - if (CarbonUIUtil.isUserAuthorized(request, "/permission/admin/manage/identity/entitlement/pdp/manage")) { - %> - - - - - -
-
- -
-
-
- -
-
- <% - } - %> - - - - - - - - - <% - if(policyFinders != null){ - for(String policyFinder : policyFinders){ - %> - - - - - <% - } - } - %> - -
<%=policyFinder%> - - - <% - if (CarbonUIUtil.isUserAuthorized(request, "/permission/admin/manage/identity/entitlement/pdp/manage")) { - %> - - - <% - } - %> -
- - - - - - - - - <% - if(pipAttributeFinders != null){ - for(String pipAttributeFinder : pipAttributeFinders){ - %> - - - - - <% - } - } - %> - -
<%=pipAttributeFinder%> - - - <% - if (CarbonUIUtil.isUserAuthorized(request, "/permission/admin/manage/identity/entitlement/pdp/manage")) { - %> - - - <% - } - %> -
- - - - - - - - - <% - if(pipResourceFinders != null){ - for(String pipResourceFinder : pipResourceFinders){ - %> - - - - - <% - } - } - %> - -
<%=pipResourceFinder%> - - - <% - if (CarbonUIUtil.isUserAuthorized(request, "/permission/admin/manage/identity/entitlement/pdp/manage")) { - %> - - - <% - } - %> -
- -
-
-
diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/policy-editor-config-view.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/policy-editor-config-view.jsp deleted file mode 100644 index 372b4f70d1da..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/policy-editor-config-view.jsp +++ /dev/null @@ -1,112 +0,0 @@ - -<%@ page import="org.owasp.encoder.Encode" %> -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> -<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" - prefix="carbon"%> - - - - -<%@ page import="org.wso2.carbon.identity.entitlement.common.EntitlementConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.common.PolicyEditorEngine" %> - -<% - String type = request.getParameter("type"); - if(type == null || type.trim().length() == 0){ - type = EntitlementConstants.PolicyEditor.STANDARD; - } - String editorConfig = PolicyEditorEngine.getInstance().getConfig(type); - if(editorConfig == null){ - editorConfig = ""; - } - editorConfig = editorConfig.trim(); -%> - - - -
-

-
-
- - - - - - - - - - - - - - -
- -
- - - - - - -
- - -
-
- - -
-
-
-
-
- - - - diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/policy-editor.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/policy-editor.jsp deleted file mode 100644 index 1b74ba4c1e48..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/policy-editor.jsp +++ /dev/null @@ -1,1767 +0,0 @@ - - -<%@ page import="org.owasp.encoder.Encode" %> -<%@ page import="org.wso2.balana.utils.Constants.PolicyConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.common.EntitlementConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.common.PolicyEditorEngine" %> -<%@ page import="org.wso2.carbon.identity.entitlement.common.dto.PolicyEditorDataHolder" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.EntitlementPolicyConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.PolicyEditorConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.ExtendAttributeDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.ObligationDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.RowDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.RuleDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.TargetDTO" %> -<%@ page import="java.util.ArrayList" %> -<%@ page import="java.util.List" %> -<%@ page import="java.util.ResourceBundle" %> -<%@ page import="java.util.Set" %> -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> -<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %> - - - - -<% - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - PolicyEditorDataHolder holder = PolicyEditorEngine.getInstance(). - getPolicyEditorData(EntitlementConstants.PolicyEditor.STANDARD); - - String ruleId = null; - RuleDTO ruleDTO = null; - String currentCategory = null; - String currentPreFunction = null; - String currentFunction = null; - String currentAttributeValue = null; - String currentAttributeId = null; - String currentAttributeDataType = null; - String currentCombineFunction = null; - - String currentRuleCategory = null; - String currentRulePreFunction = null; - String currentRuleFunction = null; - String currentRuleAttributeValue = null; - String currentRuleAttributeId = null; - String currentRuleAttributeDataType = null; - String currentRuleCombineFunction = null; - - String currentRuleTargetCategory = null; - String currentRuleTargetPreFunction = null; - String currentRuleTargetFunction = null; - String currentRuleTargetAttributeValue = null; - String currentRuleTargetAttributeId = null; - String currentRuleTargetAttributeDataType = null; - String currentRuleTargetCombineFunction = null; - - String currentDynamicId = null; - String currentDynamicSelector = null; - String currentDynamicCategory = null; - String currentDynamicFunction = null; - String currentDynamicAttributeValue= null; - String currentDynamicAttributeId= null; - String currentDynamicAttributeDataType= null; - - String currentObligationId = null; - String currentObligationEffect = null; - String currentObligationType = null; - String currentObligationAttributeValue = null; - String currentObligationAttributeId = null; - - String currentRuleObligationId = null; - String currentRuleObligationType = null; - String currentRuleObligationAttributeValue = null; - String currentRuleObligationAttributeId = null; - - String selectedAttributeNames = ""; - String ruleEffect = ""; - - String[] ruleEffects = PolicyConstants.RuleEffect.effect; - - String[] combineFunctions = new String[] {PolicyEditorConstants.COMBINE_FUNCTION_END, - PolicyEditorConstants.COMBINE_FUNCTION_AND, PolicyEditorConstants.COMBINE_FUNCTION_OR}; - - Set ruleCombingAlgorithm = holder.getRuleCombiningAlgorithms().keySet(); - - String[] obligationTypes = new String[]{"Obligation", "Advice"}; - - String[] dynamicSelectors = new String[]{PolicyEditorConstants.DYNAMIC_SELECTOR_CATEGORY, - PolicyEditorConstants.DYNAMIC_SELECTOR_FUNCTION }; - - String selectedAttributeDataType = request.getParameter("selectedAttributeDataType"); - String selectedAttributeId = request.getParameter("selectedAttributeId"); - // These are pass as hidden values. So can contain null value ... - if ("null".equals(selectedAttributeId)) { - selectedAttributeId = null; - } - - if ("null".equals(selectedAttributeDataType)) { - selectedAttributeDataType = null; - } - - int noOfSelectedAttributes = 1; - /** - * Get posted resources from jsp pages and put then in to a String object - */ - while(true) { - String attributeName = request.getParameter("attributeValue" + noOfSelectedAttributes); - if (attributeName == null || attributeName.trim().length() < 1) { - break; - } - if(selectedAttributeNames.equals("")) { - selectedAttributeNames = attributeName.trim(); - } else { - selectedAttributeNames = selectedAttributeNames + "," + attributeName.trim(); - } - noOfSelectedAttributes ++; - } - - ruleId = request.getParameter("ruleId"); - if (ruleId != null && ruleId.trim().length() > 0 && !ruleId.trim().equals("null")) { - ruleDTO = entitlementPolicyBean.getRuleDTO(ruleId); - } - - Set categories = holder.getCategoryMap().keySet(); - Set rulePreFunctions = holder.getPreFunctionMap().keySet(); - String[] targetPreFunctions = new String[]{"is"}; - Set targetFunctions = holder.getTargetFunctions(); - Set ruleFunctions = holder.getRuleFunctions(); - - List ruleDTOs = entitlementPolicyBean.getRuleDTOs(); - TargetDTO targetDTO = entitlementPolicyBean.getTargetDTO(); - List obligationDTOs = entitlementPolicyBean.getObligationDTOs(); - List extendAttributeDTOs = entitlementPolicyBean.getExtendAttributeDTOs(); -%> - - - -<% - for(String selector : dynamicSelectors){ - String tmp = ""; - if(PolicyEditorConstants.DYNAMIC_SELECTOR_FUNCTION.equals(selector)){ - for(String function : ruleFunctions){ - tmp += ""; - } - } else { - for(String category : categories){ - tmp += ""; - } - } -%> - - - - <% - } - %> - - - -<% - if(targetDTO != null){ - List rowDTOs = targetDTO.getRowDTOList(); - if(rowDTOs != null && rowDTOs.size() > 0){ - RowDTO rowDTO = rowDTOs.get(0); - currentCategory = rowDTO.getCategory(); - currentPreFunction = rowDTO.getPreFunction(); - currentFunction = rowDTO.getFunction(); - if(rowDTO.isNotCompleted()){ - if(rowDTO.getAttributeValue() != null && rowDTO.getAttributeValue().trim().length() > 0){ - if(selectedAttributeNames != null && selectedAttributeNames.trim().length() > 0){ - currentAttributeValue = rowDTO.getAttributeValue() + "," + selectedAttributeNames; - } else { - currentAttributeValue = rowDTO.getAttributeValue(); - } - } else { - currentAttributeValue = selectedAttributeNames; - } - currentAttributeId = selectedAttributeId; - currentAttributeDataType = selectedAttributeDataType; - } else { - currentAttributeValue = rowDTO.getAttributeValue(); - currentAttributeId = rowDTO.getAttributeId(); - currentAttributeDataType = rowDTO.getAttributeDataType(); - } - currentCombineFunction = rowDTO.getCombineFunction(); - } - } - - if(ruleDTO != null){ - ruleId = ruleDTO.getRuleId(); - ruleEffect = ruleDTO.getRuleEffect(); - List rowDTOs = ruleDTO.getRowDTOList(); - if(rowDTOs != null && rowDTOs.size() > 0){ - RowDTO rowDTO = rowDTOs.get(0); - currentRuleCategory = rowDTO.getCategory(); - currentRulePreFunction = rowDTO.getPreFunction(); - currentRuleFunction = rowDTO.getFunction(); - if(rowDTO.isNotCompleted()){ - if(rowDTO.getAttributeValue() != null && rowDTO.getAttributeValue().trim().length() > 0){ - if(selectedAttributeNames != null && selectedAttributeNames.trim().length() > 0){ - currentRuleAttributeValue = rowDTO.getAttributeValue() + "," + selectedAttributeNames; - } else { - currentRuleAttributeValue = rowDTO.getAttributeValue(); - } - } else { - currentRuleAttributeValue = selectedAttributeNames; - } - currentRuleAttributeId = selectedAttributeId; - currentRuleAttributeDataType = selectedAttributeDataType; - } else { - currentRuleAttributeValue = rowDTO.getAttributeValue(); - currentRuleAttributeId = rowDTO.getAttributeId(); - currentRuleAttributeDataType = rowDTO.getAttributeDataType(); - } - currentRuleCombineFunction = rowDTO.getCombineFunction(); - } - - TargetDTO targetRuleDTO = ruleDTO.getTargetDTO(); - - if(targetRuleDTO != null && targetRuleDTO.getRowDTOList() != null && - targetRuleDTO.getRowDTOList().size() > 0){ - RowDTO rowDTO = targetRuleDTO.getRowDTOList().get(0); - currentRuleTargetCategory = rowDTO.getCategory(); - currentRuleTargetPreFunction = rowDTO.getPreFunction(); - currentRuleTargetFunction = rowDTO.getFunction(); - if(rowDTO.isNotCompleted()){ - if(rowDTO.getAttributeValue() != null && rowDTO.getAttributeValue().trim().length() > 0){ - if(selectedAttributeNames != null && selectedAttributeNames.trim().length() > 0){ - currentRuleTargetAttributeValue = rowDTO.getAttributeValue() + "," + selectedAttributeNames; - } else { - currentRuleTargetAttributeValue = rowDTO.getAttributeValue(); - } - } else { - currentRuleTargetAttributeValue = selectedAttributeNames; - } - currentRuleTargetAttributeId = selectedAttributeId; - currentRuleTargetAttributeDataType = selectedAttributeDataType; - } else { - currentRuleTargetAttributeValue = rowDTO.getAttributeValue(); - currentRuleTargetAttributeId = rowDTO.getAttributeId(); - currentRuleTargetAttributeDataType = rowDTO.getAttributeDataType(); - } - currentRuleTargetCombineFunction = rowDTO.getCombineFunction(); - } - - List obligationRuleDTOs = ruleDTO.getObligationDTOs(); - - if(obligationRuleDTOs != null && obligationRuleDTOs.size() > 0){ - ObligationDTO dto = obligationRuleDTOs.get(0); - currentRuleObligationType = dto.getType(); - currentRuleObligationId = dto.getObligationId(); - currentRuleObligationAttributeValue = dto.getAttributeValue(); - currentRuleObligationAttributeId = dto.getResultAttributeId(); - } - } - - if(obligationDTOs != null && obligationDTOs.size() > 0){ - ObligationDTO dto = obligationDTOs.get(0); - currentObligationType = dto.getType(); - currentObligationId = dto.getObligationId(); - currentObligationEffect = dto.getEffect(); - currentObligationAttributeValue = dto.getAttributeValue(); - currentObligationAttributeId = dto.getResultAttributeId(); - } else { - obligationDTOs = null; - } - - if(extendAttributeDTOs != null && extendAttributeDTOs.size() > 0){ - ExtendAttributeDTO dto = extendAttributeDTOs.get(0); - currentDynamicId = dto.getId(); - currentDynamicSelector = dto.getSelector(); - if(PolicyEditorConstants.DYNAMIC_SELECTOR_FUNCTION.equals(currentDynamicSelector)){ - currentDynamicFunction = dto.getFunction(); - currentDynamicAttributeValue = dto.getAttributeValue(); - } else { - currentDynamicCategory = dto.getCategory(); - } - currentDynamicAttributeId = dto.getAttributeId(); - currentDynamicAttributeDataType = dto.getDataType(); - } else { - extendAttributeDTOs = null; - } - -%> - - -<% if(entitlementPolicyBean.isEditPolicy()){%> - -<% } else { %> - -<%}%> - - - - - - - - - -
-<%if(entitlementPolicyBean.isEditPolicy()){%> -

-<%} else {%>

<%}%> -
-
- - - - <% - if (entitlementPolicyBean.getPolicyName() != null) { - %> - - <% - } else { - %> - - <% - } - %> - - - - - - - - - - <% - if (entitlementPolicyBean.getPolicyDescription() != null) { - %> - - <% - } else { - %> - - <% - } - %> - - - - - - - - - - - - - - - - - - - - -
*
- -
- -

- -
- - - - - -
- - - - - - - - - - - - - - - - - - - - -
- - - - - - - <% - if (currentAttributeValue != null && !"".equals(currentAttributeValue)) { - - %> - - <% - } else { - %> - - - <% - } - %> - - - - - - - - -
-
-<% - - if(targetDTO != null){ - List rowDTOs = targetDTO.getRowDTOList(); - if(rowDTOs != null && rowDTOs.size() > 0){ - //rowDTOs.remove(0); - for(int i = 1; i< rowDTOs.size(); i++){ - RowDTO rowDTO = rowDTOs.get(i); - currentCategory = rowDTO.getCategory(); - currentPreFunction = rowDTO.getPreFunction(); - currentFunction = rowDTO.getFunction(); - if(rowDTO.isNotCompleted()){ - if(rowDTO.getAttributeValue() != null && rowDTO.getAttributeValue().trim().length() > 0){ - if(selectedAttributeNames != null && selectedAttributeNames.trim().length() > 0){ - currentAttributeValue = rowDTO.getAttributeValue() + "," + selectedAttributeNames; - } else { - currentAttributeValue = rowDTO.getAttributeValue(); - } - } else { - currentAttributeValue = selectedAttributeNames; - } - currentAttributeId = selectedAttributeId; - currentAttributeDataType = selectedAttributeDataType; - } else { - currentAttributeValue = rowDTO.getAttributeValue(); - currentAttributeId = rowDTO.getAttributeId(); - currentAttributeDataType = rowDTO.getAttributeDataType(); - } - currentCombineFunction = rowDTO.getCombineFunction(); - - %> - - <% - } - } - } -%> -
- -
-

- -
- - - - - - -<% - - if(ruleDTO != null && ruleDTO.getObligationDTOs() != null && ruleDTO.getObligationDTOs().size() > 1){ - List ruleObligationDTOs = ruleDTO.getObligationDTOs(); - for(int i = 1; i < ruleObligationDTOs.size(); i++){ - ObligationDTO dto = ruleObligationDTOs.get(i); - currentRuleObligationType = dto.getType(); - currentRuleObligationId = dto.getObligationId(); - currentRuleObligationAttributeValue = dto.getAttributeValue(); - currentRuleObligationAttributeId = dto.getResultAttributeId(); - %> - - <% - } - } - %> - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* - - <% - if (ruleId != null && !ruleId.trim().equals("") && !ruleId.trim().equals("null")) { - %> - - <% - } else { - %> - - <% - } - %> -
- -
- - - - - - - - - - - - - - - - - -
- - - - - - - <% - if (currentRuleTargetAttributeValue != null && currentRuleTargetAttributeValue.trim().length() > 0) { - - %> - - <% - } else { - %> - - - <% - } - %> - - - - - - - - -
-<% - - if(ruleDTO != null){ - TargetDTO ruleTargetDTO = ruleDTO.getTargetDTO(); - if(ruleTargetDTO != null && ruleTargetDTO.getRowDTOList() != null && ruleTargetDTO.getRowDTOList().size() > 0){ - List rowDTOs = ruleTargetDTO.getRowDTOList(); - //rowDTOs.remove(0); - for(int i = 1; i< rowDTOs.size(); i++){ - RowDTO rowDTO = rowDTOs.get(i); - currentRuleTargetCategory = rowDTO.getCategory(); - currentRuleTargetPreFunction = rowDTO.getPreFunction(); - currentRuleTargetFunction = rowDTO.getFunction(); - if(rowDTO.isNotCompleted()){ - if(rowDTO.getAttributeValue() != null && - rowDTO.getAttributeValue().trim().length() > 0){ - if(selectedAttributeNames != null && selectedAttributeNames.trim().length() > 0){ - currentRuleTargetAttributeValue = rowDTO.getAttributeValue() + "," + selectedAttributeNames; - } else { - currentRuleTargetAttributeValue = rowDTO.getAttributeValue(); - } - } else { - currentRuleTargetAttributeValue = selectedAttributeNames; - } - currentRuleTargetAttributeId = selectedAttributeId; - currentRuleTargetAttributeDataType = selectedAttributeDataType; - } else { - currentRuleTargetAttributeValue = rowDTO.getAttributeValue(); - currentRuleTargetAttributeId = rowDTO.getAttributeId(); - currentRuleTargetAttributeDataType = rowDTO.getAttributeDataType(); - } - currentRuleTargetCombineFunction = rowDTO.getCombineFunction(); - - %> - - <% - } - } - } - -%> -
- - - - - - - - - - - - - - - - -<% - - if(ruleDTO != null){ - List rowDTOs = ruleDTO.getRowDTOList(); - if(rowDTOs != null && rowDTOs.size() > 0){ - //rowDTOs.remove(0); - for(int i = 1; i< rowDTOs.size(); i++){ - RowDTO rowDTO = rowDTOs.get(i); - currentRuleCategory = rowDTO.getCategory(); - currentRulePreFunction = rowDTO.getPreFunction(); - currentRuleFunction = rowDTO.getFunction(); - if(rowDTO.isNotCompleted()){ - if(rowDTO.getAttributeValue() != null && rowDTO.getAttributeValue().trim().length() > 0){ - if(selectedAttributeNames != null && selectedAttributeNames.trim().length() > 0){ - currentRuleAttributeValue = rowDTO.getAttributeValue() + "," + selectedAttributeNames; - } else { - currentRuleAttributeValue = rowDTO.getAttributeValue(); - } - } else { - currentRuleAttributeValue = selectedAttributeNames; - } - currentRuleAttributeId = selectedAttributeId; - currentRuleAttributeDataType = selectedAttributeDataType; - } else { - currentRuleAttributeValue = rowDTO.getAttributeValue(); - currentRuleAttributeId = rowDTO.getAttributeId(); - currentRuleAttributeDataType = rowDTO.getAttributeDataType(); - } - currentRuleCombineFunction = rowDTO.getCombineFunction(); - - %> - - <% - } - } - } - -%> -
- - - - - - - <% - if (currentRuleAttributeValue != null && currentRuleAttributeValue.trim().length() > 0) { - - %> - - <% - } else { - %> - - - <% - } - %> - - - - - - - - -
-
- - - - - <%----%> -
Obligation TypeIdAttribute ValueAssignment Id
-
- - - - - - - <%----%> - - -
- - - <% - if (currentRuleObligationId != null && currentRuleObligationId.trim().length() > 0) { - %> - - <% - } else { - %> - - <% - } - %> - - <% - if (currentRuleObligationAttributeValue != null && currentRuleObligationAttributeValue.trim().length() > 0) { - %> - - <% - } else { - %> - - <% - } - %> - --%> - <%--<%--%> - <%--if (currentRuleObligationAttributeId != null && currentRuleObligationAttributeId.trim().length() > 0) {--%> - <%--%>--%> - <%-- - <%--value="<%=currentRuleObligationAttributeId%>" />--%> - <%--<%--%> - <%--} else {--%> - <%--%>--%> - <%----%> - <%--<%--%> - <%--}--%> - <%--%>--%> - <%-- - -
-
-
- <% - if (ruleDTO != null && ruleDTO.isCompletedRule()) { - %> - - - - - <% - } else { - %> - - - <% - } - %> -
-
-
-

-
- - - - - - -
Obligation TypeIdEffect Attribute Value
- - - - - - - - - - <%----%> - - -<% - if(obligationDTOs != null && obligationDTOs.size() > 0){ - //obligationDTOs.remove(0); - for(int i = 1; i < obligationDTOs.size(); i++){ - ObligationDTO dto = obligationDTOs.get(i); - currentObligationType = dto.getType(); - currentObligationId = dto.getObligationId(); - currentObligationEffect = dto.getEffect(); - currentObligationAttributeValue = dto.getAttributeValue(); - currentObligationAttributeId = dto.getResultAttributeId(); - %> - - <% - } - } -%> -
- - - <% - if (currentObligationId != null && currentObligationId.trim().length() > 0) { - %> - - <% - } else { - %> - - <% - } - %> - - - - <% - if (currentObligationAttributeValue != null && currentObligationAttributeValue.trim().length() > 0) { - %> - - <% - } else { - %> - - <% - } - %> - --%> - <%--<%--%> - <%--if (currentObligationAttributeId != null && currentObligationAttributeId.trim().length() > 0) {--%> - <%--%>--%> - <%-- - <%--value="<%=currentObligationAttributeId%>" />--%> - <%--<%--%> - <%--} else {--%> - <%--%>--%> - <%----%> - <%--<%--%> - <%--}--%> - <%--%>--%> - <%-- - -
-
-
- - - - - - - - - <% - if (ruleDTOs != null && ruleDTOs.size() > 0) { - List orderedRuleDTOs = new ArrayList(); - String ruleElementOrder = entitlementPolicyBean.getRuleElementOrder(); - if (ruleElementOrder != null) { - String[] orderedRuleIds = ruleElementOrder.split(EntitlementPolicyConstants.ATTRIBUTE_SEPARATOR); - for (String orderedRuleId : orderedRuleIds) { - for (RuleDTO dto : ruleDTOs) { - if (orderedRuleId.trim().equals(dto.getRuleId())) { - orderedRuleDTOs.add(dto); - } - } - } - } - - if (orderedRuleDTOs.size() < 1) { - orderedRuleDTOs = ruleDTOs; - } - for (RuleDTO orderedRuleDTO : orderedRuleDTOs) { - if (orderedRuleDTO.isCompletedRule()) { - %> - - - - - - - <% - } - } - } else { - %> - - - - <% - } - %> -
- - - - <%=orderedRuleDTO.getRuleId()%> - <%=orderedRuleDTO.getRuleEffect()%> - - - -

-
- " - class="button"/> - " - class="button"/> -
-
-
-
-
diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/policy-publish.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/policy-publish.jsp deleted file mode 100644 index 03569d10fec4..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/policy-publish.jsp +++ /dev/null @@ -1,382 +0,0 @@ - -<%@ page import="org.owasp.encoder.Encode" %> -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> -<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" - prefix="carbon" %> -<%@ page import="org.apache.axis2.context.ConfigurationContext" %> -<%@ page import="org.wso2.carbon.CarbonConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.PublisherDataHolder" %> -<%@page import="org.wso2.carbon.identity.entitlement.stub.dto.PublisherPropertyDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.EntitlementPolicyConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient" %> -<%@ page - import="org.wso2.carbon.identity.entitlement.ui.util.ClientUtil" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %> -<%@ page import="org.wso2.carbon.utils.ServerConstants" %> - -<% - - String[] subscriberIds = null; - session.removeAttribute(EntitlementPolicyConstants.ENTITLEMENT_PUBLISHER_MODULE); - - EntitlementPolicyAdminServiceClient client = null; - - int numberOfPages = 0; - boolean isPaginated = Boolean.parseBoolean(request.getParameter("isPaginated")); - String subscriberSearchString = request.getParameter("subscriberSearchString"); - if (subscriberSearchString == null) { - subscriberSearchString = "*"; - } else { - subscriberSearchString = subscriberSearchString.trim(); - } - String paginationValue = "isPaginated=true&subscriberSearchString=" + subscriberSearchString; - - String pageNumber = request.getParameter("pageNumber"); - if (pageNumber == null) { - pageNumber = "0"; - } - int pageNumberInt = 0; - try { - pageNumberInt = Integer.parseInt(pageNumber); - } catch (NumberFormatException ignored) { - // ignore - } - - String selectedModule = request.getParameter("selectedModule"); - boolean update = Boolean.parseBoolean(request.getParameter("update")); - PublisherPropertyDTO[] propertyDTOs = (PublisherPropertyDTO[]) session. - getAttribute(EntitlementPolicyConstants.ENTITLEMENT_PUBLISHER_PROPERTY); - - session.removeAttribute(EntitlementPolicyConstants.ENTITLEMENT_PUBLISHER_PROPERTY); - - if (propertyDTOs != null) { - for (PublisherPropertyDTO dto : propertyDTOs) { - String value = request.getParameter(dto.getId()); - if (value != null && value.trim().length() > 0) { - dto.setValue(value); - } - } - } - - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = - (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants. - CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - try { - - if (client == null) { - - client = new EntitlementPolicyAdminServiceClient(cookie, - serverURL, configContext); - session.setAttribute(EntitlementPolicyConstants.ENTITLEMENT_ADMIN_CLIENT, client); - } - - - if (selectedModule != null && selectedModule.trim().length() > 0 && propertyDTOs != null - && propertyDTOs.length > 0) { - PublisherDataHolder holder = new PublisherDataHolder(); - holder.setModuleName(selectedModule); - holder.setPropertyDTOs(propertyDTOs); - client.updateSubscriber(holder, update); - - } - int itemsPerPageInt = EntitlementPolicyConstants.DEFAULT_ITEMS_PER_PAGE; - // as these are just strings, get all values in to UI and the do the pagination - String[] allSubscriberIds = (String[])session.getAttribute("subscriberIds"); - if(allSubscriberIds == null || !isPaginated){ - allSubscriberIds = client.getSubscriberIds(subscriberSearchString); - session.setAttribute("subscriberIds", allSubscriberIds); - } - if (allSubscriberIds != null) { - numberOfPages = (int) Math.ceil((double) allSubscriberIds.length / itemsPerPageInt); - subscriberIds = ClientUtil.doPagingForStrings(pageNumberInt, itemsPerPageInt, allSubscriberIds); - } - } catch (Exception e) { -%> - - -<% - } -%> - - - - - - - - - - - - - -
- -

- -
- - - - - - - - - - - - - -
-
- -
-
-
- - - - -
- - - - - - - -
- - - "/>  - - - "> -
-
-
-
- -  |  - - - -
- -
- - - - - - - - <% - if (subscriberIds != null && subscriberIds.length > 0) { - for (String subscriber : subscriberIds) { - if (subscriber != null && subscriber.trim().length() > 0 ) { - %> - - - - - - <% - } - } - %> - <% - } - %> -
- - <%=Encode.forHtmlContent(subscriber)%> - - - - - - - -
- - -
-
-
\ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/policy-search.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/policy-search.jsp deleted file mode 100644 index 8abcf6a8fbd7..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/policy-search.jsp +++ /dev/null @@ -1,292 +0,0 @@ - - <%@ page import="org.owasp.encoder.Encode" %> -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> -<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" - prefix="carbon"%> -<%@ page import="org.apache.axis2.context.ConfigurationContext"%> -<%@ page import="org.wso2.carbon.CarbonConstants"%> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.AttributeDTO"%> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO"%> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.EntitlementPolicyConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIMessage" %> -<%@page import="org.wso2.carbon.ui.CarbonUIUtil"%> -<%@ page import="org.wso2.carbon.utils.ServerConstants" %> -<%@ page import="java.util.ArrayList" %> -<%@ page import="java.util.List" %> -<%@ page import="java.util.ResourceBundle" %> - -<% - String attributeValue = ""; - String attributeType = ""; - String attributeId = ""; - String attributeDataType = ""; - String[] results = null; - List policies = new ArrayList(); - String[] attributeTypes = new String[] {EntitlementPolicyConstants.RESOURCE_ELEMENT, - EntitlementPolicyConstants.SUBJECT_ELEMENT, - EntitlementPolicyConstants.ACTION_ELEMENT, - EntitlementPolicyConstants.ENVIRONMENT_ELEMENT}; - String forwardTo; - - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = - (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants. - CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - - attributeValue = (String)request.getParameter("attributeValue"); - attributeType = (String)request.getParameter("attributeType"); - attributeId = (String)request.getParameter("attributeId"); - attributeDataType = (String)request.getParameter("attributeDataType"); - - List attributeValueDTOs = new ArrayList(); - - if(attributeValue != null && !"".equals(attributeValue)){ - AttributeDTO attributeValueDTO = new AttributeDTO(); - attributeValueDTO.setAttributeValue(attributeValue); - if(!EntitlementPolicyConstants.COMBO_BOX_ANY_VALUE.equals(attributeType)){ - attributeValueDTO.setAttributeType(attributeType); - } - attributeValueDTO.setAttributeDataType(attributeDataType); - attributeValueDTO.setAttributeId(attributeId); - attributeValueDTOs.add(attributeValueDTO); - } - - try { - EntitlementPolicyAdminServiceClient client = new EntitlementPolicyAdminServiceClient(cookie, - serverURL, configContext); - if(attributeValueDTOs.size() > 0){ - results = client.getAdvanceSearchResult(attributeValueDTOs. - toArray(new AttributeDTO[attributeValueDTOs.size()])); - if(results != null){ - for (String result : results){ - policies.add(client.getPolicy(result, false)); - } - } - } - - } catch (Exception e) { - String message = resourceBundle.getString("error.while.loading.policy.resource"); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.ERROR, request); - forwardTo = "../admin/error.jsp"; -%> - - - -<% - } -%> - - - - - - - - - - - - - -
-

-
-
- - - - - - - - - - - - - - - - - - - - - - - - -
* - <% - if (attributeValue != null && !attributeValue.equals("")) { - %> - - <% - } else { - %> - - <% - } - %> -
- -
- <% - if (attributeId != null && !attributeId.equals("")) { - %> - - <% - } else { - %> - - <% - } - %> -
- <% - if (attributeDataType != null && !attributeDataType.equals("")) { - %> - - <% - } else { - %> - - <% - } - %> -
- -
-
-

-
- - - - - - - - <% - if (policies != null && policies.size() > 0) { - for (PolicyDTO policyDTO : policies) { - if(policyDTO != null){ - %> - - - - - - - - <%} } - } else { %> - - - - <%}%> - -
- <%=Encode.forHtml(policyDTO.getPolicyId())%> - - <% - if(policyDTO.getPolicyType() == null || "".equals(policyDTO.getPolicyType())){ - policyDTO.setPolicyType("Policy"); - } - %> - - <%= Encode.forHtmlAttribute(policyDTO.getPolicyType())%> - <%= Encode.forHtmlContent(policyDTO.getPolicyType())%> - - - - - <% if (Boolean.toString(policyDTO.getActive()).equals("true")) { %> - - - <% }else { %> - - - <%} %> -
-
- -
-
-
diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/policy-view-pdp.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/policy-view-pdp.jsp deleted file mode 100644 index 10741ae854e3..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/policy-view-pdp.jsp +++ /dev/null @@ -1,131 +0,0 @@ - -<%@ page import="org.owasp.encoder.Encode" %> -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> -<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" - prefix="carbon"%> -<%@ page import="org.apache.axis2.context.ConfigurationContext"%> -<%@ page import="org.wso2.carbon.CarbonConstants"%> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO"%> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient"%> - -<%@page import="org.wso2.carbon.ui.CarbonUIUtil"%> - - - -<%@page import="org.wso2.carbon.utils.ServerConstants"%> - -<%@ page import="java.text.MessageFormat"%> -<%@ page import="java.util.ResourceBundle" %> -<% - String policy = ""; - String policyId = request.getParameter("policyId"); - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = (ConfigurationContext) config.getServletContext(). - getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - - try { - EntitlementPolicyAdminServiceClient client = new EntitlementPolicyAdminServiceClient( - cookie, serverURL, configContext); - PolicyDTO policyDTO = client.getPolicy(policyId, true); - if (policyDTO != null && policyDTO.getPolicy() != null) { - policy = policyDTO.getPolicy().trim().replaceAll("><", ">\n<"); - } - } catch (Exception e) { - String message = MessageFormat.format(resourceBundle. - getString("error.while.retreiving.policies"), e.getMessage()); -%> - -<% - } -%> - - - -
-

-
- - - - - - - - - - - - - - -
- -
- - - - - - -
- - -
-
- -
-
-
-
- - - - \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/policy-view.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/policy-view.jsp deleted file mode 100644 index 1f19c3f1f24f..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/policy-view.jsp +++ /dev/null @@ -1,106 +0,0 @@ - -<%@ page import="org.apache.axis2.context.ConfigurationContext" %> -<%@ taglib uri="http://www.owasp.org/index.php/Category:OWASP_CSRFGuard_Project/Owasp.CsrfGuard.tld" prefix="csrf" %> -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> -<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" - prefix="carbon" %> -<%@ page import="org.owasp.encoder.Encode" %> -<%@ page import="org.wso2.carbon.CarbonConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient" %> - -<%@page import="org.wso2.carbon.ui.CarbonUIUtil" %> - - - -<%@page import="org.wso2.carbon.utils.ServerConstants" %> - -<%@ page import="java.text.MessageFormat" %> -<%@ page import="java.util.ResourceBundle" %> -<% - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = (ConfigurationContext) config.getServletContext(). - getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String policy = ""; - String policyId = null; - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - - try { - EntitlementPolicyAdminServiceClient client = new EntitlementPolicyAdminServiceClient( - cookie, serverURL, configContext); - policyId = request.getParameter("policyid"); - policy = (String) session.getAttribute("policy"); - if (policy == null && policyId != null && policyId.trim().length() > 0) { - PolicyDTO dto = client.getPolicy(policyId, false); - if (dto != null) { - policy = dto.getPolicy(); - } - } - - if (policy != null) { - policy = policy.trim().replaceAll("><", ">\n<"); - } else { - policy = ""; - } - session.removeAttribute("policy"); - } catch (Exception e) { - String message = MessageFormat.format(resourceBundle. - getString("error.while.retreiving.policies"), e.getMessage()); -%> - -<% - } -%> - -
-
- - - - - -
-
- - \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/prettyPrinter_ajaxprocessor.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/prettyPrinter_ajaxprocessor.jsp deleted file mode 100644 index 1145be28191f..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/prettyPrinter_ajaxprocessor.jsp +++ /dev/null @@ -1,20 +0,0 @@ -<%@ page import="org.wso2.carbon.utils.xml.XMLPrettyPrinter" %><%@ page import="java.io.ByteArrayInputStream" %><%@ page import="java.io.InputStream" %><% - - String httpMethod = request.getMethod(); - if (!"post".equalsIgnoreCase(httpMethod)) { - response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); - return; - } - - String rawXML = request.getParameter("xmlString"); - rawXML = rawXML.replaceAll("\n|\\r|\\f|\\t", ""); - InputStream xmlIn = new ByteArrayInputStream(rawXML.getBytes()); - XMLPrettyPrinter xmlPrettyPrinter = new XMLPrettyPrinter(xmlIn); - rawXML = xmlPrettyPrinter.xmlFormat(); - if (rawXML.startsWith("\n")) { - rawXML = rawXML.substring(1); - } - response.setContentType("text/plain"); - - -%><%=rawXML%> \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/publish-finish-ajaxprocessor.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/publish-finish-ajaxprocessor.jsp deleted file mode 100644 index dd62c26c5b7b..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/publish-finish-ajaxprocessor.jsp +++ /dev/null @@ -1,103 +0,0 @@ - -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> -<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" - prefix="carbon"%> -<%@ page import="org.apache.axis2.context.ConfigurationContext"%> -<%@ page import="org.wso2.carbon.CarbonConstants"%> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient"%> -<%@ page import="org.wso2.carbon.ui.CarbonUIMessage"%> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %> -<%@ page import="org.wso2.carbon.utils.ServerConstants" %> -<%@ page import="java.util.ResourceBundle"%> -<% - String httpMethod = request.getMethod(); - if (!"post".equalsIgnoreCase(httpMethod)) { - response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); - return; - } - - boolean publishToAllSubscribers = false; - boolean publishAllPolicies = false; - String[] selectedPolicies = null; - String forwardTo = "index.jsp"; - - if(session.getAttribute("selectedPolicies") != null){ - selectedPolicies= (String[]) session.getAttribute("selectedPolicies"); - } - if(session.getAttribute("publishAllPolicies") != null){ - publishAllPolicies = (Boolean) session.getAttribute("publishAllPolicies"); - } - String[] selectedSubscribers = request.getParameterValues("subscribersList"); - String allSubscribers = request.getParameter("publishToAllSubscribers"); - - if(allSubscribers != null && "true".equals(allSubscribers.trim())){ - publishToAllSubscribers = true; - } - - String publishAction = request.getParameter("publishAction"); - String publishVersion = request.getParameter("policyVersion"); - String policyOrderString = request.getParameter("policyOrder"); - boolean policyEnable = Boolean.parseBoolean(request.getParameter("policyEnable")); - int policyOrder = 0; - if(policyOrderString != null && policyOrderString.trim().length() > 0){ - try{ - policyOrder = Integer.parseInt(policyOrderString); - } catch (Exception e){ - //ignore - } - } - - session.removeAttribute("selectedPolicies"); - session.removeAttribute("publishAllPolicies"); - - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = - (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants. - CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - try { - EntitlementPolicyAdminServiceClient client = new EntitlementPolicyAdminServiceClient(cookie, - serverURL, configContext); - if(publishAllPolicies && publishToAllSubscribers){ - client.publish(null, null, publishAction, null, policyEnable, policyOrder); - } else if(publishAllPolicies && selectedSubscribers != null && selectedSubscribers.length > 0){ - client.publish(null, selectedSubscribers, publishAction, null, policyEnable, policyOrder); - } else if(selectedPolicies != null && selectedPolicies.length > 0 && publishToAllSubscribers){ - client.publish(selectedPolicies, null, publishAction, null, policyEnable, policyOrder); - } else if(selectedPolicies != null && selectedPolicies.length > 0 && selectedSubscribers != null && - selectedSubscribers.length > 0){ - client.publish(selectedPolicies, selectedSubscribers, publishAction, publishVersion, - policyEnable, policyOrder); - } - } catch (Exception e) { - String message = resourceBundle.getString("error.while.publishing.policies"); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.ERROR, request); - } -%> - - - \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/re-order-policy.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/re-order-policy.jsp deleted file mode 100644 index 6e8d159065f7..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/re-order-policy.jsp +++ /dev/null @@ -1,81 +0,0 @@ - -<%@ page import="org.apache.axis2.context.ConfigurationContext"%> -<%@ page import="org.wso2.carbon.CarbonConstants"%> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO"%> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient"%> -<%@ page import="org.wso2.carbon.ui.CarbonUIMessage"%> - -<%@page - import="org.wso2.carbon.ui.CarbonUIUtil"%> -<%@page import="org.wso2.carbon.utils.ServerConstants"%> -<%@ page import="java.util.ResourceBundle" %> -<% - String forwardTo = null; - PolicyDTO dto = null; - - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = (ConfigurationContext) config.getServletContext(). - getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String order = request.getParameter("order"); - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - String policyId = request.getParameter("policyId"); - if (( policyId != null)) { - try { - EntitlementPolicyAdminServiceClient client = - new EntitlementPolicyAdminServiceClient(cookie, serverURL, configContext); - dto = client.getLightPolicy(policyId); - if (order != null && order.trim().length() > 0){ - int oderInt = 0; - try{ - oderInt = Integer.parseInt(order); - } catch (Exception e){ - String message = resourceBundle.getString("order.not.null"); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.WARNING, request); - } - if(oderInt != 0){ - dto.setPolicyOrder(oderInt); - client.updatePolicy(dto); - } - } else { - String message = resourceBundle.getString("order.not.null"); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.WARNING, request); - } - forwardTo = "index.jsp"; - } catch (Exception e) { - String message = resourceBundle.getString("invalid.policy.not.updated"); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.ERROR, request); - forwardTo = "index.jsp"; - } - } else { - forwardTo = "index.jsp?region=region1&item=policy_menu"; - } -%> - - - - \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/refresh-finder.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/refresh-finder.jsp deleted file mode 100644 index 20e975e4432e..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/refresh-finder.jsp +++ /dev/null @@ -1,69 +0,0 @@ - -<%@ page import="org.apache.axis2.context.ConfigurationContext"%> -<%@ page import="org.wso2.carbon.CarbonConstants"%> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementAdminServiceClient"%> -<%@ page import="org.wso2.carbon.ui.CarbonUIMessage"%> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil"%> -<%@ page import="org.wso2.carbon.utils.ServerConstants"%> -<%@ page import="java.util.ResourceBundle" %> -<% - - String forwardTo = null; - String finderId = request.getParameter("finderId"); - String type = request.getParameter("type"); - - String serverURL = CarbonUIUtil.getServerURL(config - .getServletContext(), session); - ConfigurationContext configContext = (ConfigurationContext) config - .getServletContext().getAttribute( - CarbonConstants.CONFIGURATION_CONTEXT); - String cookie = (String) session - .getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - try { - EntitlementAdminServiceClient client = - new EntitlementAdminServiceClient(cookie, serverURL, configContext); - if(finderId != null){ - if("attribute".equals(type)) { - client.refreshAttributeFinder(finderId); - } else if("resource".equals(type)){ - client.refreshResourceFinder(finderId); - } else if("policy".equals(type)){ - client.refreshPolicyFinder(finderId); - } - forwardTo = "pdp-manage.jsp"; - } - } catch (Exception e) { - String message = resourceBundle.getString("invalid.policy.not.updated"); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.ERROR, request); - forwardTo = "pdp-manage.jsp"; - } -%> - - - - \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/remove-policy-ajaxprocessor.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/remove-policy-ajaxprocessor.jsp deleted file mode 100644 index 11b07c71d2d7..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/remove-policy-ajaxprocessor.jsp +++ /dev/null @@ -1,74 +0,0 @@ - -<%@ page import="org.apache.axis2.context.ConfigurationContext"%> -<%@ page import="org.wso2.carbon.CarbonConstants"%> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient"%> -<%@ page import="org.wso2.carbon.ui.CarbonUIMessage"%> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil"%> - -<% - String httpMethod = request.getMethod(); - if (!"post".equalsIgnoreCase(httpMethod)) { - response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); - return; - } - - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = - (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String forwardTo = "index.jsp"; - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - - try { - String policyId = request.getParameter("policyId"); - String dePromote = request.getParameter("dePromote"); - EntitlementPolicyAdminServiceClient client = new EntitlementPolicyAdminServiceClient(cookie, serverURL, configContext); - String[] selectedPolicies = request.getParameterValues("policies"); - if(policyId != null && policyId.trim().length() > 0){ - client.dePromotePolicy(policyId); - forwardTo = "my-pdp.jsp"; - String message = resourceBundle.getString("policy.pdp.deleted.successfully"); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.INFO, request); - } else if(Boolean.parseBoolean(dePromote)) { - client.removePolicies(selectedPolicies, true); - } else { - client.removePolicies(selectedPolicies, false); - String message = resourceBundle.getString("policy.deleted.successfully"); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.INFO, request); - } - - } catch (Exception e) { - String message = resourceBundle.getString("policy.could.not.be.deleted"); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.ERROR, request); - } -%> - -<%@page import="org.wso2.carbon.utils.ServerConstants"%> -<%@page import="java.util.ResourceBundle"%> - - - \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/remove-subscriber-ajaxprocessor.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/remove-subscriber-ajaxprocessor.jsp deleted file mode 100644 index fe6c955513c8..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/remove-subscriber-ajaxprocessor.jsp +++ /dev/null @@ -1,63 +0,0 @@ - -<%@ page import="org.apache.axis2.context.ConfigurationContext"%> -<%@ page import="org.wso2.carbon.CarbonConstants"%> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient"%> -<%@ page import="org.wso2.carbon.ui.CarbonUIMessage"%> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil"%> - -<% - String httpMethod = request.getMethod(); - if (!"post".equalsIgnoreCase(httpMethod)) { - response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); - return; - } - - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = - (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String forwardTo = "policy-publish.jsp"; - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - - try { - EntitlementPolicyAdminServiceClient client = new EntitlementPolicyAdminServiceClient(cookie, - serverURL, configContext); - String[] selectedSubscribers = request.getParameterValues("subscribers"); - for(String subscriber :selectedSubscribers){ - client.deleteSubscriber(subscriber); - } - } catch (Exception e) { - String message = resourceBundle.getString("subscriber.could.not.be.deleted"); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.ERROR, request); - } -%> - -<%@page import="org.wso2.carbon.utils.ServerConstants"%> -<%@page import="java.util.ResourceBundle"%> - - - \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/rollback-policy-ajaxprocessor.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/rollback-policy-ajaxprocessor.jsp deleted file mode 100644 index 407ae97ab41c..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/rollback-policy-ajaxprocessor.jsp +++ /dev/null @@ -1,63 +0,0 @@ - -<%@ page import="org.apache.axis2.context.ConfigurationContext"%> -<%@ page import="org.wso2.carbon.CarbonConstants"%> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient"%> -<%@ page import="org.wso2.carbon.ui.CarbonUIMessage"%> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil"%> - -<% - String httpMethod = request.getMethod(); - if (!"post".equalsIgnoreCase(httpMethod)) { - response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); - return; - } - - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = - (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String forwardTo = "index.jsp"; - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - - try { - String policyId = request.getParameter("policyId"); - String selectedVersion = request.getParameter("selectedVersion"); - EntitlementPolicyAdminServiceClient client = new EntitlementPolicyAdminServiceClient(cookie, serverURL, configContext); - client.rollBackPolicy(policyId, selectedVersion); - String message = resourceBundle.getString("policy.rollbacked.successfully"); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.INFO, request); - } catch (Exception e) { - String message = resourceBundle.getString("policy.could.not.be.rollback"); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.ERROR, request); - } -%> - -<%@page import="org.wso2.carbon.utils.ServerConstants"%> -<%@page import="java.util.ResourceBundle"%> - - - \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/select-attribute-values.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/select-attribute-values.jsp deleted file mode 100644 index 9f8aa99f18a2..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/select-attribute-values.jsp +++ /dev/null @@ -1,470 +0,0 @@ - - <%@ page import="org.owasp.encoder.Encode" %> -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> -<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" - prefix="carbon"%> -<%@ page import="org.apache.axis2.context.ConfigurationContext"%> -<%@ page import="org.wso2.carbon.CarbonConstants" %> -<%@page import="org.wso2.carbon.identity.entitlement.stub.dto.EntitlementFinderDataHolder"%> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.EntitlementTreeNodeDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.EntitlementPolicyConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %> -<%@ page import="org.wso2.carbon.utils.ServerConstants" %> -<%@ page import="java.io.IOException" %> -<%@ page import="java.util.ResourceBundle" %> -<%@ page import="java.util.Set" %> - - -<%! - public void printChildrenTree(EntitlementTreeNodeDTO node, JspWriter out) throws IOException { - if(node != null){ - EntitlementTreeNodeDTO[] children = node.getChildNodes(); - if(children != null && children.length > 0){ - out.write("
  •   " + - "" + node.getName() + ""); - out.write("
      "); - for(EntitlementTreeNodeDTO child : children){ - printChildrenTree(child, out); - } - out.write("
    "); - } else { - out.write("
  •   " + - "" + node.getName() + ""); - out.write("
  • "); - } - } - } - - public void printChildren(EntitlementTreeNodeDTO node, String parentNodeName, JspWriter out) throws IOException { - if(node != null){ - String nodeName; - if(parentNodeName != null && parentNodeName.trim().length() > 0){ - nodeName = parentNodeName + "/" + node.getName(); - } else { - nodeName = node.getName(); - } - - out.write("
  • " + nodeName + "
  • ") ; - EntitlementTreeNodeDTO[] children = node.getChildNodes(); - if(children != null && children.length > 0){ - for(EntitlementTreeNodeDTO child : children){ - printChildren(child, nodeName, out); - } - } - } - } - -%> - -<% - String forwardTo; - EntitlementFinderDataHolder finderDataHolder = null; - EntitlementTreeNodeDTO selectedTree = null; - String selectedFinderModule; - String category; - boolean showNoData = false; - String searchString = request.getParameter("searchString"); - int levels = 0; - - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = - (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - - String ruleId = request.getParameter("ruleId"); - selectedFinderModule = request.getParameter("finderModule"); - if(selectedFinderModule == null || selectedFinderModule.trim().length() < 1){ - selectedFinderModule = EntitlementPolicyConstants.DEFAULT_META_DATA_MODULE_NAME; - } - - category = request.getParameter("category"); - String selectedDataLevelString = request.getParameter("selectedDataLevel"); - int selectedDataLevel = 0; - try{ - selectedDataLevel = Integer.parseInt(selectedDataLevelString); - } catch (Exception e){ - //ignore - } - String selectedData = request.getParameter("selectedData" + selectedDataLevel); - Set holders = entitlementPolicyBean.getEntitlementFinders(category); - try { - EntitlementPolicyAdminServiceClient client = - new EntitlementPolicyAdminServiceClient(cookie, serverURL, configContext); - - if(selectedFinderModule != null && selectedFinderModule.trim().length() > 0){ - finderDataHolder = entitlementPolicyBean.getEntitlementFinders().get(selectedFinderModule); - levels = finderDataHolder.getHierarchicalLevels(); - - if(searchString != null && searchString.trim().length() > 0){ - selectedTree = client.getEntitlementData(selectedFinderModule, - category, searchString, 0, 100); - if(selectedTree == null){ - showNoData = true; - } - } else if(levels > 0 && selectedData != null && selectedData.trim().length() > 0 && - selectedDataLevel + 1 != levels){ - EntitlementTreeNodeDTO nodeDTO = client.getEntitlementData(selectedFinderModule, - category, selectedData, selectedDataLevel + 1, 100); - entitlementPolicyBean.getEntitlementLevelData().put(selectedDataLevel + 1, nodeDTO); - if(selectedData != null && selectedData.trim().length() > 0 ){ - entitlementPolicyBean.getSelectedEntitlementData().put(selectedDataLevel, selectedData); - } - } - } else { - String message = resourceBundle.getString("no.entitlement.data.finder.defined"); - %> - - <% - } - } catch (Exception e) { - String message = resourceBundle.getString("error.while.retrieving.attribute.values"); -%> - -<% - } -%> - -<% - if(holders == null || holders.size() == 0){ - String message = resourceBundle.getString("no.entitlement.data.finder.defined"); -%> - -<% - } -%> -<% - if(showNoData){ - String message = resourceBundle.getString("no.entitlement.data.defined"); -%> - -<% - } -%> - - - - - - - - - - - - - - - - - - - - - - - -
    -

    -
    -
    - - - - - - -
    - - - - - - - - - - - - - - - - - <% - } - %> -
    - - <% - if(holders != null && holders.size() > 0){ - %> - - - - - <% - int i = 1; - while (true) { - EntitlementTreeNodeDTO nodeDTO = entitlementPolicyBean.getEntitlementLevelData().get(i); - if(nodeDTO == null){ - break; - } - %> - - - - - - - <% - i++; - } - %> - <% - if(levels == 0 || selectedDataLevel + 1 == levels){ - %> - - - - - - <% - } - %> -
    - - - -
    - <%=i%> - - - - -
    - - - "/> - - "> -
    -
    - - -
    - - - - - - - - - - - <% - if(selectedTree != null){ - %> - - - - <% - } - %> - - -
    -
    -
      - <% - if(finderDataHolder.getHierarchicalTree()){ - EntitlementTreeNodeDTO[] childNodes = selectedTree.getChildNodes(); - if(childNodes != null && childNodes.length > 0){ - for(EntitlementTreeNodeDTO childNode : childNodes){ - printChildrenTree(childNode , out); - } - } - } else { - EntitlementTreeNodeDTO[] childNodes = selectedTree.getChildNodes(); - if(childNodes != null && childNodes.length > 0){ - for(EntitlementTreeNodeDTO childNode : childNodes){ - printChildren(childNode, selectedTree.getName(), out); - } - } - } - %> -
    -
    -
    - -
    -
    -
    - <% - if(selectedTree != null){ - %> - " class="button"/> - <% - } - %> - " class="button"/> -
    -
    -
    -
    -
    -
    \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/select-attribute.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/select-attribute.jsp deleted file mode 100644 index 4c84550e254b..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/select-attribute.jsp +++ /dev/null @@ -1,518 +0,0 @@ - -<%@ page import="org.owasp.encoder.Encode" %> -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> -<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" - prefix="carbon"%> -<%@ page import="org.apache.axis2.context.ConfigurationContext"%> -<%@ page import="org.wso2.carbon.CarbonConstants" %> -<%@page import="org.wso2.carbon.identity.entitlement.common.EntitlementConstants"%> -<%@ page import="org.wso2.carbon.identity.entitlement.common.PolicyEditorEngine" %> -<%@ page import="org.wso2.carbon.identity.entitlement.common.dto.PolicyEditorDataHolder" %> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.EntitlementFinderDataHolder" %> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.EntitlementTreeNodeDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.EntitlementPolicyConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %> -<%@ page import="org.wso2.carbon.utils.ServerConstants" %> -<%@ page - import="java.io.IOException" %> -<%@ page import="java.util.ResourceBundle" %> -<%@ page import="java.util.Set" %> -<%@ page import="org.apache.commons.lang.StringUtils" %> - - -<%! - public void printChildrenTree(EntitlementTreeNodeDTO node, JspWriter out) throws IOException { - if(node != null){ - EntitlementTreeNodeDTO[] children = node.getChildNodes(); - if(children != null && children.length > 0){ - out.write("
  •   " + - "" + node.getName() + ""); - out.write("
      "); - for(EntitlementTreeNodeDTO child : children){ - printChildrenTree(child, out); - } - out.write("
    "); - } else { - out.write("
  •   " + - "" + node.getName() + ""); - out.write("
  • "); - } - } - } - - public void printChildren(EntitlementTreeNodeDTO node, String parentNodeName, JspWriter out) throws IOException { - if(node != null){ - String nodeName; - if(parentNodeName != null && parentNodeName.trim().length() > 0){ - nodeName = parentNodeName + "/" + node.getName(); - } else { - nodeName = node.getName(); - } - - out.write("
  • " + nodeName + "
  • ") ; - EntitlementTreeNodeDTO[] children = node.getChildNodes(); - if(children != null && children.length > 0){ - for(EntitlementTreeNodeDTO child : children){ - printChildren(child, nodeName, out); - } - } - } - } - -%> - -<% - String forwardTo; - EntitlementFinderDataHolder finderDataHolder = null; - EntitlementTreeNodeDTO selectedTree = null; - String selectedFinderModule; - String category; - boolean showNoData = false; - String searchString = request.getParameter("searchString"); - int levels = 0; - - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = - (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - - String ruleId = request.getParameter("ruleId"); - String initiatedPage = request.getParameter("initiatedFrom"); - String returnPage; - if (StringUtils.equals("create-policy-set", initiatedPage)) { - returnPage = "create-policy-set.jsp"; - } else { - returnPage = "policy-editor.jsp"; - } - - selectedFinderModule = request.getParameter("finderModule"); - if(selectedFinderModule == null || selectedFinderModule.trim().length() < 1){ - selectedFinderModule = EntitlementPolicyConstants.DEFAULT_META_DATA_MODULE_NAME; - } - - category = request.getParameter("category"); - String selectedDataLevelString = request.getParameter("selectedDataLevel"); - int selectedDataLevel = 0; - try{ - selectedDataLevel = Integer.parseInt(selectedDataLevelString); - } catch (Exception e){ - //ignore - } - String selectedData = request.getParameter("selectedData" + selectedDataLevel); - - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - - PolicyEditorDataHolder holder = PolicyEditorEngine.getInstance(). - getPolicyEditorData(EntitlementConstants.PolicyEditor.STANDARD); - Set attributeIds = holder.getAttributeIdMap().keySet(); - if(category != null && category.trim().length() > 0){ - attributeIds = holder.getCategoryAttributeIdMap().get(category); - } - Set dataTypes = holder.getDataTypeMap().keySet(); - String selectedAttributeDataType = request.getParameter("selectedAttributeDataType"); - String selectedAttributeId = request.getParameter("selectedAttributeId"); - Set holders = entitlementPolicyBean.getEntitlementFinders(category); - try { - EntitlementPolicyAdminServiceClient client = - new EntitlementPolicyAdminServiceClient(cookie, serverURL, configContext); - - if(selectedFinderModule != null && selectedFinderModule.trim().length() > 0){ - finderDataHolder = entitlementPolicyBean.getEntitlementFinders().get(selectedFinderModule); - levels = finderDataHolder.getHierarchicalLevels(); - - if(searchString != null && searchString.trim().length() > 0){ - selectedTree = client.getEntitlementData(selectedFinderModule, - category, searchString, 0, 100); - if(selectedTree == null){ - showNoData = true; - } - } else if(levels > 0 && selectedData != null && selectedData.trim().length() > 0 && - selectedDataLevel + 1 != levels){ - EntitlementTreeNodeDTO nodeDTO = client.getEntitlementData(selectedFinderModule, - category, selectedData, selectedDataLevel + 1, 100); - if(nodeDTO != null){ - entitlementPolicyBean.getEntitlementLevelData().put(selectedDataLevel + 1, nodeDTO); - } - if(selectedData != null && selectedData.trim().length() > 0 ){ - entitlementPolicyBean.getSelectedEntitlementData().put(selectedDataLevel, selectedData); - } - } - } else { - String message = resourceBundle.getString("no.entitlement.data.finder.defined"); -%> - -<% - } - } catch (Exception e) { - String message = resourceBundle.getString("error.while.retrieving.attribute.values"); -%> - -<% - } -%> - -<% - if(holders == null || holders.size() == 0){ - String message = resourceBundle.getString("no.entitlement.data.finder.defined"); -%> - -<% - } -%> - -<% - if(showNoData){ - String message = resourceBundle.getString("no.entitlement.data.defined"); -%> - -<% - } -%> - - - - - - - - - - - - - - - - - - - - - - - - - - -
    -

    -
    -
    - - - - - - -
    - - - - - - - - - - - - <% - if(holders != null && holders.size() > 0){ - %> - - - - - <% - int i = 1; - while (true) { - EntitlementTreeNodeDTO nodeDTO = entitlementPolicyBean.getEntitlementLevelData().get(i); - if(nodeDTO == null){ - break; - } - %> - - - - - - <% - i++; - } - %> - <% - if(levels == 0 || selectedDataLevel + 1 == levels){ - %> - - - - - - <% - } - %> - - - - - - - <% - } - %> - - - -
    - - - -
    - - - -
    - - - -
    - <%=i%> - - - - -
    - - - "/> - - "> -
    - - -
    - - - - - - - - - - - <% - if(selectedTree != null){ - %> - - - - <% - } - %> - - -
    -
    -
      - <% - if(finderDataHolder.getHierarchicalTree()){ - EntitlementTreeNodeDTO[] childNodes = selectedTree.getChildNodes(); - if(childNodes != null && childNodes.length > 0){ - for(EntitlementTreeNodeDTO childNode : childNodes){ - printChildrenTree(childNode , out); - } - } - } else { - EntitlementTreeNodeDTO[] childNodes = selectedTree.getChildNodes(); - if(childNodes != null && childNodes.length > 0){ - for(EntitlementTreeNodeDTO childNode : childNodes){ - printChildren(childNode, selectedTree.getName(), out); - } - } - } - %> -
    -
    -
    - -
    -
    -
    - <%--<%--%> - <%--if(selectedTree != null){--%> - <%--%>--%> - " class="button"/> - <%--<%--%> - <%--}--%> - <%--%>--%> - " class="button"/> -
    -
    -
    -
    -
    -
    \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/select-extended-attributes.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/select-extended-attributes.jsp deleted file mode 100644 index c7fef736752a..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/select-extended-attributes.jsp +++ /dev/null @@ -1,353 +0,0 @@ - -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.ExtendAttributeDTO" %> -<%@ page import="org.owasp.encoder.Encode" %> -<%@ page import="java.util.List" %> -<%@ page import="java.util.Map" %> -<%@ page import="java.util.Set" %> -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> -<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %> - - - - - - - - - - - - - - - -<% - Set categories = entitlementPolicyBean.getCategorySet(); - Map> attributeIdMap = entitlementPolicyBean.getDefaultAttributeIdMap(); - Map> dataTypeMap = entitlementPolicyBean.getDefaultDataTypeMap(); - String selectedCategory = request.getParameter("category"); - String selectFunction = request.getParameter("function"); - String selectedAttributeId = request.getParameter("category"); - String selectedDataType = request.getParameter("category"); - String selectedParams = request.getParameter("category"); - - if(selectedCategory != null && selectedCategory.trim().length() > 0){ - ExtendAttributeDTO attributeDTO = new ExtendAttributeDTO(); - attributeDTO.setCategory(selectedCategory); - attributeDTO.setAttributeId(selectedAttributeId); - attributeDTO.setDataType(selectedDataType); - entitlementPolicyBean.addExtendAttributeDTO(attributeDTO); - } else if(selectFunction != null && selectFunction.trim().length() > 0){ - ExtendAttributeDTO attributeDTO = new ExtendAttributeDTO(); - attributeDTO.setCategory(selectedCategory); - attributeDTO.setFunction(selectedCategory); - attributeDTO.setAttributeId(selectedAttributeId); - attributeDTO.setDataType(selectedDataType); - attributeDTO.setAttributeValue(selectedDataType); - entitlementPolicyBean.addExtendAttributeDTO(attributeDTO); - } - - -%> - - - - <% - for(String selector : categories){ - String tmp = ""; - Set attributeIds = attributeIdMap.get(selector); - if(attributeIds != null){ - for(String attributeId : attributeIds){ - tmp += ""; - } - } - %> - - - - <% - } - %> - - <% - for(String selector : categories){ - String tmp = ""; - Set dataTypes = dataTypeMap.get(selector); - if(dataTypes != null){ - for(String dataType : dataTypes){ - tmp += ""; - } - } - %> - - - - <% - } - %> - - - - - -
    -

    -
    - - - - - - - - -
    -
    - - - - - - - - - - - - - -
    - Select Attributes from request.... -
    - - - - - - - -
    - - - - - - - - <% - List list = entitlementPolicyBean.getExtendAttributeDTOs(); - if(list != null){ - for(ExtendAttributeDTO attributeDTO : list){ - %> - - - - - - <% - } - } - %> - -
    CategoryAttribute IdAttribute Data Type
    <%=Encode.forHtmlContent(attributeDTO.getCategory())%><%=Encode.forHtmlContent(attributeDTO.getAttributeId())%><%=Encode.forHtmlContent(attributeDTO.getDataType())%>
    -
    - - - - - - - <% - if (selectedParams != null && selectedParams.trim().length() > 0) { - %> - - <% - } else { - %> - - <% - } - %> - - - - - - - -
    - Select Attributes from Function evaluation..... -
    - - - - - - - -
    - - - - - - - - - - -
    Selector TypeCategoryAttribute IdAttribute Data Type
    -
    -
    -
    -
    - " onclick="submitForm();" class="button"/> - " onclick="cancelForm();" class="button"/> -
    -
    -
    -
    diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/show-policy-status.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/show-policy-status.jsp deleted file mode 100644 index 71ada33b18ef..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/show-policy-status.jsp +++ /dev/null @@ -1,224 +0,0 @@ - - <%@ page import="org.owasp.encoder.Encode" %> -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> -<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" - prefix="carbon"%> -<%@ page - import="org.apache.axis2.context.ConfigurationContext" %> -<%@ page import="org.wso2.carbon.CarbonConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.common.EntitlementConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.PaginatedStatusHolder" %> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.StatusHolder" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %> -<%@ page import="org.wso2.carbon.utils.ServerConstants" %> -<%@ page import="java.util.Date" %> - - -<% - - int numberOfPages = 0; - String pageNumber = request.getParameter("pageNumber"); - if (pageNumber == null) { - pageNumber = "0"; - } - int pageNumberInt = 0; - try { - pageNumberInt = Integer.parseInt(pageNumber); - } catch (NumberFormatException ignored) { - } - - String statusSearchString = request.getParameter("statusSearchString"); - if (statusSearchString == null) { - statusSearchString = "*"; - } else { - statusSearchString = statusSearchString.trim(); - } - - String typeFilter = request.getParameter("typeFilter"); - if (typeFilter == null || "".equals(typeFilter)) { - typeFilter = "ALL"; - } - - String policyId = request.getParameter("policyid"); - String paginationValue = "policyid=" + policyId +"&typeFilter=" + typeFilter + - "&statusSearchString=" + statusSearchString; - StatusHolder[] statusHolders = new StatusHolder[0]; - - try { - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = - (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants. CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - EntitlementPolicyAdminServiceClient client = new EntitlementPolicyAdminServiceClient(cookie, - serverURL, configContext); - String type = typeFilter; - if("ALL".equals(type)){ - type = null; - } - PaginatedStatusHolder holder = client.getStatusData(EntitlementConstants.Status.ABOUT_POLICY, - policyId, type, statusSearchString, pageNumberInt); - statusHolders = holder.getStatusHolders(); - numberOfPages = holder.getNumberOfPages(); - } catch (Exception e) { -%> - -<% - } -%> - - - - - -
    -

    -
    -
    - - - - -
    - - - - - - - -
    - - - -     - - "/>  - - - - "> -
    -
    -
    - - - - - - - - - - - - - <% - if(statusHolders != null){ - for(StatusHolder dto : statusHolders){ - if(dto != null && dto.getTimeInstance() != null){ - %> - - - - - - - - - - <% - } - } - } else { - %> - - - - <% - } - %> -
    <%=Encode.forHtml((new Date(Long.parseLong(dto.getTimeInstance()))).toString())%><% if(dto.getType() != null){%> <%=Encode.forHtml(dto.getType())%><%}%><% if(dto.getUser() != null){%> <%=Encode.forHtml(dto.getUser())%><%}%><% if(dto.getTarget() != null){%> <%=Encode.forHtml(dto.getTarget())%><%}%><% if(dto.getTargetAction() != null){%> <%=Encode.forHtml(dto.getTargetAction())%><%}%><% if(dto.getSuccess()){%> <%} - else {%> <%} %><% if(dto.getMessage() != null){%> <%=Encode.forHtml(dto.getMessage())%><%}%>

    - -
    -
    - -
    -
    -
    -
    \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/show-policy-version.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/show-policy-version.jsp deleted file mode 100644 index 64d46c792046..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/show-policy-version.jsp +++ /dev/null @@ -1,224 +0,0 @@ - -<%@ page import="org.owasp.encoder.Encode" %> -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> -<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" - prefix="carbon"%> -<%@ page import="org.apache.axis2.context.ConfigurationContext"%> -<%@ page import="org.wso2.carbon.CarbonConstants"%> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO"%> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.EntitlementPolicyConstants"%> - -<%@page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient"%> - - - -<%@page import="org.wso2.carbon.ui.CarbonUIUtil"%> - -<%@ page import="org.wso2.carbon.utils.ServerConstants"%> -<%@ page import="java.text.MessageFormat" %> -<%@ page import="java.util.Date" %> -<%@ page import="java.util.ResourceBundle" %> -<% - String policy = ""; - String createdTime = ""; - String createdUser = ""; - String forwardTo = "index.jsp"; - String policyId = request.getParameter("policyId"); - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = (ConfigurationContext) config.getServletContext(). - getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String selectedVersion = request.getParameter("selectedVersion"); - String[] versions = null; - if(selectedVersion == null || selectedVersion.trim().length() == 0){ - selectedVersion = EntitlementPolicyConstants.ENTITLEMENT_CURRENT_VERSION; - } - try { - EntitlementPolicyAdminServiceClient client = new EntitlementPolicyAdminServiceClient( - cookie, serverURL, configContext); - versions = client.getPolicyVersions(policyId); - if(versions == null || versions.length == 0){ - versions = new String[]{EntitlementPolicyConstants.ENTITLEMENT_CURRENT_VERSION}; - } else { - versions[versions.length-1] = EntitlementPolicyConstants.ENTITLEMENT_CURRENT_VERSION; - } - - PolicyDTO policyDTO = null; - if(EntitlementPolicyConstants.ENTITLEMENT_CURRENT_VERSION.equals(selectedVersion)){ - policyDTO = client.getPolicy(policyId, false); - } else { - policyDTO = client.getPolicyByVersion(policyId, selectedVersion); - } - - if (policyDTO.getPolicy() != null) { - policy = policyDTO.getPolicy().trim().replaceAll("><", ">\n<"); - } - - if(policyDTO.getLastModifiedTime() != null){ - try { - Date date = new Date(Long.parseLong(policyDTO.getLastModifiedTime())); - createdTime = date.toString(); - } catch (Exception e){ - // ignore - } - } - - if(policyDTO.getLastModifiedUser() != null){ - createdUser = policyDTO.getLastModifiedUser(); - } - - } catch (Exception e) { - String message = MessageFormat.format(resourceBundle. - getString("error.while.retreiving.policies"), e.getMessage()); -%> - -<% - } -%> - - - -
    -

    -
    -
    - - - - - - - - - - - - - - - - - -
    <%=Encode.forHtml(policyId)%>
    - -
    <%=createdTime%>
    <%=createdUser%>
    -
    - - - - - - - - - - - - - - - -
    - -
    - - - - - - -
    - - -
    -
    - <% - if(!EntitlementPolicyConstants.ENTITLEMENT_CURRENT_VERSION.equals(selectedVersion) && - CarbonUIUtil.isUserAuthorized(request, - "/permission/admin/manage/identity/entitlement/pap/policy/rollback")) { - %> - - <% - } - %> - -
    -
    -
    -
    - - - - diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/show-subscriber-status.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/show-subscriber-status.jsp deleted file mode 100644 index c1933ae7a97e..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/show-subscriber-status.jsp +++ /dev/null @@ -1,224 +0,0 @@ - -<%@ page import="org.owasp.encoder.Encode" %> -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> -<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" - prefix="carbon"%> -<%@ page - import="org.apache.axis2.context.ConfigurationContext" %> -<%@ page import="org.wso2.carbon.CarbonConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.common.EntitlementConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.PaginatedStatusHolder" %> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.StatusHolder" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %> -<%@ page import="org.wso2.carbon.utils.ServerConstants" %> -<%@ page import="java.util.Date" %> - - -<% - - int numberOfPages = 0; - String pageNumber = request.getParameter("pageNumber"); - if (pageNumber == null) { - pageNumber = "0"; - } - int pageNumberInt = 0; - try { - pageNumberInt = Integer.parseInt(pageNumber); - } catch (NumberFormatException ignored) { - } - - String statusSearchString = request.getParameter("statusSearchString"); - if (statusSearchString == null) { - statusSearchString = "*"; - } else { - statusSearchString = statusSearchString.trim(); - } - - String typeFilter = request.getParameter("typeFilter"); - if (typeFilter == null || "".equals(typeFilter)) { - typeFilter = "ALL"; - } - - String subscriberId = request.getParameter("subscriberId"); - String paginationValue = "subscriberId=" + subscriberId +"&typeFilter=" + typeFilter + - "&statusSearchString=" + statusSearchString; - StatusHolder[] statusHolders = new StatusHolder[0]; - - try { - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = - (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants. CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - EntitlementPolicyAdminServiceClient client = new EntitlementPolicyAdminServiceClient(cookie, - serverURL, configContext); - String type = typeFilter; - if("ALL".equals(type)){ - type = null; - } - PaginatedStatusHolder holder = client.getStatusData(EntitlementConstants.Status.ABOUT_SUBSCRIBER, - subscriberId, type, statusSearchString, pageNumberInt); - statusHolders = holder.getStatusHolders(); - numberOfPages = holder.getNumberOfPages(); - } catch (Exception e) { -%> - -<% - } -%> - - - - - -
    -

    -
    -
    - - - - -
    - - - - - - - -
    - - <%----%> - <%----%> - <%--   --%> - - "/>  - - - - "> -
    -
    -
    - - - - - - - - - - - - - <% - if(statusHolders != null){ - for(StatusHolder dto : statusHolders){ - if(dto != null && dto.getTimeInstance() != null){ - %> - - - - - - - - - - <% - } - } - } else { - %> - - - - <% - } - %> -
    <%=(new Date(Long.parseLong(dto.getTimeInstance()))).toString()%><% if(dto.getType() != null){%> <%=Encode.forHtml(dto.getType())%><%}%><% if(dto.getUser() != null){%> <%=Encode.forHtml(dto.getUser())%><%}%><% if(dto.getTarget() != null){%> <%=Encode.forHtml(dto.getTarget())%><%}%><% if(dto.getTargetAction() != null){%> <%=Encode.forHtml(dto.getTargetAction())%><%}%><% if(dto.getSuccess()){%> <%} - else {%> <%} %><% if(dto.getMessage() != null){%> <%=Encode.forHtml(dto.getMessage())%><%}%>

    - -
    -
    - -
    -
    -
    -
    \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/simple-policy-editor.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/simple-policy-editor.jsp deleted file mode 100644 index 02993c638894..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/simple-policy-editor.jsp +++ /dev/null @@ -1,1054 +0,0 @@ - -<%@ page import="org.owasp.encoder.Encode" %> -<%@ page import="org.wso2.carbon.identity.entitlement.common.EntitlementConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.common.PolicyEditorEngine" %> -<%@ page import="org.wso2.carbon.identity.entitlement.common.dto.PolicyEditorDataHolder" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.PolicyEditorConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.SimplePolicyEditorDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.SimplePolicyEditorElementDTO" %> -<%@ page import="java.util.List" %> -<%@ page import="java.util.Set" %> -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> -<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %> - - - -<% - SimplePolicyEditorDTO policyEditorDTO = entitlementPolicyBean.getSimplePolicyEditorDTO(); - List elementDTOList = null; - String selectedPolicyApplied = request.getParameter("policyApplied"); - String policyId = request.getParameter("policyId"); - String policyDescription = request.getParameter("policyDescription"); - - PolicyEditorDataHolder holder = PolicyEditorEngine.getInstance(). - getPolicyEditorData(EntitlementConstants.PolicyEditor.RBAC); - - String[] policyApplies = new String[]{PolicyEditorConstants.SOA_CATEGORY_RESOURCE , - PolicyEditorConstants.SOA_CATEGORY_USER, PolicyEditorConstants.SOA_CATEGORY_ENVIRONMENT, - PolicyEditorConstants.SOA_CATEGORY_ACTION}; - - - Set userAttributeIds = holder.getCategoryAttributeIdMap(). - get(PolicyEditorConstants.SOA_CATEGORY_SUBJECT); - Set envAttributeIds = holder.getCategoryAttributeIdMap(). - get(PolicyEditorConstants.SOA_CATEGORY_ENVIRONMENT); - - String selectedRuleUserAttributeId = null; - String selectedRuleUserAttributeValue = null; - String selectedRuleActionValue = null; - String selectedRuleResourceValue = null; - String selectedRuleEnvironmentValue= null; - String selectedRuleEnvironmentId= null; - String selectedRuleOperationType= null; - String selectedRuleResourceFunction = null; - String selectedRuleUserFunction = null; - String selectedRuleActionFunction = null; - - String selectedUserAttributeId = null; - String selectedUserAttributeValue = null; - String selectedActionValue = null; - String selectedResourceValue = null; - String selectedEnvironmentValue= null; - String selectedEnvironmentId= null; - String selectedFunction = null; - - if(policyEditorDTO != null){ - policyId = policyEditorDTO.getPolicyId(); - policyDescription = policyEditorDTO.getDescription(); - selectedFunction = policyEditorDTO.getFunction(); - selectedUserAttributeId = policyEditorDTO.getUserAttributeId(); - selectedUserAttributeValue = policyEditorDTO.getUserAttributeValue(); - selectedActionValue= policyEditorDTO.getActionValue(); - selectedEnvironmentValue= policyEditorDTO.getEnvironmentValue(); - selectedResourceValue = policyEditorDTO.getResourceValue(); - if(selectedPolicyApplied == null || selectedPolicyApplied.trim().length() == 0){ - selectedPolicyApplied = policyEditorDTO.getAppliedCategory(); - } - - elementDTOList = policyEditorDTO.getSimplePolicyEditorElementDTOs(); - - if(elementDTOList != null && elementDTOList.size() > 0){ - SimplePolicyEditorElementDTO elementDTO = elementDTOList.get(0); - if(elementDTO != null){ - selectedRuleActionValue = elementDTO.getActionValue(); - selectedRuleUserAttributeId = elementDTO.getUserAttributeId(); - selectedRuleUserAttributeValue = elementDTO.getUserAttributeValue(); - selectedRuleResourceValue = elementDTO.getResourceValue(); - selectedRuleEnvironmentValue= elementDTO.getEnvironmentValue(); - selectedRuleEnvironmentId= elementDTO.getEnvironmentId(); - selectedRuleOperationType= elementDTO.getOperationType(); - selectedRuleResourceFunction = elementDTO.getFunctionOnResources(); - selectedRuleUserFunction = elementDTO.getFunctionOnUsers(); - } - } - - } -%> - - - -<% if(entitlementPolicyBean.isEditPolicy()){%> - -<% } else { %> - -<%}%> - - - - - - - - - - - - - -
    -<%if(entitlementPolicyBean.isEditPolicy()){%> -

    -<%} else {%>

    <%}%> -
    -
    - - - - <% - if (policyId != null && policyId.trim().length() > 0) { - %> - - <% - } else { - %> - - <% - } - %> - - - - <% - if (policyDescription != null && policyDescription.trim().length() > 0) { - %> - - <% - } else { - %> - - <% - } - %> - - - - - <%if(entitlementPolicyBean.isEditPolicy() && selectedPolicyApplied != null){%> - - <%}%> - - <%--
    *
    - -
    /////////////////// TODO--%> - <%--END Basic information section --%> - - <%--**********************--%> - <%--**********************--%> - <%--START user policy type--%> - <%--**********************--%> - <%--**********************--%> - - <% - if(PolicyEditorConstants.SOA_CATEGORY_USER.equals(selectedPolicyApplied)) { - %> - - - - - - - - - -
    User whose - - is equal to - <% - if (selectedUserAttributeValue != null && selectedUserAttributeValue.trim().length() > 0) { - %> - - <% - } else { - %> - - <% - } - %> -
    - - - - - - - - - -<% -if(elementDTOList != null && elementDTOList.size() > 0){ - elementDTOList.remove(0); - for(SimplePolicyEditorElementDTO elementDTO : elementDTOList){ - selectedRuleActionValue = elementDTO.getActionValue(); - selectedRuleUserAttributeId = elementDTO.getUserAttributeId(); - selectedRuleUserAttributeValue = elementDTO.getUserAttributeValue(); - selectedRuleResourceValue = elementDTO.getResourceValue(); - selectedRuleEnvironmentValue= elementDTO.getEnvironmentValue(); - selectedRuleEnvironmentId= elementDTO.getEnvironmentId(); - selectedRuleOperationType= elementDTO.getOperationType(); - selectedRuleResourceFunction = elementDTO.getFunctionOnResources(); - selectedRuleUserFunction = elementDTO.getFunctionOnUsers(); -%> - - <% - } - } - %> -
    - - - - - - - - - - - - - -
    Action - <% - if (selectedRuleActionValue != null && selectedRuleActionValue.trim().length() > 0) { - %> - - <% - } else { - %> - - <% - } - %> - Resource - <% - if (selectedRuleResourceValue != null && selectedRuleResourceValue.trim().length() > 0) { - %> - - <% - } else { - %> - - <% - } - %> - Environment - - <% - if (selectedRuleEnvironmentValue != null && selectedRuleEnvironmentValue.trim().length() > 0) { - %> - - <% - } else { - %> - - <% - } - %> - - -
    -
    - - - <%--********************--%> - <%--********************--%> - <%--END user policy type--%> - <%--********************--%> - <%--********************--%> - <%--********************--%> - - - <%--************************--%> - <%--************************--%> - <%--START action policy type--%> - <%--************************--%> - <%--************************--%> - <%--************************--%> - - <% - } else if(PolicyEditorConstants.SOA_CATEGORY_ACTION.equals(selectedPolicyApplied)){ - %> - - - - - - - <% - if (selectedActionValue != null && selectedActionValue.trim().length() > 0) { - %> - - <% - } else { - %> - - <% - } - %> - -
    Action which is equals to
    - - - - - - - - - - - <% - if(elementDTOList != null && elementDTOList.size() > 0){ - elementDTOList.remove(0); - for(SimplePolicyEditorElementDTO elementDTO : elementDTOList){ - selectedRuleActionValue = elementDTO.getActionValue(); - selectedRuleUserAttributeId = elementDTO.getUserAttributeId(); - selectedRuleUserAttributeValue = elementDTO.getUserAttributeValue(); - selectedRuleResourceValue = elementDTO.getResourceValue(); - selectedRuleEnvironmentValue= elementDTO.getEnvironmentValue(); - selectedRuleEnvironmentId= elementDTO.getEnvironmentId(); - selectedRuleOperationType= elementDTO.getOperationType(); - selectedRuleResourceFunction = elementDTO.getFunctionOnResources(); - selectedRuleUserFunction = elementDTO.getFunctionOnUsers(); - %> - - <% - } - } - %> -
    - - - - - - - - - - - - - - -
    Resource - <% - if (selectedRuleResourceValue != null && selectedRuleResourceValue.trim().length() > 0) { - %> - - <% - } else { - %> - - <% - } - %> - User - - - <% - if (selectedRuleUserAttributeValue != null && selectedRuleUserAttributeValue.trim().length() > 0) { - %> - - <% - } else { - %> - - <% - } - %> - Environment - - <% - if (selectedRuleEnvironmentValue != null && selectedRuleEnvironmentValue.trim().length() > 0) { - %> - - <% - } else { - %> - - <% - } - %> - - -
    -
    - - - - <%--********************--%> - <%--********************--%> - <%--END action policy type--%> - <%--********************--%> - <%--********************--%> - <%--********************--%> - - - <%--************************--%> - <%--************************--%> - <%--START environment policy type--%> - <%--************************--%> - <%--************************--%> - <%--************************--%> - - <% - } else if(PolicyEditorConstants.SOA_CATEGORY_ENVIRONMENT.equals(selectedPolicyApplied)){ - %> - - - - - - - - - - <% - if (selectedEnvironmentValue != null && selectedEnvironmentValue.trim().length() > 0) { - %> - - <% - } else { - %> - - <% - } - %> - -
    Environment which - - is equals to
    - - - - - - - - - -<% - if(elementDTOList != null && elementDTOList.size() > 0){ - elementDTOList.remove(0); - for(SimplePolicyEditorElementDTO elementDTO : elementDTOList){ - selectedRuleActionValue = elementDTO.getActionValue(); - selectedRuleUserAttributeId = elementDTO.getUserAttributeId(); - selectedRuleUserAttributeValue = elementDTO.getUserAttributeValue(); - selectedRuleResourceValue = elementDTO.getResourceValue(); - selectedRuleEnvironmentValue= elementDTO.getEnvironmentValue(); - selectedRuleEnvironmentId= elementDTO.getEnvironmentId(); - selectedRuleOperationType= elementDTO.getOperationType(); - selectedRuleResourceFunction = elementDTO.getFunctionOnResources(); - selectedRuleUserFunction = elementDTO.getFunctionOnUsers(); -%> - -<% - } - } -%> -
    - - - - - - - - - - - - -
    Resource - <% - if (selectedRuleResourceValue != null && selectedRuleResourceValue.trim().length() > 0) { - %> - - <% - } else { - %> - - <% - } - %> - User - - <% - if (selectedRuleUserAttributeValue != null && selectedRuleUserAttributeValue.trim().length() > 0) { - %> - - <% - } else { - %> - - <% - } - %> - Action <% - if (selectedRuleActionValue != null && selectedRuleActionValue.trim().length() > 0) { - %> - - <% - } else { - %> - - <% - } - %> - - -
    -
    - - - <%--********************--%> - <%--********************--%> - <%--END environment policy type--%> - <%--********************--%> - <%--********************--%> - <%--********************--%> - - - <%--************************--%> - <%--************************--%> - <%--START Resource policy type--%> - <%--************************--%> - <%--************************--%> - <%--************************--%> - <% - } else { - %> - - - - - - - - <% - if (selectedResourceValue != null && selectedResourceValue.trim().length() > 0) { - %> - - <% - } else { - %> - - <% - } - %> - -
    Resource which is equals to
    - - - - - - - - - - <% - if(elementDTOList != null && elementDTOList.size() > 0){ - elementDTOList.remove(0); - for(SimplePolicyEditorElementDTO elementDTO : elementDTOList){ - selectedRuleActionValue = elementDTO.getActionValue(); - selectedRuleUserAttributeId = elementDTO.getUserAttributeId(); - selectedRuleUserAttributeValue = elementDTO.getUserAttributeValue(); - selectedRuleResourceValue = elementDTO.getResourceValue(); - selectedRuleEnvironmentValue= elementDTO.getEnvironmentValue(); - selectedRuleEnvironmentId= elementDTO.getEnvironmentId(); - selectedRuleOperationType= elementDTO.getOperationType(); - selectedRuleResourceFunction = elementDTO.getFunctionOnResources(); - selectedRuleUserFunction = elementDTO.getFunctionOnUsers(); - %> - - <% - } - } - %> -
    - - - - - - - - - - - - - - - - - - - -
    Child resourceUserActionEnvironment
    - <% - if (selectedRuleResourceValue != null && selectedRuleResourceValue.trim().length() > 0) { - %> - - <% - } else { - %> - - <% - } - %> - - - <% - if (selectedRuleUserAttributeValue != null && selectedRuleUserAttributeValue.trim().length() > 0) { - %> - - <% - } else { - %> - - <% - } - %> - <% - if (selectedRuleActionValue != null && selectedRuleActionValue.trim().length() > 0) { - %> - - <% - } else { - %> - - <% - } - %> - - - <% - if (selectedRuleEnvironmentValue != null && selectedRuleEnvironmentValue.trim().length() > 0) { - %> - - <% - } else { - %> - - <% - } - %> - - -
    -
    - - - <% - } - %> - - - " - class="button"/> - " - class="button"/> - - - -
    -
    -
    -
    diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/simple-policy-finish-ajaxprocessor.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/simple-policy-finish-ajaxprocessor.jsp deleted file mode 100644 index 702752e8c06c..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/simple-policy-finish-ajaxprocessor.jsp +++ /dev/null @@ -1,281 +0,0 @@ - -<%@ page import="org.owasp.encoder.Encode" %> -<%@ page import="org.apache.axis2.context.ConfigurationContext" %> -<%@ page import="org.wso2.carbon.CarbonConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.common.EntitlementConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.common.PolicyEditorException" %> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO" %> -<%@ page - import="org.wso2.carbon.identity.entitlement.ui.EntitlementPolicyCreator" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.PolicyEditorConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.SimplePolicyEditorDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.SimplePolicyEditorElementDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.util.PolicyEditorUtil" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIMessage" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %> -<%@ page import="org.wso2.carbon.utils.ServerConstants" %> -<%@ page import="java.util.ArrayList" %> -<%@ page import="java.util.List" %> -<%@ page import="java.util.ResourceBundle" %> - - - -<% - String httpMethod = request.getMethod(); - if (!"post".equalsIgnoreCase(httpMethod)) { - response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); - return; - } - - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = - (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants. - CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - - int maxUserRow = 0; - int maxResourceRow = 0; - int maxActionRow = 0; - int maxEnvironmentRow = 0; - int maxRows = 0; - int maxAllowedRows = 1000; - String dynamicCategory = request.getParameter("policyApplied"); - String policyId = request.getParameter("policyId"); - String policyDescription = request.getParameter("policyDescription"); - String maxUserRowString = request.getParameter("maxUserRow"); - String maxResourceRowString = request.getParameter("maxResourceRow"); - String maxActionRowString = request.getParameter("maxActionRow"); - String maxEnvironmentRowString = request.getParameter("maxEnvironmentRow"); - if(maxResourceRowString != null){ - try{ - maxResourceRow = Integer.parseInt(maxResourceRowString); - } catch(Exception e ){ - //ignore - } - } - - if(maxUserRowString != null){ - try{ - maxUserRow = Integer.parseInt(maxUserRowString); - } catch(Exception e ){ - //ignore - } - } - - if(maxActionRowString != null){ - try{ - maxActionRow = Integer.parseInt(maxActionRowString); - } catch(Exception e ){ - //ignore - } - } - - if(maxEnvironmentRowString != null){ - try{ - maxEnvironmentRow = Integer.parseInt(maxEnvironmentRowString); - } catch(Exception e ){ - //ignore - } - } - - SimplePolicyEditorDTO editorDTO = null; - String forwardTo = null; - - if(policyId != null && policyId.trim().length() > 0){ - - editorDTO = new SimplePolicyEditorDTO(); - editorDTO.setAppliedCategory(dynamicCategory); - editorDTO.setPolicyId(policyId); - editorDTO.setDescription(policyDescription); - - List elementDTOs = new ArrayList(); - - if(PolicyEditorConstants.SOA_CATEGORY_RESOURCE.equals(dynamicCategory)){ - String resourceValue = request.getParameter("resourceValue"); - String function = request.getParameter("function"); - editorDTO.setResourceValue(resourceValue); - editorDTO.setFunction(function); - maxRows = maxResourceRow; - } else if(PolicyEditorConstants.SOA_CATEGORY_USER.equals(dynamicCategory)){ - String userAttributeValue = request.getParameter("userAttributeValue"); - String userAttributeId = request.getParameter("userAttributeId"); - String function = request.getParameter("function"); - editorDTO.setUserAttributeId(userAttributeId); - editorDTO.setUserAttributeValue(userAttributeValue); - editorDTO.setFunction(function); - maxRows = maxUserRow; - } else if(PolicyEditorConstants.SOA_CATEGORY_ACTION.equals(dynamicCategory)){ - String actionValue = request.getParameter("actionValue"); - String function = request.getParameter("function"); - editorDTO.setActionValue(actionValue); - editorDTO.setFunction(function); - maxRows = maxActionRow; - } else if(PolicyEditorConstants.SOA_CATEGORY_ENVIRONMENT.equals(dynamicCategory)){ - String actionValue = request.getParameter("environmentValue"); - String environmentId = request.getParameter("environmentId"); - editorDTO.setEnvironmentValue(actionValue); - editorDTO.setEnvironmentId(environmentId); - maxRows = maxEnvironmentRow; - } - - if (maxAllowedRows < maxRows) { - response.sendError(HttpServletResponse.SC_BAD_REQUEST); - return; - } - - for(int rowNumber = 0; rowNumber < maxRows + 1; rowNumber++){ - - SimplePolicyEditorElementDTO elementDTO = new SimplePolicyEditorElementDTO(); - - String userAttributeId = request.getParameter("userRuleAttributeId_" + rowNumber); - if(userAttributeId != null && userAttributeId.trim().length() > 0){ - elementDTO.setUserAttributeId(userAttributeId); - } - - String userAttributeValue = request.getParameter("userRuleAttributeValue_" + rowNumber); - if(userAttributeValue != null && userAttributeValue.trim().length() > 0){ - elementDTO.setUserAttributeValue(userAttributeValue); - } else { - if(PolicyEditorConstants.SOA_CATEGORY_RESOURCE.equals(dynamicCategory) - || PolicyEditorConstants.SOA_CATEGORY_ACTION.equals(dynamicCategory)){ - continue; - } - } - - String actionValue = request.getParameter("actionRuleValue_" + rowNumber); - if(actionValue != null && actionValue.trim().length() > 0){ - elementDTO.setActionValue(actionValue); - } - - String resourceValue = request.getParameter("resourceRuleValue_" + rowNumber); - if(resourceValue != null && resourceValue.trim().length() > 0){ - elementDTO.setResourceValue(resourceValue); - } else { - if(PolicyEditorConstants.SOA_CATEGORY_USER.equals(dynamicCategory)){ - continue; - } - } - - String environmentId = request.getParameter("environmentRuleId_" + rowNumber); - if(environmentId != null && environmentId.trim().length() > 0){ - elementDTO.setEnvironmentId(environmentId); - } - - String environmentValue = request.getParameter("environmentRuleValue_" + rowNumber); - if(environmentValue != null && environmentValue.trim().length() > 0){ - elementDTO.setEnvironmentValue(environmentValue); - } - - String operationType = request.getParameter("operationRuleType_" + rowNumber); - if(operationType != null && operationType.trim().length() > 0){ - elementDTO.setOperationType(operationType); - } - - String resourceFunction = request.getParameter("resourceRuleFunction_" + rowNumber); - if(resourceFunction != null && resourceFunction.trim().length() > 0){ - elementDTO.setFunctionOnResources(resourceFunction); - } - - String userFunction = request.getParameter("userRuleFunction_" + rowNumber); - if(userFunction != null && userFunction.trim().length() > 0){ - elementDTO.setFunctionOnUsers(userFunction); - } - - String actionFunction = request.getParameter("actionRuleFunction_" + rowNumber); - if(actionFunction != null && actionFunction.trim().length() > 0){ - elementDTO.setFunctionOnActions(actionFunction); - } - - elementDTOs.add(elementDTO); - } - editorDTO.setSimplePolicyEditorElementDTOs(elementDTOs); - } - - try { - String message; - EntitlementPolicyCreator creator = new EntitlementPolicyCreator(); - EntitlementPolicyAdminServiceClient client = new EntitlementPolicyAdminServiceClient(cookie, - serverURL, configContext); - PolicyDTO policyDTO = null; - if(editorDTO != null){ - String[] policyEditorData = PolicyEditorUtil.createBasicPolicyData(editorDTO); - String policy = creator.createSOAPolicy(editorDTO); - if(entitlementPolicyBean.isEditPolicy()){ - try{ - policyDTO = client.getPolicy(policyId, false); - } catch (Exception e){ - //ignore - } - - if(policyDTO == null){ - policyDTO = new PolicyDTO(); - } - - policyDTO.setPolicy(policy); - policyDTO.setPolicyEditor(EntitlementConstants.PolicyEditor.RBAC); - if(policyEditorData != null){ - policyDTO.setPolicyEditorData(policyEditorData); - } - client.updatePolicy(policyDTO); - message = resourceBundle.getString("updated.successfully"); - } else { - policyDTO = new PolicyDTO(); - policyDTO.setPolicyId(policyId); - policyDTO.setPolicy(policy); - policyDTO.setPolicyEditor(EntitlementConstants.PolicyEditor.RBAC); - if(policyEditorData != null){ - policyDTO.setPolicyEditorData(policyEditorData); - } - client.addPolicy(policyDTO); - message = resourceBundle.getString("ent.policy.added.successfully"); - } - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.INFO, request); - forwardTo = "index.jsp?"; - } else { - message = resourceBundle.getString("error.while.creating.policy"); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.ERROR, request); - forwardTo = "index.jsp?"; - } - } catch (PolicyEditorException e) { - String message = resourceBundle.getString("error.while.creating.policy"); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.ERROR, request); - forwardTo = "index.jsp?"; - } catch (Exception e) { - String message = resourceBundle.getString("error.while.adding.policy") + " " + e.getMessage(); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.ERROR, request); - forwardTo = "index.jsp?"; - } - - -%> - - - - \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/start-publish.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/start-publish.jsp deleted file mode 100644 index 5e663f6f078e..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/start-publish.jsp +++ /dev/null @@ -1,735 +0,0 @@ - -<%@ page - import="org.apache.axis2.context.ConfigurationContext" %> -<%@ page import="org.owasp.encoder.Encode" %> -<%@ page import="org.wso2.carbon.CarbonConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.common.EntitlementConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.util.ClientUtil" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %> -<%@ page import="org.wso2.carbon.utils.ServerConstants" %> -<%@ page import="java.util.ResourceBundle" %> -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> -<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" - prefix="carbon" %> - - - - - - - - - -<% - String[] subscriberIds = null; - boolean showNoSubscriber = false; - String publishAll = request.getParameter("publishAllPolicies"); - String policyId = request.getParameter("policyId"); - String toPDP = request.getParameter("toPDP"); - String[] selectedPolicies = request.getParameterValues("policies"); - String publishAction = request.getParameter("publishAction"); - String policyVersion = request.getParameter("policyVersion"); - String policyOrder = request.getParameter("policyOrder"); - String policyEnable = request.getParameter("policyEnable"); - String versionSelector = request.getParameter("versionSelector"); - String orderSelector = request.getParameter("orderSelector"); - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - - if(publishAction == null || publishAction.trim().length() == 0) { - publishAction = (String)session.getAttribute("publishAction"); - } else { - session.setAttribute("publishAction", publishAction); - } - - // setting default action - if(publishAction == null){ - publishAction = EntitlementConstants.PolicyPublish.ACTION_CREATE; - } - - if(policyOrder == null){ - policyOrder = ""; - } - - if(policyEnable == null){ - policyEnable = ""; - } - - int numberOfPages = 0; - String subscriberSearchString = request.getParameter("subscriberSearchString"); - if (subscriberSearchString == null) { - subscriberSearchString = "*"; - } else { - subscriberSearchString = subscriberSearchString.trim(); - } - String paginationValue = "subscriberSearchString=" + subscriberSearchString; - - String pageNumber = request.getParameter("pageNumber"); - if (pageNumber == null) { - pageNumber = "0"; - } - int pageNumberInt = 0; - try { - pageNumberInt = Integer.parseInt(pageNumber); - } catch (NumberFormatException ignored) { - // ignore - } - - if (publishAll != null && "true".equals(publishAll.trim())) { - session.setAttribute("publishAllPolicies", true); - } else { - session.setAttribute("publishAllPolicies", false); - } - - if (policyId != null && policyId.trim().length() > 0) { - selectedPolicies = new String[]{policyId}; - } - - if(selectedPolicies != null ){ - session.setAttribute("selectedPolicies", selectedPolicies); - } else { - selectedPolicies = (String[]) session.getAttribute("selectedPolicies"); - } - - String tmp = ""; - if(selectedPolicies != null && selectedPolicies.length == 1){ - policyId = selectedPolicies[0]; - } - - - try{ - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = - (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants. CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - EntitlementPolicyAdminServiceClient client = new EntitlementPolicyAdminServiceClient(cookie, - serverURL, configContext); - if (policyId != null && policyId.trim().length() > 0) { - String[] versions = client.getPolicyVersions(policyId); - if(versions != null && versions.length > 0){ - for(int i = 0; i < (versions.length - 1); i++){ // remove current version - String version = versions[i]; - if(policyVersion != null && policyVersion.trim().equalsIgnoreCase(version)) { - tmp += ""; - } else { - tmp += ""; - } - } - } - } - // as these are just strings, get all values in to UI and the do the pagination - subscriberIds = client.getSubscriberIds(subscriberSearchString); - if(subscriberIds != null){ - numberOfPages = (int) Math.ceil((double) subscriberIds.length / 5); - subscriberIds = ClientUtil.doPagingForStrings(pageNumberInt, 5, - client.getSubscriberIds(subscriberSearchString)); - } else { - showNoSubscriber = true; - } - } catch (Exception e) { - String message = resourceBundle.getString("error.loading.subscribers") + e.getMessage(); -%> - -<% - } -%> - - - - - - - -
    -

    -
    -
    - - <% - if(policyId != null){ - - %> - - - - - - - - - - - - - - -
    - - - - - - - - - - - -
    - - <% - } else { - %> - - - - - - - - - - - - - - -
    - - - - - - - - - -
    - - <% - } - %> - - <% - if(EntitlementConstants.PolicyPublish.ACTION_CREATE.equals(publishAction)){ - %> - <% - if(policyId != null){ - %> - - - - - - - - - - - -
    - - - - -
    - <% - } else { - %> - - - - - - - - - - - -
    - - - - -
    - <% - } - %> - - <% - } - %> - - - <% - if(policyId != null){ - %> - <% - - if(EntitlementConstants.PolicyPublish.ACTION_CREATE.equals(publishAction) || - EntitlementConstants.PolicyPublish.ACTION_UPDATE.equals(publishAction)){ - %> - - - - - - - - - - - -
    - - - - -
    - <% - } - %> - - <% - if(EntitlementConstants.PolicyPublish.ACTION_CREATE.equals(publishAction) || - EntitlementConstants.PolicyPublish.ACTION_ORDER.equals(publishAction)){ - %> - - - - - - - - - - - -
    - - - - -
    - <% - } - %> - - <% - } - %> - - <% - if(!"true".equals(toPDP)){ - %> - - - - - - - -
    - - - - - - - -
    - - - "/>  - - - "> -
    - - - <% - if (subscriberIds != null && subscriberIds.length > 0) { - for (String subscriber : subscriberIds) { - if (subscriber != null && subscriber.trim().length() > 0 ) { - %> - - - - - - <% - } - } - %> - <% - } else { - %> - - - - <% - } - %> - -
    - - <%=Encode.forHtml(subscriber)%> -

    - - - - <% - } else { - %> - - - - - - <% - } - %> - - - - - <% - if("true".equals(toPDP)){ - %> - - <% - } else { - %> - - - <% - } - %> - - - - - -<%if(policyVersion != null && policyVersion.trim().length() > 0) { %> - -<%}%> -<%if(policyOrder != null && policyOrder.trim().length() > 0) { %> - -<%}%> -<%if(showNoSubscriber) { %> - -<%}%> -
    -
    -
    \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/update-policy-ajaxprocessor.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/update-policy-ajaxprocessor.jsp deleted file mode 100644 index 4a5aa347820f..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/update-policy-ajaxprocessor.jsp +++ /dev/null @@ -1,21 +0,0 @@ - -<% - response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); - return; -%> \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/update-policy-order.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/update-policy-order.jsp deleted file mode 100644 index 4e9a44258c2f..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/update-policy-order.jsp +++ /dev/null @@ -1,111 +0,0 @@ -<%@ page import="org.apache.axis2.context.ConfigurationContext" %> -<%@ page import="org.wso2.carbon.CarbonConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.PaginatedPolicySetDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.EntitlementPolicyConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient" %> -<%@ page - import="org.wso2.carbon.ui.CarbonUIMessage" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %> -<%@ page import="org.wso2.carbon.utils.ServerConstants" %> -<%@ page import="java.util.ArrayList" %> -<%@ page import="java.util.List" %> -<%@ page import="java.util.ResourceBundle" %> - - - -<% - String forwardTo = null; - String policyOrder = request.getParameter("policyOrder"); - String policyTypeFilter = request.getParameter("policyTypeFilter"); - String policySearchString = request.getParameter("policySearchString"); - String pageNumber = request.getParameter("pageNumber"); - if (pageNumber == null) { - pageNumber = "0"; - } - int pageNumberInt = 0; - try { - pageNumberInt = Integer.parseInt(pageNumber); - } catch (NumberFormatException ignored) { - } - - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = - (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - - try { - EntitlementPolicyAdminServiceClient client = - new EntitlementPolicyAdminServiceClient(cookie, serverURL, configContext); - if(policyOrder != null && policyOrder.trim().length() > 0){ - String[] policyIds = policyOrder.split(EntitlementPolicyConstants.ATTRIBUTE_SEPARATOR); - boolean authorize = true; - PaginatedPolicySetDTO paginatedPolicySetDTO = client.getAllPolicies(policyTypeFilter, - policySearchString, pageNumberInt); - PolicyDTO[] policyDTOs = paginatedPolicySetDTO.getPolicySet(); - if(policyDTOs != null){ - List orderedArray = new ArrayList(); - for(PolicyDTO dto : policyDTOs){ - if (!dto.getPolicyEditable()) { - authorize = false; - break; - } - } - - if(authorize){ - for(int i = 0; i < policyIds.length; i ++){ - PolicyDTO policyDTO = null; - for(PolicyDTO dto : policyDTOs){ - if (policyIds[i].equals(dto.getPolicyId())) { - policyDTO = dto; - break; - } - } - if(policyDTO != null){ - policyDTO.setPolicyOrder(policyIds.length - i); - orderedArray.add(policyDTO); - } - } - client.reOderPolicies(orderedArray.toArray(new PolicyDTO[orderedArray.size()])); - } else { - String message = resourceBundle.getString("cannot.order.policies"); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.WARNING, request); - } - } - } - forwardTo = "index.jsp?policyTypeFilter" + policyTypeFilter + - "&policySearchString=" +policySearchString; - } catch (Exception e) { - String message = resourceBundle.getString("error.while.ordering.policy"); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.ERROR, request); - forwardTo = "index.jsp?region=region1&item=policy_menu"; - } -%> - - - - diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/update-policy-set.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/update-policy-set.jsp deleted file mode 100644 index e88fce8a5dc8..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/update-policy-set.jsp +++ /dev/null @@ -1,245 +0,0 @@ - -<%@ page import="org.owasp.encoder.Encode" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.ObligationDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.PolicyRefIdDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.RowDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.TargetDTO" %> -<%@ page import="java.util.ArrayList" %> -<%@ page import="java.util.List" %> - - - -<% - String forwardTo = ""; - - String httpMethod = request.getMethod(); - if (!"post".equalsIgnoreCase(httpMethod)) { - forwardTo = "update-policy-ajaxprocessor.jsp"; - } else { - int rowNumber = 0; - int targetRowIndex = -1; - int obligationRowIndex = -1; - - int maxTargetRows = 0; - int maxObligationRows = 0; - - String categoryType = null; - String selectedAttributeDataType = null; - String selectedAttributeId = null; - TargetDTO targetDTO = new TargetDTO(); - entitlementPolicyBean.setPolicyReferenceOrder(null); - - String action = request.getParameter("action"); - String policyRefId = request.getParameter("policyRefId"); - String policySearchString = request.getParameter("policySearchString"); - if(policyRefId != null && policyRefId.trim().length() > 0){ - PolicyRefIdDTO policyRefIdDTO = new PolicyRefIdDTO(); - policyRefIdDTO.setId(policyRefId); - policyRefIdDTO.setReferenceOnly(true); - String policyType = request.getParameter("policyType"); - if("PolicySet".equals(policyType)){ - policyRefIdDTO.setPolicySet(true); - } - entitlementPolicyBean.addPolicyRefId(policyRefIdDTO); - } - - - String targetRowIndexString = request.getParameter("targetRowIndex"); - String obligationRowIndexString = request.getParameter("obligationRowIndex"); - - String maxTargetRowsString = request.getParameter("maxTargetRows"); - String maxObligationRowsString = request.getParameter("maxObligationRows"); - - try{ - if(maxTargetRowsString != null && maxTargetRowsString.trim().length() > 0){ - maxTargetRows = Integer.parseInt(maxTargetRowsString); - } - if(maxObligationRowsString != null && maxObligationRowsString.trim().length() > 0){ - maxObligationRows = Integer.parseInt(maxObligationRowsString); - } - - if(targetRowIndexString != null && targetRowIndexString.trim().length() > 0){ - targetRowIndex = Integer.parseInt(targetRowIndexString); - } - if(obligationRowIndexString != null && obligationRowIndexString.trim().length() > 0){ - obligationRowIndex = Integer.parseInt(obligationRowIndexString); - } - } catch (Exception e){ - //if number format exceptions.. just ignore - } - - String policyReferenceOrder = request.getParameter("policyReferenceOrder"); - - for(rowNumber = 0; rowNumber < maxTargetRows + 1; rowNumber ++){ - - RowDTO rowDTO = new RowDTO(); - String targetCategory = request.getParameter("targetCategory_" + rowNumber); - if(targetRowIndex == rowNumber){ - categoryType = targetCategory; - rowDTO.setNotCompleted(true); - } - if(targetCategory != null && targetCategory.trim().length() > 0){ - rowDTO.setCategory(targetCategory); - } else { - continue; - } - - String targetPreFunction = request.getParameter("targetPreFunction_" + rowNumber); - if(targetPreFunction != null){ - rowDTO.setPreFunction(targetPreFunction); - } - - String targetFunction = request.getParameter("targetFunction_" + rowNumber); - if(targetFunction != null){ - rowDTO.setFunction(targetFunction); - } - - - String targetAttributeId = request.getParameter("targetAttributeId_" + rowNumber); - if(targetAttributeId != null){ - rowDTO.setAttributeId(targetAttributeId); - if(targetRowIndex == rowNumber){ - selectedAttributeId = targetAttributeId; - } - } - - String targetAttributeType = request.getParameter("targetAttributeTypes_" + rowNumber); - if(targetAttributeType != null){ - rowDTO.setAttributeDataType(targetAttributeType); - if(targetRowIndex == rowNumber){ - selectedAttributeDataType = targetAttributeType; - } - } - - String targetCombineFunction = request.getParameter("targetCombineFunctions_" + rowNumber); - if(targetCombineFunction != null){ - rowDTO.setCombineFunction(targetCombineFunction); - } - - String targetAttributeValue = request.getParameter("targetAttributeValue_" + rowNumber); - if(targetAttributeValue != null && targetAttributeValue.trim().length() > 0){ - rowDTO.setAttributeValue(targetAttributeValue); - } else { - if(targetAttributeValue != null && targetAttributeValue.trim().length() > 0){ - rowDTO.setAttributeValue(targetAttributeValue); - } else { - if(targetRowIndex == rowNumber){ - targetDTO.addRowDTO(rowDTO); - } - continue; - } - } - targetDTO.addRowDTO(rowDTO); - } - - // set target element to entitlement bean - entitlementPolicyBean.setTargetDTO(targetDTO); - - List obligationDTOs = new ArrayList(); - for(rowNumber = 0; rowNumber < maxObligationRows + 1; rowNumber ++){ - - ObligationDTO dto = new ObligationDTO(); - String obligationType = request.getParameter("obligationType_" + rowNumber); - if(obligationRowIndex == rowNumber){ - categoryType = null; // TODO - dto.setNotCompleted(true); - } - if(obligationType != null){ - dto.setType(obligationType); - } else{ - continue; - } - String obligationId = request.getParameter("obligationId_" + rowNumber); - if(obligationId != null && obligationId.trim().length() > 0){ - dto.setObligationId(obligationId); - } else { - continue; - } - - String obligationAttributeValue = request.getParameter("obligationAttributeValue_" + rowNumber); - if(obligationAttributeValue != null){ - dto.setAttributeValue(obligationAttributeValue); - } - - String obligationAttributeId = request.getParameter("obligationAttributeId_" + rowNumber); - if(obligationAttributeId != null){ - dto.setResultAttributeId(obligationAttributeId); - } - - String obligationEffect = request.getParameter("obligationEffect_" + rowNumber); - if(obligationEffect != null){ - dto.setEffect(obligationEffect); - } - // Set obligations - obligationDTOs.add(dto); - } - entitlementPolicyBean.setObligationDTOs(obligationDTOs); - - if(policyReferenceOrder != null && policyReferenceOrder.trim().length() > 0){ - if (policyRefId != null && policyRefId.trim().length() > 0 && !"delete".equals(action)) { - entitlementPolicyBean.setPolicyReferenceOrder(policyReferenceOrder + "," + policyRefId); - } else { - entitlementPolicyBean.setPolicyReferenceOrder(policyReferenceOrder); - } - } - - forwardTo = "create-policy-set.jsp"; - if ("complete".equals(action)) { - forwardTo = "finish-policy-set.jsp"; - } else if ("delete".equals(action)) { - forwardTo = "delete-policy-entry.jsp"; - if(policyRefId != null && policyRefId.trim().length() > 0){ - forwardTo = forwardTo + "?policyRefId=" + Encode.forUriComponent(policyRefId); - } - } else if ("selectAttribute".equals(action)) { - forwardTo = "select-attribute.jsp"; - } else if ("search".equals(action) || "paginate".equals(action) || "add".equals(action)) { - forwardTo = "create-policy-set.jsp"; - } - - if (!"delete".equals(action)) { - if (categoryType != null && categoryType.trim().length() > 0) { - forwardTo = forwardTo + "?category=" + categoryType; - if (selectedAttributeDataType != null && selectedAttributeDataType.trim().length() > 0) { - forwardTo = - forwardTo + "&selectedAttributeDataType=" + Encode.forUriComponent(selectedAttributeDataType); - } - if (selectedAttributeId != null && selectedAttributeId.trim().length() > 0) { - forwardTo = forwardTo + "&selectedAttributeId=" + Encode.forUriComponent(selectedAttributeId); - } - if ("selectAttribute".equals(action)) { - forwardTo = forwardTo + "&initiatedFrom=create-policy-set"; - } - } else if (policySearchString != null && policySearchString.trim().length() > 0) { - forwardTo = forwardTo + "?policySearchString=" + Encode.forUriComponent(policySearchString); - } - } - } -%> - - - - \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/update-policy-submit.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/update-policy-submit.jsp deleted file mode 100644 index cf7fdae60be8..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/update-policy-submit.jsp +++ /dev/null @@ -1,86 +0,0 @@ - -<%@ page import="org.apache.axis2.context.ConfigurationContext"%> -<%@ page import="org.wso2.carbon.CarbonConstants"%> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO"%> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient"%> -<%@ page import="org.wso2.carbon.ui.CarbonUIMessage"%> -<%@ page import="java.nio.charset.StandardCharsets"%> -<%@ page import="java.util.Base64"%> - -<% - String serverURL = CarbonUIUtil.getServerURL(config - .getServletContext(), session); - ConfigurationContext configContext = (ConfigurationContext) config - .getServletContext().getAttribute( - CarbonConstants.CONFIGURATION_CONTEXT); - String cookie = (String) session - .getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String forwardTo = request.getParameter("forwardTo"); - if(forwardTo == null){ - forwardTo = "index"; - } - forwardTo = forwardTo + ".jsp"; - String policyid = request.getParameter("policyid"); - PolicyDTO dto = null; - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - - if ((request.getParameter("policy") != null)) { - - try { - EntitlementPolicyAdminServiceClient client = new EntitlementPolicyAdminServiceClient(cookie, serverURL, configContext); - try{ - // if this already existing policy - dto = client.getLightPolicy(policyid); - } catch (Exception e){ - // ignore - } - if(dto == null){ - dto = new PolicyDTO(); - } - String policy = request.getParameter("policy"); - policy = new String(Base64.getDecoder().decode(policy), StandardCharsets.UTF_8); - dto.setPolicy(policy); - dto.setPolicyId(policyid); - dto.setPolicyEditor("XML"); - client.updatePolicy(dto); - String message = resourceBundle.getString("updated.successfully"); - CarbonUIMessage.sendCarbonUIMessage(message,CarbonUIMessage.INFO, request); - } catch (Exception e) { - String message = resourceBundle.getString("invalid.policy.not.updated") + e.getMessage(); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.ERROR, request); - } - } else { - } -%> - -<%@page - import="org.wso2.carbon.ui.CarbonUIUtil"%> -<%@page import="org.wso2.carbon.utils.ServerConstants"%> -<%@ page import="java.util.ResourceBundle" %> - - - \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/update-rule.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/update-rule.jsp deleted file mode 100644 index 657a7bf6c92b..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/update-rule.jsp +++ /dev/null @@ -1,485 +0,0 @@ - -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.ObligationDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.RowDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.RuleDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.dto.TargetDTO" %> -<%@ page import="java.util.ArrayList" %> -<%@ page import="java.util.List" %> -<%@ page import="org.owasp.encoder.Encode" %> - - - -<% - int rowNumber = 0; - int targetRowIndex = -1; - int ruleRowIndex = -1; - int targetRuleRowIndex = -1; - int dynamicRowIndex = -1; - int obligationRowIndex = -1; - - int maxTargetRows = 0; - int maxTargetRuleRows = 0; - int maxRuleRows = 0; - int maxObligationRuleRows = 0; - int maxObligationRows = 0; - - String categoryType = null; - String selectedAttributeDataType = null; - String selectedAttributeId = null; - RuleDTO ruleDTO = new RuleDTO(); - TargetDTO targetDTO = new TargetDTO(); - entitlementPolicyBean.setRuleElementOrder(null); - - String targetRowIndexString = request.getParameter("targetRowIndex"); - String ruleRowIndexString = request.getParameter("ruleRowIndex"); - String targetRuleRowIndexString = request.getParameter("targetRuleRowIndex"); - String dynamicRowIndexString = request.getParameter("dynamicRowIndex"); - String obligationRowIndexString = request.getParameter("obligationRowIndex"); - - String maxTargetRowsString = request.getParameter("maxTargetRows"); - String maxTargetRuleRowsString = request.getParameter("maxTargetRuleRows"); - String maxRuleRowsString = request.getParameter("maxRuleRows"); - String maxObligationRuleRowsString = request.getParameter("maxObligationRuleRows"); - String maxObligationRowsString = request.getParameter("maxObligationRows"); - - try{ - if(maxTargetRowsString != null && maxTargetRowsString.trim().length() > 0){ - maxTargetRows = Integer.parseInt(maxTargetRowsString); - } - if(maxTargetRuleRowsString != null && maxTargetRuleRowsString.trim().length() > 0){ - maxTargetRuleRows = Integer.parseInt(maxTargetRuleRowsString); - } - if(maxRuleRowsString != null && maxRuleRowsString.trim().length() > 0){ - maxRuleRows = Integer.parseInt(maxRuleRowsString); - } - if(maxObligationRuleRowsString != null && maxObligationRuleRowsString.trim().length() > 0){ - maxObligationRuleRows = Integer.parseInt(maxObligationRuleRowsString); - } - if(maxObligationRowsString != null && maxObligationRowsString.trim().length() > 0){ - maxObligationRows = Integer.parseInt(maxObligationRowsString); - } - - if(targetRowIndexString != null && targetRowIndexString.trim().length() > 0){ - targetRowIndex = Integer.parseInt(targetRowIndexString); - } - if(ruleRowIndexString != null && ruleRowIndexString.trim().length() > 0){ - ruleRowIndex = Integer.parseInt(ruleRowIndexString); - } - if(targetRuleRowIndexString != null && targetRuleRowIndexString.trim().length() > 0){ - targetRuleRowIndex = Integer.parseInt(targetRuleRowIndexString); - } - if(dynamicRowIndexString != null && dynamicRowIndexString.trim().length() > 0){ - dynamicRowIndex = Integer.parseInt(dynamicRowIndexString); - } - if(obligationRowIndexString != null && obligationRowIndexString.trim().length() > 0){ - obligationRowIndex = Integer.parseInt(obligationRowIndexString); - } - } catch (Exception e){ - //if number format exceptions.. just ignore - } - - String ruleElementOrder = request.getParameter("ruleElementOrder"); - String updateRule = request.getParameter("updateRule"); - String action = request.getParameter("action"); - String ruleId = request.getParameter("ruleId"); - String ruleEffect = request.getParameter("ruleEffect"); - String ruleDescription = request.getParameter("ruleDescription"); - String completedRule = request.getParameter("completedRule"); - String editRule = request.getParameter("editRule"); - - for(rowNumber = 0; rowNumber < maxTargetRows + 1; rowNumber ++){ - - RowDTO rowDTO = new RowDTO(); - String targetCategory = request.getParameter("targetCategory_" + rowNumber); - if(targetRowIndex == rowNumber){ - categoryType = targetCategory; - rowDTO.setNotCompleted(true); - } - if(targetCategory != null && targetCategory.trim().length() > 0){ - rowDTO.setCategory(targetCategory); - } else { - continue; - } - - String targetPreFunction = request.getParameter("targetPreFunction_" + rowNumber); - if(targetPreFunction != null){ - rowDTO.setPreFunction(targetPreFunction); - } - - String targetFunction = request.getParameter("targetFunction_" + rowNumber); - if(targetFunction != null){ - rowDTO.setFunction(targetFunction); - } - - String targetAttributeId = request.getParameter("targetAttributeId_" + rowNumber); - if(targetAttributeId != null && targetAttributeId.trim().length() > 0){ - rowDTO.setAttributeId(targetAttributeId); - if(targetRowIndex == rowNumber){ - selectedAttributeId = targetAttributeId; - } - } - - String targetAttributeType = request.getParameter("targetAttributeTypes_" + rowNumber); - if(targetAttributeType != null && targetAttributeType.trim().length() > 0){ - rowDTO.setAttributeDataType(targetAttributeType); - if(targetRowIndex == rowNumber){ - selectedAttributeDataType = targetAttributeType; - } - } - - String targetCombineFunction = request.getParameter("targetCombineFunctions_" + rowNumber); - if(targetCombineFunction != null){ - rowDTO.setCombineFunction(targetCombineFunction); - } - - String targetAttributeValue = request.getParameter("targetAttributeValue_" + rowNumber); - if(targetAttributeValue != null && targetAttributeValue.trim().length() > 0){ - rowDTO.setAttributeValue(targetAttributeValue); - } else { - if(targetRowIndex == rowNumber){ - targetDTO.addRowDTO(rowDTO); - } - continue; - } - - targetDTO.addRowDTO(rowDTO); - } - - // set target element to entitlement bean - entitlementPolicyBean.setTargetDTO(targetDTO); - - if(ruleId != null && ruleId.trim().length() > 0 && !ruleId.trim().equals("null") && editRule == null ) { - - ruleDTO.setRuleId(ruleId); - ruleDTO.setRuleEffect(ruleEffect); - if(ruleDescription != null && ruleDescription.trim().length() > 0 ){ - ruleDTO.setRuleDescription(ruleDescription); - } - if(completedRule != null && completedRule.equals("true")){ - ruleDTO.setCompletedRule(true); - } - - TargetDTO ruleTargetDTO = new TargetDTO(); - - for(rowNumber = 0; rowNumber < maxTargetRuleRows + 1; rowNumber ++){ - - RowDTO rowDTO = new RowDTO(); - String targetCategory = request.getParameter("ruleTargetCategory_" + rowNumber); - if(targetRuleRowIndex == rowNumber){ - categoryType = targetCategory; - rowDTO.setNotCompleted(true); - } - if(targetCategory != null && targetCategory.trim().length() > 0){ - rowDTO.setCategory(targetCategory); - } else { - continue; - } - - String targetPreFunction = request.getParameter("ruleTargetPreFunction_" + rowNumber); - if(targetPreFunction != null){ - rowDTO.setPreFunction(targetPreFunction); - } - - String targetFunction = request.getParameter("ruleTargetFunction_" + rowNumber); - if(targetFunction != null){ - rowDTO.setFunction(targetFunction); - } - - String targetAttributeId = request.getParameter("ruleTargetAttributeId_" + rowNumber); - if(targetAttributeId != null){ - rowDTO.setAttributeId(targetAttributeId); - if(targetRuleRowIndex == rowNumber){ - selectedAttributeId = targetAttributeId; - } - } - - String targetAttributeType = request.getParameter("ruleTargetAttributeTypes_" + rowNumber); - if(targetAttributeType != null){ - rowDTO.setAttributeDataType(targetAttributeType); - if(targetRuleRowIndex == rowNumber){ - selectedAttributeDataType = targetAttributeType; - } - } - - String targetCombineFunction = request.getParameter("ruleTargetCombineFunctions_" + rowNumber); - if(targetCombineFunction != null){ - rowDTO.setCombineFunction(targetCombineFunction); - } - - String targetAttributeValue = request.getParameter("ruleTargetAttributeValue_" + rowNumber); - if(targetAttributeValue != null && targetAttributeValue.trim ().length() > 0){ - rowDTO.setAttributeValue(targetAttributeValue); - } else { - if(targetRuleRowIndex == rowNumber){ - ruleTargetDTO.addRowDTO(rowDTO); - } - continue; - } - - ruleTargetDTO.addRowDTO(rowDTO); - } - - // rule's target - ruleDTO.setTargetDTO(ruleTargetDTO); - - for(rowNumber = 0; rowNumber < maxRuleRows + 1; rowNumber ++){ - - RowDTO rowDTO = new RowDTO(); - String ruleCategory = request.getParameter("ruleCategory_" + rowNumber); - if(ruleRowIndex == rowNumber){ - categoryType = ruleCategory; - rowDTO.setNotCompleted(true); - } - if(ruleCategory != null && ruleCategory.trim().length() > 0){ - rowDTO.setCategory(ruleCategory); - } else { - continue; - } - - String rulePreFunction = request.getParameter("rulePreFunction_" + rowNumber); - if(rulePreFunction != null){ - rowDTO.setPreFunction(rulePreFunction); - } - - String ruleFunction = request.getParameter("ruleFunction_" + rowNumber); - if(ruleFunction != null){ - rowDTO.setFunction(ruleFunction); - } - - String ruleAttributeId = request.getParameter("ruleAttributeId_" + rowNumber); - if(ruleAttributeId != null){ - rowDTO.setAttributeId(ruleAttributeId); - if(ruleRowIndex == rowNumber){ - selectedAttributeId = ruleAttributeId; - } - } - - String ruleAttributeType = request.getParameter("ruleAttributeTypes_" + rowNumber); - if(ruleAttributeType != null){ - rowDTO.setAttributeDataType(ruleAttributeType); - if(ruleRowIndex == rowNumber){ - selectedAttributeDataType = ruleAttributeType; - } - } - - String ruleCombineFunction = request.getParameter("ruleCombineFunctions_" + rowNumber); - if(ruleCombineFunction != null){ - rowDTO.setCombineFunction(ruleCombineFunction); - } - - String ruleAttributeValue = request.getParameter("ruleAttributeValue_" + rowNumber); - if(ruleAttributeValue != null && ruleAttributeValue.trim().length() > 0){ - rowDTO.setAttributeValue(ruleAttributeValue); - } else { - if(ruleRowIndex == rowNumber){ - ruleDTO.addRowDTO(rowDTO); - } - continue; - } - ruleDTO.addRowDTO(rowDTO); - } - - for(rowNumber = 0; rowNumber < maxObligationRuleRows + 1; rowNumber ++){ - - ObligationDTO dto = new ObligationDTO(); - String obligationType = request.getParameter("obligationRuleType_" + rowNumber); - if(obligationType != null){ - dto.setType(obligationType); - } else { - continue; - } - - String obligationId = request.getParameter("obligationRuleId_" + rowNumber); - if(obligationId != null && obligationId.trim().length() > 0){ - dto.setObligationId(obligationId); - } else { - continue; - } - - String obligationAttributeValue = request.getParameter("obligationRuleAttributeValue_" + rowNumber); - if(obligationAttributeValue != null){ - dto.setAttributeValue(obligationAttributeValue); - } - - String obligationAttributeId = request.getParameter("obligationRuleAttributeId_" + rowNumber); - if(obligationAttributeId != null){ - dto.setResultAttributeId(obligationAttributeId); - } - - dto.setEffect(ruleEffect); - - if(obligationRowIndex == rowNumber){ - categoryType = null; // TODO - dto.setNotCompleted(true); - } - - // Set rule's obligation - ruleDTO.addObligationDTO(dto); - } - - // Set rule - entitlementPolicyBean.setRuleDTO(ruleDTO); - } - - List obligationDTOs = new ArrayList(); - for(rowNumber = 0; rowNumber < maxObligationRows + 1; rowNumber ++){ - - ObligationDTO dto = new ObligationDTO(); - String obligationType = request.getParameter("obligationType_" + rowNumber); - if(obligationType != null){ - dto.setType(obligationType); - } else{ - continue; - } - String obligationId = request.getParameter("obligationId_" + rowNumber); - if(obligationId != null && obligationId.trim().length() > 0){ - dto.setObligationId(obligationId); - } else { - continue; - } - - String obligationAttributeValue = request.getParameter("obligationAttributeValue_" + rowNumber); - if(obligationAttributeValue != null){ - dto.setAttributeValue(obligationAttributeValue); - } - - String obligationAttributeId = request.getParameter("obligationAttributeId_" + rowNumber); - if(obligationAttributeId != null){ - dto.setResultAttributeId(obligationAttributeId); - } - - String obligationEffect = request.getParameter("obligationEffect_" + rowNumber); - if(obligationEffect != null){ - dto.setEffect(obligationEffect); - } - - if(obligationRowIndex == rowNumber){ - categoryType = null; // TODO - dto.setNotCompleted(true); - } - - // Set obligations - obligationDTOs.add(dto); - } - entitlementPolicyBean.setObligationDTOs(obligationDTOs); - -// rowNumber = 0; -// while(true){ -// -// ExtendAttributeDTO dto = new ExtendAttributeDTO(); -// String dynamicId = request. -// getParameter("dynamicId_" + rowNumber)); -// if(dynamicId != null){ -// dto.setId(dynamicId); -// } else { -// break; -// } -// -// String dynamicSelector = request. -// getParameter("dynamicSelector_" + rowNumber)); -// if(dynamicSelector != null){ -// dto.setSelector(dynamicSelector); -// } -// -// String dynamicFunction = request. -// getParameter("dynamicFunction_" + rowNumber)); -// if(dynamicFunction != null){ -// dto.setFunction(dynamicFunction); -// } -// -// String dynamicCategory = request. -// getParameter("dynamicCategory_" + rowNumber)); -// if(dynamicCategory != null){ -// dto.setCategory(dynamicCategory); -// } -// -// String dynamicAttributeValue = request. -// getParameter("dynamicAttributeValue_" + rowNumber)); -// if(dynamicAttributeValue != null && dynamicAttributeValue.trim().length() > 0){ -// dto.setAttributeValue(dynamicAttributeValue); -// } -// -// String dynamicAttributeId = request. -// getParameter("dynamicAttributeId_" + rowNumber)); -// if(dynamicAttributeId != null){ -// dto.setAttributeId(dynamicAttributeId); -// } -// -// String dynamicAttributeTypes = request. -// getParameter("dynamicAttributeTypes_0" + rowNumber)); -// if(dynamicAttributeTypes != null){ -// dto.setDataType(dynamicAttributeTypes); -// } -// -// if(dynamicRowIndex == rowNumber){ -// categoryType = null; // TODO -// dto.setNotCompleted(true); -// } -// -// // Set extend attributes -// entitlementPolicyBean.addExtendAttributeDTO(dto); -// rowNumber ++; -// } - - if(ruleElementOrder != null && ruleElementOrder.trim().length() > 0){ - if(ruleDTO.isCompletedRule() && !"true".equals(updateRule)){ - entitlementPolicyBean.setRuleElementOrder(ruleElementOrder.trim() + ", " + - ruleDTO.getRuleId()); - } else{ - entitlementPolicyBean.setRuleElementOrder(ruleElementOrder.trim()); - } - } - - String forwardTo = "policy-editor.jsp"; - if ("completePolicy".equals(action)) { - forwardTo = "finish.jsp"; - } else if ("updateRule".equals(action) || "addRule".equals(action) || "cancelRule".equals(action) || - "editRule".equals(action)) { - forwardTo = "policy-editor.jsp"; - } else if ("deleteRule".equals(action)) { - forwardTo = "delete-rule-entry.jsp"; - } else if ("selectAttribute".equals(action)) { - forwardTo = "select-attribute.jsp"; - } - - if (completedRule == null || !Boolean.parseBoolean(completedRule)) { - forwardTo = forwardTo + "?ruleId=" + Encode.forJavaScript(ruleId); - if(categoryType != null && categoryType.trim().length() > 0){ - forwardTo = forwardTo + "&category=" + categoryType + "&returnPage=policy-editor.jsp"; - } - if(selectedAttributeDataType != null && selectedAttributeDataType.trim().length() > 0){ - forwardTo = forwardTo + "&selectedAttributeDataType=" + selectedAttributeDataType; - } - if(selectedAttributeId != null && selectedAttributeId.trim().length() > 0){ - forwardTo = forwardTo + "&selectedAttributeId=" + selectedAttributeId; - } - } - -%> - - - - \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/update-search.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/update-search.jsp deleted file mode 100644 index e538d98eea39..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/update-search.jsp +++ /dev/null @@ -1,139 +0,0 @@ -, -<%@ page import="org.apache.axis2.context.ConfigurationContext" %> -<%@ page import="org.wso2.carbon.CarbonConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.AttributeDTO" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.EntitlementPolicyConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIMessage" %> -<%@ page - import="org.wso2.carbon.ui.CarbonUIUtil" %> -<%@ page import="org.wso2.carbon.utils.ServerConstants" %> -<%@ page import="java.util.ArrayList" %> -<%@ page import="java.util.List" %> -<%@ page import="java.util.ResourceBundle" %> - - - -<% - - String resourceNames = ""; - String resourceId = ""; - String resourceDataType = ""; - String subjectNames = ""; - String subjectId = ""; - String subjectDataType = ""; - String actionNames = ""; - String actionId = ""; - String actionDataType = ""; - String environmentNames = ""; - String environmentId = ""; - String environmentDataType = ""; - String [] results = null; - String forwardTo; - - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = - (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants. - CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - - resourceNames = (String)session.getAttribute("resourceNames"); - resourceId = (String)session.getAttribute("resourceId"); - resourceDataType = (String)session.getAttribute("resourceDataType"); - - subjectNames = (String)session.getAttribute("subjectNames"); - subjectId = (String)session.getAttribute("subjectId"); - subjectDataType = (String)session.getAttribute("subjectDataType"); - - actionNames = (String)session.getAttribute("actionNames"); - actionId = (String)session.getAttribute("actionId"); - actionDataType = (String)session.getAttribute("actionDataType"); - - environmentNames = (String)session.getAttribute("environmentNames"); - environmentId = (String)session.getAttribute("environmentId"); - environmentDataType = (String)session.getAttribute("environmentDataType"); - - List attributeValueDTOs = new ArrayList(); - - if(resourceNames != null && !"".equals(resourceNames)){ - AttributeDTO attributeValueDTO = new AttributeDTO(); - attributeValueDTO.setAttributeValue(resourceNames); - attributeValueDTO.setAttributeType(EntitlementPolicyConstants.RESOURCE_ELEMENT); - attributeValueDTO.setAttributeDataType(resourceDataType); - attributeValueDTO.setAttributeId(resourceId); - attributeValueDTOs.add(attributeValueDTO); - } - - if(subjectNames != null && !"".equals(subjectNames)){ - AttributeDTO attributeValueDTO = new AttributeDTO(); - attributeValueDTO.setAttributeValue(subjectNames); - attributeValueDTO.setAttributeType(EntitlementPolicyConstants.SUBJECT_ELEMENT); - attributeValueDTO.setAttributeId(subjectId); - attributeValueDTO.setAttributeDataType(subjectDataType); - attributeValueDTOs.add(attributeValueDTO); - } - - if(actionNames != null && !"".equals(actionNames)){ - AttributeDTO attributeValueDTO = new AttributeDTO(); - attributeValueDTO.setAttributeValue(actionNames); - attributeValueDTO.setAttributeType(EntitlementPolicyConstants.ACTION_ELEMENT); - attributeValueDTO.setAttributeId(actionId); - attributeValueDTO.setAttributeDataType(actionDataType); - attributeValueDTOs.add(attributeValueDTO); - } - - if(environmentNames != null && !"".equals(environmentNames)){ - AttributeDTO attributeValueDTO = new AttributeDTO(); - attributeValueDTO.setAttributeValue(environmentNames); - attributeValueDTO.setAttributeType(EntitlementPolicyConstants.ENVIRONMENT_ELEMENT); - attributeValueDTO.setAttributeId(environmentId); - attributeValueDTO.setAttributeDataType(environmentDataType); - attributeValueDTOs.add(attributeValueDTO); - } - - try { - - if(attributeValueDTOs.size() > 0){ - EntitlementPolicyAdminServiceClient client = new EntitlementPolicyAdminServiceClient(cookie, - serverURL, configContext); - results = client.getAdvanceSearchResult(attributeValueDTOs.toArray(new AttributeDTO[attributeValueDTOs.size()])); - } - - } catch (Exception e) { - String message = resourceBundle.getString("error.while.loading.policy.resource"); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.ERROR, request); - forwardTo = "../admin/error.jsp"; - } - - forwardTo = "advance-search.jsp"; - -%> - - - - diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/update_order-ajaxprocessor.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/update_order-ajaxprocessor.jsp deleted file mode 100644 index f58de88bef22..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/update_order-ajaxprocessor.jsp +++ /dev/null @@ -1,72 +0,0 @@ - -<%@ page import="org.apache.axis2.context.ConfigurationContext" %> -<%@ page import="org.wso2.carbon.CarbonConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementPolicyAdminServiceClient" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIMessage" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %> -<%@ page import="org.wso2.carbon.utils.ServerConstants" %> -<%@ page import="java.util.ResourceBundle" %> -<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %> -<% - String httpMethod = request.getMethod(); - if (!"post".equalsIgnoreCase(httpMethod)) { - response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); - return; - } - - String forwardTo = "my-pdp.jsp"; - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - try { - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = - (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String policyId = request.getParameter("policyId"); - String orderSting = request.getParameter("order"); - int order; - if (orderSting != null && orderSting.trim().length() > 0) { - EntitlementPolicyAdminServiceClient client = - new EntitlementPolicyAdminServiceClient(cookie, serverURL, configContext); - order = Integer.parseInt(orderSting); - if (order > 0) { - client.orderPolicy(policyId, order); - String message = resourceBundle.getString("ordered.successfully"); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.INFO, request); - } else { - String message = resourceBundle.getString("error.while.ordering.invalid.policy.value"); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.ERROR, request); - } - } - } catch (Exception e) { - String message = resourceBundle.getString("error.while.ordering.policy") + " " + e.getMessage(); - CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.ERROR, request, e); - } -%> - - - - - diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/view-finder.jsp b/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/view-finder.jsp deleted file mode 100644 index 4e2771ad5492..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.ui/src/main/resources/web/entitlement/view-finder.jsp +++ /dev/null @@ -1,193 +0,0 @@ - -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> -<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" - prefix="carbon"%> -<%@ page import="org.apache.axis2.context.ConfigurationContext" %> -<%@ page import="org.owasp.encoder.Encode" %> -<%@ page import="org.wso2.carbon.CarbonConstants" %> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.PIPFinderDataHolder" %> -<%@ page import="org.wso2.carbon.identity.entitlement.stub.dto.PolicyFinderDataHolder" %> -<%@ page import="org.wso2.carbon.identity.entitlement.ui.client.EntitlementAdminServiceClient" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %> -<%@ page import="org.wso2.carbon.utils.ServerConstants" %> -<%@ page import="java.util.ResourceBundle" %> - -<% - - PIPFinderDataHolder pipFinderDataHolder = null; - PolicyFinderDataHolder policyFinderDataHolder = null; - String policyString = ""; - String attributeString = ""; - String forwardTo = null; - - String finderId = request.getParameter("finderId"); - String type = request.getParameter("type"); - - String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); - ConfigurationContext configContext = - (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants. - CONFIGURATION_CONTEXT); - String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); - String BUNDLE = "org.wso2.carbon.identity.entitlement.ui.i18n.Resources"; - ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE, request.getLocale()); - try { - EntitlementAdminServiceClient client = new EntitlementAdminServiceClient(cookie, - serverURL, configContext); - if(finderId != null){ - if("attribute".equals(type)) { - pipFinderDataHolder = client.getPIPAttributeFinderData(finderId); - } else if("resource".equals(type)){ - pipFinderDataHolder = client.getPIPResourceFinderData(finderId); - } else if("policy".equals(type)){ - policyFinderDataHolder = client.getPolicyFinderData(finderId); - String[] policies = policyFinderDataHolder.getPolicyIdentifiers(); - if(policies != null){ - for(String policy : policies){ - if(policy == null){ - continue; - } - if("".equals(policyString)){ - policyString = policy; - } else { - policyString = policyString + " , " + policy; - } - } - } - } - - if(pipFinderDataHolder != null){ - String[] attributeIds = pipFinderDataHolder.getSupportedAttributeIds(); - if(attributeIds != null){ - for(String attribute : attributeIds){ - if(attribute == null){ - continue; - } - if("".equals(attributeString)){ - attributeString = attribute; - } else { - attributeString = attributeString + " , " + attribute; - } - } - } - } - } - - } catch (Exception e) { -%> - -<% - } -%> - - - - - - - - - - - - - - -
    -

    -
    -
    - <% - if(policyFinderDataHolder != null){ - %> - <%=Encode.forHtml(policyFinderDataHolder.getModuleName())%> - <% - } - %> - <% - if(pipFinderDataHolder != null){ - %> - <%=Encode.forHtml(pipFinderDataHolder.getModuleName())%> - <% - } - %> -
    -
    - <% - if(policyFinderDataHolder != null){ - %> - - - - - - - - - - - - -
    Name<%=Encode.forHtml(policyFinderDataHolder.getModuleName())%>
    Class Name<%=Encode.forHtml(policyFinderDataHolder.getClassName())%>
    Policy Ids <%=Encode.forHtml(policyString)%>
    - - <% - } - %> - - <% - if(pipFinderDataHolder != null){ - %> - - - - - - - - - - - - -
    Name<%=Encode.forHtml(pipFinderDataHolder.getModuleName())%>
    Class Name<%=Encode.forHtml(pipFinderDataHolder.getClassName())%>
    Support Attribute Ids <%=Encode.forHtml(attributeString)%>
    - - <% - } - %> -
    -
    - -
    -
    -
    -
    -
    diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/pom.xml b/components/entitlement/org.wso2.carbon.identity.entitlement/pom.xml index 47386b4dcaa1..e8e867486579 100644 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/pom.xml +++ b/components/entitlement/org.wso2.carbon.identity.entitlement/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.identity.framework entitlement - 7.6.20-SNAPSHOT + 7.7.0-SNAPSHOT ../pom.xml diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/EntitlementAdminService.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/EntitlementAdminService.java deleted file mode 100644 index e8bc551915e6..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/EntitlementAdminService.java +++ /dev/null @@ -1,547 +0,0 @@ -/* - * Copyright (c) Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.entitlement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.entitlement.persistence.ConfigPersistenceManager; -import org.wso2.carbon.identity.entitlement.dto.PDPDataHolder; -import org.wso2.carbon.identity.entitlement.dto.PIPFinderDataHolder; -import org.wso2.carbon.identity.entitlement.dto.PolicyFinderDataHolder; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; -import org.wso2.carbon.identity.entitlement.pap.EntitlementAdminEngine; -import org.wso2.carbon.identity.entitlement.pap.store.PAPPolicyFinder; -import org.wso2.carbon.identity.entitlement.pdp.EntitlementEngine; -import org.wso2.carbon.identity.entitlement.pip.AbstractPIPAttributeFinder; -import org.wso2.carbon.identity.entitlement.pip.CarbonAttributeFinder; -import org.wso2.carbon.identity.entitlement.pip.CarbonResourceFinder; -import org.wso2.carbon.identity.entitlement.pip.PIPAttributeFinder; -import org.wso2.carbon.identity.entitlement.pip.PIPResourceFinder; -import org.wso2.carbon.identity.entitlement.policy.finder.PolicyFinderModule; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -/** - * Entitlement PDP related admin services are exposed - */ -public class EntitlementAdminService { - - private static Log log = LogFactory.getLog(EntitlementAdminService.class); - - /** - * Clears the decision cache. - * - * @throws EntitlementException throws - */ - public void clearDecisionCache() throws EntitlementException { - EntitlementEngine.getInstance().clearDecisionCache(); - if (log.isDebugEnabled()) { - log.debug("Decision Caching is cleared by using admin service"); - } - } - - /** - * Clears the policy cache. - * - * @throws EntitlementException throws - */ - public void clearPolicyCache() throws EntitlementException { - EntitlementEngine.getInstance().invalidatePolicyCache(); - if (log.isDebugEnabled()) { - log.debug("Decision Caching is cleared by using admin service"); - } - } - - /** - * Clears Carbon attribute finder cache and All the attribute cache implementations in each - * PIP attribute finder level - * - * @throws EntitlementException throws - */ - public void clearAllAttributeCaches() throws EntitlementException { - CarbonAttributeFinder finder = EntitlementEngine.getInstance().getCarbonAttributeFinder(); - if (finder != null) { - finder.clearAttributeCache(); - // we need invalidate decision cache as well. - clearDecisionCache(); - } else { - throw new EntitlementException("Can not clear all attribute caches - Carbon Attribute Finder " - + "is not initialized"); - } - - Map designators = EntitlementServiceComponent.getEntitlementConfig() - .getDesignators(); - if (designators != null && !designators.isEmpty()) { - Set pipAttributeFinders = designators.keySet(); - for (PIPAttributeFinder pipAttributeFinder : pipAttributeFinders) { - pipAttributeFinder.clearCache(); - } - } - } - - - /** - * Clears the carbon attribute cache - * - * @throws EntitlementException throws - */ - public void clearCarbonAttributeCache() throws EntitlementException { - - CarbonAttributeFinder finder = EntitlementEngine.getInstance().getCarbonAttributeFinder(); - if (finder != null) { - finder.clearAttributeCache(); - // we need invalidate decision cache as well. - clearDecisionCache(); - } else { - throw new EntitlementException("Can not clear attribute cache - Carbon Attribute Finder " - + "is not initialized"); - } - - Map designators = EntitlementServiceComponent.getEntitlementConfig() - .getDesignators(); - if (designators != null && !designators.isEmpty()) { - Set pipAttributeFinders = designators.keySet(); - for (PIPAttributeFinder pipAttributeFinder : pipAttributeFinders) { - if (pipAttributeFinder instanceof AbstractPIPAttributeFinder) { - pipAttributeFinder.clearCache(); - } - } - } - } - - /** - * Clears the cache maintained by the attribute finder. - * - * @param attributeFinder Canonical name of the attribute finder class. - */ - public void clearAttributeFinderCache(String attributeFinder) { - - Map designators = EntitlementServiceComponent.getEntitlementConfig() - .getDesignators(); - if (designators != null && !designators.isEmpty()) { - Set pipAttributeFinders = designators.keySet(); - for (PIPAttributeFinder pipAttributeFinder : pipAttributeFinders) { - if (pipAttributeFinder instanceof AbstractPIPAttributeFinder) { - if (pipAttributeFinder.getClass().getCanonicalName().equals(attributeFinder)) { - pipAttributeFinder.clearCache(); - break; - } - } - } - } - } - - /** - * Clears the cache maintained by the attribute finder - by attributes - * - * @param attributeFinder Canonical name of the attribute finder class. - * @param attributeIds An array of attribute id. - */ - public void clearAttributeFinderCacheByAttributes(String attributeFinder, String[] attributeIds) { - - Map designators = EntitlementServiceComponent.getEntitlementConfig() - .getDesignators(); - if (designators != null && !designators.isEmpty()) { - Set pipAttributeFinders = designators.keySet(); - for (PIPAttributeFinder pipAttributeFinder : pipAttributeFinders) { - if (pipAttributeFinder.getClass().getCanonicalName().equals(attributeFinder)) { - pipAttributeFinder.clearCache(attributeIds); - break; - } - } - } - } - - /** - * Clears Carbon resource finder cache and All the resource cache implementations in each - * PIP resource finder level - * - * @throws EntitlementException throws - */ - public void clearAllResourceCaches() throws EntitlementException { - CarbonResourceFinder finder = EntitlementEngine.getInstance().getCarbonResourceFinder(); - if (finder != null) { - finder.clearAttributeCache(); - // we need invalidate decision cache as well. - clearDecisionCache(); - } else { - throw new EntitlementException("Can not clear attribute cache - Carbon Attribute Finder " - + "is not initialized"); - } - } - - /** - * Clears the carbon resource cache - * - * @throws EntitlementException throws - */ - public void clearCarbonResourceCache() throws EntitlementException { - CarbonResourceFinder finder = EntitlementEngine.getInstance().getCarbonResourceFinder(); - if (finder != null) { - finder.clearAttributeCache(); - // we need invalidate decision cache as well. - clearDecisionCache(); - } else { - throw new EntitlementException("Can not clear attribute cache - Carbon Attribute Finder " - + "is not initialized"); - } - - Map resourceConfigs = EntitlementServiceComponent.getEntitlementConfig() - .getResourceFinders(); - if (resourceConfigs != null && !resourceConfigs.isEmpty()) { - Set resourceFinders = resourceConfigs.keySet(); - for (PIPResourceFinder pipResourceFinder : resourceFinders) { - pipResourceFinder.clearCache(); - } - } - } - - /** - * Clears the cache maintained by the resource finder. - * - * @param resourceFinder Canonical name of the resource finder class. - */ - public void clearResourceFinderCache(String resourceFinder) { - - Map resourceConfigs = EntitlementServiceComponent.getEntitlementConfig() - .getResourceFinders(); - if (resourceConfigs != null && !resourceConfigs.isEmpty()) { - Set resourceFinders = resourceConfigs.keySet(); - for (PIPResourceFinder pipResourceFinder : resourceFinders) { - if (resourceFinder.getClass().getCanonicalName().equals(resourceFinder)) { - pipResourceFinder.clearCache(); - break; - } - } - } - } - - - /** - * Refreshes the supported Attribute ids of a given attribute finder module - * - * @param attributeFinder Canonical name of the attribute finder class. - * @throws EntitlementException throws if fails to refresh - */ - public void refreshAttributeFinder(String attributeFinder) throws EntitlementException { - - Map designators = EntitlementServiceComponent.getEntitlementConfig() - .getDesignators(); - if (attributeFinder != null && designators != null && !designators.isEmpty()) { - Set> pipAttributeFinders = designators.entrySet(); - for (Map.Entry entry : pipAttributeFinders) { - if (attributeFinder.equals(entry.getKey().getClass().getName()) || - attributeFinder.equals(entry.getKey().getModuleName())) { - try { - entry.getKey().init(entry.getValue()); - entry.getKey().clearCache(); - CarbonAttributeFinder carbonAttributeFinder = EntitlementEngine. - getInstance().getCarbonAttributeFinder(); - carbonAttributeFinder.init(); - } catch (Exception e) { - throw new EntitlementException("Error while refreshing attribute finder - " + - attributeFinder); - } - break; - } - } - } - } - - /** - * Refreshes the supported resource id of a given resource finder module - * - * @param resourceFinder Canonical name of the resource finder class. - * @throws EntitlementException throws if fails to refresh - */ - public void refreshResourceFinder(String resourceFinder) throws EntitlementException { - - Map resourceFinders = EntitlementServiceComponent.getEntitlementConfig() - .getResourceFinders(); - if (resourceFinder != null && resourceFinders != null && !resourceFinders.isEmpty()) { - for (Map.Entry entry : resourceFinders.entrySet()) { - if (resourceFinder.equals(entry.getKey().getClass().getName()) || - resourceFinder.equals(entry.getKey().getModuleName())) { - try { - entry.getKey().init(entry.getValue()); - entry.getKey().clearCache(); - CarbonAttributeFinder carbonAttributeFinder = EntitlementEngine. - getInstance().getCarbonAttributeFinder(); - carbonAttributeFinder.init(); - } catch (Exception e) { - throw new EntitlementException("Error while refreshing attribute finder - " + - resourceFinder); - } - break; - } - } - } - } - - /** - * Refreshes the supported resource id of a given resource finder module - * - * @param policyFinder Canonical name of the resource finder class. - * @throws EntitlementException throws if fails to refresh - */ - public void refreshPolicyFinders(String policyFinder) throws EntitlementException { - - Map policyFinders = EntitlementServiceComponent.getEntitlementConfig() - .getPolicyFinderModules(); - if (policyFinder != null && policyFinders != null && !policyFinders.isEmpty()) { - for (Map.Entry entry : policyFinders.entrySet()) { - if (policyFinder.equals(entry.getKey().getClass().getName()) || - policyFinder.equals(entry.getKey().getModuleName())) { - try { - entry.getKey().init(entry.getValue()); - EntitlementEngine.getInstance().getCarbonPolicyFinder().init(); - // need to re init all policy finder modules in the cluster. - // therefore calling invalidation cache - EntitlementEngine.getInstance().clearDecisionCache(); - } catch (Exception e) { - throw new EntitlementException("Error while refreshing attribute finder - " + - policyFinder); - } - break; - } - } - } - } - - - /** - * Tests engine of PAP policy store - * - * @param xacmlRequest - * @return - * @throws EntitlementException - */ - public String doTestRequest(String xacmlRequest) throws EntitlementException { - return EntitlementEngine.getInstance().test(xacmlRequest); - } - - /** - * Tests engine of PAP policy store - * - * @param xacmlRequest - * @param policies policy ids that is evaluated - * @return - * @throws EntitlementException - */ - public String doTestRequestForGivenPolicies(String xacmlRequest, String[] policies) - throws EntitlementException { - EntitlementEngine engine = EntitlementEngine.getInstance(); - PAPPolicyFinder papPolicyFinder = (PAPPolicyFinder) engine.getPapPolicyFinder(). - getModules().iterator().next(); - papPolicyFinder.setPolicyIds(Arrays.asList(policies)); - String response = EntitlementEngine.getInstance().test(xacmlRequest); - papPolicyFinder.initPolicyIds(); - - return response; - } - - /** - * @return - */ - public PDPDataHolder getPDPData() { - - PDPDataHolder pdpDataHolder = new PDPDataHolder(); - - Map finderModules = EntitlementServiceComponent. - getEntitlementConfig().getPolicyFinderModules(); - Map attributeModules = EntitlementServiceComponent. - getEntitlementConfig().getDesignators(); - Map resourceModules = EntitlementServiceComponent. - getEntitlementConfig().getResourceFinders(); - - if (finderModules != null) { - List list = new ArrayList(); - for (Map.Entry entry : finderModules.entrySet()) { - PolicyFinderModule module = entry.getKey(); - if (module != null) { - if (module.getModuleName() != null) { - list.add(module.getModuleName()); - } else { - list.add(module.getClass().getName()); - } - } - } - pdpDataHolder.setPolicyFinders(list.toArray(new String[list.size()])); - } - - if (attributeModules != null) { - List list = new ArrayList(); - for (Map.Entry entry : attributeModules.entrySet()) { - PIPAttributeFinder module = entry.getKey(); - if (module != null) { - if (module.getModuleName() != null) { - list.add(module.getModuleName()); - } else { - list.add(module.getClass().getName()); - } - } - } - pdpDataHolder.setPipAttributeFinders(list.toArray(new String[list.size()])); - } - - if (resourceModules != null) { - List list = new ArrayList(); - for (Map.Entry entry : resourceModules.entrySet()) { - PIPResourceFinder module = entry.getKey(); - if (module != null) { - if (module.getModuleName() != null) { - list.add(module.getModuleName()); - } else { - list.add(module.getClass().getName()); - } - } - } - pdpDataHolder.setPipResourceFinders(list.toArray(new String[list.size()])); - } - - return pdpDataHolder; - } - - /** - * @param finder - * @return - */ - public PolicyFinderDataHolder getPolicyFinderData(String finder) { - - PolicyFinderDataHolder holder = null; - // get registered finder modules - Map finderModules = EntitlementServiceComponent. - getEntitlementConfig().getPolicyFinderModules(); - if (finderModules == null || finder == null) { - return null; - } - - for (Map.Entry entry : finderModules.entrySet()) { - PolicyFinderModule module = entry.getKey(); - if (module != null && (finder.equals(module.getModuleName()) || - finder.equals(module.getClass().getName()))) { - holder = new PolicyFinderDataHolder(); - if (module.getModuleName() != null) { - holder.setModuleName(module.getModuleName()); - } else { - holder.setModuleName(module.getClass().getName()); - } - holder.setClassName(module.getClass().getName()); - holder.setPolicyIdentifiers(module.getOrderedPolicyIdentifiers()); - break; - } - - } - return holder; - } - - /** - * @param finder - * @return - */ - public PIPFinderDataHolder getPIPAttributeFinderData(String finder) { - - PIPFinderDataHolder holder = null; - // get registered finder modules - Map attributeModules = EntitlementServiceComponent. - getEntitlementConfig().getDesignators(); - if (attributeModules == null || finder == null) { - return null; - } - - for (Map.Entry entry : attributeModules.entrySet()) { - PIPAttributeFinder module = entry.getKey(); - if (module != null && (finder.equals(module.getModuleName()) || - finder.equals(module.getClass().getName()))) { - holder = new PIPFinderDataHolder(); - if (module.getModuleName() != null) { - holder.setModuleName(module.getModuleName()); - } else { - holder.setModuleName(module.getClass().getName()); - } - holder.setClassName(module.getClass().getName()); - holder.setSupportedAttributeIds(module.getSupportedAttributes(). - toArray(new String[module.getSupportedAttributes().size()])); - break; - } - } - return holder; - } - - /** - * @param finder - * @return - */ - public PIPFinderDataHolder getPIPResourceFinderData(String finder) { - - PIPFinderDataHolder holder = null; - // get registered finder modules - Map resourceModules = EntitlementServiceComponent. - getEntitlementConfig().getResourceFinders(); - - if (resourceModules == null || finder == null) { - return null; - } - - for (Map.Entry entry : resourceModules.entrySet()) { - PIPResourceFinder module = entry.getKey(); - if (module != null) { - holder = new PIPFinderDataHolder(); - if (module.getModuleName() != null) { - holder.setModuleName(module.getModuleName()); - } else { - holder.setModuleName(module.getClass().getName()); - } - holder.setClassName(module.getClass().getName()); - break; - } - } - return holder; - } - - /** - * Gets globally defined policy combining algorithm - * - * @return policy combining algorithm as a String - * @throws EntitlementException throws - */ - public String getGlobalPolicyAlgorithm() throws EntitlementException { - - ConfigPersistenceManager configPersistenceManager = EntitlementAdminEngine.getInstance().getConfigPersistenceManager(); - return configPersistenceManager.getGlobalPolicyAlgorithmName(); - } - - /** - * Sets policy combining algorithm globally - * - * @param policyCombiningAlgorithm policy combining algorithm as a String - * @throws EntitlementException throws - */ - public void setGlobalPolicyAlgorithm(String policyCombiningAlgorithm) throws EntitlementException { - - ConfigPersistenceManager configPersistenceManager = EntitlementAdminEngine.getInstance().getConfigPersistenceManager(); - configPersistenceManager.addOrUpdateGlobalPolicyAlgorithm(policyCombiningAlgorithm); - clearPolicyCache(); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/EntitlementException.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/EntitlementException.java deleted file mode 100644 index 4c8fc2db7e63..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/EntitlementException.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.entitlement; - -public class EntitlementException extends Exception { - - private static final long serialVersionUID = 4671622091461340493L; - private String message; - - public EntitlementException(String message, Throwable cause) { - super(message, cause); - this.message = message; - } - - public EntitlementException(String message) { - super(message); - this.message = message; - } - - public String getMessage() { - return message; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/EntitlementLRUCache.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/EntitlementLRUCache.java deleted file mode 100644 index b5e5edd22230..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/EntitlementLRUCache.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.entitlement; - -import java.util.LinkedHashMap; -import java.util.Map; - -/** - * This is a simple LRU cache, based on LinkedHashMap. If the cache is full and another - * entry is added, the least recently used entry is dropped. - */ -public class EntitlementLRUCache extends LinkedHashMap { - - private static final long serialVersionUID = -1308554805704597171L; - private final static int INITIAL_CACHE_CAPACITY = 16; - private final static float LOAD_FACTOR = 75f; - private int cacheSize; - - public EntitlementLRUCache(int cacheSize) { - super(INITIAL_CACHE_CAPACITY, LOAD_FACTOR, true); - this.cacheSize = cacheSize; - } - - @Override - protected boolean removeEldestEntry(Map.Entry eldest) { - // oldest entry of the cache would be removed when max cache size become - return size() == this.cacheSize; - } - -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/EntitlementNotificationExtension.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/EntitlementNotificationExtension.java deleted file mode 100644 index 63147eb76fba..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/EntitlementNotificationExtension.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - *Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - *WSO2 Inc. 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.wso2.carbon.identity.entitlement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.entitlement.common.EntitlementConstants; -import org.wso2.carbon.identity.entitlement.dto.StatusHolder; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; -import org.wso2.carbon.identity.notification.mgt.NotificationManagementException; -import org.wso2.carbon.identity.notification.mgt.NotificationSender; -import org.wso2.carbon.identity.notification.mgt.bean.PublisherEvent; - -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -/** - * This is an extension module that can be used to send policy update statuses as notifications. - * This extension will trigger notifications on policy changes only if this extension is - * registered in entitlement.properties file. - */ -@SuppressWarnings("unused") -public class EntitlementNotificationExtension implements PAPStatusDataHandler { - - private static final Log log = LogFactory.getLog(EntitlementNotificationExtension.class); - private final String eventName = "policyUpdate"; - private boolean pdpUpdate = true; - private boolean papUpdate = false; - private List pdpActions = new ArrayList(); - - /** - * At the initialization a property map which carries relevant properties to this extension - * will be passed and class variables will be set from those properties. - * - * @param properties properties - */ - @Override - public void init(Properties properties) { - - if (log.isDebugEnabled()) { - log.debug("Initiating Entitlement Notification Extension"); - } - // Reading properties and setting to default values if properties are not found - String pdpUpdateProperty = properties.getProperty(NotificationConstants - .PDP_NOTIFICATION_PROPERTY_LABEL); - String papNotificationProperty = properties.getProperty(NotificationConstants - .PAP_NOTIFICATION_PROPERTY_LABEL); - - if (pdpUpdateProperty != null && !pdpUpdateProperty.trim().isEmpty()) { - pdpUpdate = Boolean.parseBoolean(pdpUpdateProperty); - } // Else default value of false - - // only pap policy updates - if (papNotificationProperty != null && !papNotificationProperty.trim().isEmpty()) { - papUpdate = Boolean.parseBoolean(papNotificationProperty); - } - //Else default value of false - - // pdp action - String pdpActionUpdate = properties.getProperty(NotificationConstants - .PDP_NOTIFICATION_ACTION_PROPERTY_LABEL); - if (pdpActionUpdate != null) { - String[] pdpActionUpdates = pdpActionUpdate.split(";"); - for (String update : pdpActionUpdates) { - pdpActions.add(update.trim()); - } - } // Else will have an empty list - } - - @Override - public void handle(String about, String key, List statusHolder) throws - EntitlementException { - // If status is about policy return. - if (EntitlementConstants.Status.ABOUT_POLICY.equalsIgnoreCase(about)) { - return; - } - if (statusHolder != null) { - for (StatusHolder holder : statusHolder) { - handle(about, holder); - } - } - } - - /** - * handler will decide the process depending on the status in status holder - * - * @param about indicates what is related with this admin status action - * @param statusHolder StatusHolder - * @throws EntitlementException - */ - @Override - public void handle(String about, StatusHolder statusHolder) throws EntitlementException { - - if (!EntitlementConstants.Status.ABOUT_POLICY.equalsIgnoreCase(about)) { - return; - } - - String action = null; - String typeOfAction = statusHolder.getType(); - - //If papUpdate notifications are enabled through entitlement.properties - if (papUpdate) { - if (EntitlementConstants.StatusTypes.UPDATE_POLICY.equals(typeOfAction)) { - action = NotificationConstants.ACTION_LABEL_UPDATE; - } else if (EntitlementConstants.StatusTypes.DELETE_POLICY.equals(typeOfAction)) { - action = NotificationConstants.ACTION_LABEL_DELETE; - } else if (EntitlementConstants.StatusTypes.ADD_POLICY.equals(typeOfAction)) { - action = NotificationConstants.ACTION_LABEL_CREATE; - } - } - - //if pdpUpdate properties are enabled through entitlement.properties - if (pdpUpdate && action == null) { - - if (EntitlementConstants.StatusTypes.PUBLISH_POLICY.equals(typeOfAction)) { - action = statusHolder.getTargetAction(); - } - if (action == null || (pdpActions.size() > 0 && !pdpActions.contains(action))) { - return; - } - if (EntitlementConstants.PolicyPublish.ACTION_CREATE.equals(action) || - EntitlementConstants.PolicyPublish.ACTION_UPDATE.equals(action)) { - action = NotificationConstants.ACTION_LABEL_UPDATE; - } - } - - if (action == null) { - return; - } - // Setting up properties and configuration object to be sent to the NotificationSender, - // which is consumed by all subscribed Message Sending Modules - NotificationSender notificationSender = EntitlementServiceComponent.getNotificationSender(); - - if (notificationSender != null) { - try { - PublisherEvent event = new PublisherEvent(eventName); - event.addEventProperty(NotificationConstants.TARGET_ID_PROPERTY_LABEL, statusHolder.getKey()); - event.addEventProperty(NotificationConstants.USERNAME_PROPERTY_LABEL, statusHolder.getUser()); - event.addEventProperty(NotificationConstants.TARGET_PROPERTY_LABEL, statusHolder.getTarget()); - event.addEventProperty(NotificationConstants.ACTION_PROPERTY_LABEL, action); - if (log.isDebugEnabled()) { - log.debug("Invoking notification sender"); - } - notificationSender.invoke(event); - } catch (NotificationManagementException e) { - log.error("Error while invoking notification sender", e); - } - } else { - if (log.isDebugEnabled()) { - log.error("No registered notification sending service found"); - } - } - } - - @Override - public StatusHolder[] getStatusData(String about, String key, String type, - String searchString) throws EntitlementException { - return new StatusHolder[0]; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/EntitlementPolicyAdminService.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/EntitlementPolicyAdminService.java deleted file mode 100644 index fffc973e122c..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/EntitlementPolicyAdminService.java +++ /dev/null @@ -1,955 +0,0 @@ -/* - * Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.entitlement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.balana.AbstractPolicy; -import org.wso2.carbon.base.ServerConfiguration; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.context.RegistryType; -import org.wso2.carbon.identity.entitlement.common.EntitlementConstants; -import org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerFactory; -import org.wso2.carbon.identity.entitlement.persistence.PolicyPersistenceManager; -import org.wso2.carbon.identity.entitlement.persistence.SubscriberPersistenceManager; -import org.wso2.carbon.identity.entitlement.dto.AttributeDTO; -import org.wso2.carbon.identity.entitlement.dto.EntitlementFinderDataHolder; -import org.wso2.carbon.identity.entitlement.dto.EntitlementTreeNodeDTO; -import org.wso2.carbon.identity.entitlement.dto.PaginatedPolicySetDTO; -import org.wso2.carbon.identity.entitlement.dto.PaginatedStatusHolder; -import org.wso2.carbon.identity.entitlement.dto.PaginatedStringDTO; -import org.wso2.carbon.identity.entitlement.dto.PolicyDTO; -import org.wso2.carbon.identity.entitlement.dto.PublisherDataHolder; -import org.wso2.carbon.identity.entitlement.dto.StatusHolder; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; -import org.wso2.carbon.identity.entitlement.pap.EntitlementAdminEngine; -import org.wso2.carbon.identity.entitlement.pap.EntitlementDataFinder; -import org.wso2.carbon.identity.entitlement.pap.PAPPolicyReader; -import org.wso2.carbon.identity.entitlement.pap.store.PAPPolicyStoreManager; -import org.wso2.carbon.identity.entitlement.policy.publisher.PolicyPublisher; -import org.wso2.carbon.identity.entitlement.policy.publisher.PolicyPublisherModule; -import org.wso2.carbon.registry.core.Registry; -import org.wso2.carbon.registry.core.Resource; -import org.wso2.carbon.registry.core.exceptions.RegistryException; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.regex.PatternSyntaxException; - -/** - * Entitlement Admin Service Class which exposes the PAP - */ -public class EntitlementPolicyAdminService { - - private static Log log = LogFactory.getLog(EntitlementPolicyAdminService.class); - - - /** - * Add a new XACML policy in to the system. - * - * @param policyDTO policy object - * @throws EntitlementException throws - */ - public void addPolicy(PolicyDTO policyDTO) throws EntitlementException { - - addOrUpdatePolicy(policyDTO, true); - - } - - - /** - * Adds XACML policies in bulk to the system. - * - * @param policies Array of policies. - * @throws EntitlementException throws - */ - public void addPolicies(PolicyDTO[] policies) throws EntitlementException { - - if (policies != null) { - for (PolicyDTO policyDTO : policies) { - addOrUpdatePolicy(policyDTO, true); - } - } else { - throw new EntitlementException("No Entitlement policies are provided."); - } - } - - /** - * This method finds the policy file from given registry path and adds the policy - * - * @deprecated since the functionality cannot be support by the rdbms based implementation - * @param policyRegistryPath given registry path - * @throws org.wso2.carbon.identity.entitlement.EntitlementException throws when fails or registry error occurs - */ - public void importPolicyFromRegistry(String policyRegistryPath) throws EntitlementException { - - Registry registry; - PolicyDTO policyDTO = new PolicyDTO(); - String policy = ""; - BufferedReader bufferedReader = null; - InputStream inputStream = null; - - // Finding from which registry by comparing prefix of resource path - String resourceUri = policyRegistryPath.substring(policyRegistryPath.lastIndexOf(':') + 1); - String registryIdentifier = policyRegistryPath.substring(0, - policyRegistryPath.lastIndexOf(':')); - if ("conf".equals(registryIdentifier)) { - registry = (Registry) CarbonContext.getThreadLocalCarbonContext(). - getRegistry(RegistryType.SYSTEM_CONFIGURATION); - } else { - registry = (Registry) CarbonContext.getThreadLocalCarbonContext(). - getRegistry(RegistryType.SYSTEM_GOVERNANCE); - } - - try { - Resource resource = registry.get(resourceUri); - inputStream = resource.getContentStream(); - bufferedReader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8"))); - String stringLine; - StringBuilder buffer = new StringBuilder(policy); - while ((stringLine = bufferedReader.readLine()) != null) { - buffer.append(stringLine); - } - policy = buffer.toString(); - policyDTO.setPolicy(policy.replaceAll(">\\s+<", "><")); - addOrUpdatePolicy(policyDTO, true); - } catch (RegistryException e) { - log.error("Registry Error occurs while reading policy from registry", e); - throw new EntitlementException("Error loading policy from carbon registry"); - } catch (IOException e) { - log.error("I/O Error occurs while reading policy from registry", e); - throw new EntitlementException("Error loading policy from carbon registry"); - } finally { - if (bufferedReader != null) { - try { - bufferedReader.close(); - } catch (IOException e) { - log.error("Error occurs while closing inputStream", e); - } - } - if (inputStream != null) { - try { - inputStream.close(); - } catch (IOException e) { - log.error("Error occurs while closing inputStream", e); - } - } - } - } - - /** - * Updates given policy - * - * @param policyDTO policy object - * @throws EntitlementException throws if invalid policy - */ - public void updatePolicy(PolicyDTO policyDTO) throws EntitlementException { - - addOrUpdatePolicy(policyDTO, false); - - } - - - /** - * This method paginates policies - * - * @param policyTypeFilter policy type to filter - * @param policySearchString policy search String - * @param pageNumber page number - * @param isPDPPolicy whether this is a PDP policy or PAP policy - * @return paginated and filtered policy set - * @throws org.wso2.carbon.identity.entitlement.EntitlementException throws - */ - public PaginatedPolicySetDTO getAllPolicies(String policyTypeFilter, String policySearchString, - int pageNumber, boolean isPDPPolicy) throws EntitlementException { - - List policyDTOList = new ArrayList(); - PolicyDTO[] policyDTOs = null; - - if (isPDPPolicy) { - policyDTOs = EntitlementAdminEngine. - getInstance().getPolicyStoreManager().getLightPolicies(); - } else { - policyDTOs = EntitlementAdminEngine.getInstance(). - getPapPolicyStoreManager().getAllLightPolicyDTOs(); - } - policySearchString = policySearchString.replace("*", ".*"); - Pattern pattern = Pattern.compile(policySearchString, Pattern.CASE_INSENSITIVE); - for (PolicyDTO policyDTO : policyDTOs) { - boolean useAttributeFiler = false; - // Filter out policies based on policy type - if (!policyTypeFilter.equals(EntitlementConstants.PolicyType.POLICY_ALL) - && (!policyTypeFilter.equals(policyDTO.getPolicyType()) && - !(EntitlementConstants.PolicyType.POLICY_ENABLED.equals(policyTypeFilter) && - policyDTO.isActive()) && - !(EntitlementConstants.PolicyType.POLICY_DISABLED.equals(policyTypeFilter) && - !policyDTO.isActive()))) { - continue; - } - - if (policySearchString != null && policySearchString.trim().length() > 0) { - - if (!isPDPPolicy) { - // Filter out policies based on attribute value - PolicyDTO metaDataPolicyDTO = EntitlementAdminEngine.getInstance(). - getPapPolicyStoreManager().getMetaDataPolicy(policyDTO.getPolicyId()); - AttributeDTO[] attributeDTOs = metaDataPolicyDTO.getAttributeDTOs(); - if (attributeDTOs != null) { - for (AttributeDTO attributeDTO : attributeDTOs) { - if (policySearchString.equalsIgnoreCase(attributeDTO.getAttributeValue())) { - useAttributeFiler = true; - break; - } - } - } - } - - if (!useAttributeFiler) { - // Filter out policies based on policy Search String - if (policySearchString.trim().length() > 0) { - Matcher matcher = pattern.matcher(policyDTO.getPolicyId()); - if (!matcher.matches()) { - continue; - } - } - } - } - - policyDTOList.add(policyDTO); - } - - // Do the pagination and return the set of policies. - return doPaging(pageNumber, policyDTOList.toArray(new PolicyDTO[policyDTOList.size()])); - } - - /** - * Gets policy for given policy id - * - * @param policyId policy id - * @param isPDPPolicy whether policy is PDP policy or PAP policy - * @return returns policy - * @throws EntitlementException throws - */ - public PolicyDTO getPolicy(String policyId, boolean isPDPPolicy) throws EntitlementException { - - PolicyDTO policyDTO = null; - - if (isPDPPolicy) { - policyDTO = EntitlementAdminEngine.getInstance(). - getPolicyStoreManager().getPolicy(policyId); - } else { - try { - policyDTO = EntitlementAdminEngine.getInstance(). - getPapPolicyStoreManager().getPolicy(policyId); - } catch (EntitlementException e) { - policyDTO = new PolicyDTO(); - policyDTO.setPolicy(policyId); - handleStatus(EntitlementConstants.StatusTypes.GET_POLICY, policyDTO, false, e.getMessage()); - throw e; - } - handleStatus(EntitlementConstants.StatusTypes.GET_POLICY, policyDTO, true, null); - } - - return policyDTO; - } - - /** - * Gets policy for given policy id and version - * - * @param policyId policy id - * @param version version of policy - * @return returns policy - * @throws org.wso2.carbon.identity.entitlement.EntitlementException throws - */ - public PolicyDTO getPolicyByVersion(String policyId, String version) throws EntitlementException { - - PolicyDTO policyDTO = null; - - try { - PolicyPersistenceManager policyStore = EntitlementAdminEngine.getInstance().getPolicyPersistenceManager(); - policyDTO = policyStore.getPolicy(policyId, version); - } catch (EntitlementException e) { - policyDTO = new PolicyDTO(); - policyDTO.setPolicy(policyId); - handleStatus(EntitlementConstants.StatusTypes.GET_POLICY, policyDTO, false, e.getMessage()); - throw e; - } - - handleStatus(EntitlementConstants.StatusTypes.GET_POLICY, policyDTO, true, null); - - return policyDTO; - } - - /** - * Gets light weight policy DTO for given policy id - * - * @param policyId policy id - * @return returns policy - * @throws org.wso2.carbon.identity.entitlement.EntitlementException throws - */ - public PolicyDTO getLightPolicy(String policyId) throws EntitlementException { - - return EntitlementAdminEngine.getInstance(). - getPapPolicyStoreManager().getLightPolicy(policyId); - - } - - /** - * Removes policy for given policy object - * - * @param policyIds A Array of policy ids - * @param dePromote whether these policy must be removed from PDP as well - * @throws EntitlementException throws if fails - */ - public void removePolicies(String[] policyIds, boolean dePromote) throws EntitlementException { - - if (policyIds == null || policyIds.length == 0) { - throw new EntitlementException("No Entitlement policyId has been provided."); - } - - for (String policyId : policyIds) { - removePolicy(policyId, dePromote); - } - } - - - /** - * Removes policy for given policy object - * - * @param policyId policyId - * @param dePromote whether these policy must be removed from PDP as well - * @throws EntitlementException throws - */ - public void removePolicy(String policyId, boolean dePromote) throws EntitlementException { - - if (policyId == null) { - throw new EntitlementException("Entitlement PolicyId can not be null."); - } - PAPPolicyStoreManager policyAdmin = EntitlementAdminEngine.getInstance().getPapPolicyStoreManager(); - PolicyDTO oldPolicy = null; - - try { - try { - oldPolicy = getPolicy(policyId, false); - } catch (Exception e) { - // exception is ignore. as unwanted details are throws - } - if (oldPolicy == null) { - oldPolicy = new PolicyDTO(); - oldPolicy.setPolicyId(policyId); - } - policyAdmin.removePolicy(policyId); - } catch (EntitlementException e) { - oldPolicy = new PolicyDTO(); - oldPolicy.setPolicyId(policyId); - handleStatus(EntitlementConstants.StatusTypes.DELETE_POLICY, oldPolicy, false, e.getMessage()); - throw e; - } - handleStatus(EntitlementConstants.StatusTypes.DELETE_POLICY, oldPolicy, true, null); - - // policy remove from PDP. this is done by separate thread - if (dePromote) { - publishToPDP(new String[]{policyId}, null, - EntitlementConstants.PolicyPublish.ACTION_DELETE); - } - } - - /** - * This method returns the list of policy id available in PDP - * - * @param searchString search String - * @return list of ids - * @throws EntitlementException throws - */ - public String[] getAllPolicyIds(String searchString) throws EntitlementException { - - String[] policyIds = EntitlementAdminEngine.getInstance().getPapPolicyStoreManager().getPolicyIds(); - - if (searchString == null || searchString.isEmpty()) { - return policyIds; - } - - String replacedSearchString = searchString.replace("*", ".*"); - Pattern pattern; - try { - pattern = Pattern.compile(replacedSearchString, Pattern.CASE_INSENSITIVE); - } catch (PatternSyntaxException e) { - if (log.isDebugEnabled()) { - log.debug("Error while compiling pattern with search string: " + replacedSearchString, e); - } - throw new EntitlementException("Invalid search string: " + searchString); - } - - List filteredPolicyIds = new ArrayList<>(); - for (String policyId : policyIds) { - Matcher matcher = pattern.matcher(policyId); - if (matcher.matches()) { - filteredPolicyIds.add(policyId); - } - } - return filteredPolicyIds.toArray(new String[filteredPolicyIds.size()]); - } - - - /** - * Gets subscriber details - * - * @param subscribeId subscriber id - * @return subscriber details as SubscriberDTO - * @throws EntitlementException throws, if any error - */ - public PublisherDataHolder getSubscriber(String subscribeId) throws EntitlementException { - - SubscriberPersistenceManager subscriberManager = EntitlementAdminEngine.getInstance().getSubscriberPersistenceManager(); - return subscriberManager.getSubscriber(subscribeId, false); - } - - /** - * Gets all subscribers ids that is registered, - * - * @param searchString search String - * @return subscriber's ids as String array - * @throws EntitlementException throws, if fails - */ - public String[] getSubscriberIds(String searchString) throws EntitlementException { - SubscriberPersistenceManager subscriberManager = EntitlementAdminEngine.getInstance().getSubscriberPersistenceManager(); - String[] ids = subscriberManager.listSubscriberIds(searchString).toArray(new String[0]); - if (ids.length != 0) { - return ids; - } else { - return new String[0]; - } - } - - /** - * Add subscriber details in to registry - * - * @param holder subscriber data as PublisherDataHolder object - * @throws EntitlementException throws, if fails - */ - public void addSubscriber(PublisherDataHolder holder) throws EntitlementException { - - SubscriberPersistenceManager subscriberManager = EntitlementAdminEngine.getInstance().getSubscriberPersistenceManager(); - subscriberManager.addSubscriber(holder); - - } - - /** - * Update subscriber details in registry - * - * @param holder subscriber data as PublisherDataHolder object - * @throws EntitlementException throws, if fails - */ - public void updateSubscriber(PublisherDataHolder holder) throws EntitlementException { - - SubscriberPersistenceManager subscriberManager = EntitlementAdminEngine.getInstance().getSubscriberPersistenceManager(); - subscriberManager.updateSubscriber(holder); - - } - - /** - * delete subscriber details from registry - * - * @param subscriberId subscriber id - * @throws EntitlementException throws, if fails - */ - public void deleteSubscriber(String subscriberId) throws EntitlementException { - - SubscriberPersistenceManager subscriberManager = EntitlementAdminEngine.getInstance().getSubscriberPersistenceManager(); - subscriberManager.removeSubscriber(subscriberId); - - } - - /** - * Publishes given set of policies to all subscribers - * - * @param policyIds policy ids to publish, if null or empty, all policies are published - * @param subscriberIds subscriber ids to publish, if null or empty, all policies are published - * @param action publishing action - * @param version version - * @param enabled whether policy must be enabled or not - * @param order order of the policy - * @throws EntitlementException throws, if fails - */ - public void publishPolicies(String[] policyIds, String[] subscriberIds, String action, String version, - boolean enabled, int order) throws EntitlementException { - - PolicyPublisher publisher = EntitlementAdminEngine.getInstance().getPolicyPublisher(); - if (policyIds == null || policyIds.length < 1) { - policyIds = EntitlementAdminEngine.getInstance().getPapPolicyStoreManager().getPolicyIds(); - } - if (subscriberIds == null || subscriberIds.length < 1) { - SubscriberPersistenceManager subscriberManager = EntitlementAdminEngine.getInstance().getSubscriberPersistenceManager(); - subscriberIds = subscriberManager.listSubscriberIds("*").toArray(new String[0]); - } - - if (policyIds == null || policyIds.length < 1) { - throw new EntitlementException("There are no policies to publish"); - } - - if (subscriberIds.length < 1) { - throw new EntitlementException("There are no subscribers to publish"); - } - - publisher.publishPolicy(policyIds, version, action, enabled, order, subscriberIds, null); - } - - /** - * Publishes given set of policies to all subscribers - * - * @param verificationCode verification code that is received by administrator to publish - * @throws EntitlementException throws, if fails - */ - public void publish(String verificationCode) throws EntitlementException { - - PolicyPublisher publisher = EntitlementAdminEngine.getInstance().getPolicyPublisher(); - publisher.publishPolicy(null, null, null, false, 0, null, verificationCode); - - } - - /** - * @param policyIds - * @throws EntitlementException - */ - private void publishToPDP(String[] policyIds, String version, - String action) throws EntitlementException { - - PolicyPublisher publisher = EntitlementAdminEngine.getInstance().getPolicyPublisher(); - String[] subscribers = new String[]{EntitlementConstants.PDP_SUBSCRIBER_ID}; - publisher.publishPolicy(policyIds, version, action, false, 0, subscribers, null); - } - - /** - * @param policyIds - * @throws EntitlementException - */ - public void publishToPDP(String[] policyIds, String action, String version, boolean enabled, - int order) throws EntitlementException { - - PolicyPublisher publisher = EntitlementAdminEngine.getInstance().getPolicyPublisher(); - String[] subscribers = new String[]{EntitlementConstants.PDP_SUBSCRIBER_ID}; - publisher.publishPolicy(policyIds, version, action, enabled, order, subscribers, null); - } - - /** - * @param policyId - * @param version - */ - public void rollBackPolicy(String policyId, String version) throws EntitlementException { - - PolicyPersistenceManager policyStore = EntitlementAdminEngine.getInstance().getPolicyPersistenceManager(); - PolicyDTO policyDTO = policyStore.getPolicy(policyId, version); - addOrUpdatePolicy(policyDTO, false); - - } - - /** - * @param type - * @param key - * @return - */ - public PaginatedStatusHolder getStatusData(String about, String key, String type, - String searchString, int pageNumber) throws EntitlementException { - - PAPStatusDataHandler dataRetrievingHandler = null; - Set handlers = EntitlementAdminEngine.getInstance(). - getPapStatusDataHandlers(); - for (PAPStatusDataHandler handler : handlers) { - if (PersistenceManagerFactory.getPAPStatusDataHandler().getClass().isInstance(handler)) { - dataRetrievingHandler = handler; - break; - } - } - - if (dataRetrievingHandler == null) { - throw new EntitlementException("No Status Data Handler is defined for data retrieving"); - } - StatusHolder[] holders = dataRetrievingHandler.getStatusData(about, key, type, searchString); - return doPaging(pageNumber, holders); - } - - - /** - * Gets policy publisher module data to populate in the UI - * - * @return - */ - public PublisherDataHolder[] getPublisherModuleData() { - - List holders = EntitlementServiceComponent. - getEntitlementConfig().getModulePropertyHolders(PolicyPublisherModule.class.getName()); - if (holders != null) { - return holders.toArray(new PublisherDataHolder[holders.size()]); - } - - return null; - } - - - /** - * @param dataModule - * @param category - * @param regexp - * @param dataLevel - * @param limit - * @return - */ - public EntitlementTreeNodeDTO getEntitlementData(String dataModule, String category, - String regexp, int dataLevel, int limit) { - - EntitlementDataFinder dataFinder = EntitlementAdminEngine.getInstance().getEntitlementDataFinder(); - return dataFinder.getEntitlementData(dataModule, category, regexp, dataLevel, limit); - } - - /** - * @return - */ - public EntitlementFinderDataHolder[] getEntitlementDataModules() { - - EntitlementDataFinder dataFinder = EntitlementAdminEngine.getInstance().getEntitlementDataFinder(); - return dataFinder.getEntitlementDataModules(); - } - - /** - * @param policyId - * @return - * @throws EntitlementException - */ - public String[] getPolicyVersions(String policyId) throws EntitlementException { - - PolicyPersistenceManager policyStore = EntitlementAdminEngine.getInstance().getPolicyPersistenceManager(); - String[] versions = policyStore.getVersions(policyId); - if(versions == null){ - throw new EntitlementException("Error obtaining policy versions"); - } - Arrays.sort(versions); - return versions; - - } - - public void orderPolicy(String policyId, int newOrder) throws EntitlementException { - - PolicyDTO policyDTO = new PolicyDTO(); - policyDTO.setPolicyId(policyId); - policyDTO.setPolicyOrder(newOrder); - PAPPolicyStoreManager storeManager = EntitlementAdminEngine. - getInstance().getPapPolicyStoreManager(); - if (storeManager.isExistPolicy(policyId)) { - storeManager.addOrUpdatePolicy(policyDTO, false); - } - publishToPDP(new String[]{policyDTO.getPolicyId()}, EntitlementConstants.PolicyPublish.ACTION_ORDER, null, - false, newOrder); - } - - public void enableDisablePolicy(String policyId, boolean enable) throws EntitlementException { - - PolicyDTO policyDTO = new PolicyDTO(); - policyDTO.setPolicyId(policyId); - policyDTO.setActive(enable); - PAPPolicyStoreManager storeManager = EntitlementAdminEngine. - getInstance().getPapPolicyStoreManager(); - if (storeManager.isExistPolicy(policyId)) { - storeManager.addOrUpdatePolicy(policyDTO, false); - } - - if (enable) { - publishToPDP(new String[]{policyDTO.getPolicyId()}, null, - EntitlementConstants.PolicyPublish.ACTION_ENABLE); - } else { - publishToPDP(new String[]{policyDTO.getPolicyId()}, null, - EntitlementConstants.PolicyPublish.ACTION_DISABLE); - } - } - - /** - * @param policyId - * @throws EntitlementException - */ - public void dePromotePolicy(String policyId) throws EntitlementException { - - publishToPDP(new String[]{policyId}, null, - EntitlementConstants.PolicyPublish.ACTION_DELETE); - - } - - /** - * This method persists a XACML policy - * - * @param policyDTO PolicyDTO object - * @param isAdd whether this is policy adding or updating - * @throws EntitlementException throws if invalid policy or if policy - * with same id is exist - */ - private void addOrUpdatePolicy(PolicyDTO policyDTO, boolean isAdd) throws EntitlementException { - - - String regString = EntitlementServiceComponent.getEntitlementConfig(). - getEngineProperties().getProperty(PDPConstants.POLICY_ID_REGEXP_PATTERN); - if (regString == null || regString.trim().length() == 0) { - regString = "[a-zA-Z0-9._:-]{3,100}$"; - } - - PAPPolicyStoreManager policyAdmin = EntitlementAdminEngine.getInstance().getPapPolicyStoreManager(); - - AbstractPolicy policyObj; - String policyId = null; - String policy = null; - String operation = EntitlementConstants.StatusTypes.UPDATE_POLICY; - if (isAdd) { - operation = EntitlementConstants.StatusTypes.ADD_POLICY; - } - if (policyDTO == null) { - throw new EntitlementException("Entitlement Policy can not be null."); - } - - if (isAdd && policyDTO.getPolicy() == null) { - throw new EntitlementException("Entitlement Policy can not be null."); - } - - try { - policy = policyDTO.getPolicy(); - if (policy != null) { - policyDTO.setPolicy(policy.replaceAll(">\\s+<", "><")); - if (!EntitlementUtil.validatePolicy(policyDTO)) { - throw new EntitlementException("Invalid Entitlement Policy. " + - "Policy is not valid according to XACML schema"); - } - policyObj = PAPPolicyReader.getInstance(null).getPolicy(policy); - if (policyObj != null) { - policyId = policyObj.getId().toASCIIString(); - policyDTO.setPolicyId(policyId); - // All the policies wont be active at the time been added. - policyDTO.setActive(policyDTO.isActive()); - - if (policyId.contains("/")) { - throw new EntitlementException( - " Policy Id cannot contain / characters. Please correct and upload again"); - } - if (!policyId.matches(regString)) { - throw new EntitlementException( - "An Entitlement Policy Id is not valid. It contains illegal characters"); - } - - policyDTO.setPolicyId(policyId); - if (isAdd) { - if (policyAdmin.isExistPolicy(policyId)) { - throw new EntitlementException( - "An Entitlement Policy with the given Id already exists"); - } - } - } else { - throw new EntitlementException("Unsupported Entitlement Policy. Policy can not be parsed"); - } - } - policyAdmin.addOrUpdatePolicy(policyDTO, true); - } catch (EntitlementException e) { - handleStatus(operation, policyDTO, false, e.getMessage()); - throw e; - } - - handleStatus(operation, policyDTO, true, null); - - - // publish policy to PDP directly - if (policyDTO.isPromote()) { - if (isAdd) { - publishToPDP(new String[]{policyDTO.getPolicyId()}, EntitlementConstants.PolicyPublish.ACTION_CREATE, - null, policyDTO.isActive(), policyDTO.getPolicyOrder()); - } else { - publishToPDP(new String[]{policyDTO.getPolicyId()}, EntitlementConstants.PolicyPublish.ACTION_UPDATE, - null, policyDTO.isActive(), policyDTO.getPolicyOrder()); - } - } - } - - - /** - * This method is used internally to do the pagination purposes. - * - * @param pageNumber page Number - * @param policySet set of policies - * @return PaginatedPolicySetDTO object containing the number of pages and the set of policies - * that reside in the given page. - */ - private PaginatedPolicySetDTO doPaging(int pageNumber, PolicyDTO[] policySet) { - - PaginatedPolicySetDTO paginatedPolicySet = new PaginatedPolicySetDTO(); - if (policySet.length == 0) { - paginatedPolicySet.setPolicySet(new PolicyDTO[0]); - return paginatedPolicySet; - } - String itemsPerPage = EntitlementServiceComponent.getEntitlementConfig(). - getEngineProperties().getProperty(PDPConstants.ENTITLEMENT_ITEMS_PER_PAGE); - if (itemsPerPage != null) { - itemsPerPage = ServerConfiguration.getInstance().getFirstProperty("ItemsPerPage"); - } - int itemsPerPageInt = PDPConstants.DEFAULT_ITEMS_PER_PAGE; - if (itemsPerPage != null) { - itemsPerPageInt = Integer.parseInt(itemsPerPage); - } - int numberOfPages = (int) Math.ceil((double) policySet.length / itemsPerPageInt); - if (pageNumber > numberOfPages - 1) { - pageNumber = numberOfPages - 1; - } - int startIndex = pageNumber * itemsPerPageInt; - int endIndex = (pageNumber + 1) * itemsPerPageInt; - PolicyDTO[] returnedPolicySet = new PolicyDTO[itemsPerPageInt]; - - for (int i = startIndex, j = 0; i < endIndex && i < policySet.length; i++, j++) { - returnedPolicySet[j] = policySet[i]; - } - - paginatedPolicySet.setPolicySet(returnedPolicySet); - paginatedPolicySet.setNumberOfPages(numberOfPages); - - return paginatedPolicySet; - } - - - /** - * This method is used internally to do the pagination purposes. - * - * @param pageNumber page Number - * @param statusHolders StatusHolder - * @return PaginatedPolicySetDTO object containing the number of pages and the set of policies - * that reside in the given page. - */ - private PaginatedStatusHolder doPaging(int pageNumber, StatusHolder[] statusHolders) { - - PaginatedStatusHolder paginatedStatusHolder = new PaginatedStatusHolder(); - if (statusHolders.length == 0) { - paginatedStatusHolder.setStatusHolders(new StatusHolder[0]); - return paginatedStatusHolder; - } - String itemsPerPage = EntitlementServiceComponent.getEntitlementConfig(). - getEngineProperties().getProperty(PDPConstants.ENTITLEMENT_ITEMS_PER_PAGE); - if (itemsPerPage != null) { - itemsPerPage = ServerConfiguration.getInstance().getFirstProperty("ItemsPerPage"); - } - int itemsPerPageInt = PDPConstants.DEFAULT_ITEMS_PER_PAGE; - if (itemsPerPage != null) { - itemsPerPageInt = Integer.parseInt(itemsPerPage); - } - int numberOfPages = (int) Math.ceil((double) statusHolders.length / itemsPerPageInt); - if (pageNumber > numberOfPages - 1) { - pageNumber = numberOfPages - 1; - } - int startIndex = pageNumber * itemsPerPageInt; - int endIndex = (pageNumber + 1) * itemsPerPageInt; - StatusHolder[] returnedHolders = new StatusHolder[itemsPerPageInt]; - - for (int i = startIndex, j = 0; i < endIndex && i < statusHolders.length; i++, j++) { - returnedHolders[j] = statusHolders[i]; - } - - paginatedStatusHolder.setStatusHolders(returnedHolders); - paginatedStatusHolder.setNumberOfPages(numberOfPages); - - return paginatedStatusHolder; - } - - - /** - * This method is used internally to do the pagination purposes. - * - * @param pageNumber page Number - * @param ids String - * @return PaginatedStringDTO object containing the number of pages and the set of policies - * that reside in the given page. - */ - private PaginatedStringDTO doPagingString(int pageNumber, String[] ids) { - - PaginatedStringDTO paginatedStatusHolder = new PaginatedStringDTO(); - if (ids.length == 0) { - paginatedStatusHolder.setStatusHolders(new String[0]); - return paginatedStatusHolder; - } - - String itemsPerPage = EntitlementServiceComponent.getEntitlementConfig(). - getEngineProperties().getProperty(PDPConstants.ENTITLEMENT_ITEMS_PER_PAGE); - if (itemsPerPage != null) { - itemsPerPage = ServerConfiguration.getInstance().getFirstProperty("ItemsPerPage"); - } - int itemsPerPageInt = PDPConstants.DEFAULT_ITEMS_PER_PAGE; - if (itemsPerPage != null) { - itemsPerPageInt = Integer.parseInt(itemsPerPage); - } - int numberOfPages = (int) Math.ceil((double) ids.length / itemsPerPageInt); - if (pageNumber > numberOfPages - 1) { - pageNumber = numberOfPages - 1; - } - int startIndex = pageNumber * itemsPerPageInt; - int endIndex = (pageNumber + 1) * itemsPerPageInt; - String[] returnedHolders = new String[itemsPerPageInt]; - - for (int i = startIndex, j = 0; i < endIndex && i < ids.length; i++, j++) { - returnedHolders[j] = ids[i]; - } - - paginatedStatusHolder.setStatusHolders(returnedHolders); - paginatedStatusHolder.setNumberOfPages(numberOfPages); - - return paginatedStatusHolder; - } - - - private void handleStatus(String action, PolicyDTO policyDTO, boolean success, String message) { - - Set handlers = EntitlementServiceComponent. - getEntitlementConfig().getPapStatusDataHandlers().keySet(); - - String target = "PAP POLICY STORE"; - String targetAction = ""; - if (EntitlementConstants.StatusTypes.ADD_POLICY.equals(action) || - EntitlementConstants.StatusTypes.UPDATE_POLICY.equals(action)) { - targetAction = "PERSIST"; - } else if (EntitlementConstants.StatusTypes.DELETE_POLICY.equals(action)) { - targetAction = "REMOVE"; - } else if (EntitlementConstants.StatusTypes.GET_POLICY.equals(action)) { - targetAction = "LOAD"; - } - - String policyId = policyDTO.getPolicyId(); - if (policyId == null) { - policyId = "UNKNOWN"; - } - - StatusHolder holder = - new StatusHolder(action, policyId, policyDTO.getVersion(), - target, targetAction, success, message); - - if (handlers != null) { - for (PAPStatusDataHandler handler : handlers) { - try { - handler.handle(EntitlementConstants.Status.ABOUT_POLICY, holder); - } catch (EntitlementException e) { - log.error(e); - } - } - } - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/EntitlementService.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/EntitlementService.java deleted file mode 100644 index 9b97cc8728a2..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/EntitlementService.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.entitlement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.entitlement.dto.AttributeDTO; -import org.wso2.carbon.identity.entitlement.dto.EntitledResultSetDTO; -import org.wso2.carbon.identity.entitlement.pdp.EntitlementEngine; -import org.wso2.carbon.identity.entitlement.policy.search.PolicySearch; -import org.wso2.carbon.identity.entitlement.wsxacml.XACMLHandler; - -/** - * Entitlement Service class which exposes the PDP - */ -public class EntitlementService implements XACMLHandler { - - private static Log log = LogFactory.getLog(EntitlementService.class); - - /** - * Evaluates the given XACML request and returns the Response that the EntitlementEngine will - * hand back to the PEP. PEP needs construct the XACML request before sending it to the - * EntitlementEngine - * - * @param request XACML request as a String Object - * @return XACML response as a String Object - * @throws EntitlementException throws - */ - public String getDecision(String request) throws EntitlementException { - - String response; - try { - EntitlementEngine entitlementEngine = EntitlementEngine.getInstance(); - response = entitlementEngine.evaluate(request); - return response; - } catch (Exception e) { - log.error("Error occurred while evaluating XACML request", e); - throw new EntitlementException("Error occurred while evaluating XACML request"); - } - } - - /** - * Evaluates the given XACML request and returns the Response that the EntitlementEngine will - * hand back to the PEP. Here PEP does not need construct the XACML request before sending it to the - * EntitlementEngine. Just can send the single attribute value. But here default attribute ids and data types - * are used - * - * @param subject subject - * @param resource resource - * @param action action - * @param environment environment - * @return XACML response as a String Object - * @throws EntitlementException throws - */ - public String getDecisionByAttributes(String subject, String resource, String action, - String[] environment) throws EntitlementException { - try { - EntitlementEngine entitlementEngine = EntitlementEngine.getInstance(); - return entitlementEngine.evaluate(subject, resource, action, environment); - } catch (Exception e) { - log.error("Error occurred while evaluating XACML request", e); - throw new EntitlementException("Error occurred while evaluating XACML request"); - } - } - - - /** - * Evaluates the given XACML request and returns the Response as boolean value. - * Here PEP does not need construct the XACML request before sending it to the - * EntitlementEngine. Just can send the single attribute value. But here default - * attribute ids and data types are used. - * if result permit, return true else false such as Deny based PEP - * - * @param subject subject - * @param resource resource - * @param action action - * @return XACML response as boolean true or false - * @throws Exception throws - */ - public boolean getBooleanDecision(String subject, String resource, String action) throws Exception { - try { - EntitlementEngine entitlementEngine = EntitlementEngine.getInstance(); - String response = entitlementEngine.evaluate(subject, resource, action, null); - if (response.contains("Permit")) { - return true; - } - return false; - } catch (Exception e) { - log.error("Error occurred while evaluating XACML request", e); - throw new Exception("Error occurred while evaluating XACML request"); - } - } - - /** - * Gets entitled resources for given user or role - * This method can be only used, if all policies in PDP are defined with default categories i.e - * subject, resource and action and default attribute Ids and #string data type. - * - * @param subjectName subject Name, User or Role name - * @param subjectId attribute id of the subject, user or role - * @param resourceName resource Name - * @param action action name - * @param enableChildSearch whether search is done for the child resources under the given resource name - * @return entitled resources as String array - * @throws org.wso2.carbon.identity.entitlement.EntitlementException throws if invalid data is provided - */ - public EntitledResultSetDTO getEntitledAttributes(String subjectName, String resourceName, - String subjectId, String action, boolean enableChildSearch) - throws EntitlementException { - - if (subjectName == null) { - throw new EntitlementException( - "Invalid input data - either the user name or role name should be non-null"); - } - - PolicySearch policySearch = EntitlementEngine.getInstance().getPolicySearch(); - return policySearch.getEntitledAttributes(subjectName, resourceName, subjectId, action, - enableChildSearch); - } - - /** - * Gets all entitled attributes for given set of attributes - * this an universal method to do policy search and find entitlement attributes - * - * @param identifier identifier to separate out the attributes that is used for search - * this is not required and can be null - * @param givenAttributes user provided attributes - * @return all the attributes that is entitled - * @throws EntitlementException if fails - */ - public EntitledResultSetDTO getAllEntitlements(String identifier, AttributeDTO[] givenAttributes) - throws EntitlementException { - PolicySearch policySearch = EntitlementEngine.getInstance().getPolicySearch(); - return policySearch.getEntitledAttributes(identifier, givenAttributes); - } - - /** - * Evaluates the given XACML request for given SAML based authorization query - * - * @param request XACML request as a String Object - * @return XACML response as a String Object - * @throws Exception throws if fails - */ - public String XACMLAuthzDecisionQuery(String request) throws Exception { - return getDecision(request); - } - -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/EntitlementUtil.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/EntitlementUtil.java deleted file mode 100644 index 79d33ace239f..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/EntitlementUtil.java +++ /dev/null @@ -1,785 +0,0 @@ -/* - * Copyright (c) 2005-2024, WSO2 LLC (https://www.wso2.com) All Rights Reserved. - * - * WSO2 LLC 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.wso2.carbon.identity.entitlement; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.lang.ArrayUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.wso2.balana.AbstractPolicy; -import org.wso2.balana.Balana; -import org.wso2.balana.ParsingException; -import org.wso2.balana.Policy; -import org.wso2.balana.PolicySet; -import org.wso2.balana.XACMLConstants; -import org.wso2.balana.attr.AttributeValue; -import org.wso2.balana.attr.BooleanAttribute; -import org.wso2.balana.attr.DateAttribute; -import org.wso2.balana.attr.DateTimeAttribute; -import org.wso2.balana.attr.DoubleAttribute; -import org.wso2.balana.attr.HexBinaryAttribute; -import org.wso2.balana.attr.IntegerAttribute; -import org.wso2.balana.attr.StringAttribute; -import org.wso2.balana.attr.TimeAttribute; -import org.wso2.balana.combine.PolicyCombiningAlgorithm; -import org.wso2.balana.combine.xacml2.FirstApplicablePolicyAlg; -import org.wso2.balana.combine.xacml2.OnlyOneApplicablePolicyAlg; -import org.wso2.balana.combine.xacml3.DenyOverridesPolicyAlg; -import org.wso2.balana.combine.xacml3.DenyUnlessPermitPolicyAlg; -import org.wso2.balana.combine.xacml3.OrderedDenyOverridesPolicyAlg; -import org.wso2.balana.combine.xacml3.OrderedPermitOverridesPolicyAlg; -import org.wso2.balana.combine.xacml3.PermitOverridesPolicyAlg; -import org.wso2.balana.combine.xacml3.PermitUnlessDenyPolicyAlg; -import org.wso2.balana.ctx.AbstractRequestCtx; -import org.wso2.balana.ctx.Attribute; -import org.wso2.balana.xacml3.Attributes; -import org.wso2.carbon.identity.core.util.IdentityUtil; -import org.wso2.carbon.identity.entitlement.cache.EntitlementBaseCache; -import org.wso2.carbon.identity.entitlement.cache.IdentityCacheEntry; -import org.wso2.carbon.identity.entitlement.cache.IdentityCacheKey; -import org.wso2.carbon.identity.entitlement.common.EntitlementConstants; -import org.wso2.carbon.identity.entitlement.dto.AttributeDTO; -import org.wso2.carbon.identity.entitlement.dto.PolicyDTO; -import org.wso2.carbon.identity.entitlement.dto.PublisherDataHolder; -import org.wso2.carbon.identity.entitlement.dto.PublisherPropertyDTO; -import org.wso2.carbon.identity.entitlement.dto.StatusHolder; -import org.wso2.carbon.identity.entitlement.internal.EntitlementExtensionBuilder; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; -import org.wso2.carbon.identity.entitlement.pap.EntitlementAdminEngine; -import org.wso2.carbon.identity.entitlement.pap.store.PAPPolicyStoreManager; -import org.wso2.carbon.identity.entitlement.pap.store.PAPPolicyStoreReader; -import org.wso2.carbon.identity.entitlement.persistence.PolicyPersistenceManager; -import org.wso2.carbon.registry.core.Registry; -import org.wso2.carbon.utils.CarbonUtils; -import org.xml.sax.SAXException; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.URISyntaxException; -import java.text.DateFormat; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.dom.DOMResult; -import javax.xml.transform.dom.DOMSource; -import javax.xml.validation.Schema; -import javax.xml.validation.Validator; - -import static org.wso2.carbon.identity.entitlement.PDPConstants.Algorithms.DENY_OVERRIDES; -import static org.wso2.carbon.identity.entitlement.PDPConstants.Algorithms.FIRST_APPLICABLE; -import static org.wso2.carbon.identity.entitlement.PDPConstants.Algorithms.ONLY_ONE_APPLICABLE; -import static org.wso2.carbon.identity.entitlement.PDPConstants.Algorithms.ORDERED_DENY_OVERRIDES; -import static org.wso2.carbon.identity.entitlement.PDPConstants.Algorithms.ORDERED_PERMIT_OVERRIDES; -import static org.wso2.carbon.identity.entitlement.PDPConstants.Algorithms.PERMIT_OVERRIDES; -import static org.wso2.carbon.identity.entitlement.PDPConstants.POLICY_COMBINING_PREFIX_1; -import static org.wso2.carbon.identity.entitlement.PDPConstants.POLICY_COMBINING_PREFIX_3; - -/** - * Provides utility functionalities used across different classes. - */ -public class EntitlementUtil { - - private static Log log = LogFactory.getLog(EntitlementUtil.class); - - /** - * Return an instance of a named cache that is common to all tenants. - * - * @param name the name of the cache. - * @return the named cache instance. - */ - public static EntitlementBaseCache getCommonCache(String name) { - // TODO Should verify the cache creation done per tenant or as below - - // We create a single cache for all tenants. It is not a good choice to create per-tenant - // caches in this case. We qualify tenants by adding the tenant identifier in the cache key. -// PrivilegedCarbonContext currentContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); -// PrivilegedCarbonContext.startTenantFlow(); -// try { -// currentContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID); -// return CacheManager.getInstance().getCache(name); -// } finally { -// PrivilegedCarbonContext.endTenantFlow(); -// } - - return new EntitlementBaseCache(name); - } - - /** - * Return the Attribute Value Object for given string value and data type - * - * @param value attribute value as a String object - * @param type attribute data type name as String object - * @return Attribute Value Object - * @throws EntitlementException throws - */ - public static AttributeValue getAttributeValue(final String value, String type) - throws EntitlementException { - - try { - if (StringAttribute.identifier.equals(type)) { - return new StringAttribute(value); - } - if (IntegerAttribute.identifier.equals(type)) { - return new IntegerAttribute(Long.parseLong(value)); - } - if (BooleanAttribute.identifier.equals(type)) { - return BooleanAttribute.getInstance(value); - } - if (DoubleAttribute.identifier.equals(type)) { - return new DoubleAttribute(Double.parseDouble(value)); - } - if (DateAttribute.identifier.equals(type)) { - return new DateAttribute(DateFormat.getDateInstance().parse(value)); - } - if (DateTimeAttribute.identifier.equals(type)) { - return new DateTimeAttribute(DateFormat.getDateInstance().parse(value)); - } - if (TimeAttribute.identifier.equals(type)) { - return TimeAttribute.getInstance(value); - } - if (HexBinaryAttribute.identifier.equals(type)) { - return new HexBinaryAttribute(value.getBytes()); - } - - return new AttributeValue(new URI(type)) { - @Override - public String encode() { - return value; - } - }; - - } catch (ParsingException e) { - throw new EntitlementException("Error while creating AttributeValue object for given " + - "string value and data type"); - } catch (ParseException e) { - throw new EntitlementException("Error while creating AttributeValue object for given " + - "string value and data type"); - } catch (URISyntaxException e) { - throw new EntitlementException("Error while creating AttributeValue object for given " + - "string value and data type"); - } - } - - /** - * This creates the XACML 3.0 Request context from AttributeDTO object model - * - * @param attributeDTOs AttributeDTO objects as List - * @return DOM element as XACML request - * @throws EntitlementException throws, if fails - */ - public static AbstractRequestCtx createRequestContext(List attributeDTOs) { - - Set attributesSet = new HashSet(); - - for (AttributeDTO DTO : attributeDTOs) { - Attributes attributes = getAttributes(DTO); - if (attributes != null) { - attributesSet.add(attributes); - } - } - return new org.wso2.balana.ctx.xacml3.RequestCtx(attributesSet, null); - } - - /** - * Validates the given policy XML files against the standard XACML policies. - * - * @param policy Policy to validate - * @return return false, If validation failed or XML parsing failed or any IOException occurs - */ - public static boolean validatePolicy(PolicyDTO policy) { - try { - - if (!"true".equalsIgnoreCase((String) EntitlementServiceComponent.getEntitlementConfig() - .getEngineProperties().get(EntitlementExtensionBuilder.PDP_SCHEMA_VALIDATION))) { - return true; - } - - // there may be cases where you only updated the policy meta data in PolicyDTO not the - // actual XACML policy String - if (policy.getPolicy() == null || policy.getPolicy().trim().length() < 1) { - return true; - } - - //get policy version - String policyXMLNS = getPolicyVersion(policy.getPolicy()); - - Map schemaMap = EntitlementServiceComponent. - getEntitlementConfig().getPolicySchemaMap(); - //load correct schema by version - Schema schema = schemaMap.get(policyXMLNS); - - if (schema != null) { - //build XML document - DocumentBuilder documentBuilder = getSecuredDocumentBuilder(false); - InputStream stream = new ByteArrayInputStream(policy.getPolicy().getBytes()); - Document doc = documentBuilder.parse(stream); - //Do the DOM validation - DOMSource domSource = new DOMSource(doc); - DOMResult domResult = new DOMResult(); - Validator validator = schema.newValidator(); - validator.validate(domSource, domResult); - if (log.isDebugEnabled()) { - log.debug("XACML Policy validation succeeded with the Schema"); - } - return true; - } else { - log.error("Invalid Namespace in policy"); - } - } catch (SAXException e) { - log.error("XACML policy is not valid according to the schema :" + e.getMessage(), e); - } catch (IOException e) { - //ignore - } catch (ParserConfigurationException e) { - //ignore - } - return false; - } - - - public static String getPolicyVersion(String policy) { - - try { - //build XML document - DocumentBuilder documentBuilder = getSecuredDocumentBuilder(false); - InputStream stream = new ByteArrayInputStream(policy.getBytes()); - Document doc = documentBuilder.parse(stream); - - - //get policy version - Element policyElement = doc.getDocumentElement(); - return policyElement.getNamespaceURI(); - } catch (Exception e) { - log.debug(e); - // ignore exception as default value is used - log.warn("Policy version can not be identified. Default XACML 3.0 version is used"); - return XACMLConstants.XACML_3_0_IDENTIFIER; - } - } - - - public static Attributes getAttributes(AttributeDTO attributeDataDTO) { - - try { - AttributeValue value = Balana.getInstance().getAttributeFactory(). - createValue(new URI(attributeDataDTO.getAttributeDataType()), - attributeDataDTO.getAttributeValue()); - Attribute attribute = new Attribute(new URI(attributeDataDTO.getAttributeId()), - null, null, value, XACMLConstants.XACML_VERSION_3_0); - Set set = new HashSet(); - set.add(attribute); - String category = attributeDataDTO.getCategory(); - // We are only creating XACML 3.0 requests Therefore covert order XACML categories to new uris - if (PDPConstants.SUBJECT_ELEMENT.equals(category)) { - category = PDPConstants.SUBJECT_CATEGORY_URI; - } else if (PDPConstants.RESOURCE_ELEMENT.equals(category)) { - category = PDPConstants.RESOURCE_CATEGORY_URI; - } else if (PDPConstants.ACTION_ELEMENT.equals(category)) { - category = PDPConstants.ACTION_CATEGORY_URI; - } else if (PDPConstants.ENVIRONMENT_ELEMENT.equals(category)) { - category = PDPConstants.ENVIRONMENT_CATEGORY_URI; - } - return new Attributes(new URI(category), set); - } catch (Exception e) { - log.debug(e); - //ignore and return null; - } - - return null; - } - - /** - * Creates PolicyCombiningAlgorithm object based on policy combining url - * - * @param uri policy combining url as String - * @return PolicyCombiningAlgorithm object - * @throws EntitlementException throws if unsupported algorithm - */ - public static PolicyCombiningAlgorithm getPolicyCombiningAlgorithm(String uri) - throws EntitlementException { - - if (FirstApplicablePolicyAlg.algId.equals(uri)) { - return new FirstApplicablePolicyAlg(); - } else if (DenyOverridesPolicyAlg.algId.equals(uri)) { - return new DenyOverridesPolicyAlg(); - } else if (PermitOverridesPolicyAlg.algId.equals(uri)) { - return new PermitOverridesPolicyAlg(); - } else if (OnlyOneApplicablePolicyAlg.algId.equals(uri)) { - return new OnlyOneApplicablePolicyAlg(); - } else if (OrderedDenyOverridesPolicyAlg.algId.equals(uri)) { - return new OrderedDenyOverridesPolicyAlg(); - } else if (OrderedPermitOverridesPolicyAlg.algId.equals(uri)) { - return new OrderedPermitOverridesPolicyAlg(); - } else if (DenyUnlessPermitPolicyAlg.algId.equals(uri)) { - return new DenyUnlessPermitPolicyAlg(); - } else if (PermitUnlessDenyPolicyAlg.algId.equals(uri)) { - return new PermitUnlessDenyPolicyAlg(); - } - - throw new EntitlementException("Unsupported policy algorithm " + uri); - } - - /** - * Gets all supported policy combining algorithm names - * - * @return array of policy combining algorithm names - */ - public static String[] getAllGlobalPolicyAlgorithmNames() { - - return new String[]{DENY_OVERRIDES, PERMIT_OVERRIDES, FIRST_APPLICABLE, ORDERED_DENY_OVERRIDES, - ORDERED_PERMIT_OVERRIDES, ONLY_ONE_APPLICABLE}; - } - - /** - * Gets the maximum no of status records to persist - * - * @return maximum no of status records - */ - public static int getMaxNoOfStatusRecords() { - - int maxRecords = 0; - String maxRecordsString = EntitlementServiceComponent.getEntitlementConfig().getEngineProperties(). - getProperty(PDPConstants.MAX_NO_OF_STATUS_RECORDS); - - if (maxRecordsString != null) { - maxRecords = Integer.parseInt(maxRecordsString); - } - if (maxRecords == 0) { - maxRecords = PDPConstants.DEFAULT_MAX_NO_OF_STATUS_RECORDS; - } - - return maxRecords; - } - - /** - * Gets the maximum no of policy versions allowed - * - * @return maximum no of policy versions - */ - public static int getMaxNoOfPolicyVersions() { - - int maxVersions = 0; - String maxVersionsString = EntitlementServiceComponent.getEntitlementConfig().getEngineProperties(). - getProperty(PDPConstants.MAX_NO_OF_POLICY_VERSIONS); - - if (maxVersionsString != null) { - maxVersions = Integer.parseInt(maxVersionsString); - } - if (maxVersions == 0) { - maxVersions = PDPConstants.DEFAULT_MAX_NO_OF_POLICY_VERSIONS; - } - - return maxVersions; - } - - /** - * Creates Simple XACML request using given attribute value.Here category, attribute ids and datatypes are - * taken as default values. - * - * @param subject user or role - * @param resource resource name - * @param action action name - * @param environment environment name - * @return String XACML request as String - */ - public static String createSimpleXACMLRequest(String subject, String resource, String action, String environment) { - - return "\n" + - "\n" + - "\n" + - "" + action + "\n" + - "\n" + - "\n" + - "\n" + - "\n" + - "" + subject + "\n" + - "\n" + - "\n" + - "\n" + - "\n" + - "" + environment + "\n" + - "\n" + - "\n" + - "\n" + - "\n" + - "" + resource + "\n" + - "\n" + - "\n" + - " "; - } - - public static void addSamplePolicies() { - - File policyFolder = new File(CarbonUtils.getCarbonHome() + File.separator - + "repository" + File.separator + "resources" + File.separator - + "identity" + File.separator + "policies" + File.separator + "xacml" - + File.separator + "default"); - - File[] fileList; - if (policyFolder.exists() && ArrayUtils.isNotEmpty(fileList = policyFolder.listFiles())) { - for (File policyFile : fileList) { - if (policyFile.isFile()) { - PolicyDTO policyDTO = new PolicyDTO(); - try { - policyDTO.setPolicy(FileUtils.readFileToString(policyFile)); - EntitlementUtil.addFilesystemPolicy(policyDTO, false); - } catch (Exception e) { - // log and ignore - log.error("Error while adding sample XACML policies", e); - } - } - } - } - } - - /** - * This method checks whether there is a policy having the same policyId as the given policyId - * - * @param policyId - * @return - * @throws EntitlementException - */ - public static boolean isPolicyExists(String policyId) throws EntitlementException { - PAPPolicyStoreReader policyReader; - PolicyPersistenceManager store = EntitlementAdminEngine.getInstance().getPolicyPersistenceManager(); - policyReader = new PAPPolicyStoreReader(store); - return policyReader.isExistPolicy(policyId); - } - - /** - * This method persists a new XACML policy, which was read from filesystem, - * in the policy store - * - * @param policyDTO PolicyDTO object - * @param promote where policy must be promote PDP or not - * @return returns whether True/False - * @throws org.wso2.carbon.identity.entitlement.EntitlementException throws if policy with same id is exist - */ - public static boolean addFilesystemPolicy(PolicyDTO policyDTO, boolean promote) - throws EntitlementException { - - PAPPolicyStoreManager policyAdmin; - AbstractPolicy policyObj; - - if (policyDTO.getPolicy() != null) { - policyDTO.setPolicy(policyDTO.getPolicy().replaceAll(">\\s+<", "><")); - } - - policyObj = getPolicy(policyDTO.getPolicy()); - - if (policyObj != null) { - policyAdmin = new PAPPolicyStoreManager(); - policyDTO.setPolicyId(policyObj.getId().toASCIIString()); - policyDTO.setActive(true); - - if (isPolicyExists(policyDTO.getPolicyId())) { - return false; - } - - policyDTO.setPromote(promote); - policyAdmin.addOrUpdatePolicy(policyDTO, true); - - if (promote) { - EntitlementAdminEngine adminEngine = EntitlementAdminEngine.getInstance(); - adminEngine.getPolicyStoreManager().addPolicy(policyDTO); - } - return true; - } else { - throw new EntitlementException("Invalid Entitlement Policy"); - } - } - - - public static AbstractPolicy getPolicy(String policy) { - - DocumentBuilder builder; - InputStream stream = null; - // now use the factory to create the document builder - try { - builder = getSecuredDocumentBuilder(true); - stream = new ByteArrayInputStream(policy.getBytes("UTF-8")); - Document doc = builder.parse(stream); - Element root = doc.getDocumentElement(); - String name = root.getTagName(); - // see what type of policy this is - if (name.equals("Policy")) { - return Policy.getInstance(root); - } else if (name.equals("PolicySet")) { - return PolicySet.getInstance(root, null); - } else { - // this isn't a root type that we know how to handle - throw new ParsingException("Unknown root document type: " + name); - } - } catch (Exception e) { - throw new IllegalArgumentException("Error while parsing start up policy", e); - } finally { - if (stream != null) { - try { - stream.close(); - } catch (IOException e) { - log.error("Error while closing input stream"); - } - } - } - } - - - /** - * Gets policy dto for a given policy id - * - * @param policyId policy id - * @param registry Registry - * @return returns policy - * @throws org.wso2.carbon.identity.entitlement.EntitlementException - */ - public static PolicyDTO getPolicy(String policyId, Registry registry) throws EntitlementException { - PAPPolicyStoreReader policyReader; - PolicyPersistenceManager store = EntitlementAdminEngine.getInstance().getPolicyPersistenceManager(); - policyReader = new PAPPolicyStoreReader(store); - return policyReader.readPolicyDTO(policyId); - } - - /** - * This will return all the properties of entitlement.properties config - * @return Properties of config - */ - public static Properties getPropertiesFromEntitlementConfig() { - - return EntitlementServiceComponent.getEntitlementConfig().getEngineProperties(); - } - - /** - * * This method provides a secured document builder which will secure XXE attacks. - * - * @param setIgnoreComments whether to set setIgnoringComments in DocumentBuilderFactory. - * @return DocumentBuilder - * @throws ParserConfigurationException - */ - private static DocumentBuilder getSecuredDocumentBuilder(boolean setIgnoreComments) throws - ParserConfigurationException { - - DocumentBuilderFactory documentBuilderFactory = IdentityUtil.getSecuredDocumentBuilderFactory(); - documentBuilderFactory.setIgnoringComments(setIgnoreComments); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - return documentBuilder; - - } - - /** - * Read PAP.Policy.Store.MetaData property from entitlement.properties file. - * - * @return true if policy meta data storing is enabled, false otherwise. - */ - public static boolean isPolicyMetadataStoringEnabled() { - - String propertyValue = EntitlementServiceComponent.getEntitlementConfig(). - getEngineProperties().getProperty(PDPConstants.STORE_POLICY_META_DATA); - - // The default behavior is to store policy meta data. - return StringUtils.isEmpty(propertyValue) || Boolean.parseBoolean(propertyValue); - } - - /** - * Get policy attributes for search. - * - * @param policyDTOs PolicyDTO array. - * @return Map of policy id to self and referenced policy attributes. - */ - public static Map> getAttributesFromPolicies(PolicyDTO[] policyDTOs) { - - Map> attributeMap = new HashMap<>(); - for (PolicyDTO policyDTO : policyDTOs) { - Set attributeDTOs = new HashSet<>(Arrays.asList(policyDTO.getAttributeDTOs())); - String[] policyIdRef = policyDTO.getPolicyIdReferences(); - String[] policySetIdRef = policyDTO.getPolicySetIdReferences(); - - if (ArrayUtils.isNotEmpty(policyIdRef) || ArrayUtils.isNotEmpty(policySetIdRef)) { - for (PolicyDTO dto : policyDTOs) { - if (policyIdRef != null) { - for (String policyId : policyIdRef) { - if (dto.getPolicyId().equals(policyId)) { - attributeDTOs.addAll(Arrays.asList(dto.getAttributeDTOs())); - } - } - } - for (String policySetId : policySetIdRef) { - if (dto.getPolicyId().equals(policySetId)) { - attributeDTOs.addAll(Arrays.asList(dto.getAttributeDTOs())); - } - } - } - } - attributeMap.put(policyDTO.getPolicyId(), attributeDTOs); - } - return attributeMap; - } - - /** - * Resolves the global policy combining algorithm. - * - * @param algorithm policy combining algorithm. - * @return PolicyCombiningAlgorithm object. - */ - public static PolicyCombiningAlgorithm resolveGlobalPolicyAlgorithm(String algorithm) { - - if (StringUtils.isBlank(algorithm)) { - // read algorithm from entitlement.properties file - algorithm = EntitlementServiceComponent.getEntitlementConfig().getEngineProperties(). - getProperty(PDPConstants.PDP_GLOBAL_COMBINING_ALGORITHM); - log.info("The global policy combining algorithm which is defined in the configuration file, is used."); - } else { - if (FIRST_APPLICABLE.equals(algorithm) || ONLY_ONE_APPLICABLE.equals(algorithm)) { - algorithm = POLICY_COMBINING_PREFIX_1 + algorithm; - } else { - algorithm = POLICY_COMBINING_PREFIX_3 + algorithm; - } - } - try { - return getPolicyCombiningAlgorithm(algorithm); - } catch (EntitlementException e) { - log.error("Exception while getting global policy combining algorithm.", e); - } - log.warn("Global policy combining algorithm is not defined. Therefore the default algorithm is used."); - return new DenyOverridesPolicyAlg(); - } - - /** - * Filter status holders based on search criteria. Allows full regex matching for search string. - * - * @param holders List of status holders. - * @param searchString Search string. - * @param about About. - * @param type Type. - * @return Filtered status holders. - */ - public static StatusHolder[] filterStatus(List holders, String searchString, String about, - String type) { - - List filteredHolders = new ArrayList<>(); - if (!holders.isEmpty()) { - searchString = searchString.replace("*", ".*"); - Pattern pattern = Pattern.compile(searchString, Pattern.CASE_INSENSITIVE); - for (StatusHolder holder : holders) { - String id = EntitlementConstants.Status.ABOUT_POLICY.equals(about) - ? holder.getUser() - : holder.getTarget(); - Matcher matcher = pattern.matcher(id); - if (!matcher.matches()) { - continue; - } - if (!EntitlementConstants.Status.ABOUT_POLICY.equals(about) || type == null || - type.equals(holder.getType())) { - filteredHolders.add(holder); - } - } - } - return filteredHolders.toArray(new StatusHolder[0]); - } - - /** - * Resolve subscriber id from publisher data holder. - * - * @param holder Publisher data holder. - * @return Subscriber id. - * @throws EntitlementException throws if publisher data is null. - */ - public static String resolveSubscriberId(PublisherDataHolder holder) throws EntitlementException { - - String subscriberId = null; - if (holder == null || holder.getPropertyDTOs() == null) { - throw new EntitlementException("Publisher data can not be null"); - } - - for (PublisherPropertyDTO dto : holder.getPropertyDTOs()) { - if (PDPConstants.SUBSCRIBER_ID.equals(dto.getId())) { - subscriberId = dto.getValue(); - } - } - return subscriberId; - } - - /** - * Filter subscriber ids based on search criteria. Allows full regex matching for search string. - * - * @param subscriberIdList List of subscriber ids. - * @param filter Search filter. - * @return Filtered subscriber ids. - */ - public static List filterSubscribers(List subscriberIdList, String filter) { - - filter = filter.replace("*", ".*"); - Pattern pattern = Pattern.compile(filter, Pattern.CASE_INSENSITIVE); - List filteredSubscriberIdList = new ArrayList<>(); - for (String subscriberId : subscriberIdList) { - Matcher matcher = pattern.matcher(subscriberId); - if (matcher.matches()) { - filteredSubscriberIdList.add(subscriberId); - } - } - return filteredSubscriberIdList; - } - - /** - * Merges two lists and removes duplicates. - * - * @param list1 first list. - * @param list2 second list. - * @return Merged list without duplicates. - */ - public static List mergeLists(List list1, List list2) { - - Set uniqueElements = new HashSet<>(); - uniqueElements.addAll(list1); - uniqueElements.addAll(list2); - return removeNullElements(new ArrayList<>((uniqueElements))); - } - - /** - * Removes null elements from a list. - * - * @param list list to remove null elements. - * @return list without null elements. - */ - public static List removeNullElements(List list) { - - List nonNullElements = new ArrayList<>(); - for (T element : list) { - if (element != null) { - nonNullElements.add(element); - } - } - return nonNullElements; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/NotificationConstants.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/NotificationConstants.java deleted file mode 100644 index 090a5008ed13..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/NotificationConstants.java +++ /dev/null @@ -1,45 +0,0 @@ -/* -* -* Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement; - -public class NotificationConstants { - - - public static final String EVENT_LABEL_POLICY_CHANGE = "policyChange"; - public static final String EVENT_TYPE_PROFILE_UPDATE = "profileUpdate"; - public static final String EVENT_TYPE_ROLE_UPDATE = "roleUpdate"; - - public static final String USERNAME_PROPERTY_LABEL = "username"; - public static final String EVENT_TYPE_PROPERTY_LABEL = "eventType"; - public static final String PDP_NOTIFICATION_PROPERTY_LABEL = "pdpNotification"; - public static final String PAP_NOTIFICATION_PROPERTY_LABEL = "papNotification"; - public static final String PDP_NOTIFICATION_ACTION_PROPERTY_LABEL = "pdpNotificationAction"; - public static final String TARGET_ID_PROPERTY_LABEL = "targetId"; - public static final String TARGET_PROPERTY_LABEL = "target"; - public static final String ACTION_PROPERTY_LABEL = "action"; - - public static final String ACTION_LABEL_UPDATE = "UPDATE"; - public static final String ACTION_LABEL_CREATE = "CREATE"; - public static final String ACTION_LABEL_DELETE = "DELETE"; - - public static final String SUBSCRIBED_EVENT_USER_OPERATION = "userOperation"; -} - diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/PAPStatusDataHandler.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/PAPStatusDataHandler.java deleted file mode 100644 index 5d0e651f2f32..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/PAPStatusDataHandler.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.entitlement; - -import org.wso2.carbon.identity.entitlement.dto.StatusHolder; - -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -/** - * This listener would be fired after an admin action is done - */ -public interface PAPStatusDataHandler { - - /** - * init entitlement status data handler module - * - * @param properties properties - */ - public void init(Properties properties); - - /** - * Handles - * - * @param about indicates what is related with this admin status action - * @param key key value of the status - * @param statusHolder StatusHolder - * @throws EntitlementException throws, if fails to handle - */ - public void handle(String about, String key, List statusHolder) throws EntitlementException; - - /** - * @param about indicates what is related with this admin status action - * @param statusHolder StatusHolder - * @throws EntitlementException if fails to handle - */ - default void handle(String about, StatusHolder statusHolder) throws EntitlementException { - - List list = new ArrayList<>(); - list.add(statusHolder); - handle(about, statusHolder.getKey(), list); - } - - /** - * @param about indicates what is related with this admin status action - * @param key key value of the status - * @param type admin action type - * @param searchString search string for StatusHolder - * @return An array of StatusHolder - * @throws EntitlementException - */ - public StatusHolder[] getStatusData(String about, String key, String type, - String searchString) throws EntitlementException; -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/PDPConstants.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/PDPConstants.java deleted file mode 100644 index 4fc1822d23b9..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/PDPConstants.java +++ /dev/null @@ -1,324 +0,0 @@ -/* - * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.entitlement; - -/** - * Entitlement and XACML related constant values - */ -public class PDPConstants { - - public static final String POLICY_TYPE = "policyType"; - - public static final String POLICY_EDITOR_TYPE = "policyEditor"; - - public static final String BASIC_POLICY_EDITOR_META_DATA = "basicPolicyEditorMetaData"; - - public static final String BASIC_POLICY_EDITOR_META_DATA_AMOUNT = "NoOfBasicPolicyEditorMetaData"; - - public static final String ACTIVE_POLICY = "isActive"; - - public static final String PROMOTED_POLICY = "promoted"; - - public static final String POLICY_VERSION = "version"; - - public static final String LAST_MODIFIED_TIME = "lastModifiedTime"; - - public static final String LAST_MODIFIED_USER = "lastModifiedUser"; - - public static final String POLICY_LIFE_CYCLE = "policyLifeStatus"; - - public static final String POLICY_ORDER = "policyOrder"; - - public static final String MAX_POLICY_ORDER = "maxPolicyOrder"; - - public static final String POLICY_ELEMENT = "Policy"; - - public static final String POLICY_REFERENCE = "policyIdReferences"; - - public static final String POLICY_SET_REFERENCE = "policySetIdReferences"; - - public static final String APPLY_ELEMENT = "Apply"; - - public static final String MATCH_ELEMENT = "Match"; - - public static final String SUBJECT_ELEMENT = "Subject"; - - public static final String ACTION_ELEMENT = "Action"; - - public static final String RESOURCE_ELEMENT = "Resource"; - - public static final String ENVIRONMENT_ELEMENT = "Environment"; - - public static final String SUBJECT_CATEGORY_ID = "Subject"; - - public static final String ACTION_CATEGORY_ID = "Action"; - - public static final String RESOURCE_CATEGORY_ID = "Resource"; - - public static final String ENVIRONMENT_CATEGORY_ID = "Environment"; - - public static final String ANY_OF = "AnyOf"; - - public static final String ALL_OF = "AllOf"; - - public static final String RESOURCE_CATEGORY_URI = "urn:oasis:names:tc:xacml:3.0:" + - "attribute-category:resource"; - - public static final String SUBJECT_CATEGORY_URI = "urn:oasis:names:tc:xacml:1.0:" + - "subject-category:access-subject"; - - public static final String ACTION_CATEGORY_URI = "urn:oasis:names:tc:xacml:3.0:" + - "attribute-category:action"; - - public static final String ENVIRONMENT_CATEGORY_URI = "urn:oasis:names:tc:xacml:3.0:" + - "attribute-category:environment"; - - public static final String TARGET_ELEMENT = "Target"; - - public static final String RULE_ELEMENT = "Rule"; - - public static final String CONDITION_ELEMENT = "Condition"; - - public static final String FUNCTION_ELEMENT = "Function"; - - public static final String ATTRIBUTE_SELECTOR = "AttributeSelector"; - - public static final String ATTRIBUTE_VALUE = "AttributeValue"; - - public static final String FUNCTION = "Function"; - - public static final String VARIABLE_REFERENCE = "VariableReference"; - - public static final String ATTRIBUTE_DESIGNATOR = "AttributeDesignator"; - - public static final String ATTRIBUTE_ID = "AttributeId"; - - public static final String ATTRIBUTE = "Attribute"; - - public static final String DATA_TYPE = "DataType"; - - public static final String CATEGORY = "Category"; - - public static final String REQUEST_CONTEXT_PATH = "RequestContextPath"; - - public static final String SUBJECT_ID_DEFAULT = "urn:oasis:names:tc:xacml:1.0:subject:subject-id"; - - public static final String SUBJECT_CATEGORY_DEFAULT = - "urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"; - - public static final String SUBJECT_ID_ROLE = "http://wso2.org/claims/roles"; - - public static final String SERVICE_PROVIDER_NAME = "http://wso2.org/identity/sp/sp-name"; - - public static final String SERVICE_PROVIDER_TENANT_DOMAIN = "http://wso2.org/identity/sp/sp-tenant-domain"; - - public static final String SERVICE_PROVIDER = "http://wso2.org/identity/sp"; - - public static final String RULE_EFFECT_PERMIT = "Permit"; - - public static final String RULE_EFFECT_DENY = "Deny"; - - public static final String RESPONSE_RESULT = "Result"; - - public static final String RESPONSE_DECISION = "Decision"; - - public static final String RESPONSE_RESOURCE_ID = "ResourceId"; - - public static final String POLICY_META_DATA = "policyMetaData"; - - public static final int POLICY_META_DATA_ARRAY_LENGTH = 4; - - public static final String AUTHORIZATION_PERMISSION = "/permission/admin/configure"; - - public static final String ENTITLEMENT_CACHE_MANAGER = "ENTITLEMENT_CACHE_MANAGER"; - - public static final String PIP_RESOURCE_CACHE = "PIP_RESOURCE_CACHE"; - - public static final String PDP_DECISION_CACHE = "PDP_DECISION_CACHE"; - - public static final String PDP_SIMPLE_DECISION_CACHE = "PDP_SIMPLE_DECISION_CACHE"; - - public static final String PDP_DECISION_INVALIDATION_CACHE = "PDP_DECISION_INVALIDATION_CACHE"; - - public static final String PIP_ABSTRACT_INVALIDATION_CACHE = "PIP_ABSTRACT_INVALIDATION_CACHE"; - - public static final String POLICY_SEARCH_CACHE = "POLICY_SEARCH_CACHE"; - - public static final String PIP_ABSTRACT_RESOURCE_CACHE = "PIP_ABSTRACT_RESOURCE_CACHE"; - - public static final String PIP_ATTRIBUTE_CACHE = "PIP_ATTRIBUTE_CACHE"; - - public static final String PIP_ABSTRACT_ATTRIBUTE_CACHE = "PIP_ABSTRACT_ATTRIBUTE_CACHE"; - - public static final String ENTITLEMENT_POLICY_INVALIDATION_CACHE = "ENTITLEMENT_POLICY_INVALIDATION_CACHE"; - - public static final int DEFAULT_ITEMS_PER_PAGE = 10; - - public static final String UNKNOWN = "UNKNOWN"; - - public static final String REQUEST_ELEMENT = "Request"; - - public static final String REQ_RES_CONTEXT = "urn:oasis:names:tc:xacml:2.0:context:schema:os"; - - public static final String REQ_SCHEME = "http://www.w3.org/2001/XMLSchema-instance"; - - public static final String STRING_DATA_TYPE = "http://www.w3.org/2001/XMLSchema#string"; - - public static final String RESOURCE_ID_DEFAULT = "urn:oasis:names:tc:xacml:1.0:resource:resource-id"; - - public static final String ACTION_ID_DEFAULT = "urn:oasis:names:tc:xacml:1.0:action:action-id"; - - public static final String ENVIRONMENT_ID_DEFAULT = "urn:oasis:names:tc:xacml:1.0:environment:environment-id"; - - public static final String RESOURCE_SCOPE_ID = "urn:oasis:names:tc:xacml:1.0:resource:scope"; - - public static final String RESOURCE_DESCENDANTS = "Descendants"; - - public static final String RESOURCE_CHILDREN = "Children"; - - public static final String ATTRIBUTE_SEPARATOR = ","; - - public static final String SEARCH_WARNING_MESSAGE1 = "Attribute values are not defined directly"; - - public static final String SEARCH_WARNING_MESSAGE2 = "No Attributes are defined"; - - public static final String SEARCH_WARNING_MESSAGE3 = "Attribute Selector Element is contained " + - "with Xpath expression"; - - public static final String SEARCH_WARNING_MESSAGE4 = "Apply Element is not contained within Condition Element"; - - public static final String SEARCH_ERROR = "Search_Error"; - - public static final String SEARCH_ERROR_MESSAGE = "Therefore Advance Search can not be proceeded. " + - "Please de-active this policy, If policy is not" + - " relevant for the search"; - - public static final String XACML_3_POLICY_XMLNS = "urn:oasis:names:tc:xacml:3.0:core:schema:wd-17"; - - public static final String XACML_2_POLICY_XMLNS = "urn:oasis:names:tc:xacml:2.0:policy:schema:os"; - - public static final String XACML_1_POLICY_XMLNS = "urn:oasis:names:tc:xacml:1.0:policy"; - - public static final String XACML_3_POLICY_SCHEMA_FILE = "xacml3.xsd"; - - public static final String XACML_2_POLICY_SCHEMA_FILE = "xacml2.xsd"; - - public static final String XACML_1_POLICY_SCHEMA_FILE = "xacml1.xsd"; - - public static final String ENTITLEMENT_POLICY_PUBLISHER = "/repository/identity/entitlement/publisher/"; - - public static final String ENTITLEMENT_POLICY_PUBLISHER_VERIFICATION = - "/repository/identity/entitlement/publisher/verification/"; - - public static final String ENTITLEMENT_POLICY_VERSION = - "/repository/identity/entitlement/policy/version/"; - - public static final String ENTITLEMENT_POLICY_DATA = - "/repository/identity/entitlement/policy/data/"; - - public static final String ENTITLEMENT_POLICY_PAP = "/repository/identity/entitlement/policy/pap/"; - - // entitlement.properties file configurations - - public static final String ON_DEMAND_POLICY_LOADING = "PDP.OnDemangPolicyLoading.Enable"; - - public static final String ON_DEMAND_POLICY_MAX_POLICY_ENTRIES = - "PDP.OnDemangPolicyLoading.MaxInMemoryPolicies"; - - public static final String MAX_POLICY_REFERENCE_ENTRIES = "PDP.References.MaxPolicyEntries"; - - public static final int MAX_NO_OF_IN_MEMORY_POLICIES = 10; - - public static final String DECISION_CACHING = "PDP.DecisionCaching.Enable"; - - public static final String DECISION_CACHING_INTERVAL = "PDP.DecisionCaching.CachingInterval"; - - public static final String ATTRIBUTE_CACHING = "PDP.AttributeCaching.Enable"; - - public static final String ATTRIBUTE_CACHING_INTERVAL = "PDP.AttributeCaching.CachingInterval"; - - public static final String RESOURCE_CACHING = "PDP.ResourceCaching.Enable"; - - public static final String RESOURCE_CACHING_INTERVAL = "PDP.DecisionCaching.CachingInterval"; - - public static final String PDP_ENABLE = "PDP.Enable"; - - public static final String PAP_ENABLE = "PAP.Enable"; - - public static final String BALANA_CONFIG_ENABLE = "PDP.Balana.Config.Enable"; - - public static final String MULTIPLE_DECISION_PROFILE_ENABLE = "PDP.Multiple.Decision.Profile.Enable"; - - public static final String FILESYSTEM_POLICY_PATH = "PAP.Policy.Add.Start.Policy.File.Path"; - - public static final String START_UP_POLICY_ADDING = "PAP.Policy.Add.Start.Enable"; - - public static final String POLICY_ID_REGEXP_PATTERN = "PAP.Policy.Id.Regexp.Pattern"; - - public static final String ENTITLEMENT_ITEMS_PER_PAGE = "PAP.Items.Per.Page"; - - public static final String PDP_GLOBAL_COMBINING_ALGORITHM = "PDP.Global.Policy.Combining.Algorithm"; - - public static final String REGISTRY_MEDIA_TYPE = "application/xacml-policy+xml"; - - public static final String ENTITLEMENT_ENGINE_CACHING_INTERVAL = "Entitlement.Engine.CachingInterval"; - - public static final String PDP_REGISTRY_LEVEL_POLICY_CACHE_CLEAR = "PDP.Registry.Level.Policy.Cache.Clear"; - - public static final String POLICY_CACHING_INTERVAL = "PDP.PolicyCaching.CachingInterval"; - - public static final String XACML_JSON_SHORT_FORM_ENABLED = "JSON.Shorten.Form.Enabled"; - - public static final String USER_CATEGORY = "http://wso2.org/identity/user"; - - public static final String USER_TYPE_ID = USER_CATEGORY + "/user-type"; - - public static final String STORE_POLICY_META_DATA = "PAP.Policy.Store.MetaData"; - - public static final String MAX_NO_OF_STATUS_RECORDS = "maxRecodesToPersist"; - - public static final int DEFAULT_MAX_NO_OF_STATUS_RECORDS = 50; - - public static final String MAX_NO_OF_POLICY_VERSIONS = "maxVersions"; - - public static final int DEFAULT_MAX_NO_OF_POLICY_VERSIONS = 5; - - public static final String GLOBAL_POLICY_COMBINING_ALGORITHM = "globalPolicyCombiningAlgorithm"; - - public static final String POLICY_COMBINING_PREFIX_1 = "urn:oasis:names:tc:xacml:1.0:policy-combining-algorithm:"; - - public static final String POLICY_COMBINING_PREFIX_3 = "urn:oasis:names:tc:xacml:3.0:policy-combining-algorithm:"; - - public static final String SUBSCRIBER_ID = "subscriberId"; - public static final String POLICY_STORAGE_CONFIG = "DataStorageType.XACML"; - public static final String MODULE_NAME = "Registry Policy Finder Module"; - - public static final class Algorithms { - - private Algorithms() { - - } - public static final String DENY_OVERRIDES = "deny-overrides"; - public static final String PERMIT_OVERRIDES = "permit-overrides"; - public static final String FIRST_APPLICABLE = "first-applicable"; - public static final String ORDERED_DENY_OVERRIDES = "ordered-deny-overrides"; - public static final String ONLY_ONE_APPLICABLE = "only-one-applicable"; - public static final String ORDERED_PERMIT_OVERRIDES = "ordered-permit-overrides"; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/PolicyOrderComparator.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/PolicyOrderComparator.java deleted file mode 100644 index 9eb0e8aa024d..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/PolicyOrderComparator.java +++ /dev/null @@ -1,61 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement; - -import org.wso2.carbon.identity.entitlement.dto.PolicyDTO; -import org.wso2.carbon.identity.entitlement.dto.PolicyStoreDTO; - -import java.io.Serializable; -import java.util.Comparator; - -/** - * - */ -public class PolicyOrderComparator implements Serializable, Comparator { - - private static final long serialVersionUID = -4125227115004608650L; - - @Override - public int compare(Object o1, Object o2) { - - if (o1 instanceof PolicyStoreDTO && o2 instanceof PolicyStoreDTO) { - PolicyStoreDTO dto1 = (PolicyStoreDTO) o1; - PolicyStoreDTO dto2 = (PolicyStoreDTO) o2; - if (dto1.getPolicyOrder() > dto2.getPolicyOrder()) { - return -1; - } else if (dto1.getPolicyOrder() == dto2.getPolicyOrder()) { - return 0; - } else { - return 1; - } - } else if (o1 instanceof PolicyDTO && o2 instanceof PolicyDTO) { - PolicyDTO dto1 = (PolicyDTO) o1; - PolicyDTO dto2 = (PolicyDTO) o2; - if (dto1.getPolicyOrder() > dto2.getPolicyOrder()) { - return -1; - } else if (dto1.getPolicyOrder() == dto2.getPolicyOrder()) { - return 0; - } else { - return 1; - } - } else { - throw new ClassCastException("PolicyOrderComparator only works for PolicyDTO and PolicyStoreDTO types"); - } - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/PolicyStatusClusterMessage.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/PolicyStatusClusterMessage.java deleted file mode 100644 index 5c972b3b706c..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/PolicyStatusClusterMessage.java +++ /dev/null @@ -1,71 +0,0 @@ - -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * Licensed 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.wso2.carbon.identity.entitlement; - - -import org.apache.axis2.clustering.ClusteringCommand; -import org.apache.axis2.clustering.ClusteringFault; -import org.apache.axis2.clustering.ClusteringMessage; -import org.apache.axis2.context.ConfigurationContext; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.entitlement.cache.IdentityCacheKey; -import org.wso2.carbon.identity.entitlement.cache.PolicyCache; -import org.wso2.carbon.identity.entitlement.cache.PolicyStatus; - -/** - * ClusterMessage to carry policy status changes (like UPDATE, CREATED) to other nodes. - */ -public class PolicyStatusClusterMessage extends ClusteringMessage { - - private static Log log = LogFactory.getLog(PolicyStatusClusterMessage.class); - private static final long serialVersionUID = -5025603871368248102L; - - private IdentityCacheKey key; - private PolicyStatus status; - - public PolicyStatusClusterMessage(IdentityCacheKey key, PolicyStatus status) { - this.key = key; - this.status = status; - } - - public IdentityCacheKey getKey() { - return key; - } - - public PolicyStatus getStatus() { - return status; - } - - @Override - public ClusteringCommand getResponse() { - return null; - } - - @Override - public void execute(ConfigurationContext configurationContext) throws ClusteringFault { - - if (log.isDebugEnabled()) { - log.debug("Received PolicyStatusClusterMessage."); - } - // we need to update our local policy status map based on the received cluster message from other node - PolicyCache.updateLocalPolicyCacheMap(key, status); - if (log.isDebugEnabled()) { - log.debug("Updated Local Policy Status Map."); - } - } -} \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/SimplePAPStatusDataHandler.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/SimplePAPStatusDataHandler.java deleted file mode 100644 index 98027d28c737..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/SimplePAPStatusDataHandler.java +++ /dev/null @@ -1,336 +0,0 @@ -/* - * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.entitlement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.CarbonConstants; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.identity.central.log.mgt.utils.LoggerUtils; -import org.wso2.carbon.identity.core.util.IdentityUtil; -import org.wso2.carbon.identity.entitlement.common.EntitlementConstants; -import org.wso2.carbon.identity.entitlement.dto.PublisherPropertyDTO; -import org.wso2.carbon.identity.entitlement.dto.StatusHolder; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; -import org.wso2.carbon.registry.core.Registry; -import org.wso2.carbon.registry.core.RegistryConstants; -import org.wso2.carbon.registry.core.Resource; -import org.wso2.carbon.registry.core.exceptions.RegistryException; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.UUID; - -/** - * TODO - */ -public class SimplePAPStatusDataHandler implements PAPStatusDataHandler { - - private static final String ENTITLEMENT_POLICY_STATUS = "/repository/identity/entitlement/status/policy/"; - private static final String ENTITLEMENT_PUBLISHER_STATUS = "/repository/identity/entitlement/status/publisher/"; - private static final int SEARCH_BY_USER = 0; - private static final int SEARCH_BY_POLICY = 1; - private static Log log = LogFactory.getLog(SimplePAPStatusDataHandler.class); - private static final Log AUDIT_LOG = CarbonConstants.AUDIT_LOG; - private static final String AUDIT_MESSAGE - = "Initiator : %s | Action : %s | Target : %s | Data : { %s } | Result : %s "; - private int DEFAULT_MAX_RECODES = 50; - private int maxRecodes; - - @Override - public void init(Properties properties) { - String maxRecodesString = (String) properties.get("maxRecodesToPersist"); - if (maxRecodesString != null) { - try { - maxRecodes = Integer.parseInt(maxRecodesString); - } catch (Exception e) { - //ignore - } - } - if (maxRecodes == 0) { - maxRecodes = DEFAULT_MAX_RECODES; - } - } - - @Override - public void handle(String about, String key, List statusHolder) - throws EntitlementException { - - if (EntitlementConstants.Status.ABOUT_POLICY.equals(about)) { - String path = ENTITLEMENT_POLICY_STATUS + key; - // policy would be deleted. - for (StatusHolder holder : statusHolder) { - if (EntitlementConstants.StatusTypes.DELETE_POLICY.equals(holder.getType())) { - deletedPersistedData(path); - return; - } - } - persistStatus(path, statusHolder, false); - } else { - String path = ENTITLEMENT_PUBLISHER_STATUS + key; - // subscriber would be deleted. - for (StatusHolder holder : statusHolder) { - if (EntitlementConstants.StatusTypes.DELETE_POLICY.equals(holder.getType())) { - deletedPersistedData(path); - return; - } - } - persistStatus(path, statusHolder, false); - } - } - - @Override - public StatusHolder[] getStatusData(String about, String key, String type, String searchString) - throws EntitlementException { - - String path; - String statusAboutType; - - if (EntitlementConstants.Status.ABOUT_POLICY.equals(about)) { - path = ENTITLEMENT_POLICY_STATUS + key; - statusAboutType = EntitlementConstants.Status.ABOUT_POLICY; - } else { - path = ENTITLEMENT_PUBLISHER_STATUS + key; - statusAboutType = EntitlementConstants.Status.ABOUT_SUBSCRIBER; - } - - List holders = readStatus(path, statusAboutType); - return EntitlementUtil.filterStatus(holders, searchString, about, type); - } - - private synchronized void deletedPersistedData(String path) throws EntitlementException { - - Registry registry = null; - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - try { - registry = EntitlementServiceComponent.getRegistryService(). - getGovernanceSystemRegistry(tenantId); - if (registry.resourceExists(path)) { - registry.delete(path); - } - } catch (RegistryException e) { - log.error(e); - throw new EntitlementException("Error while persisting policy status", e); - } - } - - private synchronized void persistStatus(String path, List statusHolders, boolean isNew) - throws EntitlementException { - - Resource resource = null; - Registry registry = null; - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - - try { - registry = EntitlementServiceComponent.getRegistryService(). - getGovernanceSystemRegistry(tenantId); - boolean useLastStatusOnly = Boolean.parseBoolean( - IdentityUtil.getProperty(EntitlementConstants.PROP_USE_LAST_STATUS_ONLY)); - if (registry.resourceExists(path) && !isNew && !useLastStatusOnly) { - resource = registry.get(path); - String[] versions = registry.getVersions(path); - // remove all versions. As we have no way to disable versioning for specific resource - if (versions != null) { - for (String version : versions) { - long versionInt = 0; - String[] versionStrings = version.split(RegistryConstants.VERSION_SEPARATOR); - if (versionStrings != null && versionStrings.length == 2) { - try { - versionInt = Long.parseLong(versionStrings[1]); - } catch (Exception e) { - // ignore - } - } - if (versionInt != 0) { - registry.removeVersionHistory(version, versionInt); - } - } - } - } else { - resource = registry.newResource(); - } - - if (resource != null && statusHolders != null && statusHolders.size() > 0) { - resource.setVersionableChange(false); - StatusHolder[] statusHolderList = statusHolders.toArray(new StatusHolder[statusHolders.size()]); - populateStatusProperties(statusHolderList, resource); - registry.put(path, resource); - // When useLastStatusOnly is set to true, only the last action can be seen in the management console. - // Therefore print an audit log for every action. - if (useLastStatusOnly) { - auditAction(statusHolderList); - } - } - } catch (RegistryException e) { - log.error(e); - throw new EntitlementException("Error while persisting policy status", e); - } - - } - - private synchronized List readStatus(String path, String about) throws EntitlementException { - - Resource resource = null; - Registry registry = null; - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - try { - registry = EntitlementServiceComponent.getRegistryService(). - getGovernanceSystemRegistry(tenantId); - if (registry.resourceExists(path)) { - resource = registry.get(path); - } - } catch (RegistryException e) { - log.error(e); - throw new EntitlementException("Error while persisting policy status", e); - } - - List statusHolders = new ArrayList(); - if (resource != null && resource.getProperties() != null) { - Properties properties = resource.getProperties(); - for (Map.Entry entry : properties.entrySet()) { - PublisherPropertyDTO dto = new PublisherPropertyDTO(); - dto.setId((String) entry.getKey()); - Object value = entry.getValue(); - if (value instanceof ArrayList) { - List list = (ArrayList) entry.getValue(); - if (list != null && list.size() > 0 && list.get(0) != null) { - StatusHolder statusHolder = new StatusHolder(about); - if (list.size() > 0 && list.get(0) != null) { - statusHolder.setType((String) list.get(0)); - } - if (list.size() > 1 && list.get(1) != null) { - statusHolder.setTimeInstance((String) list.get(1)); - } else { - continue; - } - if (list.size() > 2 && list.get(2) != null) { - String user = (String) list.get(2); - statusHolder.setUser(user); - } else { - continue; - } - if (list.size() > 3 && list.get(3) != null) { - statusHolder.setKey((String) list.get(3)); - } - if (list.size() > 4 && list.get(4) != null) { - statusHolder.setSuccess(Boolean.parseBoolean((String) list.get(4))); - } - if (list.size() > 5 && list.get(5) != null) { - statusHolder.setMessage((String) list.get(5)); - } - if (list.size() > 6 && list.get(6) != null) { - statusHolder.setTarget((String) list.get(6)); - } - if (list.size() > 7 && list.get(7) != null) { - statusHolder.setTargetAction((String) list.get(7)); - } - if (list.size() > 8 && list.get(8) != null) { - statusHolder.setVersion((String) list.get(8)); - } - statusHolders.add(statusHolder); - } - } - } - } - if (statusHolders.size() > 0) { - StatusHolder[] array = statusHolders.toArray(new StatusHolder[statusHolders.size()]); - java.util.Arrays.sort(array, new StatusHolderComparator()); - if (statusHolders.size() > maxRecodes) { - statusHolders = new ArrayList(); - for (int i = 0; i < maxRecodes; i++) { - statusHolders.add(array[i]); - } - persistStatus(path, statusHolders, true); - } else { - statusHolders = new ArrayList(Arrays.asList(array)); - } - } - - return statusHolders; - } - - - /** - * @param statusHolders - * @param resource - */ - private void populateStatusProperties(StatusHolder[] statusHolders, Resource resource) { - if (statusHolders != null) { - for (StatusHolder statusHolder : statusHolders) { - if (statusHolder != null) { - List list = new ArrayList(); - list.add(statusHolder.getType()); - list.add(statusHolder.getTimeInstance()); - list.add(statusHolder.getUser()); - list.add(statusHolder.getKey()); - list.add(Boolean.toString(statusHolder.isSuccess())); - if (statusHolder.getMessage() != null) { - list.add(statusHolder.getMessage()); - } else { - list.add(""); - } - if (statusHolder.getTarget() != null) { - list.add(statusHolder.getTarget()); - } else { - list.add(""); - } - if (statusHolder.getTargetAction() != null) { - list.add(statusHolder.getTargetAction()); - } else { - list.add(""); - } - if (statusHolder.getVersion() != null) { - list.add(statusHolder.getVersion()); - } else { - list.add(""); - } - resource.setProperty(UUID.randomUUID().toString(), list); - } - } - } - } - - private void auditAction(StatusHolder[] statusHolders) { - - if (statusHolders != null) { - for (StatusHolder statusHolder : statusHolders) { - if (statusHolder != null) { - String initiator = statusHolder.getUser(); - if (LoggerUtils.isLogMaskingEnable) { - initiator = LoggerUtils.getMaskedContent(initiator); - } - String action = statusHolder.getType(); - String key = statusHolder.getKey(); - String target = statusHolder.getTarget(); - String targetAction = statusHolder.getTargetAction(); - String result = "FAILURE"; - if (statusHolder.isSuccess()) { - result = "SUCCESS"; - } - String auditData = String.format("\"Key\" : \"%s\" , \"Target Action\" : \"%s\"", - key, targetAction); - - AUDIT_LOG.info(String.format(AUDIT_MESSAGE, initiator, action, target, auditData, result)); - } - } - } - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/StatusHolderComparator.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/StatusHolderComparator.java deleted file mode 100644 index ea0579bb5c84..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/StatusHolderComparator.java +++ /dev/null @@ -1,56 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement; - -import org.wso2.carbon.identity.entitlement.dto.StatusHolder; - -import java.io.Serializable; -import java.util.Comparator; - -/** - * - */ -public class StatusHolderComparator implements Serializable, Comparator { - - private static final long serialVersionUID = -6675867912216533133L; - - @Override - public int compare(Object o1, Object o2) { - - StatusHolder dto1 = (StatusHolder) o1; - StatusHolder dto2 = (StatusHolder) o2; - long time1 = 0; - long time2 = 0; - try { - time1 = Long.parseLong(dto1.getTimeInstance()); - time2 = Long.parseLong(dto2.getTimeInstance()); - } catch (Exception e) { - // if time stamp is missing there can be null pointer - // ignore - } - if (time1 > time2) { - return -1; - } else if (time1 == time2) { - return 0; - } else { - return 1; - } - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/DecisionCache.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/DecisionCache.java deleted file mode 100644 index c3e87d41bb7c..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/DecisionCache.java +++ /dev/null @@ -1,96 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.cache; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.identity.entitlement.PDPConstants; - - -/** - * Decision cache to handle request against response cache within the cluster. - */ -public class DecisionCache extends EntitlementBaseCache { - - private static final Log log = LogFactory.getLog(DecisionCache.class); - - public DecisionCache(int timeOut) { - super(PDPConstants.PDP_DECISION_CACHE, timeOut); - } - - /** - * Can add decision to the cluster with key - * - * @param key - * @param decision - */ - public void addToCache(String key, Object decision) { - if (log.isDebugEnabled()) { - String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - log.debug("DecisionCache is added for tenant : " + tenantDomain + " tenantId : " + tenantId + " " + - "cache key : " + key + " cache value : " + decision); - } - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - IdentityCacheKey cacheKey = new IdentityCacheKey(tenantId, key); - addToCache(cacheKey, decision); - - } - - /** - * Can get the decision for the request if it available in the cache. - * - * @param key - * @return - */ - public Object getFromCache(String key) { - - if (log.isDebugEnabled()) { - String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - log.debug("DecisionCache is get for tenant : " + tenantDomain + " tenantId : " + tenantId + " " + - "cache key : " + key); - } - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - IdentityCacheKey cacheKey = new IdentityCacheKey(tenantId, key); - - - Object entry = getValueFromCache(cacheKey); - if (entry != null) { - return entry; - } - - return null; - } - - /** - * Clear all decision cache - */ - public void clearCache() { - if (log.isDebugEnabled()) { - String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - log.debug("DecisionCache clear all cache from the cluster and tenant domain " + tenantDomain); - } - clear(); - } - -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/EntitlementBaseCache.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/EntitlementBaseCache.java deleted file mode 100644 index 297e2220a3d3..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/EntitlementBaseCache.java +++ /dev/null @@ -1,232 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.cache; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.CarbonContext; - -import javax.cache.Cache; -import javax.cache.CacheBuilder; -import javax.cache.CacheConfiguration; -import javax.cache.CacheManager; -import javax.cache.Caching; -import javax.cache.event.CacheEntryCreatedListener; -import javax.cache.event.CacheEntryUpdatedListener; -import java.util.concurrent.TimeUnit; - -/** - * A base class for all cache implementations in user entitlement module. - */ -public class EntitlementBaseCache { - - private static final String ENTITLEMENT_CACHE_MANAGER = "ENTITLEMENT_CACHE_MANAGER"; - private static Log log = LogFactory.getLog(EntitlementBaseCache.class); - private String Entitlement_CACHE_NAME; - private int cacheTimeout; - private CacheBuilder cacheBuilder; - private CacheEntryUpdatedListener cacheEntryUpdatedListener; - private CacheEntryCreatedListener cacheEntryCreatedListener; - - /** - * Create Entitlement cache object - * - * @param cacheName Name for the cache, entitlement caches differentiate from this name. - * @param timeout Cache timeout in milliseconds. - */ - public EntitlementBaseCache(String cacheName, int timeout) { - this.Entitlement_CACHE_NAME = cacheName; - if (timeout > 0) { - this.cacheTimeout = timeout; - } else { - this.cacheTimeout = -1; - } - if (log.isDebugEnabled()) { - String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - log.debug( - "Cache : " + Entitlement_CACHE_NAME + " is initialized" + " for tenant domain : " + tenantDomain); - } - } - - /** - * Create Entiltement cache object - * - * @param cacheName Name for the cache, entitlement caches differentiate from this name. - */ - public EntitlementBaseCache(String cacheName) { - this.Entitlement_CACHE_NAME = cacheName; - this.cacheTimeout = -1; - if (log.isDebugEnabled()) { - String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - log.debug( - "Cache : " + Entitlement_CACHE_NAME + " is initialized" + " for tenant domain : " + tenantDomain); - } - } - - /** - * Getting existing cache if the cache available, else returns a newly created cache. - * This logic handles by javax.cache implementation - * - * @return - */ - private Cache getEntitlementCache() { - - Cache cache = null; - CacheManager cacheManager = Caching.getCacheManagerFactory().getCacheManager(ENTITLEMENT_CACHE_MANAGER); - if (this.cacheTimeout > 0) { - if (cacheBuilder == null) { - synchronized (Entitlement_CACHE_NAME.intern()) { - if (cacheBuilder == null) { - cacheManager.removeCache(Entitlement_CACHE_NAME); - this.cacheBuilder = cacheManager.createCacheBuilder(Entitlement_CACHE_NAME). - setExpiry(CacheConfiguration.ExpiryType.MODIFIED, - new CacheConfiguration.Duration(TimeUnit.SECONDS, cacheTimeout)). - setStoreByValue(false); - cache = cacheBuilder.build(); - - if (cacheEntryUpdatedListener != null) { - this.cacheBuilder.registerCacheEntryListener(cacheEntryUpdatedListener); - } - if (cacheEntryCreatedListener != null) { - this.cacheBuilder.registerCacheEntryListener(cacheEntryCreatedListener); - } - if (log.isDebugEnabled()) { - String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - log.debug("Cache : " + Entitlement_CACHE_NAME + " is built with time out value " + ": " + - cacheTimeout + " for tenant domain : " + tenantDomain); - } - } - } - } else { - cache = cacheManager.getCache(Entitlement_CACHE_NAME); - } - } else { - cache = cacheManager.getCache(Entitlement_CACHE_NAME); - } - return cache; - } - - public void initCacheBuilder() { - getEntitlementCache(); - } - - /** - * Add a cache entry. - * - * @param key Key which cache entry is indexed. - * @param entry Actual object where cache entry is placed. - */ - public void addToCache(K key, V entry) { - // Element already in the cache. Remove it first - clearCacheEntry(key); - updateToCache(key, entry); - } - - - /** - * Update the cache without clearing the cache item - * - * @param key - * @param entry - */ - public void updateToCache(K key, V entry) { - // Element already in the cache. Remove it first - - Cache cache = getEntitlementCache(); - if (cache != null) { - cache.put(key, entry); - } - if (log.isDebugEnabled()) { - String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - log.debug("Cache : " + Entitlement_CACHE_NAME + " is populated with new entry " + "in tenant domain : " + - tenantDomain); - } - } - - /** - * Retrieves a cache entry. - * - * @param key CacheKey - * @return Cached entry. - */ - public V getValueFromCache(K key) { - Cache cache = getEntitlementCache(); - if (cache != null) { - if (cache.containsKey(key)) { - if (log.isDebugEnabled()) { - String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - log.debug("Cache : " + Entitlement_CACHE_NAME + " is HIT " + "in tenant domain : " + tenantDomain); - } - return cache.get(key); - } - } - if (log.isDebugEnabled()) { - String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - log.debug("Cache : " + Entitlement_CACHE_NAME + " is MISSED " + "in tenant domain : " + tenantDomain); - } - return null; - } - - /** - * Clears a cache entry. - * - * @param key Key to clear cache. - */ - public void clearCacheEntry(K key) { - Cache cache = getEntitlementCache(); - if (cache != null) { - if (cache.containsKey(key)) { - cache.remove(key); - if (log.isDebugEnabled()) { - String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - log.debug("Cache : " + Entitlement_CACHE_NAME + " entry is removed " + "in tenant domain : " + - tenantDomain); - } - } - } - } - - /** - * Remove everything in the cache. - */ - public void clear() { - Cache cache = getEntitlementCache(); - if (cache != null) { - try { - cache.removeAll(); - if (log.isDebugEnabled()) { - String tenantDomain = CarbonContext - .getThreadLocalCarbonContext().getTenantDomain(); - log.debug("Cache : " + Entitlement_CACHE_NAME + " is cleared " + "in tenant domain : " + - tenantDomain); - } - } catch (Exception e) { - //TODO - Handle the IdentityCacheKey exception in cluster env. - } - } - } - - public void setCacheEntryUpdatedListener(CacheEntryUpdatedListener cacheEntryUpdatedListener) { - this.cacheEntryUpdatedListener = cacheEntryUpdatedListener; - } - - public void setCacheEntryCreatedListener(CacheEntryCreatedListener cacheEntryCreatedListener) { - this.cacheEntryCreatedListener = cacheEntryCreatedListener; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/EntitlementEngineCache.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/EntitlementEngineCache.java deleted file mode 100644 index 9b62f30bc77d..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/EntitlementEngineCache.java +++ /dev/null @@ -1,168 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.cache; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.caching.impl.CachingConstants; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.identity.entitlement.PDPConstants; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; -import org.wso2.carbon.identity.entitlement.pdp.EntitlementEngine; -import org.wso2.carbon.utils.multitenancy.MultitenantConstants; - -import javax.cache.Cache; -import javax.cache.CacheBuilder; -import javax.cache.CacheConfiguration; -import javax.cache.CacheManager; -import javax.cache.Caching; -import java.util.Properties; -import java.util.concurrent.TimeUnit; - -/** - * - */ -public class EntitlementEngineCache { - - public static final String ENTITLEMENT_ENGINE_CACHE_MANAGER = "ENTITLEMENT_ENGINE_CACHE_MANAGER"; - public static final String ENTITLEMENT_ENGINE_CACHE = - CachingConstants.LOCAL_CACHE_PREFIX + "ENTITLEMENT_ENGINE_CACHE"; - private static final EntitlementEngineCache instance = new EntitlementEngineCache(); - private static CacheBuilder cacheBuilder; - private static final Log log = LogFactory.getLog(EntitlementEngineCache.class); - private static final long DEFAULT_ENTITLEMENT_ENGINE_CACHING_INTERVAL = 900; - - private EntitlementEngineCache(){ - - } - - /** - * Gets a new instance of EntitlementEngineCache. - * - * @return A new instance of EntitlementEngineCache. - */ - public static EntitlementEngineCache getInstance() { - return instance; - } - - - private Cache getEntitlementCache() { - Cache cache; - CacheManager cacheManager = Caching.getCacheManagerFactory().getCacheManager(ENTITLEMENT_ENGINE_CACHE_MANAGER); - if (cacheManager != null) { - if (cacheBuilder == null) { - Properties properties = EntitlementServiceComponent.getEntitlementConfig().getEngineProperties(); - String engineCachingInterval = properties.getProperty(PDPConstants.ENTITLEMENT_ENGINE_CACHING_INTERVAL); - long entitlementEngineCachingInterval = DEFAULT_ENTITLEMENT_ENGINE_CACHING_INTERVAL; - if (engineCachingInterval != null) { - try { - entitlementEngineCachingInterval = Long.parseLong(engineCachingInterval); - } catch (NumberFormatException e) { - log.warn("Invalid value for " + PDPConstants.ENTITLEMENT_ENGINE_CACHING_INTERVAL + ". Using " + - "default value " + entitlementEngineCachingInterval + " seconds."); - } - } else { - if (log.isDebugEnabled()) { - log.debug(PDPConstants.ENTITLEMENT_ENGINE_CACHING_INTERVAL + " not set. Using default value " + - entitlementEngineCachingInterval + " seconds."); - } - } - cacheManager.removeCache(ENTITLEMENT_ENGINE_CACHE); - cacheBuilder = cacheManager.createCacheBuilder(ENTITLEMENT_ENGINE_CACHE). - setExpiry(CacheConfiguration.ExpiryType.ACCESSED, - new CacheConfiguration.Duration(TimeUnit.SECONDS, entitlementEngineCachingInterval)). - setExpiry(CacheConfiguration.ExpiryType.MODIFIED, - new CacheConfiguration.Duration(TimeUnit.SECONDS, entitlementEngineCachingInterval)); - cache = cacheBuilder.build(); - } else { - cache = cacheManager.getCache(ENTITLEMENT_ENGINE_CACHE); - } - } else { - cache = Caching.getCacheManager().getCache(ENTITLEMENT_ENGINE_CACHE); - } - if (log.isDebugEnabled()) { - log.debug("created authorization cache : " + cache); - } - return cache; - } - - public EntitlementEngine get(int key) { - try { - PrivilegedCarbonContext.startTenantFlow(); - PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID); - carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); - EntitlementEngine entitlementEngine = getEntitlementCache().get(key); - if (entitlementEngine != null) { - if (log.isDebugEnabled()) { - log.debug("Cache : " + ENTITLEMENT_ENGINE_CACHE + " is HIT " + - "for tenantId : " + key); - } - } else { - if (log.isDebugEnabled()) { - log.debug("Cache : " + ENTITLEMENT_ENGINE_CACHE + " is MISSED " + - "for tenantId : " + key); - } - } - return entitlementEngine; - } finally { - PrivilegedCarbonContext.endTenantFlow(); - } - } - - public void put(int key, EntitlementEngine engine) { - try { - PrivilegedCarbonContext.startTenantFlow(); - PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID); - carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); - getEntitlementCache().put(key, engine); - if (log.isDebugEnabled()) { - log.debug("Cache : " + ENTITLEMENT_ENGINE_CACHE + " is populated with new entry " + - "with tenantId : " + key); - } - } finally { - PrivilegedCarbonContext.endTenantFlow(); - } - } - - public boolean contains(int key) { - try { - PrivilegedCarbonContext.startTenantFlow(); - PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID); - carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); - boolean contain = getEntitlementCache().containsKey(key); - if (contain) { - if (log.isDebugEnabled()) { - log.debug("Cache : " + ENTITLEMENT_ENGINE_CACHE + " is HIT " + - "for tenantId : " + key); - } - } else { - if (log.isDebugEnabled()) { - log.debug("Cache : " + ENTITLEMENT_ENGINE_CACHE + " is MISSED " + - "for tenantId : " + key); - } - } - return contain; - } finally { - PrivilegedCarbonContext.endTenantFlow(); - } - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/IdentityCacheEntry.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/IdentityCacheEntry.java deleted file mode 100644 index 5b20036a3691..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/IdentityCacheEntry.java +++ /dev/null @@ -1,105 +0,0 @@ -/* -* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.cache; - -import java.io.Serializable; -import java.security.Key; -import java.util.Arrays; -import java.util.Date; -import java.util.Set; - -/** - * Identity Cache entry which wraps the identity related cache entry values - */ -public class IdentityCacheEntry implements Serializable { - - private static final long serialVersionUID = 6982031255566292798L; - - private String cacheEntry; - private Set cacheEntrySet; - private String[] cacheEntryArray; - private int hashEntry; - private long cacheInterval; - private boolean cacheClearing; - private Key secretKey; - private Date date; - - public IdentityCacheEntry(String cacheEntry) { - this.cacheEntry = cacheEntry; - } - - public IdentityCacheEntry(int hashEntry) { - this.hashEntry = hashEntry; - } - - public IdentityCacheEntry(boolean cacheClearing) { - this.cacheClearing = cacheClearing; - } - - public IdentityCacheEntry(String cacheEntry, long cacheInterval) { - this.cacheEntry = cacheEntry; - this.cacheInterval = cacheInterval; - } - - public IdentityCacheEntry(String[] cacheEntryArray) { - this.cacheEntryArray = Arrays.copyOf(cacheEntryArray, cacheEntryArray.length); - } - - public IdentityCacheEntry(Set cacheEntrySet) { - this.cacheEntrySet = cacheEntrySet; - } - - public IdentityCacheEntry(String cacheEntry, Key secretKey, Date date) { - this.cacheEntry = cacheEntry; - this.secretKey = secretKey; - this.date = new Date(date.getTime()); - } - - public String getCacheEntry() { - return cacheEntry; - } - - public int getHashEntry() { - return hashEntry; - } - - public long getCacheInterval() { - return cacheInterval; - } - - public Set getCacheEntrySet() { - return cacheEntrySet; - } - - public boolean isCacheClearing() { - return cacheClearing; - } - - public String[] getCacheEntryArray() { - return Arrays.copyOf(cacheEntryArray, cacheEntryArray.length); - } - - public Key getSecretKey() { - return secretKey; - } - - public Date getDate() { - return new Date(date.getTime()); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/IdentityCacheKey.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/IdentityCacheKey.java deleted file mode 100644 index 44569377f26a..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/IdentityCacheKey.java +++ /dev/null @@ -1,65 +0,0 @@ -/* -* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.cache; - -import java.io.Serializable; - -/** - * Identity Cache key which wraps the identity related cache key values - */ -public class IdentityCacheKey implements Serializable { - - private static final long serialVersionUID = 3413834923591132863L; - - private int tenantId; - private String key; - - public IdentityCacheKey(int tenantId, String key) { - this.tenantId = tenantId; - this.key = key; - } - - public String getKey() { - return key; - } - - public int getTenantId() { - return tenantId; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof IdentityCacheKey)) return false; - - IdentityCacheKey that = (IdentityCacheKey) o; - - if (tenantId != that.tenantId) return false; - if (key != null ? !key.equals(that.key) : that.key != null) return false; - - return true; - } - - @Override - public int hashCode() { - int result = tenantId; - result = 31 * result + (key != null ? key.hashCode() : 0); - return result; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PIPAbstractAttributeCache.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PIPAbstractAttributeCache.java deleted file mode 100644 index 4bf11289a90b..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PIPAbstractAttributeCache.java +++ /dev/null @@ -1,59 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.cache; - -import org.wso2.carbon.caching.impl.CachingConstants; -import org.wso2.carbon.identity.entitlement.PDPConstants; - -import java.util.Set; - -/** - * - */ -public class PIPAbstractAttributeCache extends EntitlementBaseCache { - - public PIPAbstractAttributeCache(int timeOut) { - super(CachingConstants.LOCAL_CACHE_PREFIX + PDPConstants.PIP_ABSTRACT_ATTRIBUTE_CACHE, timeOut); - } - - public void addToCache(int tenantId, String key, Set attributes) { - - IdentityCacheKey cacheKey = new IdentityCacheKey(tenantId, key); - IdentityCacheEntry cacheEntry = new IdentityCacheEntry(attributes); - addToCache(cacheKey, cacheEntry); - } - - public Set getFromCache(int tenantId, String key) { - - Set attributes = null; - IdentityCacheKey cacheKey = new IdentityCacheKey(tenantId, key); - Object entry = getValueFromCache(cacheKey); - if (entry != null) { - IdentityCacheEntry cacheEntry = (IdentityCacheEntry) entry; - attributes = cacheEntry.getCacheEntrySet(); - } - - return attributes; - } - - public void clearCache() { - - clear(); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PIPAttributeCache.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PIPAttributeCache.java deleted file mode 100644 index 86c0feee1afd..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PIPAttributeCache.java +++ /dev/null @@ -1,55 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.cache; - -import org.wso2.carbon.identity.entitlement.PDPConstants; - -import java.util.Set; - -/** - * - */ -public class PIPAttributeCache extends EntitlementBaseCache { - - public PIPAttributeCache(int timeOut) { - super(PDPConstants.PIP_ATTRIBUTE_CACHE, timeOut); - } - - public void addToCache(int tenantId, String key, Set attributes) { - - IdentityCacheKey cacheKey = new IdentityCacheKey(tenantId, key); - IdentityCacheEntry cacheEntry = new IdentityCacheEntry(attributes); - addToCache(cacheKey, cacheEntry); - } - - public Set getFromCache(int tenantId, String key) { - - Set attributes = null; - IdentityCacheKey cacheKey = new IdentityCacheKey(tenantId, key); - IdentityCacheEntry cacheEntry = getValueFromCache(cacheKey); - if (cacheEntry != null) { - attributes = cacheEntry.getCacheEntrySet(); - } - return attributes; - } - - public void clearCache() { - clear(); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PapPolicyCache.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PapPolicyCache.java deleted file mode 100644 index 57dc7f4b3128..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PapPolicyCache.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.cache; - -import org.wso2.carbon.identity.core.cache.BaseCache; -import org.wso2.carbon.identity.entitlement.dto.PolicyDTO; - -/** - * Cache implementation for PAP policies. - * Cache entry: - */ -public class PapPolicyCache extends BaseCache { - - private static final String CACHE_NAME = "PapPolicyCache"; - private static final PapPolicyCache instance = new PapPolicyCache(); - - private PapPolicyCache() { - - super(CACHE_NAME); - } - - public static PapPolicyCache getInstance() { - - return instance; - } - - @Override - public void addToCache(String key, PolicyDTO policyDTO, int tenantId) { - - if (policyDTO != null) { - PolicyDTO policyDTOCopy = new PolicyDTO(policyDTO); - super.addToCache(key, policyDTOCopy, tenantId); - } - } - - @Override - public PolicyDTO getValueFromCache(String key, int tenantId) { - - PolicyDTO policyDTO = super.getValueFromCache(key, tenantId); - PolicyDTO policyDTOCopy = null; - if (policyDTO != null) { - policyDTOCopy = new PolicyDTO(policyDTO); - } - return policyDTOCopy; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PapPolicyListCache.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PapPolicyListCache.java deleted file mode 100644 index ddda10e3a6c7..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PapPolicyListCache.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.cache; - -import org.wso2.carbon.identity.core.cache.BaseCache; -import org.wso2.carbon.identity.entitlement.dto.PolicyDTO; - -import java.util.ArrayList; - -/** - * Cache implementation for PAP policy list. - * Cache entry: - */ -public class PapPolicyListCache extends BaseCache> { - - private static final String CACHE_NAME = "PapPolicyListCache"; - private static final PapPolicyListCache instance = new PapPolicyListCache(); - - private PapPolicyListCache() { - - super(CACHE_NAME); - } - - public static PapPolicyListCache getInstance() { - - return instance; - } - - @Override - public void addToCache(String key, ArrayList policyDTOs, int tenantId) { - - ArrayList policyDTOList = createCopy(policyDTOs); - super.addToCache(key, policyDTOList, tenantId); - } - - @Override - public ArrayList getValueFromCache(String key, int tenantId) { - - ArrayList policyDTOs = super.getValueFromCache(key, tenantId); - return createCopy(policyDTOs); - } - - private ArrayList createCopy(ArrayList policyDTOs) { - - if (policyDTOs == null) { - return null; - } - - ArrayList policyDTOList = new ArrayList<>(); - for (PolicyDTO policyDTO : policyDTOs) { - if (policyDTO != null) { - policyDTOList.add(new PolicyDTO(policyDTO)); - } - } - return policyDTOList; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PdpPolicyCache.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PdpPolicyCache.java deleted file mode 100644 index bfd2baa4523c..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PdpPolicyCache.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.cache; - -import org.wso2.carbon.identity.core.cache.BaseCache; -import org.wso2.carbon.identity.entitlement.dto.PolicyStoreDTO; - -/** - * Cache implementation for PAP policies. - * Cache entry: - */ -public class PdpPolicyCache extends BaseCache { - - private static final String CACHE_NAME = "PdpPolicyCache"; - private static final PdpPolicyCache instance = new PdpPolicyCache(); - - private PdpPolicyCache() { - - super(CACHE_NAME); - } - - public static PdpPolicyCache getInstance() { - - return instance; - } - - @Override - public void addToCache(String key, PolicyStoreDTO policyStoreDTO, int tenantId) { - - if (policyStoreDTO != null){ - PolicyStoreDTO policyStoreDTOCopy = new PolicyStoreDTO(policyStoreDTO); - super.addToCache(key, policyStoreDTOCopy, tenantId); - } - } - - @Override - public PolicyStoreDTO getValueFromCache(String key, int tenantId) { - - PolicyStoreDTO policyStoreDTO = super.getValueFromCache(key, tenantId); - PolicyStoreDTO policyStoreDTOCopy = null; - if (policyStoreDTO != null) { - policyStoreDTOCopy = new PolicyStoreDTO(policyStoreDTO); - } - return policyStoreDTOCopy; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PdpPolicyListCache.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PdpPolicyListCache.java deleted file mode 100644 index 7f7505bfab40..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PdpPolicyListCache.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.cache; - -import org.wso2.carbon.identity.core.cache.BaseCache; -import org.wso2.carbon.identity.entitlement.dto.PolicyStoreDTO; - -import java.util.ArrayList; - -/** - * Cache implementation for PDP policy list. - * Cache entry: - */ -public class PdpPolicyListCache extends BaseCache { - - private static final String CACHE_NAME = "PdpPolicyListCache"; - private static final PdpPolicyListCache instance = new PdpPolicyListCache(); - - private PdpPolicyListCache() { - - super(CACHE_NAME); - } - - public static PdpPolicyListCache getInstance() { - - return instance; - } - - @Override - public void addToCache(String key, PolicyStoreDTO[] policyDTOs, int tenantId) { - - PolicyStoreDTO[] policyDTOList = createCopy(policyDTOs); - super.addToCache(key, policyDTOList, tenantId); - } - - @Override - public PolicyStoreDTO[] getValueFromCache(String key, int tenantId) { - - PolicyStoreDTO[] policyDTOs = super.getValueFromCache(key, tenantId); - return createCopy(policyDTOs); - } - - private PolicyStoreDTO[] createCopy(PolicyStoreDTO[] policyDTOs) { - - if (policyDTOs == null) { - return null; - } - ArrayList policyDTOList = new ArrayList<>(); - for (PolicyStoreDTO policyDTO : policyDTOs) { - if (policyDTO != null) { - policyDTOList.add(new PolicyStoreDTO(policyDTO)); - } - } - return policyDTOList.toArray(new PolicyStoreDTO[0]); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PolicyCache.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PolicyCache.java deleted file mode 100644 index 4f73a8da0915..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PolicyCache.java +++ /dev/null @@ -1,348 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.cache; - -import org.apache.axis2.clustering.ClusteringAgent; -import org.apache.axis2.clustering.ClusteringFault; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.identity.entitlement.PDPConstants; -import org.wso2.carbon.identity.entitlement.PolicyStatusClusterMessage; -import org.wso2.carbon.identity.entitlement.common.EntitlementConstants; -import org.wso2.carbon.identity.entitlement.internal.EntitlementConfigHolder; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -/** - * PolicyCache is to manage cluster level distributed cache for the status of the policy file. This is not distribute - * complete policy file within cluster itself. - */ -public class PolicyCache extends EntitlementBaseCache{ - - private static final Log log = LogFactory.getLog(PolicyCache.class); - private static final Object lock = new Object(); - private int myHashCode; - private static final int INVALID_STATE = 1; - private static Map cacheInvalidationState = new HashMap(); - private static Map> localPolicyCacheMap = new HashMap>(); - - /** - * - * @param timeout - */ - public PolicyCache(int timeout) { - super(PDPConstants.ENTITLEMENT_POLICY_INVALIDATION_CACHE,timeout); - PolicyCacheUpdateListener policyCacheUpdateListener = new PolicyCacheUpdateListener(); - PolicyCacheCreatedListener policyCacheCreatedListener = new PolicyCacheCreatedListener(); - setCacheEntryUpdatedListener(policyCacheUpdateListener); - setCacheEntryCreatedListener(policyCacheCreatedListener); - initCacheBuilder(); - - if(log.isDebugEnabled()){ - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - log.debug("PolicyCache initializing for tenant " + tenantId); - } - } - - /** - * This method triggered by cache entry listener. - * - * @param identityCacheKey - * @param policyStatus - */ - public static void updateLocalPolicyCacheMap(IdentityCacheKey identityCacheKey, PolicyStatus policyStatus){ - if(identityCacheKey.getKey()!=null) { - if(!identityCacheKey.getKey().equals("")) { - if(log.isDebugEnabled()){ - log.debug("Updating local cache map for the tenant : " + identityCacheKey.getTenantId() + " and Policy : " + identityCacheKey.getKey()); - } - synchronized (localPolicyCacheMap) { - if (localPolicyCacheMap.get(identityCacheKey.getTenantId()) != null) { - if(localPolicyCacheMap.get(identityCacheKey.getTenantId()).get(identityCacheKey.getKey())!=null){ - if (policyStatus != null && StringUtils.isNotEmpty(policyStatus.getPolicyId())) { - if (policyStatus.getPolicyId() - .equals(localPolicyCacheMap.get(identityCacheKey.getTenantId()) - .get(identityCacheKey.getKey()).getPolicyId())) { - validateAndUpdatePolicyAction(identityCacheKey, policyStatus); - } - } - PolicyStatus status = localPolicyCacheMap.get(identityCacheKey.getTenantId()).get(identityCacheKey.getKey()); - status.setPolicyAction(getPriorityAction(status.getPolicyAction(),policyStatus.getPolicyAction())); - if(log.isDebugEnabled()){ - log.debug("Updated existing policy in local cache map : Policy : " + identityCacheKey.getKey() + " and new action : " + getPriorityAction(status.getPolicyAction(),policyStatus.getPolicyAction())); - } - }else{ - localPolicyCacheMap.get(identityCacheKey.getTenantId()).put(policyStatus.getPolicyId(),policyStatus); - if(log.isDebugEnabled()){ - log.debug("Adding policy in to the local cache policy map : policy : " + identityCacheKey.getKey() ); - } - } - } else { - Map map = new HashMap(); - - map.put(policyStatus.getPolicyId(),policyStatus); - localPolicyCacheMap.put(identityCacheKey.getTenantId(), map); - if(log.isDebugEnabled()){ - log.debug("Adding policy in to the local cache policy map : policy : " + identityCacheKey.getKey() + " add new entry for this tenant : " + identityCacheKey.getTenantId() ); - } - - } - } - }else{ - cacheInvalidationState.put(identityCacheKey.getTenantId(),1); - if(log.isDebugEnabled()){ - log.debug("Trigger event to clear all cache in tenant : " + identityCacheKey.getTenantId()); - } - } - } - } - - /** - * To update the localPolicyCacheMap whenever the deletion and publishing are carried out at the same time. - *

    - * In this edge case, when the user deletes the policy, the deleted policy is added to the policy cache - * (policies to be invalidated) with the status- "DELETE" and when the policy is published back again since - * there is already a cache entry with the status- "DELETE" the status would not be changed to "UPDATE". - * - * @param identityCacheKey Identity Cache key which wraps the identity related cache key values. - * @param policyStatus The status of the policy. - */ - private static void validateAndUpdatePolicyAction(IdentityCacheKey identityCacheKey, PolicyStatus policyStatus) { - - if (("UPDATE").equals(policyStatus.getPolicyAction()) && - ("DELETE").equals(localPolicyCacheMap.get(identityCacheKey.getTenantId()).get(identityCacheKey.getKey()) - .getPolicyAction())) { - localPolicyCacheMap.get(identityCacheKey.getTenantId()).get(identityCacheKey.getKey()) - .setPolicyAction(policyStatus.getPolicyAction()); - } - } - - /** - * Do invalidate all policy cache - */ - public void invalidateCache() { - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - if (log.isDebugEnabled()) { - log.debug("Trigger invalidateCache to tenant : " + tenantId + " and all policy "); - } - - IdentityCacheKey cacheKey = new IdentityCacheKey(tenantId, ""); - // update local cache map of this node. - updateLocalPolicyCacheMap(cacheKey, new PolicyStatus()); - // send out a cluster message to notify other nodes - if (isClusteringEnabled()) { - sendClusterMessage(new PolicyStatusClusterMessage(cacheKey, new PolicyStatus()), true); - } else { - if (log.isDebugEnabled()) { - log.debug("Clustering not enabled. Not sending cluster message to other nodes."); - } - } - - } - - - /** - * Check the state of expire in local cache. - * - * @return - */ - public boolean isInvalidate() { - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - int state = 0; - - synchronized (cacheInvalidationState) { - if (cacheInvalidationState.get(tenantId) != null) { - state = cacheInvalidationState.get(tenantId); - } else { - // we ignore the case where the cache invalidation state is not present.This means the cache is valid. - } - } - - boolean isInvalid = (state == INVALID_STATE); - if (log.isDebugEnabled()) { - log.debug("Check the invalidation state of all cache, isCacheInvalid: " + isInvalid); - } - - return isInvalid; - } - - public void resetCacheInvalidateState() { - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - // since the cache is invalidated already making cacheInvalidationState to '0' - cacheInvalidationState.put(tenantId, 0); - } - - /** - * - * Invalidate any policy with action. It will send the cluster message to clean this policy in all the nodes. - * - * @param policyId - * @param action - */ - public void invalidateCache(String policyId, String action) { - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - - if(log.isDebugEnabled()){ - log.debug("Trigger invalidateCache to tenant : " + tenantId + " and policy " + policyId + " for action " + - ": " + action); - } - - IdentityCacheKey cacheKey = new IdentityCacheKey(tenantId, policyId); - PolicyStatus policyStatus = (PolicyStatus) getValueFromCache(cacheKey); - - if (policyStatus == null) { - policyStatus = new PolicyStatus(policyId, 0, action); - } else { - policyStatus.setStatusCount(policyStatus.getStatusCount() + 1); - policyStatus.setPolicyAction(action); - } - // update local cache map of this node. - updateLocalPolicyCacheMap(cacheKey, policyStatus); - - // send out a cluster message to notify other nodes. - if (isClusteringEnabled()) { - sendClusterMessage(new PolicyStatusClusterMessage(cacheKey, policyStatus), true); - } else { - if (log.isDebugEnabled()) { - log.debug("Clustering not enabled. Not sending cluster message to other nodes."); - } - } - - - - synchronized (localPolicyCacheMap) { - if(localPolicyCacheMap.get(cacheKey.getTenantId())!=null){ - if(localPolicyCacheMap.get(cacheKey.getTenantId()).get(cacheKey.getKey())!=null){ - PolicyStatus status = localPolicyCacheMap.get(cacheKey.getTenantId()).get(cacheKey.getKey()); - status.setPolicyAction(getPriorityAction(status.getPolicyAction(),action)); - } - }else{ - Map map = new HashMap(); - - map.put(policyId,policyStatus); - localPolicyCacheMap.put(cacheKey.getTenantId(),map); - } - } - } - - - - /** - * Read the invalidated policies in the local cache. Local cache always synch up with the cluster cache. - * - * @return - */ - public Collection getInvalidatedPolicies(){ - - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - - - if(log.isDebugEnabled()){ - log.debug("Reading invalidated policy files for : "+ tenantId); - } - Collection tmpSet = null ; - - if(localPolicyCacheMap.get(tenantId)!=null) { - - Map tmpMap = localPolicyCacheMap.get(tenantId); - tmpSet = tmpMap.values(); - } - - return tmpSet ; - } - - /** - * This method is for get the priority of the action. - * - * ex: There is already updated action saying change the order of that. But another action coming syaing delete - * this. What would be the latest state of that policy cache ? It is decided by the following order. In this case - * even though the older state is -re-order, we have to change it to the delete because delete is highher than - * the re-order. - * - * @param currentAction - * @param newAction - * @return - */ - private static String getPriorityAction(String currentAction, String newAction){ - - if(EntitlementConstants.PolicyPublish.ACTION_DELETE.equals(currentAction) || EntitlementConstants.PolicyPublish.ACTION_DELETE.equals(newAction)){ - return EntitlementConstants.PolicyPublish.ACTION_DELETE; - }else if(EntitlementConstants.PolicyPublish.ACTION_DISABLE.equals(currentAction) || EntitlementConstants.PolicyPublish.ACTION_DISABLE.equals(newAction)){ - return EntitlementConstants.PolicyPublish.ACTION_DELETE; - }else if(EntitlementConstants.PolicyPublish.ACTION_ENABLE.equals(currentAction) || EntitlementConstants.PolicyPublish.ACTION_ENABLE.equals(newAction)){ - return EntitlementConstants.PolicyPublish.ACTION_CREATE; - }else if(EntitlementConstants.PolicyPublish.ACTION_UPDATE.equals(currentAction) || EntitlementConstants.PolicyPublish.ACTION_UPDATE.equals(newAction)){ - return EntitlementConstants.PolicyPublish.ACTION_UPDATE; - }else if(EntitlementConstants.PolicyPublish.ACTION_ORDER.equals(currentAction) || EntitlementConstants.PolicyPublish.ACTION_ORDER.equals(newAction)){ - return EntitlementConstants.PolicyPublish.ACTION_ORDER; - } - return newAction ; - } - - - /** - * Send out policy status change notification to other nodes. - * - * @param clusterMessage - * @param isSync - */ - private void sendClusterMessage(PolicyStatusClusterMessage clusterMessage, boolean isSync) { - try { - if (log.isDebugEnabled()) { - log.debug("Sending policy status change cluster message to all other nodes"); - } - - ClusteringAgent clusteringAgent = EntitlementConfigHolder.getInstance() - .getConfigurationContextService() - .getServerConfigContext() - .getAxisConfiguration() - .getClusteringAgent(); - - if (clusteringAgent != null) { - clusteringAgent.sendMessage(clusterMessage, isSync); - } else { - log.error("Clustering Agent not available."); - } - } catch (ClusteringFault clusteringFault) { - log.error("Error while sending policy status change cluster message", clusteringFault); - } - } - - - /** - * Check whether clustering is enabled. - * - * @return boolean returns true if clustering enabled, false otherwise. - */ - private boolean isClusteringEnabled() { - - return EntitlementConfigHolder.getInstance().getConfigurationContextService() - .getServerConfigContext().getAxisConfiguration().getClusteringAgent() != null; - } - -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PolicyCacheCreatedListener.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PolicyCacheCreatedListener.java deleted file mode 100644 index 69bd5826bfd3..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PolicyCacheCreatedListener.java +++ /dev/null @@ -1,49 +0,0 @@ -/* -* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.cache; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.cache.event.CacheEntryCreatedListener; -import javax.cache.event.CacheEntryEvent; -import javax.cache.event.CacheEntryListenerException; - -/** - * Created for get update when the cache entry created by any node in the cluster - */ -public class PolicyCacheCreatedListener implements CacheEntryCreatedListener { - - private static final Log log = LogFactory.getLog(PolicyCacheCreatedListener.class); - - /** - * - * @param event The entry just added. - * @throws CacheEntryListenerException - */ - @Override - public void entryCreated(CacheEntryEvent event) throws CacheEntryListenerException { - if(log.isDebugEnabled()){ - log.debug("ConfigCacheCreatedListener triggered for tenant: " + event.getKey().getTenantId() + " and " + - "key : " + event.getKey() - .getKey()); - } - PolicyCache.updateLocalPolicyCacheMap(event.getKey(),event.getValue()); - } - -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PolicyCacheUpdateListener.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PolicyCacheUpdateListener.java deleted file mode 100644 index 6d2fa958777a..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PolicyCacheUpdateListener.java +++ /dev/null @@ -1,48 +0,0 @@ -/* -* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.cache; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.cache.event.CacheEntryEvent; -import javax.cache.event.CacheEntryListenerException; -import javax.cache.event.CacheEntryUpdatedListener; - -/** - * Created for get update when the cache entry update by any node in the cluster - */ -public class PolicyCacheUpdateListener implements CacheEntryUpdatedListener{ - - private static final Log log = LogFactory.getLog(PolicyCacheUpdateListener.class); - - - /** - * - * @param event The event just updated. - * @throws CacheEntryListenerException - */ - @Override - public void entryUpdated(CacheEntryEvent event) throws CacheEntryListenerException { - if(event!=null) { - PolicyCache.updateLocalPolicyCacheMap(event.getKey(), event.getValue()); - } - } - - -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PolicySearchCache.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PolicySearchCache.java deleted file mode 100644 index 9f4771555575..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PolicySearchCache.java +++ /dev/null @@ -1,128 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.cache; - -import org.apache.axis2.clustering.ClusteringAgent; -import org.apache.axis2.clustering.ClusteringFault; -import org.apache.axis2.clustering.ClusteringMessage; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.caching.impl.CachingConstants; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.identity.core.util.IdentityTenantUtil; -import org.wso2.carbon.identity.entitlement.PDPConstants; -import org.wso2.carbon.identity.entitlement.internal.EntitlementConfigHolder; -import org.wso2.carbon.identity.entitlement.policy.search.PolicySearchCacheInvalidationClusteringMessage; -import org.wso2.carbon.identity.entitlement.policy.search.SearchResult; - -/** - * - */ -public class PolicySearchCache extends EntitlementBaseCache { - - private static final Log log = LogFactory.getLog(PolicySearchCache.class); - - public PolicySearchCache(int timeOut) { - super(CachingConstants.LOCAL_CACHE_PREFIX + PDPConstants.POLICY_SEARCH_CACHE, timeOut); - } - - - public void addToCache(String key, SearchResult result) { - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - IdentityCacheKey cacheKey = new IdentityCacheKey(tenantId, key); - addToCache(cacheKey, result); - } - - public SearchResult getFromCache(String key) { - - SearchResult searchResult = null; - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - IdentityCacheKey cacheKey = new IdentityCacheKey(tenantId, key); - Object entry = getValueFromCache(cacheKey); - if (entry != null) { - searchResult = (SearchResult) entry; - } - - return searchResult; - } - - public void clearCache() { - clear(); - } - - /** - * Invalidate {@link PolicySearchCache}. It will send the cluster message to clean the {@link PolicySearchCache} - * in all the nodes. - */ - public void invalidateCache() { - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - - if (log.isDebugEnabled()) { - log.debug("Trigger invalidate policy search cache to tenant : " + IdentityTenantUtil.getTenantDomain(tenantId)); - } - - // Update local policy search cache of this node. - clearCache(); - - // Send out a cluster message to notify other nodes. - if (isClusteringEnabled()) { - sendClusterMessage(new PolicySearchCacheInvalidationClusteringMessage(tenantId), true); - } else { - if (log.isDebugEnabled()) { - log.debug("Clustering not enabled. Not sending cluster message to other nodes."); - } - } - } - - /** - * Send out policy status change notification to other nodes. - * - * @param clusterMessage - * @param isSync - */ - private void sendClusterMessage(ClusteringMessage clusterMessage, boolean isSync) { - try { - if (log.isDebugEnabled()) { - log.debug("Sending cluster message to all other nodes"); - } - ClusteringAgent clusteringAgent = EntitlementConfigHolder.getInstance().getConfigurationContextService() - .getServerConfigContext().getAxisConfiguration().getClusteringAgent(); - if (clusteringAgent != null) { - clusteringAgent.sendMessage(clusterMessage, isSync); - } else { - log.error("Clustering Agent not available."); - } - } catch (ClusteringFault clusteringFault) { - log.error("Error while sending cluster message", clusteringFault); - } - } - - /** - * Check whether clustering is enabled. - * - * @return boolean returns true if clustering enabled, false otherwise. - */ - private boolean isClusteringEnabled() { - - return EntitlementConfigHolder.getInstance().getConfigurationContextService() - .getServerConfigContext().getAxisConfiguration().getClusteringAgent() != null; - - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PolicyStatus.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PolicyStatus.java deleted file mode 100644 index c88687357fb0..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/PolicyStatus.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.wso2.carbon.identity.entitlement.cache; - -import java.io.Serializable; - -/** - * Created by harsha on 1/25/15. - */ -public class PolicyStatus implements Serializable { - - private static final long serialVersionUID = -5173389109938987102L; - - private String policyId = null; - private int statusCount = 0; - private String policyAction; - - public PolicyStatus() { - - } - - public PolicyStatus(String policyId) { - this.policyId = policyId; - } - - public PolicyStatus(String policyId, int statusCount, String policyAction) { - this.policyId = policyId; - this.statusCount = statusCount; - this.policyAction = policyAction; - } - - public PolicyStatus(int statusCount, String policyAction) { - this.statusCount = statusCount; - this.policyAction = policyAction; - } - - public int getStatusCount() { - return statusCount; - } - - public void setStatusCount(int statusCount) { - this.statusCount = statusCount; - } - - public String getPolicyAction() { - return policyAction; - } - - public void setPolicyAction(String policyAction) { - this.policyAction = policyAction; - } - - public String getPolicyId() { - return policyId; - } - - public void setPolicyId(String policyId) { - this.policyId = policyId; - } - - -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/SimpleDecisionCache.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/SimpleDecisionCache.java deleted file mode 100644 index 9712dea304c2..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/SimpleDecisionCache.java +++ /dev/null @@ -1,57 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.cache; - -import org.wso2.carbon.caching.impl.CachingConstants; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.identity.entitlement.PDPConstants; - -/** - * Simple Decision Cache - */ -public class SimpleDecisionCache extends EntitlementBaseCache { - - public SimpleDecisionCache(int timeOut) { - super(CachingConstants.LOCAL_CACHE_PREFIX + PDPConstants.PDP_SIMPLE_DECISION_CACHE, timeOut); - } - - - public void addToCache(String key, Object decision) { - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - IdentityCacheKey cacheKey = new IdentityCacheKey(tenantId, key); - addToCache(cacheKey, decision); - } - - public Object getFromCache(String key) { - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - IdentityCacheKey cacheKey = new IdentityCacheKey(tenantId, key); - Object entry = getValueFromCache(cacheKey); - if (entry != null) { - return (String) entry; - } - return null; - } - - public void clearCache() { - clear(); - } - -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/AttributeDTO.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/AttributeDTO.java deleted file mode 100644 index 9d68a5c31368..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/AttributeDTO.java +++ /dev/null @@ -1,95 +0,0 @@ -/* -* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.dto; - -import java.io.Serializable; - -/** - * This encapsulates the attribute element data of the XACML policy - */ -public class AttributeDTO implements Serializable { - - private String attributeValue; - - private String attributeDataType; - - private String attributeId; - - private String attributeCategory; - - public String getAttributeDataType() { - return attributeDataType; - } - - public void setAttributeDataType(String attributeDataType) { - this.attributeDataType = attributeDataType; - } - - public String getCategory() { - return attributeCategory; - } - - public void setCategory(String category) { - this.attributeCategory = category; - } - - public String getAttributeId() { - return attributeId; - } - - public void setAttributeId(String attributeId) { - this.attributeId = attributeId; - } - - public String getAttributeValue() { - return attributeValue; - } - - public void setAttributeValue(String attributeValue) { - this.attributeValue = attributeValue; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof AttributeDTO)) return false; - - AttributeDTO dto = (AttributeDTO) o; - - if (attributeDataType != null ? !attributeDataType.equals(dto.attributeDataType) : dto.attributeDataType != null) - return false; - if (attributeId != null ? !attributeId.equals(dto.attributeId) : dto.attributeId != null) - return false; - if (attributeCategory != null ? !attributeCategory.equals(dto.attributeCategory) : dto.attributeCategory != null) - return false; - if (attributeValue != null ? !attributeValue.equals(dto.attributeValue) : dto.attributeValue != null) - return false; - - return true; - } - - @Override - public int hashCode() { - int result = attributeValue != null ? attributeValue.hashCode() : 0; - result = 31 * result + (attributeDataType != null ? attributeDataType.hashCode() : 0); - result = 31 * result + (attributeId != null ? attributeId.hashCode() : 0); - result = 31 * result + (attributeCategory != null ? attributeCategory.hashCode() : 0); - return result; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/EntitledAttributesDTO.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/EntitledAttributesDTO.java deleted file mode 100644 index 8c9b5856d177..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/EntitledAttributesDTO.java +++ /dev/null @@ -1,121 +0,0 @@ -/* -* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.dto; - -import java.util.Arrays; - -/** - * Encapsulates the entitled attributes that user has been entitled for - */ -public class EntitledAttributesDTO { - - private String resourceName; - - private String action; - - private String environment; - - private boolean allActions; - - private boolean allResources; - - private AttributeDTO[] attributeDTOs = new AttributeDTO[0]; - - public String getResourceName() { - return resourceName; - } - - public void setResourceName(String resourceName) { - this.resourceName = resourceName; - } - - public String getAction() { - return action; - } - - public void setAction(String action) { - - this.action = action; - } - - public boolean isAllActions() { - return allActions; - } - - public void setAllActions(boolean allActions) { - this.allActions = allActions; - } - - public boolean isAllResources() { - return allResources; - } - - public void setAllResources(boolean allResources) { - this.allResources = allResources; - } - - public String getEnvironment() { - return environment; - } - - public void setEnvironment(String environment) { - this.environment = environment; - } - - public AttributeDTO[] getAttributeDTOs() { - return Arrays.copyOf(attributeDTOs, attributeDTOs.length); - } - - public void setAttributeDTOs(AttributeDTO[] attributeDTOs) { - this.attributeDTOs = Arrays.copyOf(attributeDTOs, attributeDTOs.length); - } - -// @Override -// public boolean equals(Object o) { -// if (this == o) return true; -// if (!(o instanceof EntitledAttributesDTO)) return false; -// -// EntitledAttributesDTO that = (EntitledAttributesDTO) o; -// -// if (allActions != that.allActions) return false; -// if (allResources != that.allResources) return false; -// if (action != null ? !action.equals(that.action) : that.action != null) return false; -// if (environment != null ? !environment.equals(that.environment) : that.environment != null) -// return false; -// if (resourceName != null ? !resourceName.equals(that.resourceName) : that.resourceName != null) -// return false; -// -// return true; -// } -// -// @Override -// public int hashCode() { -// return super.hashCode(); //To change body of overridden methods use File | Settings | File Templates. -// } -// -// // @Override -//// public int hashCode() { -//// int result = resourceName != null ? resourceName.hashCode() : 0; -//// result = 31 * result + (action != null ? action.hashCode() : 0); -//// result = 31 * result + (environment != null ? environment.hashCode() : 0); -//// result = 31 * result + (allActions ? 1 : 0); -//// result = 31 * result + (allResources ? 1 : 0); -//// return result; -//// } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/EntitledResultSetDTO.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/EntitledResultSetDTO.java deleted file mode 100644 index 3003c2ee28dd..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/EntitledResultSetDTO.java +++ /dev/null @@ -1,92 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.dto; - -import java.util.Arrays; - -/** - * Encapsulates the entitle result set for given search result - */ -public class EntitledResultSetDTO { - - private EntitledAttributesDTO[] entitledAttributesDTOs = new EntitledAttributesDTO[0]; - - private boolean advanceResult; - - private String message; - - private String messageType; - - public EntitledAttributesDTO[] getEntitledAttributesDTOs() { - return Arrays.copyOf(entitledAttributesDTOs, entitledAttributesDTOs.length); - } - - public void setEntitledAttributesDTOs(EntitledAttributesDTO[] entitledAttributesDTOs) { - this.entitledAttributesDTOs = Arrays.copyOf(entitledAttributesDTOs, entitledAttributesDTOs.length); - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public String getMessageType() { - return messageType; - } - - public void setMessageType(String messageType) { - this.messageType = messageType; - } - - public boolean isAdvanceResult() { - return advanceResult; - } - - public void setAdvanceResult(boolean advanceResult) { - this.advanceResult = advanceResult; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof EntitledResultSetDTO)) return false; - - EntitledResultSetDTO that = (EntitledResultSetDTO) o; - - if (advanceResult != that.advanceResult) return false; - if (!Arrays.equals(entitledAttributesDTOs, that.entitledAttributesDTOs)) return false; - if (message != null ? !message.equals(that.message) : that.message != null) return false; - if (messageType != null ? !messageType.equals(that.messageType) : that.messageType != null) - return false; - - return true; - } - - @Override - public int hashCode() { - int result = entitledAttributesDTOs != null ? Arrays.hashCode(entitledAttributesDTOs) : 0; - result = 31 * result + (advanceResult ? 1 : 0); - result = 31 * result + (message != null ? message.hashCode() : 0); - result = 31 * result + (messageType != null ? messageType.hashCode() : 0); - return result; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/EntitlementFinderDataHolder.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/EntitlementFinderDataHolder.java deleted file mode 100644 index 3d6dd26ff400..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/EntitlementFinderDataHolder.java +++ /dev/null @@ -1,107 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.dto; - -import java.util.Arrays; - -/** - * Encapsulates the data of entitlement data finder modules - */ -public class EntitlementFinderDataHolder { - - private String name; - - private String[] applicationIds = new String[0]; - - private String[] supportedCategory = new String[0]; - - private int hierarchicalLevels; - - private boolean fullPathSupported; - - private boolean hierarchicalTree; - - private boolean searchSupported; - - private boolean allApplicationRelated; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String[] getApplicationIds() { - return Arrays.copyOf(applicationIds, applicationIds.length); - } - - public void setApplicationIds(String[] applicationIds) { - this.applicationIds = applicationIds; - } - - public boolean isFullPathSupported() { - return fullPathSupported; - } - - public void setFullPathSupported(boolean fullPathSupported) { - this.fullPathSupported = fullPathSupported; - } - - public int getHierarchicalLevels() { - return hierarchicalLevels; - } - - public void setHierarchicalLevels(int hierarchicalLevels) { - this.hierarchicalLevels = hierarchicalLevels; - } - - public boolean isHierarchicalTree() { - return hierarchicalTree; - } - - public void setHierarchicalTree(boolean hierarchicalTree) { - this.hierarchicalTree = hierarchicalTree; - } - - public boolean isAllApplicationRelated() { - return allApplicationRelated; - } - - public void setAllApplicationRelated(boolean allApplicationRelated) { - this.allApplicationRelated = allApplicationRelated; - } - - public String[] getSupportedCategory() { - return Arrays.copyOf(supportedCategory, supportedCategory.length); - } - - public void setSupportedCategory(String[] supportedCategory) { - this.supportedCategory = supportedCategory; - } - - public boolean isSearchSupported() { - return searchSupported; - } - - public void setSearchSupported(boolean searchSupported) { - this.searchSupported = searchSupported; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/EntitlementTreeNodeDTO.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/EntitlementTreeNodeDTO.java deleted file mode 100644 index e3df05ab146e..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/EntitlementTreeNodeDTO.java +++ /dev/null @@ -1,65 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.dto; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -/** - * - */ -public class EntitlementTreeNodeDTO { - - /** - * Node name - */ - private String name; - - /** - * children of the Node - */ - private EntitlementTreeNodeDTO[] childNodes = new EntitlementTreeNodeDTO[]{}; - - public EntitlementTreeNodeDTO(String name) { - this.name = name; - } - - public EntitlementTreeNodeDTO() { - - } - - public String getName() { - return name; - } - - public EntitlementTreeNodeDTO[] getChildNodes() { - return Arrays.copyOf(childNodes, childNodes.length); - } - - public void setChildNodes(EntitlementTreeNodeDTO[] childNodes) { - this.childNodes = Arrays.copyOf(childNodes, childNodes.length); - } - - public void addChildNode(EntitlementTreeNodeDTO node) { - Set valueNodes = new HashSet(Arrays.asList(this.childNodes)); - valueNodes.add(node); - this.childNodes = valueNodes.toArray(new EntitlementTreeNodeDTO[valueNodes.size()]); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/PDPDataHolder.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/PDPDataHolder.java deleted file mode 100644 index 8ec883229e97..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/PDPDataHolder.java +++ /dev/null @@ -1,68 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.dto; - -import java.util.Arrays; - -/** - * - */ -public class PDPDataHolder { - - private String[] policyFinders = new String[0]; - - private String[] pipAttributeFinders = new String[0]; - - private String[] pipResourceFinders = new String[0]; - - private boolean decisionCacheEnable; - - public String[] getPolicyFinders() { - return Arrays.copyOf(policyFinders, policyFinders.length); - } - - public void setPolicyFinders(String[] policyFinders) { - this.policyFinders = Arrays.copyOf(policyFinders, policyFinders.length); - } - - public String[] getPipAttributeFinders() { - return Arrays.copyOf(pipAttributeFinders, pipAttributeFinders.length); - } - - public void setPipAttributeFinders(String[] pipAttributeFinders) { - this.pipAttributeFinders = Arrays.copyOf(pipAttributeFinders, pipAttributeFinders.length); - } - - public String[] getPipResourceFinders() { - return Arrays.copyOf(pipResourceFinders, pipResourceFinders.length); - } - - public void setPipResourceFinders(String[] pipResourceFinders) { - this.pipResourceFinders = Arrays.copyOf(pipResourceFinders, pipResourceFinders.length); - } - - public boolean isDecisionCacheEnable() { - return decisionCacheEnable; - } - - public void setDecisionCacheEnable(boolean decisionCacheEnable) { - this.decisionCacheEnable = decisionCacheEnable; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/PIPFinderDataHolder.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/PIPFinderDataHolder.java deleted file mode 100644 index a0af3e5ed02a..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/PIPFinderDataHolder.java +++ /dev/null @@ -1,57 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.dto; - -import java.util.Arrays; - -/** - * encapsulates policy finder related data - */ -public class PIPFinderDataHolder { - - private String moduleName; - - private String className; - - private String[] supportedAttributeIds = new String[0]; - - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - public String getModuleName() { - return moduleName; - } - - public void setModuleName(String moduleName) { - this.moduleName = moduleName; - } - - public String[] getSupportedAttributeIds() { - return Arrays.copyOf(supportedAttributeIds, supportedAttributeIds.length); - } - - public void setSupportedAttributeIds(String[] supportedAttributeIds) { - this.supportedAttributeIds = Arrays.copyOf(supportedAttributeIds, supportedAttributeIds.length); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/PaginatedPolicySetDTO.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/PaginatedPolicySetDTO.java deleted file mode 100644 index 1ae933863dd4..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/PaginatedPolicySetDTO.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2004,2005 The Apache Software Foundation. - * - * Licensed 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.wso2.carbon.identity.entitlement.dto; - -import java.util.Arrays; - -public class PaginatedPolicySetDTO { - - private PolicyDTO[] policySet = new PolicyDTO[0]; - - private int numberOfPages; - - public PolicyDTO[] getPolicySet() { - return Arrays.copyOf(policySet, policySet.length); - } - - public void setPolicySet(PolicyDTO[] policySet) { - this.policySet = Arrays.copyOf(policySet, policySet.length); - } - - public int getNumberOfPages() { - return numberOfPages; - } - - public void setNumberOfPages(int numberOfPages) { - this.numberOfPages = numberOfPages; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/PaginatedStatusHolder.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/PaginatedStatusHolder.java deleted file mode 100644 index 3f3e53213877..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/PaginatedStatusHolder.java +++ /dev/null @@ -1,46 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.dto; - -import java.util.Arrays; - -/** - * - */ -public class PaginatedStatusHolder { - - private StatusHolder[] statusHolders = new StatusHolder[0]; - - private int numberOfPages; - - public StatusHolder[] getStatusHolders() { - return Arrays.copyOf(statusHolders, statusHolders.length); - } - - public void setStatusHolders(StatusHolder[] statusHolders) { - this.statusHolders = Arrays.copyOf(statusHolders, statusHolders.length); - } - - public int getNumberOfPages() { - return numberOfPages; - } - - public void setNumberOfPages(int numberOfPages) { - this.numberOfPages = numberOfPages; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/PaginatedStringDTO.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/PaginatedStringDTO.java deleted file mode 100644 index 981366b355e8..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/PaginatedStringDTO.java +++ /dev/null @@ -1,46 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.dto; - -import java.util.Arrays; - -/** - * - */ -public class PaginatedStringDTO { - - private String[] statusHolders = new String[0]; - - private int numberOfPages; - - public String[] getStatusHolders() { - return Arrays.copyOf(statusHolders, statusHolders.length); - } - - public void setStatusHolders(String[] statusHolders) { - this.statusHolders = Arrays.copyOf(statusHolders, statusHolders.length); - } - - public int getNumberOfPages() { - return numberOfPages; - } - - public void setNumberOfPages(int numberOfPages) { - this.numberOfPages = numberOfPages; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/PolicyDTO.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/PolicyDTO.java deleted file mode 100644 index cba00139f7a1..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/PolicyDTO.java +++ /dev/null @@ -1,248 +0,0 @@ -/* -* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.dto; - -import java.io.Serializable; -import java.util.Arrays; - -/** - * This class encapsulate the XACML policy related the data - */ -public class PolicyDTO implements Serializable { - - - private String policy; - - private String policyId; - - private boolean active; - - private boolean promote; - - private String policyType; - - private String policyEditor; - - private String[] policyEditorData = new String[0]; - - private int policyOrder; - - private String version; - - private String lastModifiedTime; - - private String lastModifiedUser; - - private AttributeDTO[] attributeDTOs = new AttributeDTO[0]; - - private String[] policySetIdReferences = new String[0]; - - private String[] policyIdReferences = new String[0]; - - public PolicyDTO() { - - } - - public PolicyDTO(PolicyDTO policyDTO) { - - this.policy = policyDTO.policy; - this.policyId = policyDTO.policyId; - this.active = policyDTO.active; - this.promote = policyDTO.promote; - this.policyType = policyDTO.policyType; - this.policyEditor = policyDTO.policyEditor; - this.policyEditorData = Arrays.copyOf(policyDTO.policyEditorData, policyDTO.policyEditorData.length); - this.policyOrder = policyDTO.policyOrder; - this.version = policyDTO.version; - this.lastModifiedTime = policyDTO.lastModifiedTime; - this.lastModifiedUser = policyDTO.lastModifiedUser; - this.attributeDTOs = Arrays.copyOf(policyDTO.attributeDTOs, policyDTO.attributeDTOs.length); - this.policySetIdReferences = Arrays.copyOf(policyDTO.policySetIdReferences, policyDTO.policySetIdReferences.length); - this.policyIdReferences = Arrays.copyOf(policyDTO.policyIdReferences, policyDTO.policyIdReferences.length); - } - - public PolicyDTO(String policyId) { - this.policyId = policyId; - } - - public String getPolicyId() { - return policyId; - } - - public void setPolicyId(String policyId) { - this.policyId = policyId; - } - - public String getPolicy() { - return policy; - } - - public void setPolicy(String policy) { - this.policy = policy; - } - - public void setActive(boolean active) { - this.active = active; - } - - public boolean isActive() { - return active; - } - - - public String getPolicyType() { - return policyType; - } - - public void setPolicyType(String policyType) { - this.policyType = policyType; - } - - public String getPolicyEditor() { - return policyEditor; - } - - public void setPolicyEditor(String policyEditor) { - this.policyEditor = policyEditor; - } - - public String[] getPolicyEditorData() { - return Arrays.copyOf(policyEditorData, policyEditorData.length); - } - - public void setPolicyEditorData(String[] policyEditorData) { - this.policyEditorData = Arrays.copyOf(policyEditorData, - policyEditorData.length); - } - - public AttributeDTO[] getAttributeDTOs() { - return Arrays.copyOf(attributeDTOs, attributeDTOs.length); - } - - public void setAttributeDTOs(AttributeDTO[] attributeDTOs) { - this.attributeDTOs = Arrays.copyOf(attributeDTOs, attributeDTOs.length); - } - - public int getPolicyOrder() { - return policyOrder; - } - - public void setPolicyOrder(int policyOrder) { - this.policyOrder = policyOrder; - } - - public String[] getPolicySetIdReferences() { - return Arrays.copyOf(policySetIdReferences, policySetIdReferences.length); - } - - public void setPolicySetIdReferences(String[] policySetIdReferences) { - this.policySetIdReferences = Arrays.copyOf(policySetIdReferences, policySetIdReferences.length); - } - - public String[] getPolicyIdReferences() { - return Arrays.copyOf(policyIdReferences, policyIdReferences.length); - } - - public void setPolicyIdReferences(String[] policyIdReferences) { - this.policyIdReferences = Arrays.copyOf(policyIdReferences, policyIdReferences.length); - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public boolean isPromote() { - return promote; - } - - public void setPromote(boolean promote) { - this.promote = promote; - } - - public String getLastModifiedTime() { - return lastModifiedTime; - } - - public void setLastModifiedTime(String lastModifiedTime) { - this.lastModifiedTime = lastModifiedTime; - } - - public String getLastModifiedUser() { - return lastModifiedUser; - } - - public void setLastModifiedUser(String lastModifiedUser) { - this.lastModifiedUser = lastModifiedUser; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof PolicyDTO)) return false; - - PolicyDTO policyDTO = (PolicyDTO) o; - - if (active != policyDTO.active) return false; - if (policyOrder != policyDTO.policyOrder) return false; - if (promote != policyDTO.promote) return false; - if (!Arrays.equals(attributeDTOs, policyDTO.attributeDTOs)) return false; - if (lastModifiedTime != null ? !lastModifiedTime.equals(policyDTO.lastModifiedTime) : - policyDTO.lastModifiedTime != null) { - return false; - } - if (lastModifiedUser != null ? !lastModifiedUser.equals(policyDTO.lastModifiedUser) : - policyDTO.lastModifiedUser != null) { - return false; - } - if (policy != null ? !policy.equals(policyDTO.policy) : policyDTO.policy != null) return false; - if (policyEditor != null ? !policyEditor.equals(policyDTO.policyEditor) : policyDTO.policyEditor != null) { - return false; - } - if (!Arrays.equals(policyEditorData, policyDTO.policyEditorData)) return false; - if (!policyId.equals(policyDTO.policyId)) return false; - if (!Arrays.equals(policyIdReferences, policyDTO.policyIdReferences)) return false; - if (!Arrays.equals(policySetIdReferences, policyDTO.policySetIdReferences)) return false; - if (policyType != null ? !policyType.equals(policyDTO.policyType) : policyDTO.policyType != null) return false; - if (version != null ? !version.equals(policyDTO.version) : policyDTO.version != null) return false; - - return true; - } - - @Override - public int hashCode() { - int result = policy != null ? policy.hashCode() : 0; - result = 31 * result + policyId.hashCode(); - result = 31 * result + (active ? 1 : 0); - result = 31 * result + (promote ? 1 : 0); - result = 31 * result + (policyType != null ? policyType.hashCode() : 0); - result = 31 * result + (policyEditor != null ? policyEditor.hashCode() : 0); - result = 31 * result + (policyEditorData != null ? Arrays.hashCode(policyEditorData) : 0); - result = 31 * result + policyOrder; - result = 31 * result + (version != null ? version.hashCode() : 0); - result = 31 * result + (lastModifiedTime != null ? lastModifiedTime.hashCode() : 0); - result = 31 * result + (lastModifiedUser != null ? lastModifiedUser.hashCode() : 0); - result = 31 * result + (attributeDTOs != null ? Arrays.hashCode(attributeDTOs) : 0); - result = 31 * result + (policySetIdReferences != null ? Arrays.hashCode(policySetIdReferences) : 0); - result = 31 * result + (policyIdReferences != null ? Arrays.hashCode(policyIdReferences) : 0); - return result; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/PolicyFinderDataHolder.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/PolicyFinderDataHolder.java deleted file mode 100644 index 714cd07bf54d..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/PolicyFinderDataHolder.java +++ /dev/null @@ -1,69 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.dto; - -import java.util.Arrays; - -/** - * encapsulates policy finder related data - */ -public class PolicyFinderDataHolder { - - private String moduleName; - - private String className; - - private String[] policyIdentifiers = new String[0]; - - private String combiningAlgorithm; - - public String getModuleName() { - return moduleName; - } - - public void setModuleName(String moduleName) { - this.moduleName = moduleName; - } - - public String[] getPolicyIdentifiers() { - return Arrays.copyOf(policyIdentifiers, policyIdentifiers.length); - } - - public void setPolicyIdentifiers(String[] policyIdentifiers) { - if (policyIdentifiers != null) { - this.policyIdentifiers = Arrays.copyOf(policyIdentifiers, policyIdentifiers.length); - } - } - - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - public String getCombiningAlgorithm() { - return combiningAlgorithm; - } - - public void setCombiningAlgorithm(String combiningAlgorithm) { - this.combiningAlgorithm = combiningAlgorithm; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/PolicyStoreDTO.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/PolicyStoreDTO.java deleted file mode 100644 index bf4164a261dc..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/PolicyStoreDTO.java +++ /dev/null @@ -1,125 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.dto; - -import java.io.Serializable; -import java.util.Arrays; - -/** - * encapsulates the policy data that is stored in the policy store - */ -public class PolicyStoreDTO implements Serializable { - - private String policyId; - - private String policy; - - private int policyOrder; - - private boolean active; - - private boolean setOrder; - - private boolean setActive; - - private String version; - - private AttributeDTO[] attributeDTOs = new AttributeDTO[0]; - - public PolicyStoreDTO() { - - } - - public PolicyStoreDTO(PolicyStoreDTO policyStoreDTO) { - - this.policyId = policyStoreDTO.getPolicyId(); - this.policy = policyStoreDTO.getPolicy(); - this.policyOrder = policyStoreDTO.getPolicyOrder(); - this.active = policyStoreDTO.isActive(); - this.setOrder = policyStoreDTO.isSetOrder(); - this.setActive = policyStoreDTO.isSetActive(); - this.version = policyStoreDTO.getVersion(); - this.attributeDTOs = policyStoreDTO.getAttributeDTOs(); - } - - public String getPolicyId() { - return policyId; - } - - public void setPolicyId(String policyId) { - this.policyId = policyId; - } - - public String getPolicy() { - return policy; - } - - public void setPolicy(String policy) { - this.policy = policy; - } - - public int getPolicyOrder() { - return policyOrder; - } - - public void setPolicyOrder(int policyOrder) { - this.policyOrder = policyOrder; - } - - public AttributeDTO[] getAttributeDTOs() { - return Arrays.copyOf(attributeDTOs, attributeDTOs.length); - } - - public void setAttributeDTOs(AttributeDTO[] attributeDTOs) { - this.attributeDTOs = Arrays.copyOf(attributeDTOs, attributeDTOs.length); - } - - public boolean isActive() { - return active; - } - - public void setActive(boolean active) { - this.active = active; - } - - public boolean isSetOrder() { - return setOrder; - } - - public void setSetOrder(boolean setOrder) { - this.setOrder = setOrder; - } - - public boolean isSetActive() { - return setActive; - } - - public void setSetActive(boolean setActive) { - this.setActive = setActive; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/PublisherDataHolder.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/PublisherDataHolder.java deleted file mode 100644 index 65df750bd6d8..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/PublisherDataHolder.java +++ /dev/null @@ -1,144 +0,0 @@ -/* -* Copyright (c) WSO2 LLC (https://www.wso2.com) All Rights Reserved. -* -* WSO2 LLC 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.wso2.carbon.identity.entitlement.dto; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.core.util.CryptoException; -import org.wso2.carbon.core.util.CryptoUtil; -import org.wso2.carbon.registry.core.Resource; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -/** - * - */ -public class PublisherDataHolder implements Serializable { - - public static final String MODULE_NAME = "EntitlementModuleName"; - private static Log log = LogFactory.getLog(PublisherDataHolder.class); - private String moduleName; - private PublisherPropertyDTO[] propertyDTOs = new PublisherPropertyDTO[0]; - - public PublisherDataHolder() { - } - - public PublisherDataHolder(String moduleName) { - this.moduleName = moduleName; - } - - /** - * @param propertyDTOs propertyDTOs. - * @param moduleName module name. - */ - public PublisherDataHolder(List propertyDTOs, String moduleName) { - - this.moduleName = moduleName; - this.propertyDTOs = propertyDTOs.toArray(new PublisherPropertyDTO[0]); - } - - /** - * @param resource resource. - * @param returnSecrets return secrets. - * @deprecated use other constructors instead. - */ - @Deprecated - public PublisherDataHolder(Resource resource, boolean returnSecrets) { - List propertyDTOs = new ArrayList(); - if (resource != null && resource.getProperties() != null) { - Properties properties = resource.getProperties(); - for (Map.Entry entry : properties.entrySet()) { - PublisherPropertyDTO dto = new PublisherPropertyDTO(); - dto.setId((String) entry.getKey()); - Object value = entry.getValue(); - if (value instanceof ArrayList) { - List list = (ArrayList) entry.getValue(); - if (list != null && list.size() > 0 && list.get(0) != null) { - dto.setValue((String) list.get(0)); - - if (list.size() > 1 && list.get(1) != null) { - dto.setDisplayName((String) list.get(1)); - } - if (list.size() > 2 && list.get(2) != null) { - dto.setDisplayOrder(Integer.parseInt((String) list.get(2))); - } - if (list.size() > 3 && list.get(3) != null) { - dto.setRequired(Boolean.parseBoolean((String) list.get(3))); - } - if (list.size() > 4 && list.get(4) != null) { - dto.setSecret(Boolean.parseBoolean((String) list.get(4))); - } - - if (dto.isSecret()) { - if (returnSecrets) { - String password = dto.getValue(); - try { - password = new String(CryptoUtil.getDefaultCryptoUtil(). - base64DecodeAndDecrypt(dto.getValue())); - } catch (CryptoException e) { - log.error(e); - // ignore - } - dto.setValue(password); - } - } - } - } - if (MODULE_NAME.equals(dto.getId())) { - moduleName = dto.getValue(); - continue; - } - - propertyDTOs.add(dto); - } - } - this.propertyDTOs = propertyDTOs.toArray(new PublisherPropertyDTO[propertyDTOs.size()]); - } - - public String getModuleName() { - return moduleName; - } - - public void setModuleName(String moduleName) { - this.moduleName = moduleName; - } - - public PublisherPropertyDTO[] getPropertyDTOs() { - return Arrays.copyOf(propertyDTOs, propertyDTOs.length); - } - - public void setPropertyDTOs(PublisherPropertyDTO[] propertyDTOs) { - this.propertyDTOs = Arrays.copyOf(propertyDTOs, propertyDTOs.length); - } - - - public PublisherPropertyDTO getPropertyDTO(String id) { - for (PublisherPropertyDTO dto : propertyDTOs) { - if (dto.getId().equalsIgnoreCase(id)) { - return dto; - } - } - return null; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/PublisherPropertyDTO.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/PublisherPropertyDTO.java deleted file mode 100644 index 9ff33b480828..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/PublisherPropertyDTO.java +++ /dev/null @@ -1,97 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.dto; - -import java.io.Serializable; - -/** - * - */ -public class PublisherPropertyDTO implements Serializable { - - private String id; - - private String displayName; - - private String value; - - private boolean required; - - private int displayOrder; - - private boolean secret; - - private String module; - - public String getDisplayName() { - return displayName; - } - - public void setDisplayName(String displayName) { - this.displayName = displayName; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public int getDisplayOrder() { - return displayOrder; - } - - public void setDisplayOrder(int displayOrder) { - this.displayOrder = displayOrder; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - public String getModule() { - return module; - } - - public void setModule(String module) { - this.module = module; - } - - public boolean isRequired() { - return required; - } - - public void setRequired(boolean required) { - this.required = required; - } - - public boolean isSecret() { - return secret; - } - - public void setSecret(boolean secret) { - this.secret = secret; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/StatusHolder.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/StatusHolder.java deleted file mode 100644 index 0fa568a6776c..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/dto/StatusHolder.java +++ /dev/null @@ -1,172 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.dto; - -import org.wso2.carbon.context.CarbonContext; - -/** - * - */ -public class StatusHolder { - - /** - * Status type - */ - private String type; - /** - * key to identify status. basically policy Id - */ - private String key; - - /** - * basically policy version - */ - private String version; - - /** - * whether this is success status or not - */ - private boolean success; - - /** - * the user who is involved with this - */ - private String user; - - /** - * target - */ - private String target; - - /** - * target action - */ - private String targetAction; - - /** - * time instance - */ - private String timeInstance; - - /** - * message - */ - private String message; - - - public StatusHolder(String type, String key, String version, String target, - String targetAction, boolean success, String message) { - this.type = type; - this.key = key; - this.user = CarbonContext.getThreadLocalCarbonContext().getUsername(); - this.message = message; - this.version = version; - this.target = target; - this.targetAction = targetAction; - this.success = success; - this.timeInstance = Long.toString(System.currentTimeMillis()); - } - - public StatusHolder(String type, String key, String version, String target, String targetAction) { - this.type = type; - this.key = key; - this.version = version; - this.target = target; - this.targetAction = targetAction; - this.user = CarbonContext.getThreadLocalCarbonContext().getUsername(); - this.success = true; - this.timeInstance = Long.toString(System.currentTimeMillis()); - } - - public StatusHolder(String type) { - this.type = type; - } - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - public boolean isSuccess() { - return success; - } - - public void setSuccess(boolean success) { - this.success = success; - } - - public String getTimeInstance() { - return timeInstance; - } - - public void setTimeInstance(String timeInstance) { - this.timeInstance = timeInstance; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public String getUser() { - return user; - } - - public void setUser(String user) { - this.user = user; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public String getTarget() { - return target; - } - - public void setTarget(String target) { - this.target = target; - } - - public String getTargetAction() { - return targetAction; - } - - public void setTargetAction(String targetAction) { - this.targetAction = targetAction; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/extension/EvalPermissionTreeFunction.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/extension/EvalPermissionTreeFunction.java deleted file mode 100644 index 51d2f06ab51f..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/extension/EvalPermissionTreeFunction.java +++ /dev/null @@ -1,89 +0,0 @@ -/* -* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* Licensed 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.wso2.carbon.identity.entitlement.extension; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.balana.attr.AttributeValue; -import org.wso2.balana.attr.BooleanAttribute; -import org.wso2.balana.attr.StringAttribute; -import org.wso2.balana.cond.Evaluatable; -import org.wso2.balana.cond.EvaluationResult; -import org.wso2.balana.cond.FunctionBase; -import org.wso2.balana.ctx.EvaluationCtx; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; -import org.wso2.carbon.user.core.UserStoreException; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -public class EvalPermissionTreeFunction extends FunctionBase { - - /** - * Standard identifier for the eval-permission-tree function - */ - public static final String SUBJECT_HAS_PERMISSION = FUNCTION_NS + "eval-permission-tree"; - - // private identifiers for the supported functions - private static final int ID_EVAL_PERMISSION_TREE = 0; - - private static final Log log = LogFactory.getLog(EvalPermissionTreeFunction.class); - - public EvalPermissionTreeFunction() { - - super(SUBJECT_HAS_PERMISSION, ID_EVAL_PERMISSION_TREE, StringAttribute.identifier, false, 2, 2, - BooleanAttribute.identifier, false); - } - - public static Set getSupportedIdentifiers() { - - Set set = new HashSet(); - set.add(SUBJECT_HAS_PERMISSION); - - return set; - } - - public EvaluationResult evaluate(List inputs, EvaluationCtx context) { - - AttributeValue[] argValues = new AttributeValue[inputs.size()]; - EvaluationResult result = evalArgs(inputs, context, argValues); - if (result != null) { - return result; - } - - switch (getFunctionId()) { - case ID_EVAL_PERMISSION_TREE: - String resource = ((StringAttribute) argValues[0]).getValue().trim(); - String subject = ((StringAttribute) argValues[1]).getValue().trim(); - - boolean isAuthorised = false; - - try { - isAuthorised = EntitlementServiceComponent.getRealmservice().getBootstrapRealm(). - getAuthorizationManager().isUserAuthorized(subject, resource, "ui.execute"); - } catch (UserStoreException e) { - log.error("Error while authorising" + subject + " to perform ui.execute on " + resource, e); - } - - result = new EvaluationResult(BooleanAttribute.getInstance(isAuthorised)); - break; - } - - return result; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/internal/EntitlementConfigHolder.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/internal/EntitlementConfigHolder.java deleted file mode 100644 index eac8d84fa687..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/internal/EntitlementConfigHolder.java +++ /dev/null @@ -1,296 +0,0 @@ -/* -* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.internal; - -import org.wso2.carbon.identity.application.mgt.ApplicationManagementService; -import org.wso2.carbon.identity.entitlement.PAPStatusDataHandler; -import org.wso2.carbon.identity.entitlement.dto.PublisherDataHolder; -import org.wso2.carbon.identity.entitlement.pap.EntitlementDataFinderModule; -import org.wso2.carbon.identity.entitlement.pip.PIPAttributeFinder; -import org.wso2.carbon.identity.entitlement.pip.PIPExtension; -import org.wso2.carbon.identity.entitlement.pip.PIPResourceFinder; -import org.wso2.carbon.identity.entitlement.policy.collection.PolicyCollection; -import org.wso2.carbon.identity.entitlement.policy.finder.PolicyFinderModule; -import org.wso2.carbon.identity.entitlement.policy.publisher.PolicyPublisherModule; -import org.wso2.carbon.identity.entitlement.policy.publisher.PostPublisherModule; -import org.wso2.carbon.identity.entitlement.policy.publisher.PublisherVerificationModule; -import org.wso2.carbon.identity.entitlement.policy.store.PolicyDataStore; -import org.wso2.carbon.identity.entitlement.policy.store.PolicyStoreManageModule; -import org.wso2.carbon.utils.ConfigurationContextService; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import javax.xml.validation.Schema; - -/** - * keeps track of the configuration found in entitlement-config.xml - */ -public class EntitlementConfigHolder { - - /** - * PIPExtensions will be fired for each and every XACML request - which will give a handle to - * the incoming request. - */ - private Map extensions = new HashMap(); - - /** - * This will be fired by CarbonAttributeFinder whenever it finds an attribute supported by this - * module and missing in the XACML request. - */ - private Map designators = new HashMap(); - - /** - * This will be fired by CarbonResourceFinder whenever it wants to find a descendant or child resource - * of a given resource - */ - private Map resourceFinders = new HashMap(); - - /** - * This will be fired by EntitlementDataFinder, whenever it wants to retrieve an attribute values to build the - * XACML policy - */ - private Map policyEntitlementDataFinders = - new HashMap(); - - /** - * Will be fired by PolicyPublisher, whenever it wants to publish a policy - */ - private Map policyPublisherModules = - new HashMap(); - - /** - * Will be fired by PolicyPublisher, after a policy is published - */ - private Map policyPostPublisherModules = - new HashMap(); - - /** - * Will be fired by PolicyPublisher, before a policy is published - */ - private Map publisherVerificationModule = - new HashMap(); - - /** - * Will be fired by CarbonPolicyFinder, whenever it wants to find policies - */ - private Map policyFinderModules = - new HashMap(); - - /** - * This holds all the policies of entitlement engine - */ - private Map policyCollections = - new HashMap(); - - /** - * Will be fired by admin services, whenever it wants send notifications - */ - private Map papStatusDataHandlers = - new HashMap(); - - /** - * This holds all the policy storing logic of entitlement engine - */ - private Map policyStore = new HashMap<>(); - - /** - * This holds all the policy versioning of PAP - */ - private Map policyDataStore = new HashMap<>(); - - /** - * This holds the policy schema against its version - */ - private Map policySchemaMap = new HashMap(); - - /** - * Holds all caching related configurations - */ - private Properties engineProperties; - - /** - * Holds the properties of all modules. - */ - private Map> modulePropertyHolderMap = - new HashMap>(); - - private ConfigurationContextService configurationContextService; - private ApplicationManagementService applicationManagementService; - private static EntitlementConfigHolder instance = new EntitlementConfigHolder(); - - private EntitlementConfigHolder() { - } - - public static EntitlementConfigHolder getInstance() { - return instance; - } - - public Map getExtensions() { - return extensions; - } - - public void addExtensions(PIPExtension extension, Properties properties) { - this.extensions.put(extension, properties); - } - - public Map getDesignators() { - return designators; - } - - public void addDesignators(PIPAttributeFinder attributeFinder, Properties properties) { - this.designators.put(attributeFinder, properties); - } - - public Map getResourceFinders() { - return resourceFinders; - } - - public void addResourceFinders(PIPResourceFinder resourceFinder, Properties properties) { - this.resourceFinders.put(resourceFinder, properties); - } - - public Map getPolicyEntitlementDataFinders() { - return policyEntitlementDataFinders; - } - - public void addPolicyEntitlementDataFinder(EntitlementDataFinderModule metaDataFinderModule, - Properties properties) { - this.policyEntitlementDataFinders.put(metaDataFinderModule, properties); - } - - public Properties getEngineProperties() { - return engineProperties; - } - - public void setEngineProperties(Properties engineProperties) { - this.engineProperties = engineProperties; - } - - public Map getPolicySchemaMap() { - return policySchemaMap; - } - - public void setPolicySchema(String schemaNS, Schema schema) { - this.policySchemaMap.put(schemaNS, schema); - } - - public Map getPolicyPublisherModules() { - return policyPublisherModules; - } - - public void addPolicyPublisherModule(PolicyPublisherModule policyPublisherModules, - Properties properties) { - this.policyPublisherModules.put(policyPublisherModules, properties); - } - - public List getModulePropertyHolders(String type) { - return modulePropertyHolderMap.get(type); - } - - public void addModulePropertyHolder(String type, PublisherDataHolder holder) { - if (this.modulePropertyHolderMap.get(type) == null) { - List holders = new ArrayList(); - holders.add(holder); - this.modulePropertyHolderMap.put(type, holders); - } else { - this.modulePropertyHolderMap.get(type).add(holder); - } - } - - public Map getPolicyFinderModules() { - return policyFinderModules; - } - - public void addPolicyFinderModule(PolicyFinderModule policyFinderModule, - Properties properties) { - this.policyFinderModules.put(policyFinderModule, properties); - } - - public Map getPolicyCollections() { - return policyCollections; - } - - public void addPolicyCollection(PolicyCollection collection, Properties properties) { - this.policyCollections.put(collection, properties); - } - - public Map getPolicyStore() { - return policyStore; - } - - public void addPolicyStore(PolicyStoreManageModule policyStoreStore, Properties properties) { - this.policyStore.put(policyStoreStore, properties); - } - - public Map getPolicyPostPublisherModules() { - return policyPostPublisherModules; - } - - public void addPolicyPostPublisherModule(PostPublisherModule postPublisherModule, Properties properties) { - this.policyPostPublisherModules.put(postPublisherModule, properties); - } - - public Map getPublisherVerificationModule() { - return publisherVerificationModule; - } - - public void addPublisherVerificationModule(PublisherVerificationModule publisherVerificationModule, - Properties properties) { - this.publisherVerificationModule.put(publisherVerificationModule, properties); - } - - public Map getPapStatusDataHandlers() { - return papStatusDataHandlers; - } - - public void addNotificationHandler(PAPStatusDataHandler notificationHandler, - Properties properties) { - this.papStatusDataHandlers.put(notificationHandler, properties); - } - - public Map getPolicyDataStore() { - return policyDataStore; - } - - public void addPolicyDataStore(PolicyDataStore policyDataStore, Properties properties) { - this.policyDataStore.put(policyDataStore, properties); - } - - public ConfigurationContextService getConfigurationContextService() { - return configurationContextService; - } - - public void setConfigurationContextService(ConfigurationContextService configurationContextService) { - this.configurationContextService = configurationContextService; - } - - public ApplicationManagementService getApplicationManagementService() { - - return applicationManagementService; - } - - public void setApplicationManagementService(ApplicationManagementService applicationManagementService) { - - this.applicationManagementService = applicationManagementService; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/internal/EntitlementExtensionBuilder.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/internal/EntitlementExtensionBuilder.java deleted file mode 100644 index 538a3751240d..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/internal/EntitlementExtensionBuilder.java +++ /dev/null @@ -1,565 +0,0 @@ -/* - * Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.entitlement.internal; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.framework.BundleContext; -import org.wso2.carbon.identity.core.util.IdentityUtil; -import org.wso2.carbon.identity.entitlement.PAPStatusDataHandler; -import org.wso2.carbon.identity.entitlement.PDPConstants; -import org.wso2.carbon.identity.entitlement.pap.EntitlementDataFinderModule; -import org.wso2.carbon.identity.entitlement.pip.PIPAttributeFinder; -import org.wso2.carbon.identity.entitlement.pip.PIPExtension; -import org.wso2.carbon.identity.entitlement.pip.PIPResourceFinder; -import org.wso2.carbon.identity.entitlement.policy.collection.PolicyCollection; -import org.wso2.carbon.identity.entitlement.policy.finder.PolicyFinderModule; -import org.wso2.carbon.identity.entitlement.policy.publisher.PolicyPublisherModule; -import org.wso2.carbon.identity.entitlement.policy.publisher.PostPublisherModule; -import org.wso2.carbon.identity.entitlement.policy.publisher.PublisherVerificationModule; -import org.wso2.carbon.identity.entitlement.policy.store.PolicyDataStore; -import org.wso2.carbon.identity.entitlement.policy.store.PolicyStoreManageModule; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.Properties; - -/** - * Build Entitlement configuration from entitlement.properties. First this will try to find the - * configuration file from [CARBON_HOME]\repository\conf - failing to do so will load the file from - * this bundle it self.The default file ships with the bundle only includes - * org.wso2.carbon.identity.entitlement.pip.DefaultAttributeFinder as an AttributeDesignator and - * default caching configurations. - *

    - *

    - * PDP.OnDemangPolicyLoading.Enable=false - * PDP.OnDemangPolicyLoading.MaxInMemoryPolicies=1000 - * PDP.DecisionCaching.Enable=true - * PDP.DecisionCaching.CachingInterval=30000 - * PDP.AttributeCaching.Enable=true - * PDP.DecisionCaching.CachingInterval=30000 - * PDP.ResourceCaching.Enable=true - * PDP.ResourceCaching.CachingInterval=30000 - * JSON.Shorten.Form.Enabled.ForDefault=false - *

    - * PDP.Extensions.Extension.1=org.wso2.carbon.identity.entitlement.pdp.DefaultExtension - *

    - * PIP.AttributeDesignators.Designator.1=org.wso2.carbon.identity.entitlement.pip.DefaultAttributeFinder - * PIP.ResourceFinders.Finder.1="org.wso2.carbon.identity.entitlement.pip.DefaultResourceFinder - *

    - * PAP.MetaDataFinders.Finder.1=org.wso2.carbon.identity.entitlement.pap.CarbonEntitlementDataFinder - * PAP.PolicyPublishers.Publisher.1=org.wso2.carbon.identity.entitlement.policy.publisher - * .CarbonBasicPolicyPublisherModule - *

    - * # Properties needed for each extension. # - * org.wso2.carbon.identity.entitlement.pip.DefaultAttributeFinder.1=name,value # - * org.wso2.carbon.identity.entitlement.pip.DefaultAttributeFinder.2=name,value # - * org.wso2.carbon.identity.entitlement.pip.DefaultResourceFinder.1=name.value # - * org.wso2.carbon.identity.entitlement.pip.DefaultResourceFinder.2=name,value # - * org.wso2.carbon.identity.entitlement.pap.CarbonEntitlementDataFinder.1=name,value # - * org.wso2.carbon.identity.entitlement.pap.CarbonEntitlementDataFinder.2=name,value - */ -public class EntitlementExtensionBuilder { - - - public static final String PDP_SCHEMA_VALIDATION = "PDP.SchemaValidation.Enable"; - - private static final String ENTITLEMENT_CONFIG = "entitlement.properties"; - - private static final Log log = LogFactory.getLog(EntitlementExtensionBuilder.class); - - private BundleContext bundleContext; - - public void setBundleContext(BundleContext bundleContext) { - this.bundleContext = bundleContext; - } - - public void buildEntitlementConfig(EntitlementConfigHolder holder) throws Exception { - - Properties properties; - - if ((properties = loadProperties()) != null) { - populateEntitlementAttributes(properties, holder); - populatePDPExtensions(properties, holder); - populateAttributeFinders(properties, holder); - populateEntitlementDataFinders(properties, holder); - populateResourceFinders(properties, holder); - populatePolicyPublishers(properties, holder); - populatePolicyFinders(properties, holder); - populatePolicyCollection(properties, holder); - populatePolicyStoreModule(properties, holder); - populatePolicyDataStore(properties, holder); - populatePolicyPostPublishers(properties, holder); - populateAdminNotificationHandlers(properties, holder); - populatePublisherVerificationHandler(properties, holder); - } - } - - /** - * @return properties - * @throws IOException - */ - private Properties loadProperties() throws IOException { - - Properties properties = new Properties(); - InputStream inStream = null; - String warningMessage = null; - - File pipConfigXml = new File(IdentityUtil.getIdentityConfigDirPath(), ENTITLEMENT_CONFIG); - - try { - if (pipConfigXml.exists()) { - inStream = new FileInputStream(pipConfigXml); - } else { - URL url; - if (bundleContext != null) { - if ((url = bundleContext.getBundle().getResource(ENTITLEMENT_CONFIG)) != null) { - inStream = url.openStream(); - } else { - warningMessage = "Bundle context could not find resource " - + ENTITLEMENT_CONFIG - + " or user does not have sufficient permission to access the resource."; - } - - } else { - - if ((url = this.getClass().getClassLoader().getResource(ENTITLEMENT_CONFIG)) != null) { - inStream = url.openStream(); - } else { - warningMessage = "PIP Config Builder could not find resource " - + ENTITLEMENT_CONFIG - + " or user does not have sufficient permission to access the resource."; - } - } - } - - if (inStream == null) { - log.warn(warningMessage); - return null; - } - - properties.load(inStream); - - } catch (FileNotFoundException e) { - if (log.isDebugEnabled()) { - log.debug(e); - } - throw e; - } catch (IOException e) { - if (log.isDebugEnabled()) { - log.debug(e); - } - throw e; - } finally { - try { - if (inStream != null) { - inStream.close(); - } - } catch (Exception e) { - log.error("Error while closing input stream ", e); - } - } - - return properties; - } - - /** - * @param properties which are used to populate pdp properties - * @param holder holder of properties - */ - private void populateEntitlementAttributes(Properties properties, EntitlementConfigHolder holder) { - - Properties pdpProperties = new Properties(); - - setProperty(properties, pdpProperties, PDPConstants.ON_DEMAND_POLICY_LOADING); - setProperty(properties, pdpProperties, PDPConstants.ON_DEMAND_POLICY_MAX_POLICY_ENTRIES); - setProperty(properties, pdpProperties, PDPConstants.DECISION_CACHING); - setProperty(properties, pdpProperties, PDPConstants.DECISION_CACHING_INTERVAL); - setProperty(properties, pdpProperties, PDPConstants.ATTRIBUTE_CACHING); - setProperty(properties, pdpProperties, PDPConstants.ATTRIBUTE_CACHING_INTERVAL); - setProperty(properties, pdpProperties, PDPConstants.RESOURCE_CACHING); - setProperty(properties, pdpProperties, PDPConstants.RESOURCE_CACHING_INTERVAL); - setProperty(properties, pdpProperties, PDPConstants.PDP_ENABLE); - setProperty(properties, pdpProperties, PDPConstants.PAP_ENABLE); - setProperty(properties, pdpProperties, PDPConstants.BALANA_CONFIG_ENABLE); - setProperty(properties, pdpProperties, PDPConstants.MULTIPLE_DECISION_PROFILE_ENABLE); - setProperty(properties, pdpProperties, PDPConstants.MAX_POLICY_REFERENCE_ENTRIES); - setProperty(properties, pdpProperties, PDPConstants.FILESYSTEM_POLICY_PATH); - setProperty(properties, pdpProperties, PDPConstants.POLICY_ID_REGEXP_PATTERN); - setProperty(properties, pdpProperties, PDPConstants.PDP_GLOBAL_COMBINING_ALGORITHM); - setProperty(properties, pdpProperties, PDPConstants.ENTITLEMENT_ITEMS_PER_PAGE); - setProperty(properties, pdpProperties, PDPConstants.START_UP_POLICY_ADDING); - setProperty(properties, pdpProperties, PDP_SCHEMA_VALIDATION); - setProperty(properties, pdpProperties, PDPConstants.ENTITLEMENT_ENGINE_CACHING_INTERVAL); - setProperty(properties, pdpProperties, PDPConstants.PDP_REGISTRY_LEVEL_POLICY_CACHE_CLEAR); - setProperty(properties, pdpProperties, PDPConstants.POLICY_CACHING_INTERVAL); - setProperty(properties, pdpProperties, PDPConstants.XACML_JSON_SHORT_FORM_ENABLED); - setProperty(properties, pdpProperties, PDPConstants.STORE_POLICY_META_DATA); - - holder.setEngineProperties(pdpProperties); - } - - - private void setProperty(Properties inProp, Properties outProp, String name) { - String value; - if ((value = inProp.getProperty(name)) != null) { - outProp.setProperty(name, value.trim()); - } - } - - /** - * @param properties - * @param holder - * @throws Exception - */ - private void populateAttributeFinders(Properties properties, EntitlementConfigHolder holder) - throws Exception { - int i = 1; - PIPAttributeFinder designator = null; - - while (properties.getProperty("PIP.AttributeDesignators.Designator." + i) != null) { - String className = properties.getProperty("PIP.AttributeDesignators.Designator." + i++); - Class clazz = Thread.currentThread().getContextClassLoader().loadClass(className); - designator = (PIPAttributeFinder) clazz.newInstance(); - - int j = 1; - Properties designatorProps = new Properties(); - while (properties.getProperty(className + "." + j) != null) { - String[] props = properties.getProperty(className + "." + j++).split(","); - designatorProps.put(props[0], props[1]); - } - - designator.init(designatorProps); - holder.addDesignators(designator, designatorProps); - } - } - - /** - * @param properties - * @param holder - * @throws Exception - */ - private void populateResourceFinders(Properties properties, EntitlementConfigHolder holder) - throws Exception { - - int i = 1; - PIPResourceFinder resource = null; - - while (properties.getProperty("PIP.ResourceFinders.Finder." + i) != null) { - String className = properties.getProperty("PIP.ResourceFinders.Finder." + i++); - Class clazz = Thread.currentThread().getContextClassLoader().loadClass(className); - resource = (PIPResourceFinder) clazz.newInstance(); - - int j = 1; - Properties resourceProps = new Properties(); - while (properties.getProperty(className + "." + j) != null) { - String[] props = properties.getProperty(className + "." + j++).split(","); - resourceProps.put(props[0], props[1]); - } - - resource.init(resourceProps); - holder.addResourceFinders(resource, resourceProps); - } - } - - /** - * @param properties - * @param holder - * @throws Exception - */ - private void populatePDPExtensions(Properties properties, EntitlementConfigHolder holder) - throws Exception { - - int i = 1; - PIPExtension extension = null; - - while (properties.getProperty("PDP.Extensions.Extension." + i) != null) { - String className = properties.getProperty("PDP.Extensions.Extension." + i++); - Class clazz = Thread.currentThread().getContextClassLoader().loadClass(className); - extension = (PIPExtension) clazz.newInstance(); - - int j = 1; - Properties extensionProps = new Properties(); - while (properties.getProperty(className + "." + j) != null) { - String[] props = properties.getProperty(className + "." + j++).split(","); - extensionProps.put(props[0], props[1]); - } - - extension.init(extensionProps); - holder.addExtensions(extension, extensionProps); - } - } - - /** - * @param properties - * @param holder - * @throws Exception - */ - private void populatePolicyFinders(Properties properties, EntitlementConfigHolder holder) - throws Exception { - - int i = 1; - PolicyFinderModule finderModule = null; - - while (properties.getProperty("PDP.Policy.Finder." + i) != null) { - String className = properties.getProperty("PDP.Policy.Finder." + i++); - Class clazz = Thread.currentThread().getContextClassLoader().loadClass(className); - finderModule = (PolicyFinderModule) clazz.newInstance(); - - int j = 1; - Properties finderModuleProps = new Properties(); - while (properties.getProperty(className + "." + j) != null) { - String[] props = properties.getProperty(className + "." + j++).split(","); - finderModuleProps.put(props[0], props[1]); - } - - finderModule.init(finderModuleProps); - if (finderModule instanceof PolicyStoreManageModule) { - holder.addPolicyStore((PolicyStoreManageModule) finderModule, finderModuleProps); - } - holder.addPolicyFinderModule(finderModule, finderModuleProps); - } - } - - /** - * @param properties - * @param holder - * @throws Exception - */ - private void populatePolicyCollection(Properties properties, EntitlementConfigHolder holder) - throws Exception { - - PolicyCollection collection = null; - - //only one policy collection can be there - if (properties.getProperty("PDP.Policy.Collection") != null) { - String className = properties.getProperty("PDP.Policy.Collection"); - Class clazz = Thread.currentThread().getContextClassLoader().loadClass(className); - collection = (PolicyCollection) clazz.newInstance(); - - int j = 1; - Properties collectionProps = new Properties(); - while (properties.getProperty(className + "." + j) != null) { - String[] props = properties.getProperty(className + "." + j++).split(","); - collectionProps.put(props[0], props[1]); - } - - collection.init(collectionProps); - holder.addPolicyCollection(collection, collectionProps); - } - } - - /** - * @param properties - * @param holder - * @throws Exception - */ - private void populatePolicyStoreModule(Properties properties, EntitlementConfigHolder holder) - throws Exception { - - PolicyStoreManageModule policyStoreStore = null; - - if (properties.getProperty("PDP.Policy.Store.Module") != null) { - String className = properties.getProperty("PDP.Policy.Store.Module"); - Class clazz = Thread.currentThread().getContextClassLoader().loadClass(className); - policyStoreStore = (PolicyStoreManageModule) clazz.newInstance(); - - int j = 1; - Properties storeProps = new Properties(); - while (properties.getProperty(className + "." + j) != null) { - String[] props = properties.getProperty(className + "." + j++).split(","); - storeProps.put(props[0], props[1]); - } - - policyStoreStore.init(storeProps); - holder.addPolicyStore(policyStoreStore, storeProps); - } - } - - /** - * @param properties properties. - * @param holder holder. - * @throws Exception throws if fails. - */ - private void populatePolicyDataStore(Properties properties, EntitlementConfigHolder holder) - throws Exception { - - PolicyDataStore policyDataStore; - - if (properties.getProperty("PDP.Policy.Data.Store.Module") != null) { - String className = properties.getProperty("PDP.Policy.Data.Store.Module"); - Class clazz = Thread.currentThread().getContextClassLoader().loadClass(className); - policyDataStore = (PolicyDataStore) clazz.newInstance(); - - int j = 1; - Properties storeProps = new Properties(); - while (properties.getProperty(className + "." + j) != null) { - String[] props = properties.getProperty(className + "." + j++).split(","); - storeProps.put(props[0], props[1]); - } - - policyDataStore.init(storeProps); - holder.addPolicyDataStore(policyDataStore, storeProps); - } - } - - /** - * @param properties - * @param holder - * @throws Exception - */ - private void populateEntitlementDataFinders(Properties properties, EntitlementConfigHolder holder) - throws Exception { - int i = 1; - EntitlementDataFinderModule metadata = null; - - while (properties.getProperty("PAP.Entitlement.Data.Finder." + i) != null) { - String className = properties.getProperty("PAP.Entitlement.Data.Finder." + i++); - Class clazz = Thread.currentThread().getContextClassLoader().loadClass(className); - metadata = (EntitlementDataFinderModule) clazz.newInstance(); - - int j = 1; - Properties metadataProps = new Properties(); - while (properties.getProperty(className + "." + j) != null) { - String value = properties.getProperty(className + "." + j++); - metadataProps.put(value.substring(0, value.indexOf(",")), - value.substring(value.indexOf(",") + 1)); - } - - metadata.init(metadataProps); - holder.addPolicyEntitlementDataFinder(metadata, metadataProps); - } - } - - - /** - * @param properties - * @param holder - * @throws Exception - */ - private void populatePolicyPublishers(Properties properties, EntitlementConfigHolder holder) - throws Exception { - - int i = 1; - PolicyPublisherModule publisher = null; - - while (properties.getProperty("PAP.Policy.Publisher.Module." + i) != null) { - String className = properties.getProperty("PAP.Policy.Publisher.Module." + i++); - Class clazz = Thread.currentThread().getContextClassLoader().loadClass(className); - publisher = (PolicyPublisherModule) clazz.newInstance(); - - int j = 1; - Properties publisherProps = new Properties(); - while (properties.getProperty(className + "." + j) != null) { - String[] props = properties.getProperty(className + "." + j++).split(","); - publisherProps.put(props[0], props[1]); - } - - publisher.init(publisherProps); - holder.addPolicyPublisherModule(publisher, publisherProps); - } - } - - /** - * @param properties - * @param holder - * @throws Exception - */ - private void populatePolicyPostPublishers(Properties properties, EntitlementConfigHolder holder) - throws Exception { - - int i = 1; - PostPublisherModule postPublisherModule = null; - - while (properties.getProperty("PAP.Policy.Post.Publisher.Module." + i) != null) { - String className = properties.getProperty("PAP.Policy.Post.Publisher.Module." + i++); - Class clazz = Thread.currentThread().getContextClassLoader().loadClass(className); - postPublisherModule = (PostPublisherModule) clazz.newInstance(); - - int j = 1; - Properties publisherProps = new Properties(); - while (properties.getProperty(className + "." + j) != null) { - String[] props = properties.getProperty(className + "." + j++).split(","); - publisherProps.put(props[0], props[1]); - } - - postPublisherModule.init(publisherProps); - holder.addPolicyPostPublisherModule(postPublisherModule, publisherProps); - } - } - - /** - * @param properties - * @param holder - * @throws Exception - */ - private void populatePublisherVerificationHandler(Properties properties, EntitlementConfigHolder holder) - throws Exception { - - PublisherVerificationModule verificationModule = null; - - if (properties.getProperty("PAP.Policy.Publisher.Verification.Handler") != null) { - String className = properties.getProperty("PAP.Policy.Publisher.Verification.Handler"); - Class clazz = Thread.currentThread().getContextClassLoader().loadClass(className); - verificationModule = (PublisherVerificationModule) clazz.newInstance(); - - int j = 1; - Properties storeProps = new Properties(); - while (properties.getProperty(className + "." + j) != null) { - String[] props = properties.getProperty(className + "." + j++).split(","); - storeProps.put(props[0], props[1]); - } - - verificationModule.init(storeProps); - holder.addPublisherVerificationModule(verificationModule, storeProps); - } - } - - /** - * @param properties - * @param holder - * @throws Exception - */ - private void populateAdminNotificationHandlers(Properties properties, EntitlementConfigHolder holder) - throws Exception { - - int i = 1; - PAPStatusDataHandler handler = null; - - while (properties.getProperty("PAP.Status.Data.Handler." + i) != null) { - String className = properties.getProperty("PAP.Status.Data.Handler." + i++); - Class clazz = Thread.currentThread().getContextClassLoader().loadClass(className); - handler = (PAPStatusDataHandler) clazz.newInstance(); - - int j = 1; - Properties publisherProps = new Properties(); - while (properties.getProperty(className + "." + j) != null) { - String[] props = properties.getProperty(className + "." + j++).split(","); - publisherProps.put(props[0], props[1]); - } - - handler.init(publisherProps); - holder.addNotificationHandler(handler, publisherProps); - } - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/internal/EntitlementServiceComponent.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/internal/EntitlementServiceComponent.java deleted file mode 100644 index 578f62d26dd8..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/internal/EntitlementServiceComponent.java +++ /dev/null @@ -1,637 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.internal; - -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.io.FileUtils; -import org.apache.commons.lang.ArrayUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.thrift.server.TServer; -import org.apache.thrift.server.TThreadPoolServer; -import org.apache.thrift.transport.TSSLTransportFactory; -import org.apache.thrift.transport.TServerSocket; -import org.apache.thrift.transport.TTransportException; -import org.osgi.service.component.ComponentContext; -import org.osgi.service.component.annotations.Activate; -import org.osgi.service.component.annotations.Component; -import org.osgi.service.component.annotations.Deactivate; -import org.osgi.service.component.annotations.Reference; -import org.osgi.service.component.annotations.ReferenceCardinality; -import org.osgi.service.component.annotations.ReferencePolicy; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.identity.application.mgt.ApplicationManagementService; -import org.wso2.carbon.identity.core.util.IdentityCoreInitializedEvent; -import org.wso2.carbon.identity.core.util.IdentityUtil; -import org.wso2.carbon.identity.entitlement.EntitlementUtil; -import org.wso2.carbon.identity.entitlement.PDPConstants; -import org.wso2.carbon.identity.entitlement.persistence.PolicyPersistenceManager; -import org.wso2.carbon.identity.entitlement.dto.PolicyDTO; -import org.wso2.carbon.identity.entitlement.listener.CacheClearingUserOperationListener; -import org.wso2.carbon.identity.entitlement.pap.EntitlementAdminEngine; -import org.wso2.carbon.identity.entitlement.thrift.EntitlementService; -import org.wso2.carbon.identity.entitlement.thrift.ThriftConfigConstants; -import org.wso2.carbon.identity.entitlement.thrift.ThriftEntitlementServiceImpl; -import org.wso2.carbon.identity.notification.mgt.NotificationSender; -import org.wso2.carbon.identity.thrift.authentication.ThriftAuthenticatorService; -import org.wso2.carbon.registry.core.Registry; -import org.wso2.carbon.registry.core.exceptions.RegistryException; -import org.wso2.carbon.registry.core.service.RegistryService; -import org.wso2.carbon.user.core.listener.UserOperationEventListener; -import org.wso2.carbon.user.core.service.RealmService; -import org.wso2.carbon.utils.CarbonUtils; -import org.wso2.carbon.utils.ConfigurationContextService; -import org.wso2.carbon.utils.NetworkUtils; -import org.wso2.carbon.utils.multitenancy.MultitenantConstants; - -import java.io.File; -import java.io.IOException; -import java.net.InetAddress; -import java.net.SocketException; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -@Component( - name = "identity.entitlement.component", - immediate = true) -public class EntitlementServiceComponent { - - /** - * Property used to specify the configuration file. - */ - public static final String PDP_CONFIG_FILE_PATH = "org.wso2.balana.PDPConfigFile"; - - /** - * Property used to enhance the XACML policy loading flow from the filesystem. - */ - private static final String ENHANCED_XACML_LOADING_SYSTEM_PROPERTY = "enableEnhancedXACMLLoading"; - - private static final Log log = LogFactory.getLog(EntitlementServiceComponent.class); - private static RegistryService registryService = null; - private static RealmService realmservice; - private static NotificationSender notificationSender; - private ThriftAuthenticatorService thriftAuthenticationService; - private ExecutorService executor = Executors.newFixedThreadPool(2); - - /** - * - */ - public EntitlementServiceComponent() { - } - - /** - * @return - */ - public static EntitlementConfigHolder getEntitlementConfig() { - return EntitlementConfigHolder.getInstance(); - } - - /** - * @return - */ - public static RealmService getRealmservice() { - return realmservice; - } - - /** - * @param realmservice - */ - public static void setRealmservice(RealmService realmservice) { - EntitlementServiceComponent.realmservice = realmservice; - } - - /** - * Return registry service - * - * @return RegistryService - */ - public static RegistryService getRegistryService() { - return registryService; - } - - /** - * sets registry service - * - * @param registryService RegistryService - */ - @Reference( - name = "registry.service", - service = RegistryService.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetRegistryService" - ) - protected void setRegistryService(RegistryService registryService) { - if (log.isDebugEnabled()) { - log.debug("RegistryService set in Entitlement bundle"); - } - EntitlementServiceComponent.registryService = registryService; - } - - public static Registry getGovernanceRegistry(int tenantId) { - try { - return registryService.getGovernanceSystemRegistry(tenantId); - } catch (RegistryException e) { - // ignore - } - return null; - } - - public static NotificationSender getNotificationSender() { - return EntitlementServiceComponent.notificationSender; - } - - @Reference( - name = "carbon.identity.notification.mgt", - service = NotificationSender.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetNotificationSender" - ) - protected void setNotificationSender(NotificationSender notificationSender) { - if (log.isDebugEnabled()) { - log.debug("Un-setting notification sender in Entitlement bundle"); - } - this.notificationSender = notificationSender; - } - - /** - * @param ctxt - */ - @Activate - protected void activate(ComponentContext ctxt) { - - if (log.isDebugEnabled()) { - log.debug("Identity Entitlement bundle is activated"); - } - - try { - // build configuration file - EntitlementExtensionBuilder builder = new EntitlementExtensionBuilder(); - builder.setBundleContext(ctxt.getBundleContext()); - builder.buildEntitlementConfig(EntitlementConfigHolder.getInstance()); - - boolean balanaConfig = Boolean.parseBoolean((String) EntitlementServiceComponent.getEntitlementConfig(). - getEngineProperties().get(PDPConstants.BALANA_CONFIG_ENABLE)); - - String configProperty = System.getProperty(PDP_CONFIG_FILE_PATH); - - if (balanaConfig && configProperty == null) { - String configFilePath = CarbonUtils.getCarbonConfigDirPath() + File.separator + "security" - + File.separator + "balana-config.xml"; - - System.setProperty(PDP_CONFIG_FILE_PATH, configFilePath); - } - - if (log.isDebugEnabled()) { - log.debug("Setting org.wso2.balana.PDPConfigFile property to " - + System.getProperty(PDP_CONFIG_FILE_PATH)); - } - - // Start loading schema. - new Thread(new SchemaBuilder(EntitlementConfigHolder.getInstance())).start(); - - // Read XACML policy files from a pre-defined location in the filesystem - PolicyPersistenceManager papPolicyStore = EntitlementAdminEngine.getInstance().getPolicyPersistenceManager(); - - String startUpPolicyAdding = EntitlementConfigHolder.getInstance().getEngineProperties().getProperty( - PDPConstants.START_UP_POLICY_ADDING); - - List policyIdList = new ArrayList<>(); - - if (papPolicyStore != null) { - List policyIds = papPolicyStore.listPolicyIds(); - if (CollectionUtils.isNotEmpty(policyIds)) { - policyIdList = policyIds; - } - } - - if (startUpPolicyAdding != null && Boolean.parseBoolean(startUpPolicyAdding)) { - - File policyFolder = null; - String policyPathFromConfig = EntitlementConfigHolder.getInstance().getEngineProperties().getProperty( - PDPConstants.FILESYSTEM_POLICY_PATH); - - if (StringUtils.isNotBlank(policyPathFromConfig)) { - policyFolder = new File(policyPathFromConfig); - } - - if (policyFolder != null && !policyFolder.exists()) { - log.warn("Defined policy directory location is not exit. " + - "Therefore using default policy location"); - } - - if (policyPathFromConfig == null || (policyFolder != null && !policyFolder.exists())) { - policyFolder = new File(CarbonUtils.getCarbonHome() + File.separator - + "repository" + File.separator + "resources" + File.separator - + "identity" + File.separator + "policies" + File.separator + "xacml"); - - } - - boolean customPolicies = false; - - File[] fileList; - if (policyFolder != null && policyFolder.exists() - && ArrayUtils.isNotEmpty(fileList = policyFolder.listFiles())) { - if (Boolean.parseBoolean(System.getProperty(ENHANCED_XACML_LOADING_SYSTEM_PROPERTY))) { - try { - PrivilegedCarbonContext.startTenantFlow(); - PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID); - carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); - long startTime = System.currentTimeMillis(); - - customPolicies = addPolicyFiles(policyIdList, fileList); - - long endTime = (System.currentTimeMillis() - startTime) / 1000; - log.info("XACML Policies loaded in " + endTime + " sec"); - } finally { - PrivilegedCarbonContext.endTenantFlow(); - } - } else { - customPolicies = addPolicyFiles(policyIdList, fileList); - } - } - - if (!customPolicies) { - // load default policies - EntitlementUtil.addSamplePolicies(); - } - } - // Cache clearing listener is always registered since cache clearing is a must when - // an update happens of user attributes - CacheClearingUserOperationListener pipUserOperationListener = - new CacheClearingUserOperationListener(); - ctxt.getBundleContext().registerService( - UserOperationEventListener.class.getName(), pipUserOperationListener, null); - - // Register Notification sending on user operations. Even though this is registered - // only subscribed modules will send messages. - if (log.isDebugEnabled()) { - log.debug("Registering notification sender on user operations"); - } - - //TODO: Read from identity.xml, the configurations to be used in thrift based entitlement service. - //initialize thrift authenticator - ThriftEntitlementServiceImpl.init(thriftAuthenticationService); - //initialize thrift based Entitlement Service. - startThriftServices(); - org.wso2.carbon.identity.entitlement.EntitlementService entitlementService = - new org.wso2.carbon.identity.entitlement.EntitlementService(); - ctxt.getBundleContext().registerService( - org.wso2.carbon.identity.entitlement.EntitlementService.class.getName(), entitlementService, null); - } catch (Throwable throwable) { - log.error("Failed to initialize Entitlement Service", throwable); - } - } - - /** - * Adds policy files with unique policyIDs to the registry. - * - * @param policyIdList List of IDs of existing policies. - * @param fileList List of files in policy folder. - * @return Boolean stating whether custom policies exist. - * @throws IOException Error when reading policy files. - */ - private boolean addPolicyFiles(List policyIdList, File[] fileList) throws IOException { - - boolean customPolicies = false; - for (File policyFile : fileList) { - if (policyFile.isFile()) { - PolicyDTO policyDTO = new PolicyDTO(); - policyDTO.setPolicy(FileUtils.readFileToString(policyFile)); - if (!policyIdList.contains(policyDTO.getPolicyId())) { - try { - EntitlementUtil.addFilesystemPolicy(policyDTO, true); - } catch (Exception e) { - // Log error and continue with the rest of the files. - log.error("Error while adding XACML policies", e); - } - } - customPolicies = true; - } - } - return customPolicies; - } - - /** - * @param ctxt - */ - @Deactivate - protected void deactivate(ComponentContext ctxt) { - if (log.isDebugEnabled()) { - log.debug("Identity Entitlement bundle is deactivated"); - } - } - - /** - * un-sets registry service - * - * @param registryService RegistryService - */ - protected void unsetRegistryService(RegistryService registryService) { - if (log.isDebugEnabled()) { - log.debug("RegistryService unset in Entitlement bundle"); - } - EntitlementServiceComponent.registryService = null; - } - - /** - * sets realm service - * - * @param realmService RealmService - */ - @Reference( - name = "user.realmservice.default", - service = org.wso2.carbon.user.core.service.RealmService.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetRealmService" - ) - protected void setRealmService(RealmService realmService) { - if (log.isDebugEnabled()) { - log.debug("DefaultUserRealm set in Entitlement bundle"); - } - EntitlementServiceComponent.realmservice = realmService; - } - - /** - * un-sets realm service - * - * @param realmService RealmService - */ - protected void unsetRealmService(RealmService realmService) { - if (log.isDebugEnabled()) { - log.debug("DefaultUserRealm unset in Entitlement bundle"); - } - EntitlementServiceComponent.realmservice = null; - } - - /** - * set Thrift authentication service - * - * @param authenticationService ThriftAuthenticatorService - */ - @Reference( - name = "org.wso2.carbon.identity.thrift.authentication.internal.ThriftAuthenticationServiceComponent", - service = ThriftAuthenticatorService.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetThriftAuthenticationService" - ) - protected void setThriftAuthenticationService(ThriftAuthenticatorService authenticationService) { - if (log.isDebugEnabled()) { - log.debug("ThriftAuthenticatorService set in Entitlement bundle"); - } - this.thriftAuthenticationService = authenticationService; - - } - - /** - * un-set Thrift authentication service - * - * @param authenticationService ThriftAuthenticatorService - */ - protected void unsetThriftAuthenticationService( - ThriftAuthenticatorService authenticationService) { - if (log.isDebugEnabled()) { - log.debug("ThriftAuthenticatorService unset in Entitlement bundle"); - } - this.thriftAuthenticationService = null; - } - - private void startThriftServices() throws Exception { - startThriftEntitlementService(); - } - - private void startThriftEntitlementService() throws Exception { - try { - //read identity.xml - IdentityUtil.populateProperties(); - //if thrift based EntitlementService is enabled. - String thriftEnabled = IdentityUtil.getProperty(ThriftConfigConstants.PARAM_ENABLE_THRIFT_SERVICE); - - if (thriftEnabled != null && Boolean.parseBoolean(thriftEnabled)) { - - TSSLTransportFactory.TSSLTransportParameters transportParam = - new TSSLTransportFactory.TSSLTransportParameters(); - - //read the keystore and password used for ssl communication from config - String keystorePath = IdentityUtil.getProperty( - ThriftConfigConstants.PARAM_KEYSTORE_LOCATION); - String keystorePassword = IdentityUtil.getProperty( - ThriftConfigConstants.PARAM_KEYSTORE_PASSWORD); - - //set it in parameters - transportParam.setKeyStore(keystorePath, keystorePassword); - //int receivePort = 10395; - int receivePort = readThriftReceivePort(); - //int clientTimeOut = 10000; - int clientTimeOut = Integer.parseInt(IdentityUtil.getProperty( - ThriftConfigConstants.PARAM_CLIENT_TIMEOUT)); - //String ifAddress = "localhost"; - TServerSocket serverTransport = - TSSLTransportFactory.getServerSocket(receivePort, - clientTimeOut, - getHostAddress(readThriftHostName()), - transportParam); - - EntitlementService.Processor processor = new EntitlementService.Processor( - new ThriftEntitlementServiceImpl()); - - //TODO: have to decide on the protocol. - TServer server = new TThreadPoolServer(new TThreadPoolServer.Args(serverTransport). - processor(processor)); - //TServer server = new TThreadPoolServer(new TThreadPoolServer.Args()) -/* - TServer server = new TThreadPoolServer(processor, serverTransport, - new TCompactProtocol.Factory());*/ - Runnable serverThread = new ServerRunnable(server); - executor.submit(serverThread); - - if (log.isDebugEnabled()) { - log.debug("Started thrift entitlement service at port:" + receivePort); - } - } - - - } catch (TTransportException e) { - String transportErrorMsg = "Error in initializing thrift transport"; - log.error(transportErrorMsg, e); - throw new Exception(transportErrorMsg); - } catch (UnknownHostException e) { - String hostErrorMsg = "Error in obtaining host name"; - log.error(hostErrorMsg, e); - throw new Exception(hostErrorMsg); - } - - - } - - /** - * Read the port from identity.xml which is overridden by carbon.xml to facilitating - * multiple servers at a time. - */ - private int readThriftReceivePort() { - int port = -1; - String portValue = IdentityUtil.getProperty(ThriftConfigConstants.PARAM_RECEIVE_PORT); - //if the port contains a template string that refers to carbon.xml - if ((portValue.contains("${")) && (portValue.contains("}"))) { - port = (CarbonUtils.getPortFromServerConfig(portValue)); - } else { //if port directly mentioned in identity.xml - port = Integer.parseInt(portValue); - } - return port; - } - - /** - * Get INetAddress by host name or IP Address - * - * @param host name or host IP String - * @return InetAddress - * @throws UnknownHostException - */ - private InetAddress getHostAddress(String host) throws UnknownHostException { - - String[] splittedString = host.split("\\."); - - if (splittedString.length == 4) { - // check whether this is ip address or not. - try { - Integer.parseInt(splittedString[0]); - Integer.parseInt(splittedString[1]); - Integer.parseInt(splittedString[2]); - Integer.parseInt(splittedString[3]); - byte[] byteAddress = new byte[4]; - for (int i = 0; i < splittedString.length; i++) { - if (Integer.parseInt(splittedString[i]) > 127) { - byteAddress[i] = Integer.valueOf(Integer.parseInt(splittedString[i]) - 256).byteValue(); - } else { - byteAddress[i] = Byte.parseByte(splittedString[i]); - } - } - return InetAddress.getByAddress(byteAddress); - } catch (Exception e) { - log.debug(e); - // ignore. - } - } - // if not ip address return host name - return InetAddress.getByName(host); - } - - /** - * Read the thrift hostname from identity.xml which overrides the hostName from carbon.xml on facilitating - * identifying the host for thrift server . - */ - private String readThriftHostName() throws SocketException { - - String thriftHostName = IdentityUtil.getProperty(ThriftConfigConstants.PARAM_HOST_NAME); - - //if the thrift host name doesn't exist in config, load from carbon.xml - if (thriftHostName != null) { - return thriftHostName; - } else { - return NetworkUtils.getLocalHostname(); - } - } - - protected void unsetNotificationSender(NotificationSender notificationSender) { - if (log.isDebugEnabled()) { - log.debug("Setting notification sender in Entitlement bundle"); - } - this.notificationSender = null; - } - - @Reference( - name = "identityCoreInitializedEventService", - service = IdentityCoreInitializedEvent.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetIdentityCoreInitializedEventService" - ) - - protected void setIdentityCoreInitializedEventService(IdentityCoreInitializedEvent identityCoreInitializedEvent) { - /* reference IdentityCoreInitializedEvent service to guarantee that this component will wait until identity core - is started */ - } - - protected void unsetIdentityCoreInitializedEventService(IdentityCoreInitializedEvent identityCoreInitializedEvent) { - /* reference IdentityCoreInitializedEvent service to guarantee that this component will wait until identity core - is started */ - } - - @Reference( - name = "config.context.service", - service = ConfigurationContextService.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetConfigurationContextService" - ) - protected void setConfigurationContextService(ConfigurationContextService configCtxtService) { - if (log.isDebugEnabled()) { - log.debug("ConfigurationContextService set in EntitlementServiceComponent bundle."); - } - EntitlementConfigHolder.getInstance().setConfigurationContextService(configCtxtService); - } - - protected void unsetConfigurationContextService(ConfigurationContextService configCtxtService) { - if (log.isDebugEnabled()) { - log.debug("ConfigurationContextService unset in EntitlementServiceComponent bundle."); - } - EntitlementConfigHolder.getInstance().setConfigurationContextService(null); - } - - @Reference( - name = "org.wso2.carbon.identity.application.mgt.ApplicationManagementService", - service = org.wso2.carbon.identity.application.mgt.ApplicationManagementService.class, - cardinality = ReferenceCardinality.MANDATORY, - policy = ReferencePolicy.DYNAMIC, - unbind = "unsetApplicationManagementService") - protected void setApplicationManagementService(ApplicationManagementService applicationManagementService) { - - EntitlementConfigHolder.getInstance().setApplicationManagementService(applicationManagementService); - log.debug("ApplicationManagementService set in EntitlementServiceComponent bundle."); - } - - protected void unsetApplicationManagementService(ApplicationManagementService applicationManagementService) { - - EntitlementConfigHolder.getInstance().setApplicationManagementService(null); - log.debug("ApplicationManagementService unset in EntitlementServiceComponent bundle."); - } - - - /** - * Thread that starts thrift server - */ - private static class ServerRunnable implements Runnable { - TServer server; - - public ServerRunnable(TServer server) { - this.server = server; - } - - public void run() { - server.serve(); - } - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/internal/SchemaBuilder.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/internal/SchemaBuilder.java deleted file mode 100644 index f807e6431051..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/internal/SchemaBuilder.java +++ /dev/null @@ -1,94 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.internal; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.core.util.IdentityIOStreamUtils; -import org.wso2.carbon.identity.entitlement.PDPConstants; -import org.xml.sax.SAXException; - -import javax.xml.XMLConstants; -import javax.xml.transform.stream.StreamSource; -import javax.xml.validation.Schema; -import javax.xml.validation.SchemaFactory; -import java.io.InputStream; - -public class SchemaBuilder implements Runnable { - - private static Log log = LogFactory.getLog(SchemaBuilder.class); - - private EntitlementConfigHolder configHolder; - - public SchemaBuilder(EntitlementConfigHolder configHolder) { - this.configHolder = configHolder; - } - - @Override - public void run() { - try { - buildPolicySchema(); - log.info("XACML policy schema loaded successfully."); - } catch (Exception e) { - configHolder.getEngineProperties().setProperty(EntitlementExtensionBuilder.PDP_SCHEMA_VALIDATION, "false"); - log.warn("Error while loading policy schema. Schema validation will be disabled."); - } - } - - /** - * Builds the policy schema map. There are three schemas. - * - * @param configHolder holder EntitlementConfigHolder - * @throws SAXException if fails - */ - public void buildPolicySchema() throws SAXException { - - if (!"true".equalsIgnoreCase((String) configHolder.getEngineProperties().get( - EntitlementExtensionBuilder.PDP_SCHEMA_VALIDATION))) { - log.warn("PDP schema validation disabled."); - return; - } - - String[] schemaNSs = new String[]{PDPConstants.XACML_1_POLICY_XMLNS, - PDPConstants.XACML_2_POLICY_XMLNS, - PDPConstants.XACML_3_POLICY_XMLNS}; - - for (String schemaNS : schemaNSs) { - - String schemaFile; - - if (PDPConstants.XACML_1_POLICY_XMLNS.equals(schemaNS)) { - schemaFile = PDPConstants.XACML_1_POLICY_SCHEMA_FILE; - } else if (PDPConstants.XACML_2_POLICY_XMLNS.equals(schemaNS)) { - schemaFile = PDPConstants.XACML_2_POLICY_SCHEMA_FILE; - } else { - schemaFile = PDPConstants.XACML_3_POLICY_SCHEMA_FILE; - } - - InputStream schemaFileStream = EntitlementExtensionBuilder.class.getResourceAsStream("/" + schemaFile); - try{ - SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); - Schema schema = schemaFactory.newSchema(new StreamSource(schemaFileStream)); - configHolder.getPolicySchemaMap().put(schemaNS, schema); - } finally { - IdentityIOStreamUtils.closeInputStream(schemaFileStream); - } - } - } - -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/listener/CacheClearingUserOperationListener.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/listener/CacheClearingUserOperationListener.java deleted file mode 100644 index e1fdcd99da77..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/listener/CacheClearingUserOperationListener.java +++ /dev/null @@ -1,323 +0,0 @@ -/* - * Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.entitlement.listener; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.core.AbstractIdentityUserOperationEventListener; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; -import org.wso2.carbon.identity.entitlement.pdp.EntitlementEngine; -import org.wso2.carbon.identity.entitlement.pip.CarbonAttributeFinder; -import org.wso2.carbon.identity.entitlement.pip.PIPAttributeFinder; -import org.wso2.carbon.user.api.Permission; -import org.wso2.carbon.user.core.UserStoreException; -import org.wso2.carbon.user.core.UserStoreManager; - -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -/** - * This listener is registered as a user operation listener. Whenever a user operation takes place - * this listener fires and responsible for clearing caches within entitlement engine. This will - * clear all 3 caches including PIP_ATTRIBUTE_CACHE, PDP_DECISION_INVALIDATION_CACHE, - * ENTITLEMENT_POLICY_INVALIDATION_CACHE - */ -public class CacheClearingUserOperationListener extends AbstractIdentityUserOperationEventListener { - - private static final Log log = LogFactory.getLog(CacheClearingUserOperationListener.class); - - @Override - public int getExecutionOrderId() { - return 6; - } - - /** - * TThis method is overridden to clear caches on doPostDeleteUser operation - * - * @param userName username - * @param userStoreManager UserStoreManagerClass - * @return Returns true always since no major effect on further procedures - * @throws org.wso2.carbon.user.core.UserStoreException - */ - @Override - public boolean doPostDeleteUser(String userName, UserStoreManager userStoreManager) throws - UserStoreException { - if (!isEnable()) { - return true; - } - - if (log.isDebugEnabled()) { - log.debug("Clearing entitlement cache on post delete user operation for user " + - userName); - } - clearCarbonAttributeCache(); - // Always returns true since cache clearing failure does not make an effect on subsequent - // User Operation Listeners - return true; - } - - /** - * This method is overridden to clear caches on doPostSetUserClaimValue operation - * - * @param userName username - * @param userStoreManager UserStoreManagerClass - * @return Returns true always since no major effect on further procedures - * @throws org.wso2.carbon.user.core.UserStoreException - */ - @Override - public boolean doPostSetUserClaimValue(String userName, UserStoreManager userStoreManager) - throws UserStoreException { - if (!isEnable()) { - return true; - } - - if (log.isDebugEnabled()) { - log.debug("Clearing entitlement cache on post set user claim value operation for user " - + userName); - } - // Always returns true since cache clearing failure does not make an effect on subsequent - // User Operation Listeners - clearCarbonAttributeCache(); - return true; - } - - /** - * This method is overridden to clear caches on doPostSetUserClaimValues operation - * - * @param userName Username of subjected user for claim updating - * @param claims Set of updated claims - * @param profileName Name of the profile - * @param userStoreManager UserStoreManager instance got called - * @return Always returns true since no major effect on further operations - * @throws org.wso2.carbon.user.core.UserStoreException - */ - @Override - public boolean doPostSetUserClaimValues(String userName, Map claims, - String profileName, UserStoreManager userStoreManager) - throws UserStoreException { - if (!isEnable()) { - return true; - } - - if (log.isDebugEnabled()) { - log.debug("Clearing entitlement cache on post set user claim values operation for " + - "user " + userName); - } - // Always returns true since cache clearing failure does not make an effect on subsequent - // User Operation Listeners - clearCarbonAttributeCache(); - return true; - } - - /** - * TThis method is overridden to clear caches on doPostDeleteUserClaimValues operation - * - * @param userName username - * @param userStoreManager UserStoreManagerClass - * @return Returns true always since no major effect on further procedures - * @throws org.wso2.carbon.user.core.UserStoreException - */ - @Override - public boolean doPostDeleteUserClaimValues(String userName, - UserStoreManager userStoreManager) throws - UserStoreException { - if (!isEnable()) { - return true; - } - - if (log.isDebugEnabled()) { - log.debug("Clearing entitlement cache on post delete user claim values operation for " + - "user " + userName); - } - // Always returns true since cache clearing failure does not make an effect on subsequent - // User Operation Listeners - clearCarbonAttributeCache(); - return true; - } - - /** - * This method is overridden to clear caches on doPostDeleteUserClaimValue operation - * - * @param userName username - * @param userStoreManager UserStoreManagerClass - * @return Always Returns true, since no major effect on further procedures - * @throws org.wso2.carbon.user.core.UserStoreException - */ - @Override - public boolean doPostDeleteUserClaimValue(String userName, UserStoreManager userStoreManager) - throws UserStoreException { - if (!isEnable()) { - return true; - } - - if (log.isDebugEnabled()) { - log.debug("Clearing entitlement cache on post delete user claim value operation for " + - "user " + userName); - } - // Always returns true since cache clearing failure does not make an effect on subsequent - // User Operation Listeners - clearCarbonAttributeCache(); - return true; - } - - /** - * This method is overridden to clear caches on doPostAddRole operation - * - * @param roleName Name of the added role - * @param userList List of the users who got added the role - * @param permissions set of permissions - * @param userStoreManager UserStoreManager instance got called - * @return Always Returns true, since no major effect on further procedures - * @throws org.wso2.carbon.user.core.UserStoreException - */ - @Override - public boolean doPostAddRole(String roleName, String[] userList, Permission[] permissions, - UserStoreManager userStoreManager) throws UserStoreException { - if (!isEnable()) { - return true; - } - - if (log.isDebugEnabled()) { - log.debug("Clearing entitlement cache on post add role operation for role " + - roleName); - } - clearCarbonAttributeCache(); - // Always returns true since cache clearing failure does not make an effect on subsequent - // User Operation Listeners - return true; - } - - /** - * This method is overridden to clear caches on doPostDeleteRole operation - * - * @param roleName Deleted role name - * @param userStoreManager UserStoreManagerClass - * @return Always Returns true, since no major effect on further procedures - * @throws org.wso2.carbon.user.core.UserStoreException - */ - @Override - public boolean doPostDeleteRole(String roleName, UserStoreManager userStoreManager) throws - UserStoreException { - if (!isEnable()) { - return true; - } - - if (log.isDebugEnabled()) { - log.debug("Clearing entitlement cache on post delete role operation for role " + - roleName); - } - clearCarbonAttributeCache(); - // Always returns true since cache clearing failure does not make an effect on subsequent - // User Operation Listeners - return true; - } - - /** - * @param roleName Old role name of the updating role - * @param newRoleName New role name of the updating role name - * @param userStoreManager UserStoreManager instance got called - * @return Always returns true since no major effect on further procedure. - * @throws org.wso2.carbon.user.core.UserStoreException - */ - @Override - public boolean doPostUpdateRoleName(String roleName, String newRoleName, - UserStoreManager userStoreManager) throws - UserStoreException { - if (!isEnable()) { - return true; - } - - if (log.isDebugEnabled()) { - log.debug("Clearing entitlement cache on post update role operation for role " + - roleName); - } - clearCarbonAttributeCache(); - // Always returns true since cache clearing failure does not make an effect on subsequent - // User Operation Listeners - return true; - } - - /** - * @param roleName Role to be updated with users. - * @param deletedUsers Users removed from the particular role. - * @param newUsers New users added to the particular role. - * @param userStoreManager UserStoreManager instance got called. - * @return Always returns true since no major effect on further procedure. - * @throws org.wso2.carbon.user.core.UserStoreException - */ - public boolean doPostUpdateUserListOfRole(String roleName, String[] deletedUsers, String[] newUsers, - UserStoreManager userStoreManager) throws UserStoreException { - if (log.isDebugEnabled()) { - log.debug("Clearing entitlement cache on post update user operation for role " + - roleName); - } - clearCarbonAttributeCache(); - // Always returns true since cache clearing failure does not make an effect on subsequent - // User Operation Listeners - return true; - } - - /** - * @param userName User name to be updated. - * @param deletedRoles Roles removed from the particular user. - * @param newRoles New roles added to the particular user. - * @param userStoreManager UserStoreManager instance got called - * @return Always returns true since no major effect on further procedure. - * @throws org.wso2.carbon.user.core.UserStoreException - */ - public boolean doPostUpdateRoleListOfUser(String userName, String[] deletedRoles, String[] newRoles, - UserStoreManager userStoreManager) throws UserStoreException { - if (log.isDebugEnabled()) { - log.debug("Clearing entitlement cache on post update role operation for user " + - userName); - } - clearCarbonAttributeCache(); - // Always returns true since cache clearing failure does not make an effect on subsequent - // User Operation Listeners - return true; - } - - /** - * this method is responsible for clearing all 3 major caches of entitlement engine - * including PIP_ATTRIBUTE_CACHE , PDP_DECISION_INVALIDATION_CACHE, ENTITLEMENT_POLICY_INVALIDATION_CACHE - */ - private void clearCarbonAttributeCache() { - - CarbonAttributeFinder finder = EntitlementEngine.getInstance().getCarbonAttributeFinder(); - if (finder != null) { - finder.clearAttributeCache(); - //Decision cache is cleared within clearAttributeCache. - } else { - // Return if no finders are found - return; - } - // clearing pip attribute finder caches - Map designators = - EntitlementServiceComponent.getEntitlementConfig() - .getDesignators(); - if (designators != null && !designators.isEmpty()) { - - Set pipAttributeFinders = designators.keySet(); - for (PIPAttributeFinder pipAttributeFinder : pipAttributeFinders) { - pipAttributeFinder.clearCache(); - } - } - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pap/CarbonEntitlementDataFinder.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pap/CarbonEntitlementDataFinder.java deleted file mode 100644 index c34fbd12c239..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pap/CarbonEntitlementDataFinder.java +++ /dev/null @@ -1,174 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.pap; - -import org.wso2.carbon.CarbonConstants; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.identity.entitlement.dto.EntitlementTreeNodeDTO; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; -import org.wso2.carbon.registry.api.Resource; -import org.wso2.carbon.registry.core.Collection; -import org.wso2.carbon.registry.core.Registry; -import org.wso2.carbon.registry.core.exceptions.RegistryException; -import org.wso2.carbon.user.api.UserStoreManager; -import org.wso2.carbon.user.core.common.AbstractUserStoreManager; - -import java.util.HashSet; -import java.util.Properties; -import java.util.Set; - -/** - * this is default implementation of the policy meta data finder module which finds the resource in the - * under-line registry - */ -public class CarbonEntitlementDataFinder implements EntitlementDataFinderModule { - - private static final String MODULE_NAME = "Carbon Attribute Finder Module"; - - private static final String SUBJECT_CATEGORY = "Subject"; - - private static final String ACTION_CATEGORY = "Action"; - - private static final String RESOURCE_CATEGORY = "Resource"; - - private Registry registry; - - private String[] defaultActions = new String[]{"read", "write", "delete", "edit"}; - - @Override - public void init(Properties properties) throws Exception { - - } - - @Override - public String getModuleName() { - return MODULE_NAME; - } - - @Override - public Set getRelatedApplications() { - return null; - } - - @Override - public Set getSupportedCategories() { - Set set = new HashSet(); - set.add(SUBJECT_CATEGORY); - set.add(ACTION_CATEGORY); - set.add(RESOURCE_CATEGORY); - return set; - } - - @Override - public EntitlementTreeNodeDTO getEntitlementData(String category, String regex, - int limit) throws Exception { - - registry = EntitlementServiceComponent.getRegistryService().getSystemRegistry(CarbonContext. - getThreadLocalCarbonContext().getTenantId()); - if (RESOURCE_CATEGORY.equalsIgnoreCase(category)) { - EntitlementTreeNodeDTO nodeDTO = new EntitlementTreeNodeDTO("/"); - getChildResources(nodeDTO, "_system"); - return nodeDTO; - } else if (ACTION_CATEGORY.equalsIgnoreCase(category)) { - EntitlementTreeNodeDTO nodeDTO = new EntitlementTreeNodeDTO(""); - for (String action : defaultActions) { - EntitlementTreeNodeDTO childNode = new EntitlementTreeNodeDTO(action); - nodeDTO.addChildNode(childNode); - } - return nodeDTO; - } else if (SUBJECT_CATEGORY.equalsIgnoreCase(category)) { - EntitlementTreeNodeDTO nodeDTO = new EntitlementTreeNodeDTO(""); - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - UserStoreManager userStoreManager = EntitlementServiceComponent.getRealmservice(). - getTenantUserRealm(tenantId).getUserStoreManager(); - - String[] roleNames = ((AbstractUserStoreManager) userStoreManager). - getRoleNames(regex, limit, false, true, true); - - for (String roleName : roleNames) { - if (CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME.equals(roleName)) { - continue; - } - EntitlementTreeNodeDTO childNode = new EntitlementTreeNodeDTO(roleName); - nodeDTO.addChildNode(childNode); - } - return nodeDTO; - } - - return null; - } - - @Override - public EntitlementTreeNodeDTO getEntitlementDataByLevel(String category, int level) throws Exception { - return null; - } - - @Override - public int getSupportedHierarchicalLevels() { - return 0; - } - - @Override - public boolean isFullPathSupported() { - return true; - } - - @Override - public boolean isHierarchicalTree() { - return true; - } - - @Override - public boolean isAllApplicationRelated() { - return true; - } - - @Override - public boolean isSearchSupported() { - return true; - } - - /** - * This helps to find resources un a recursive manner - * - * @param node attribute value node - * @param parentResource parent resource Name - * @return child resource set - * @throws RegistryException throws - */ - private EntitlementTreeNodeDTO getChildResources(EntitlementTreeNodeDTO node, - String parentResource) throws RegistryException { - - if (registry.resourceExists(parentResource)) { - String[] resourcePath = parentResource.split("/"); - EntitlementTreeNodeDTO childNode = - new EntitlementTreeNodeDTO(resourcePath[resourcePath.length - 1]); - node.addChildNode(childNode); - Resource root = registry.get(parentResource); - if (root instanceof Collection) { - Collection collection = (Collection) root; - String[] resources = collection.getChildren(); - for (String resource : resources) { - getChildResources(childNode, resource); - } - } - } - return node; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pap/EntitlementAdminEngine.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pap/EntitlementAdminEngine.java deleted file mode 100644 index 696afda30403..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pap/EntitlementAdminEngine.java +++ /dev/null @@ -1,169 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.pap; - -import org.apache.commons.collections.MapUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.PAPStatusDataHandler; -import org.wso2.carbon.identity.entitlement.persistence.ConfigPersistenceManager; -import org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerFactory; -import org.wso2.carbon.identity.entitlement.persistence.PolicyPersistenceManager; -import org.wso2.carbon.identity.entitlement.persistence.SubscriberPersistenceManager; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; -import org.wso2.carbon.identity.entitlement.pap.store.PAPPolicyStoreManager; -import org.wso2.carbon.identity.entitlement.policy.publisher.PolicyPublisher; -import org.wso2.carbon.identity.entitlement.policy.store.DefaultPolicyDataStore; -import org.wso2.carbon.identity.entitlement.policy.store.PolicyDataStore; -import org.wso2.carbon.identity.entitlement.policy.store.PolicyStoreManageModule; -import org.wso2.carbon.identity.entitlement.policy.store.PolicyStoreManager; - -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -/** - * - */ -public class EntitlementAdminEngine { - - private static final Object lock = new Object(); - private static ConcurrentHashMap entitlementAdminEngines = - new ConcurrentHashMap(); - private static Log log = LogFactory.getLog(EntitlementAdminEngine.class); - private PolicyPublisher policyPublisher; - private EntitlementDataFinder entitlementDataFinder; - private PolicyDataStore policyDataStore; - private PolicyStoreManager policyStoreManager; - private PAPPolicyStoreManager papPolicyStoreManager; - private Set papStatusDataHandlers; - private ConfigPersistenceManager configPersistenceManager; - private PolicyPersistenceManager policyPersistenceManager; - private SubscriberPersistenceManager subscriberPersistenceManager; - - public EntitlementAdminEngine() { - - this.entitlementDataFinder = new EntitlementDataFinder(); - this.policyPublisher = new PolicyPublisher(); - this.papPolicyStoreManager = new PAPPolicyStoreManager(); - - Map policyCollections = EntitlementServiceComponent. - getEntitlementConfig().getPolicyStore(); - Properties policyStoreProperties = new Properties(); - if (MapUtils.isNotEmpty(policyCollections)) { - policyStoreProperties = policyCollections.entrySet().iterator().next().getValue(); - } - Map dataStoreModules = EntitlementServiceComponent. - getEntitlementConfig().getPolicyDataStore(); - if (MapUtils.isNotEmpty(dataStoreModules)) { - this.policyDataStore = dataStoreModules.entrySet().iterator().next().getKey(); - } else { - this.policyDataStore = new DefaultPolicyDataStore(); - } - try { - this.policyDataStore.init(policyStoreProperties); - } catch (EntitlementException e) { - log.warn("Error occurred while initializing the policy data store", e); - } - - Map statusDataHandlers = EntitlementServiceComponent. - getEntitlementConfig().getPapStatusDataHandlers(); - papStatusDataHandlers = statusDataHandlers.keySet(); - this.policyPublisher.setPapStatusDataHandlers(papStatusDataHandlers); - this.policyStoreManager = new PolicyStoreManager(policyDataStore); - this.configPersistenceManager = PersistenceManagerFactory.getConfigPersistenceManager(); - this.policyPersistenceManager = PersistenceManagerFactory.getPolicyPersistenceManager(); - this.subscriberPersistenceManager = PersistenceManagerFactory.getSubscriberPersistenceManager(); - - } - - /** - * Get a EntitlementEngine instance for that tenant. This method will return an - * EntitlementEngine instance if exists, or creates a new one - * - * @return EntitlementEngine instance for that tenant - */ - public static EntitlementAdminEngine getInstance() { - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - if (!entitlementAdminEngines.containsKey(Integer.toString(tenantId))) { - synchronized (lock) { - if (!entitlementAdminEngines.containsKey(Integer.toString(tenantId))) { - entitlementAdminEngines.put(Integer.toString(tenantId), new EntitlementAdminEngine()); - } - } - } - return entitlementAdminEngines.get(Integer.toString(tenantId)); - } - - /** - * This method returns policy publisher - * - * @return PolicyPublisher - */ - public PolicyPublisher getPolicyPublisher() { - return policyPublisher; - } - - /** - * This method returns the entitlement data finder - * - * @return EntitlementDataFinder - */ - public EntitlementDataFinder getEntitlementDataFinder() { - return entitlementDataFinder; - } - - /** - * @return PolicyDataStore. - */ - public PolicyDataStore getPolicyDataStore() { - - return policyDataStore; - } - - /** - * This returns policy store manager - * - * @return - */ - public PolicyStoreManager getPolicyStoreManager() { - return policyStoreManager; - } - - /** - * @return - */ - public PAPPolicyStoreManager getPapPolicyStoreManager() { - return papPolicyStoreManager; - } - - public Set getPapStatusDataHandlers() { - return papStatusDataHandlers; - } - - public ConfigPersistenceManager getConfigPersistenceManager() { return configPersistenceManager; } - - public PolicyPersistenceManager getPolicyPersistenceManager() { return policyPersistenceManager; } - - public SubscriberPersistenceManager getSubscriberPersistenceManager() { return subscriberPersistenceManager; } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pap/EntitlementDataFinder.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pap/EntitlementDataFinder.java deleted file mode 100644 index 3e87416890d1..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pap/EntitlementDataFinder.java +++ /dev/null @@ -1,120 +0,0 @@ -/* -* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.pap; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.identity.entitlement.dto.EntitlementFinderDataHolder; -import org.wso2.carbon.identity.entitlement.dto.EntitlementTreeNodeDTO; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -/** - * When creating XACML policies from WSO2 Identity server, We can define set of pre-defined attribute - * values, attribute ids, function and so on. These data can be retrieved from external sources such as - * databases, LDAPs, or file systems. we can register, set of data retriever modules with this class. - */ -public class EntitlementDataFinder { - - private static Log log = LogFactory.getLog(EntitlementDataFinder.class); - - /** - * List of entitlement data finder modules - */ - Set dataFinderModules = new HashSet(); - - /** - * tenant id - */ - int tenantId; - - public EntitlementDataFinder() { - - this.tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - Map metaDataFinderConfigs = EntitlementServiceComponent. - getEntitlementConfig().getPolicyEntitlementDataFinders(); - // only one module can be there. - if (metaDataFinderConfigs != null && !metaDataFinderConfigs.isEmpty()) { - dataFinderModules = metaDataFinderConfigs.keySet(); - } - } - - public EntitlementFinderDataHolder[] getEntitlementDataModules() { - - List dataHolders = new ArrayList(); - - for (EntitlementDataFinderModule module : dataFinderModules) { - EntitlementFinderDataHolder holder = new EntitlementFinderDataHolder(); - - String name = module.getModuleName(); - if (name == null || name.trim().length() == 0) { - name = module.getClass().getName(); - } - - Set applicationIds = module.getRelatedApplications(); - if (applicationIds == null) { - applicationIds = new HashSet(); - } - - Set supportedCategories = module.getSupportedCategories(); - if (supportedCategories == null) { - supportedCategories = new HashSet(); - } - - holder.setName(name); - holder.setApplicationIds(applicationIds.toArray(new String[applicationIds.size()])); - holder.setFullPathSupported(module.isFullPathSupported()); - holder.setHierarchicalLevels(module.getSupportedHierarchicalLevels()); - holder.setHierarchicalTree(module.isHierarchicalTree()); - holder.setAllApplicationRelated(module.isAllApplicationRelated()); - holder.setSupportedCategory(supportedCategories.toArray(new String[supportedCategories.size()])); - holder.setSearchSupported(module.isSearchSupported()); - dataHolders.add(holder); - } - - return dataHolders.toArray(new EntitlementFinderDataHolder[dataHolders.size()]); - } - - public EntitlementTreeNodeDTO getEntitlementData(String dataModule, String category, - String regex, int level, int limit) { - - for (EntitlementDataFinderModule module : dataFinderModules) { - if (dataModule != null && dataModule.trim().equalsIgnoreCase(module.getModuleName())) { - try { - if (level == 0) { - return module.getEntitlementData(category, regex, limit); - } else { - return module.getEntitlementDataByLevel(category, level); - } - } catch (Exception e) { - log.error("Error while retrieving entitlement data by " + dataModule, e); - } - } - } - - return new EntitlementTreeNodeDTO(); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pap/EntitlementDataFinderModule.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pap/EntitlementDataFinderModule.java deleted file mode 100644 index 30a575f2d9f6..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pap/EntitlementDataFinderModule.java +++ /dev/null @@ -1,131 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.pap; - -import org.wso2.carbon.identity.entitlement.dto.EntitlementTreeNodeDTO; - -import java.util.Properties; -import java.util.Set; - -/** - * When entitlement rules are created from WSO2 Identity Server, It can be defined pre-defined - * entitlement data that can be used for creating rules. These entitlement data are related with - * an external application. Same entitlement data can be used for more than one application. - * This interface supports to retrieve data from external sources such as - * databases, LDAPs,or file systems. - */ -public interface EntitlementDataFinderModule { - - /** - * Initializes data retriever module - * - * @param properties properties, that need to initialize the module. These properties can be - * defined in entitlement.properties file - * @throws Exception throws when initialization is failed - */ - public void init(Properties properties) throws Exception; - - /** - * Gets name of this module - * - * @return name as String - */ - public String getModuleName(); - - /** - * Returns application names that are related with entitlement data that is retrieved by this - * module - * - * @return Set of related applications - */ - public Set getRelatedApplications(); - - - /** - * Returns categories that are supported with entitlement data that is retrieved by this - * module - * - * @return Set of related applications - */ - public Set getSupportedCategories(); - - /** - * Finds entitlement data values for given category type - * - * @param category category of the entitlement data. - * @param regex regex values for filter out the return data - * @param limit limit for filtered data - * @return Set of entitlement data values that has been encapsulated - * in to EntitlementTreeNodeDTO - * @throws Exception throws, if fails - */ - public EntitlementTreeNodeDTO getEntitlementData(String category, String regex, - int limit) throws Exception; - - /** - * Finds entitlement data values for given category and for given hierarchical level - * - * @param category category of the entitlement data. - * @param level hierarchical level that data must be retrieved. If root level, value must be 1 - * @return Set of entitlement data values that has been encapsulated - * in to EntitlementTreeNodeDTO - * @throws Exception throws, if fails - */ - public EntitlementTreeNodeDTO getEntitlementDataByLevel(String category, int level) throws Exception; - - /** - * Returns supported hierarchical levels of that data must be retrieved. If levels are not supported - * value must be zero - * - * @return number of levels - */ - public int getSupportedHierarchicalLevels(); - - /** - * Defines whether node EntitlementTreeNodeDTO is defined by child node name - * or by full path name with parent node names - * - * @return true or false - */ - public boolean isFullPathSupported(); - - /** - * Defines whether tree nodes of EntitlementTreeNodeDTO elements are shown - * in UI by as a tree or flat structure - * - * @return if as a tree -> true or else -> false - */ - public boolean isHierarchicalTree(); - - - /** - * Defines whether we can search the tree nodes of EntitlementTreeNodeDTO elements - * using regexp expressions - * - * @return if as a tree -> true or else -> false - */ - public boolean isSearchSupported(); - - /** - * Defines whether entitlement data that is retrieved by this module, - * is related with all applications - * - * @return true or false - */ - public boolean isAllApplicationRelated(); -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pap/PAPPolicyReader.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pap/PAPPolicyReader.java deleted file mode 100644 index 99109d93a587..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pap/PAPPolicyReader.java +++ /dev/null @@ -1,206 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.pap; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.wso2.balana.AbstractPolicy; -import org.wso2.balana.ParsingException; -import org.wso2.balana.Policy; -import org.wso2.balana.PolicySet; -import org.wso2.balana.finder.PolicyFinder; -import org.wso2.carbon.identity.core.util.IdentityUtil; -import org.wso2.carbon.identity.entitlement.policy.PolicyTarget; -import org.xml.sax.ErrorHandler; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import java.io.ByteArrayInputStream; -import java.io.InputStream; - -/** - * - */ -public class PAPPolicyReader implements ErrorHandler { - - // the standard attribute for specifying the XML schema language - private static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage"; - - // the standard identifier for the XML schema specification - private static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema"; - - // the standard attribute for specifying schema source - private static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource"; - // To enable attempted thread-safety using double-check locking - private static final Object lock = new Object(); - private static Log log = LogFactory.getLog(PAPPolicyReader.class); - private static volatile PAPPolicyReader reader; - // the builder used to create DOM documents - private DocumentBuilder builder; - - // policy finder module to find policies - private PolicyFinder policyFinder; - - private PAPPolicyReader(PolicyFinder policyFinder) { - - this.policyFinder = policyFinder; - - // create the factory - DocumentBuilderFactory documentBuilderFactory = IdentityUtil.getSecuredDocumentBuilderFactory(); - documentBuilderFactory.setIgnoringComments(true); - - // now use the factory to create the document builder - try { - builder = documentBuilderFactory.newDocumentBuilder(); - builder.setErrorHandler(this); - } catch (ParserConfigurationException pce) { - throw new IllegalArgumentException("Failed to create the DocumentBuilder. : ", pce); - } - } - - /** - * @param policyFinder - * @return - */ - public static PAPPolicyReader getInstance(PolicyFinder policyFinder) { - if (reader == null) { - synchronized (lock) { - if (reader == null) { - reader = new PAPPolicyReader(policyFinder); - } - } - } - return reader; - } - - /** - * @param policy - * @return - */ - public boolean isValidPolicy(String policy) { - InputStream stream = null; - try { - stream = new ByteArrayInputStream(policy.getBytes("UTF-8")); - handleDocument(builder.parse(stream)); - } catch (Exception e) { - return false; - } - return true; - } - - /** - * @param policy - * @return - */ - public synchronized AbstractPolicy getPolicy(String policy) { - InputStream stream = null; - try { - stream = new ByteArrayInputStream(policy.getBytes("UTF-8")); - return handleDocument(builder.parse(stream)); - } catch (Exception e) { - log.error("Error while parsing the policy", e); - return null; - } - } - - /** - * Reads policy target from the policy - * - * @param policy policy as a String - * @return target as PolicyTarget object - */ - public PolicyTarget getTarget(String policy) { - InputStream stream = null; - PolicyTarget policyTarget = new PolicyTarget(); - try { - stream = new ByteArrayInputStream(policy.getBytes("UTF-8")); - AbstractPolicy abstractPolicy = handleDocument(builder.parse(stream)); - policyTarget.setTarget(abstractPolicy.getTarget()); - policyTarget.setPolicyId(abstractPolicy.getId().toString()); - return policyTarget; - } catch (Exception e) { - log.error("Error while parsing the policy", e); - return null; - } - } - - /** - * @param doc - * @return - * @throws org.wso2.balana.ParsingException - */ - private AbstractPolicy handleDocument(Document doc) throws ParsingException { - // handle the policy, if it's a known type - Element root = doc.getDocumentElement(); - String name = root.getLocalName(); - // see what type of policy this is - if (name.equals("Policy")) { - return Policy.getInstance(root); - } else if (name.equals("PolicySet")) { - return PolicySet.getInstance(root, policyFinder); - } else { - // this isn't a root type that we know how to handle - throw new ParsingException("Unknown root document type: " + name); - } - } - - /** - * {@inheritDoc} - */ - public void warning(SAXParseException exception) throws SAXException { - if (log.isWarnEnabled()) { - String message = null; - message = "Warning on line " + exception.getLineNumber() + ": " - + exception.getMessage(); - log.warn(message); - } - } - - /** - * {@inheritDoc} - */ - public void error(SAXParseException exception) throws SAXException { - if (log.isWarnEnabled()) { - log.warn("Error on line " + exception.getLineNumber() + ": " + exception.getMessage() - + " ... " + "Policy will not be available"); - } - - throw new SAXException("error parsing policy"); - } - - /** - * {@inheritDoc} - */ - public void fatalError(SAXParseException exception) throws SAXException { - if (log.isWarnEnabled()) { - log.warn("Fatal error on line " + exception.getLineNumber() + ": " - + exception.getMessage() + " ... " + "Policy will not be available"); - } - - throw new SAXException("fatal error parsing policy"); - } - - public PolicyFinder getPolicyFinder() { - return policyFinder; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pap/store/PAPPolicyFinder.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pap/store/PAPPolicyFinder.java deleted file mode 100644 index d182150a04df..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pap/store/PAPPolicyFinder.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.entitlement.pap.store; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.balana.AbstractPolicy; -import org.wso2.balana.MatchResult; -import org.wso2.balana.Policy; -import org.wso2.balana.PolicyMetaData; -import org.wso2.balana.PolicyReference; -import org.wso2.balana.PolicySet; -import org.wso2.balana.VersionConstraints; -import org.wso2.balana.combine.PolicyCombiningAlgorithm; -import org.wso2.balana.combine.xacml2.OnlyOneApplicablePolicyAlg; -import org.wso2.balana.ctx.EvaluationCtx; -import org.wso2.balana.ctx.Status; -import org.wso2.balana.finder.PolicyFinder; -import org.wso2.balana.finder.PolicyFinderModule; -import org.wso2.balana.finder.PolicyFinderResult; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.dto.PolicyDTO; -import org.wso2.carbon.identity.entitlement.policy.collection.DefaultPolicyCollection; - -import java.net.URI; -import java.util.ArrayList; -import java.util.List; - -public class PAPPolicyFinder extends PolicyFinderModule { - - // the logger we'll use for all messages - private static final Log log = LogFactory.getLog(PAPPolicyFinder.class); - // the list of policy URLs passed to the constructor - private PAPPolicyStoreReader policyReader; - // the map of policies - private DefaultPolicyCollection policies; - //keeps policy ids according to the order - private List policyIds; - private PolicyFinder policyFinder; - // only five policies are allowed - private int maxInMemoryPolicies = 5; - - /** - * Creates a PAPPolicyFinder that provides access to the given collection of policies. - * Any policy that cannot be loaded will be noted in the log, but will not cause an error. The - * schema file used to validate policies is defined by the property - * PolicyRepository.POLICY_SCHEMA_PROPERTY. If the retrieved property is null, then no schema - * validation will occur. - * - * @param policyReader Policy store repository for Registry - */ - public PAPPolicyFinder(PAPPolicyStoreReader policyReader) { - this.policyReader = policyReader; - } - - /** - * Always returns true since this module does support finding policies based on - * reference. - * - * @return true - */ - public boolean isIdReferenceSupported() { - return true; - } - - /* - * (non-Javadoc) - * - * @see org.wso2.balana.finder.PolicyFinderModule#isRequestSupported() - */ - public boolean isRequestSupported() { - return true; - } - - /* - * (non-Javadoc) - * - * @see org.wso2.balana.finder.PolicyFinderModule#init(org.wso2.balana.finder.CarbonPolicyFinder) - */ - public void init(PolicyFinder finder) { - - PolicyCombiningAlgorithm algorithm; - this.policyFinder = finder; - - try { - // for PAP policy store, Global policy combining algorithm is not needed. As we are - // only evaluating one policy therefore using default algorithm. - algorithm = new OnlyOneApplicablePolicyAlg(); - initPolicyIds(); - this.policies = new DefaultPolicyCollection(algorithm, 0); - } catch (EntitlementException e) { - log.error("Error while initializing PAPPolicyFinder", e); - } - } - - /* - * (non-Javadoc) - * - * @see org.wso2.balana.finder.PolicyFinderModule#findPolicy(java.net.URI, int, - * org.wso2.balana.VersionConstraints, org.wso2.balana.PolicyMetaData) - */ - public PolicyFinderResult findPolicy(URI idReference, int type, VersionConstraints constraints, - PolicyMetaData parentMetaData) { - - // clear all current policies - policies.getPolicies().clear(); - - AbstractPolicy policy = null; - - try { - AbstractPolicy policyFromStore = policyReader.readPolicy(idReference.toString(), - this.policyFinder); - - if (policyFromStore != null) { - if (type == PolicyReference.POLICY_REFERENCE) { - if (policyFromStore instanceof Policy) { - policy = policyFromStore; - policies.addPolicy(policy); - } - } else { - if (policyFromStore instanceof PolicySet) { - policy = policyFromStore; - policies.addPolicy(policy); - } - } - } - } catch (EntitlementException e) { - // ignore and just log the error. - log.error(e); - } - - if (policy == null) { - return new PolicyFinderResult(); - } else { - return new PolicyFinderResult(policy); - } - } - - /* - * (non-Javadoc) - * - * @see org.wso2.balana.finder.PolicyFinderModule#findPolicy(org.wso2.balana.EvaluationCtx) - */ - public PolicyFinderResult findPolicy(EvaluationCtx context) { - - // clear all current policies - policies.getPolicies().clear(); - - ArrayList list = new ArrayList(); - - try { - for (String policyId : policyIds) { - - if (list.size() == maxInMemoryPolicies) { - break; - } - AbstractPolicy policy = null; - - try { - policy = policyReader.readPolicy(policyId, this.policyFinder); - } catch (EntitlementException e) { - //log and ignore - log.error(e); - } - if (policy == null) { - continue; - } else { - policies.addPolicy(policy); - } - // see if we match - MatchResult match = policy.match(context); - int result = match.getResult(); - - // if there was an error, we stop right away - if (result == MatchResult.INDETERMINATE) { - log.error(match.getStatus().getMessage()); - throw new EntitlementException(match.getStatus().getMessage()); - } - - // if we matched, we keep track of the matching policy... - if (result == MatchResult.MATCH) { - if (log.isDebugEnabled()) { - log.debug("Matching XACML policy found " + policy.getId().toString()); - } - list.add(policy); - } - } - - AbstractPolicy policy = policies.getEffectivePolicy(list); - if (policy == null) { - return new PolicyFinderResult(); - } else { - return new PolicyFinderResult(policy); - } - } catch (EntitlementException e) { - ArrayList code = new ArrayList(); - code.add(Status.STATUS_PROCESSING_ERROR); - Status status = new Status(code, e.getMessage()); - return new PolicyFinderResult(status); - } - } - - - /** - * Sets polices ids that is evaluated - * - * @param policyIds - */ - public void setPolicyIds(List policyIds) { - this.policyIds = policyIds; - } - - public void initPolicyIds() throws EntitlementException { - this.policyIds = new ArrayList(); - PolicyDTO[] policyDTOs = policyReader.readAllLightPolicyDTOs(); - for (PolicyDTO dto : policyDTOs) { - if (dto.isActive()) { - policyIds.add(dto.getPolicyId()); - } - } - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pap/store/PAPPolicyStoreManager.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pap/store/PAPPolicyStoreManager.java deleted file mode 100644 index 65baa30d327b..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pap/store/PAPPolicyStoreManager.java +++ /dev/null @@ -1,81 +0,0 @@ -/* -* Copyright (c) 2005-2024, WSO2 LLC (https://www.wso2.com) All Rights Reserved. -* -* WSO2 LLC 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.wso2.carbon.identity.entitlement.pap.store; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerFactory; -import org.wso2.carbon.identity.entitlement.persistence.PolicyPersistenceManager; -import org.wso2.carbon.identity.entitlement.dto.PolicyDTO; -import org.wso2.carbon.registry.core.Resource; - -public class PAPPolicyStoreManager { - - private static final Log log = LogFactory.getLog(PAPPolicyStoreManager.class); - private PolicyPersistenceManager store; - private PAPPolicyStoreReader storeReader; - - public PAPPolicyStoreManager() { - store = PersistenceManagerFactory.getPolicyPersistenceManager(); - storeReader = new PAPPolicyStoreReader(store); - } - - public void addOrUpdatePolicy(PolicyDTO policy, boolean enableVersioning) throws EntitlementException { - store.addOrUpdatePolicy(policy, enableVersioning); - } - - public void removePolicy(String policyId) throws EntitlementException { - store.removePolicy(policyId); - } - - public String[] getPolicyIds() throws EntitlementException { - return store.listPolicyIds().toArray(new String[0]); - } - - public PolicyDTO getPolicy(String policyId) throws EntitlementException { - return storeReader.readPolicyDTO(policyId); - } - - public boolean isExistPolicy(String policyId) { - return storeReader.isExistPolicy(policyId); - } - - public PolicyDTO getLightPolicy(String policyId) throws EntitlementException { - return storeReader.readLightPolicyDTO(policyId); - } - - public PolicyDTO getMetaDataPolicy(String policyId) throws EntitlementException { - return storeReader.readMetaDataPolicyDTO(policyId); - } - - /** - * @param resource resource - * @return policy - * @throws EntitlementException throws, if fails - * @deprecated use {@link #getPolicy(String)} instead - */ - @Deprecated - public PolicyDTO getPolicy(Resource resource) throws EntitlementException { - return storeReader.readPolicyDTO(resource); - } - - public PolicyDTO[] getAllLightPolicyDTOs() throws EntitlementException { - return storeReader.readAllLightPolicyDTOs(); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pap/store/PAPPolicyStoreReader.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pap/store/PAPPolicyStoreReader.java deleted file mode 100644 index 798b04e9dacd..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pap/store/PAPPolicyStoreReader.java +++ /dev/null @@ -1,238 +0,0 @@ -/* - * Copyright (c) 2005-2024, WSO2 LLC (https://www.wso2.com) All Rights Reserved. - * - * WSO2 LLC 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.wso2.carbon.identity.entitlement.pap.store; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.balana.AbstractPolicy; -import org.wso2.balana.finder.PolicyFinder; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.PDPConstants; -import org.wso2.carbon.identity.entitlement.persistence.PolicyPersistenceManager; -import org.wso2.carbon.identity.entitlement.dto.AttributeDTO; -import org.wso2.carbon.identity.entitlement.dto.PolicyDTO; -import org.wso2.carbon.identity.entitlement.pap.PAPPolicyReader; -import org.wso2.carbon.identity.entitlement.policy.PolicyAttributeBuilder; -import org.wso2.carbon.registry.core.Resource; -import org.wso2.carbon.registry.core.exceptions.RegistryException; - -import java.nio.charset.Charset; -import java.util.List; - -public class PAPPolicyStoreReader { - - // the optional logger used for error reporting - private static Log log = LogFactory.getLog(PAPPolicyStoreReader.class); - - private final PolicyPersistenceManager store; - - /** - * @param store - */ - public PAPPolicyStoreReader(PolicyPersistenceManager store) { - this.store = store; - } - - /** - * @param policyId policyId - * @param finder policy finder - * @return abstract policy - * @throws EntitlementException, throws, if fails - */ - public synchronized AbstractPolicy readPolicy(String policyId, PolicyFinder finder) - throws EntitlementException { - - PolicyDTO dto = store.getPAPPolicy(policyId); - if (dto != null) { - String policy = dto.getPolicy(); - return PAPPolicyReader.getInstance(null).getPolicy(policy); - } - return null; - } - - /** - * Reads All policies as Light Weight PolicyDTO - * - * @return Array of PolicyDTO but does not contain XACML policy and attribute metadata - * @throws EntitlementException throws, if fails - */ - public PolicyDTO[] readAllLightPolicyDTOs() throws EntitlementException { - - List policyIds = store.listPolicyIds(); - - List policyDTOList = store.getPAPPolicies(policyIds); - policyDTOList.forEach(this::getLightPolicyDTO); - return policyDTOList.toArray(new PolicyDTO[0]); - } - - /** - * Reads PolicyDTO for given policy id - * - * @param policyId policy id - * @return PolicyDTO - * @throws EntitlementException throws, if fails - */ - public PolicyDTO readPolicyDTO(String policyId) throws EntitlementException { - - PolicyDTO dto = store.getPAPPolicy(policyId); - if (dto == null) { - log.error("Policy does not exist in the system with id " + policyId); - throw new EntitlementException("Policy does not exist in the system with id " + policyId); - } - return dto; - } - - /** - * Checks whether policy exists for the given policy id - * - * @param policyId policy id - * @return true of false - */ - public boolean isExistPolicy(String policyId) { - - PolicyDTO dto; - try { - dto = store.getPAPPolicy(policyId); - if (dto != null) { - return true; - } - } catch (EntitlementException e) { - //ignore - } - return false; - } - - - /** - * Reads light weight PolicyDTO for given policy id - * - * @param policyId policy id - * @return PolicyDTO but does not contain XACML policy and attribute meta data - * @throws EntitlementException throws, if fails - */ - public PolicyDTO readLightPolicyDTO(String policyId) throws EntitlementException { - - PolicyDTO dto = store.getPAPPolicy(policyId); - return getLightPolicyDTO(dto); - } - - - /** - * Reads Light Weight PolicyDTO with Attribute metadata for given policy id - * - * @param policyId policy id - * @return PolicyDTO but don not contains XACML policy - * @throws EntitlementException throws, if fails - */ - public PolicyDTO readMetaDataPolicyDTO(String policyId) throws EntitlementException { - - PolicyDTO dto = store.getPAPPolicy(policyId); - if (dto == null) { - return null; - } - dto.setPolicy(null); - return dto; - } - - /** - * Reads PolicyDTO for given registry resource - * - * @param resource Registry resource - * @return PolicyDTO - * @throws EntitlementException throws, if fails - * @deprecated use {@link #readPolicyDTO(String)} instead - */ - @Deprecated - public PolicyDTO readPolicyDTO(Resource resource) throws EntitlementException { - - String policy = null; - String policyId = null; - AbstractPolicy absPolicy = null; - PolicyDTO dto = null; - try { - policy = new String((byte[]) resource.getContent(), Charset.forName("UTF-8")); - absPolicy = PAPPolicyReader.getInstance(null).getPolicy(policy); - policyId = absPolicy.getId().toASCIIString(); - dto = new PolicyDTO(); - dto.setPolicyId(policyId); - dto.setPolicy(policy); - dto.setActive(Boolean.parseBoolean(resource.getProperty(PDPConstants.ACTIVE_POLICY))); - String policyOrder = resource.getProperty(PDPConstants.POLICY_ORDER); - if (policyOrder != null) { - dto.setPolicyOrder(Integer.parseInt(policyOrder)); - } else { - dto.setPolicyOrder(0); - } - String version = resource.getProperty(PDPConstants.POLICY_VERSION); - if (version != null) { - dto.setVersion(version); - } - String lastModifiedTime = resource.getProperty(PDPConstants.LAST_MODIFIED_TIME); - if (lastModifiedTime != null) { - dto.setLastModifiedTime(lastModifiedTime); - } - String lastModifiedUser = resource.getProperty(PDPConstants.LAST_MODIFIED_USER); - if (lastModifiedUser != null) { - dto.setLastModifiedUser(lastModifiedUser); - } - dto.setPolicyType(resource.getProperty(PDPConstants.POLICY_TYPE)); - String policyReferences = resource.getProperty(PDPConstants.POLICY_REFERENCE); - if (policyReferences != null && policyReferences.trim().length() > 0) { - dto.setPolicyIdReferences(policyReferences.split(PDPConstants.ATTRIBUTE_SEPARATOR)); - } - - String policySetReferences = resource.getProperty(PDPConstants.POLICY_SET_REFERENCE); - if (policySetReferences != null && policySetReferences.trim().length() > 0) { - dto.setPolicySetIdReferences(policySetReferences.split(PDPConstants.ATTRIBUTE_SEPARATOR)); - } - - //read policy meta data that is used for basic policy editor - dto.setPolicyEditor(resource.getProperty(PDPConstants.POLICY_EDITOR_TYPE)); - String basicPolicyEditorMetaDataAmount = resource.getProperty(PDPConstants. - BASIC_POLICY_EDITOR_META_DATA_AMOUNT); - if (basicPolicyEditorMetaDataAmount != null) { - int amount = Integer.parseInt(basicPolicyEditorMetaDataAmount); - String[] basicPolicyEditorMetaData = new String[amount]; - for (int i = 0; i < amount; i++) { - basicPolicyEditorMetaData[i] = resource. - getProperty(PDPConstants.BASIC_POLICY_EDITOR_META_DATA + i); - } - dto.setPolicyEditorData(basicPolicyEditorMetaData); - } - PolicyAttributeBuilder policyAttributeBuilder = new PolicyAttributeBuilder(); - dto.setAttributeDTOs(policyAttributeBuilder. - getPolicyMetaDataFromRegistryProperties(resource.getProperties())); - return dto; - } catch (RegistryException e) { - log.error("Error while loading entitlement policy " + policyId + " from PAP policy store", e); - throw new EntitlementException("Error while loading entitlement policy " + policyId + - " from PAP policy store"); - } - } - - private PolicyDTO getLightPolicyDTO(PolicyDTO dto) { - - if (dto != null) { - dto.setPolicy(null); - dto.setAttributeDTOs(new AttributeDTO[0]); - dto.setPolicyEditorData(new String[0]); - return dto; - } - return null; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pdp/EntitlementEngine.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pdp/EntitlementEngine.java deleted file mode 100644 index 7f640ec3bda8..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pdp/EntitlementEngine.java +++ /dev/null @@ -1,707 +0,0 @@ -/* - * Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.entitlement.pdp; - -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.CacheLoader; -import com.google.common.cache.LoadingCache; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.w3c.dom.Element; -import org.wso2.balana.Balana; -import org.wso2.balana.PDP; -import org.wso2.balana.PDPConfig; -import org.wso2.balana.ParsingException; -import org.wso2.balana.ctx.AbstractRequestCtx; -import org.wso2.balana.ctx.RequestCtxFactory; -import org.wso2.balana.ctx.ResponseCtx; -import org.wso2.balana.finder.AttributeFinder; -import org.wso2.balana.finder.AttributeFinderModule; -import org.wso2.balana.finder.PolicyFinder; -import org.wso2.balana.finder.PolicyFinderModule; -import org.wso2.balana.finder.ResourceFinder; -import org.wso2.balana.finder.ResourceFinderModule; -import org.wso2.balana.finder.impl.CurrentEnvModule; -import org.wso2.balana.finder.impl.SelectorModule; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.identity.base.IdentityConstants; -import org.wso2.carbon.identity.core.util.IdentityUtil; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.EntitlementUtil; -import org.wso2.carbon.identity.entitlement.PDPConstants; -import org.wso2.carbon.identity.entitlement.cache.DecisionCache; -import org.wso2.carbon.identity.entitlement.cache.PolicyCache; -import org.wso2.carbon.identity.entitlement.cache.SimpleDecisionCache; -import org.wso2.carbon.identity.entitlement.persistence.PolicyPersistenceManager; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; -import org.wso2.carbon.identity.entitlement.pap.EntitlementAdminEngine; -import org.wso2.carbon.identity.entitlement.pap.store.PAPPolicyFinder; -import org.wso2.carbon.identity.entitlement.pap.store.PAPPolicyStoreReader; -import org.wso2.carbon.identity.entitlement.pip.CarbonAttributeFinder; -import org.wso2.carbon.identity.entitlement.pip.CarbonResourceFinder; -import org.wso2.carbon.identity.entitlement.pip.PIPExtension; -import org.wso2.carbon.identity.entitlement.policy.PolicyRequestBuilder; -import org.wso2.carbon.identity.entitlement.policy.finder.CarbonPolicyFinder; -import org.wso2.carbon.identity.entitlement.policy.search.PolicySearch; -import org.wso2.carbon.utils.multitenancy.MultitenantConstants; -import org.xml.sax.SAXException; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - -public class EntitlementEngine { - - private PolicyFinder papPolicyFinder; - private CarbonAttributeFinder carbonAttributeFinder; - private CarbonResourceFinder carbonResourceFinder; - private PolicyFinder carbonPolicyFinder; - private PolicySearch policySearch; - private PDP pdp; - private PDP pdpTest; - private Balana balana; - private int tenantId; - private static final Object lock = new Object(); - private boolean pdpDecisionCacheEnable; - private List attributeModules = new ArrayList(); - private List resourceModules = new ArrayList(); - private static EntitlementEngine entitlementEngine; - private static final long DEFAULT_ENTITLEMENT_ENGINE_CACHING_INTERVAL = 900; - private static LoadingCache entitlementEngineLoadingCache; - - private DecisionCache decisionCache = null; - private PolicyCache policyCache = null; - - private SimpleDecisionCache simpleDecisionCache = null; - - private static final Log log = LogFactory.getLog(EntitlementEngine.class); - - public PolicyCache getPolicyCache() { - return policyCache; - } - - public void clearDecisionCache() { - this.decisionCache.clear(); - this.simpleDecisionCache.clear(); - } - - /** - * Get a EntitlementEngine instance for that tenant. This method will return an - * EntitlementEngine instance if exists, or creates a new one - * - * @return EntitlementEngine instance for that tenant - */ - public static EntitlementEngine getInstance() { - - Integer tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - if (tenantId == MultitenantConstants.SUPER_TENANT_ID) { - if (entitlementEngine == null) { - synchronized (lock) { - if (entitlementEngine == null) { - entitlementEngine = new EntitlementEngine(tenantId); - } - } - } - return entitlementEngine; - } - if (entitlementEngineLoadingCache == null) { - synchronized (lock) { - if (entitlementEngineLoadingCache == null) { - entitlementEngineLoadingCache = CacheBuilder.newBuilder().weakValues().expireAfterAccess - (getCacheInterval(), TimeUnit.SECONDS) - .build(new CacheLoader() { - @Override - public EntitlementEngine load(Integer key) { - - return new EntitlementEngine(key); - } - }); - } - } - } - - EntitlementEngine entitleEngine = entitlementEngineLoadingCache.getIfPresent(tenantId); - if (entitleEngine == null) { - synchronized (lock) { - entitleEngine = entitlementEngineLoadingCache.getIfPresent(tenantId); - if (entitleEngine == null) { - entitlementEngineLoadingCache.put(tenantId, new EntitlementEngine(tenantId)); - } - } - } - try { - entitleEngine = entitlementEngineLoadingCache.get(tenantId); - } catch (ExecutionException e) { - log.error("Error while getting the entitle engine for the tenant : " + tenantId); - } - return entitleEngine; - } - - private static long getCacheInterval() { - - Properties properties = EntitlementServiceComponent.getEntitlementConfig().getEngineProperties(); - String engineCachingInterval = properties.getProperty(PDPConstants - .ENTITLEMENT_ENGINE_CACHING_INTERVAL); - long entitlementEngineCachingInterval = DEFAULT_ENTITLEMENT_ENGINE_CACHING_INTERVAL; - if (engineCachingInterval != null) { - try { - entitlementEngineCachingInterval = Long.parseLong(engineCachingInterval); - } catch (NumberFormatException e) { - log.warn("Invalid value for " + PDPConstants.ENTITLEMENT_ENGINE_CACHING_INTERVAL + ". Using " + - "default value " + entitlementEngineCachingInterval + " seconds."); - } - } else { - if (log.isDebugEnabled()) { - log.debug(PDPConstants.ENTITLEMENT_ENGINE_CACHING_INTERVAL + " not set. Using default value " + - entitlementEngineCachingInterval + " seconds."); - } - } - return entitlementEngineCachingInterval; - } - - private EntitlementEngine(int tenantId) { - - boolean isPDP = Boolean.parseBoolean((String) EntitlementServiceComponent.getEntitlementConfig(). - getEngineProperties().get(PDPConstants.PDP_ENABLE)); - boolean isPAP = Boolean.parseBoolean((String) EntitlementServiceComponent.getEntitlementConfig(). - getEngineProperties().get(PDPConstants.PAP_ENABLE)); - - boolean pdpMultipleDecision = Boolean.parseBoolean((String) EntitlementServiceComponent. - getEntitlementConfig().getEngineProperties().get(PDPConstants.MULTIPLE_DECISION_PROFILE_ENABLE)); - - if (!isPAP && !isPDP) { - isPAP = true; - } - - // if PDP config file is not configured, then balana instance is created from default configurations - balana = Balana.getInstance(); - - setUpAttributeFinders(); - setUpResourceFinders(); - setUPPolicyFinder(); - - this.tenantId = tenantId; - - Properties properties = EntitlementServiceComponent.getEntitlementConfig().getEngineProperties(); - pdpDecisionCacheEnable = Boolean.parseBoolean(properties.getProperty(PDPConstants.DECISION_CACHING)); - - int pdpDecisionCachingInterval = -1; - if (pdpDecisionCacheEnable) { - String cacheInterval = properties.getProperty(PDPConstants.DECISION_CACHING_INTERVAL); - if (cacheInterval != null) { - try { - pdpDecisionCachingInterval = Integer.parseInt(cacheInterval.trim()); - } catch (Exception e) { - //ignore - } - } - } - - int pdpPolicyCachingInterval = -1; - String policyCacheInterval = properties.getProperty(PDPConstants.POLICY_CACHING_INTERVAL); - if (policyCacheInterval != null) { - try { - pdpPolicyCachingInterval = Integer.parseInt(policyCacheInterval.trim()); - } catch (Exception e) { - //ignore - } - } - - - //init caches - decisionCache = new DecisionCache(pdpDecisionCachingInterval); - simpleDecisionCache = new SimpleDecisionCache(pdpDecisionCachingInterval); - this.policyCache = new PolicyCache(pdpPolicyCachingInterval); - - // policy search - - policySearch = new PolicySearch(pdpDecisionCacheEnable, pdpDecisionCachingInterval); - - // Finally, initialize - if (isPAP) { - // Test PDP with all finders but policy finder is different - PolicyFinder policyFinder = new PolicyFinder(); - Set policyModules = new HashSet(); - PolicyPersistenceManager store = EntitlementAdminEngine.getInstance().getPolicyPersistenceManager(); - PAPPolicyFinder papPolicyFinder = new PAPPolicyFinder(new PAPPolicyStoreReader(store)); - policyModules.add(papPolicyFinder); - policyFinder.setModules(policyModules); - this.papPolicyFinder = policyFinder; - - AttributeFinder attributeFinder = new AttributeFinder(); - attributeFinder.setModules(attributeModules); - - ResourceFinder resourceFinder = new ResourceFinder(); - resourceFinder.setModules(resourceModules); - - PDPConfig pdpConfig = new PDPConfig(attributeFinder, policyFinder, resourceFinder, true); - pdpTest = new PDP(pdpConfig); - } - - if (isPDP) { - // Actual PDP with all finders but policy finder is different - AttributeFinder attributeFinder = new AttributeFinder(); - attributeFinder.setModules(attributeModules); - - ResourceFinder resourceFinder = new ResourceFinder(); - resourceFinder.setModules(resourceModules); - - PDPConfig pdpConfig = - new PDPConfig(attributeFinder, carbonPolicyFinder, resourceFinder, pdpMultipleDecision); - pdp = new PDP(pdpConfig); - } - } - - - /** - * Test request for PDP - * - * @param xacmlRequest XACML request as String - * @return response as String - */ - public String test(String xacmlRequest) { - - if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_REQUEST)) { - log.debug("XACML Request : " + xacmlRequest); - } - - String xacmlResponse = pdpTest.evaluate(xacmlRequest); - - if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_RESPONSE)) { - log.debug("XACML Response : " + xacmlResponse); - } - - return xacmlResponse; - } - - /** - * Evaluates the given XACML request and returns the Response that the EntitlementEngine will - * hand back to the PEP. PEP needs construct the XACML request before sending it to the - * EntitlementEngine - * - * @param xacmlRequest XACML request as String - * @return XACML response as String - * @throws org.wso2.balana.ParsingException throws - * @throws org.wso2.carbon.identity.entitlement.EntitlementException throws - */ - - public String evaluate(String xacmlRequest) throws EntitlementException, ParsingException { - - if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_REQUEST)) { - log.debug("XACML Request : " + xacmlRequest); - } - - String xacmlResponse; - - if ((xacmlResponse = (String) getFromCache(xacmlRequest, false)) != null) { - if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_RESPONSE)) { - log.debug("XACML Response : " + xacmlResponse); - } - return xacmlResponse; - } - - Map extensions = EntitlementServiceComponent.getEntitlementConfig() - .getExtensions(); - - if (extensions != null && !extensions.isEmpty()) { - PolicyRequestBuilder policyRequestBuilder = new PolicyRequestBuilder(); - Element xacmlRequestElement = policyRequestBuilder.getXacmlRequest(xacmlRequest); - AbstractRequestCtx requestCtx = RequestCtxFactory.getFactory(). - getRequestCtx(xacmlRequestElement); - Set pipExtensions = extensions.keySet(); - for (PIPExtension pipExtension : pipExtensions) { - pipExtension.update(requestCtx); - } - ResponseCtx responseCtx = pdp.evaluate(requestCtx); - xacmlResponse = responseCtx.encode(); - } else { - xacmlResponse = pdp.evaluate(xacmlRequest); - } - - addToCache(xacmlRequest, xacmlResponse, false); - - if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_RESPONSE)) { - log.debug("XACML Response : " + xacmlResponse); - } - - return xacmlResponse; - - } - - /** - * Evaluates the given XACML request and returns the ResponseCtx Response that the EntitlementEngine will - * hand back to the PEP. PEP needs construct the XACML request before sending it to the - * EntitlementEngine - * - * @param xacmlRequest XACML request as String - * @return ResponseCtx response - * @throws org.wso2.balana.ParsingException throws - * @throws org.wso2.carbon.identity.entitlement.EntitlementException throws - * @throws javax.xml.parsers.ParserConfigurationException throws - * @throws org.xml.sax.SAXException throws - * @throws java.io.IOException throws - */ - - public ResponseCtx evaluateReturnResponseCtx(String xacmlRequest) throws EntitlementException, ParsingException, - ParserConfigurationException, SAXException, IOException { - - if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_REQUEST)) { - log.debug("XACML Request : " + xacmlRequest); - } - - String xacmlResponse; - ResponseCtx responseCtx; - - if ((xacmlResponse = (String) getFromCache(xacmlRequest, false)) != null) { - if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_RESPONSE)) { - log.debug("XACML Response : " + xacmlResponse); - } - - DocumentBuilderFactory documentBuilderFactory = IdentityUtil.getSecuredDocumentBuilderFactory(); - Element node = documentBuilderFactory.newDocumentBuilder().parse - (new ByteArrayInputStream(xacmlResponse.getBytes())).getDocumentElement(); - - - return (ResponseCtx.getInstance(node)); - - } - - Map extensions = EntitlementServiceComponent.getEntitlementConfig() - .getExtensions(); - - if (extensions != null && !extensions.isEmpty()) { - PolicyRequestBuilder policyRequestBuilder = new PolicyRequestBuilder(); - Element xacmlRequestElement = policyRequestBuilder.getXacmlRequest(xacmlRequest); - AbstractRequestCtx requestCtx = RequestCtxFactory.getFactory(). - getRequestCtx(xacmlRequestElement); - Set pipExtensions = extensions.keySet(); - for (PIPExtension pipExtension : pipExtensions) { - pipExtension.update(requestCtx); - } - responseCtx = pdp.evaluate(requestCtx); - } else { - responseCtx = pdp.evaluateReturnResponseCtx(xacmlRequest); - } - - xacmlResponse = responseCtx.encode(); - - addToCache(xacmlRequest, xacmlResponse, false); - - if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_RESPONSE)) { - log.debug("XACML Response : " + xacmlResponse); - } - - return responseCtx; - - } - - /** - * Evaluates XACML request directly. This is used by advance search module. - * Therefore caching and logging has not be implemented for this - * - * @param requestCtx Balana Object model for request - * @return ResponseCtx Balana Object model for response - */ - public ResponseCtx evaluateByContext(AbstractRequestCtx requestCtx) { - return pdp.evaluate(requestCtx); - } - - /** - * Evaluates the given XACML request and returns the Response - * - * @param requestCtx Balana Object model for request - * @param xacmlRequest Balana Object model for request - * @return ResponseCtx Balana Object model for response - */ - public ResponseCtx evaluate(AbstractRequestCtx requestCtx, String xacmlRequest) { - - if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_REQUEST)) { - log.debug("XACML Request : " + xacmlRequest); - } - - ResponseCtx xacmlResponse; - - if ((xacmlResponse = (ResponseCtx) getFromCache(xacmlRequest, false)) != null) { - if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_RESPONSE)) { - log.debug("XACML Response : " + xacmlResponse); - } - return xacmlResponse; - } - - xacmlResponse = pdp.evaluate(requestCtx); - - addToCache(xacmlRequest, xacmlResponse, false); - - if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_RESPONSE)) { - log.debug("XACML Response : " + xacmlResponse); - } - return xacmlResponse; - } - - /** - * Evaluates the given XACML request and returns the Response that the EntitlementEngine will - * hand back to the PEP. Here PEP does not need construct the XACML request before sending it to the - * EntitlementEngine. Just can send the single attribute value. But here default attribute ids and data types - * are used - * - * @param subject subject - * @param resource resource - * @param action action - * @param environment environment - * @return XACML request as String object - * @throws Exception throws, if fails - */ - public String evaluate(String subject, String resource, String action, String[] environment) - throws Exception { - - String environmentValue = null; - if (environment != null && environment.length > 0) { - environmentValue = environment[0]; - } - String response; - String request = (subject != null ? subject : "") + (resource != null ? resource : "") + - (action != null ? action : "") + (environmentValue != null ? environmentValue : ""); - - if ((response = (String) getFromCache(request, true)) != null) { - if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_REQUEST)) { - log.debug("XACML Request : " + EntitlementUtil. - createSimpleXACMLRequest(subject, resource, action, environmentValue)); - } - if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_RESPONSE)) { - log.debug("XACML Response : " + response); - } - return response; - } - - String requestAsString = EntitlementUtil.createSimpleXACMLRequest(subject, resource, action, environmentValue); - - if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_REQUEST)) { - log.debug("XACML Request : " + requestAsString); - } - - response = pdp.evaluate(requestAsString); - - addToCache(request, response, true); - - if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_RESPONSE)) { - log.debug("XACML Response : " + response); - } - - return response; - } - - - /** - * This method is returns the registry based policy finder for current tenant - * - * @return RegistryBasedPolicyFinder - */ - public PolicyFinder getPapPolicyFinder() { - return papPolicyFinder; - } - - - /** - * This method returns the carbon based attribute finder for the current tenant - * - * @return CarbonAttributeFinder - */ - public CarbonAttributeFinder getCarbonAttributeFinder() { - return carbonAttributeFinder; - } - - /** - * This method returns the carbon based resource finder for the current tenant - * - * @return CarbonResourceFinder - */ - public CarbonResourceFinder getCarbonResourceFinder() { - return carbonResourceFinder; - } - - /** - * This method returns the carbon based policy finder for the current tenant - * - * @return CarbonPolicyFinder - */ - public PolicyFinder getCarbonPolicyFinder() { - return carbonPolicyFinder; - } - - /** - * get entry from decision caching - * - * @param request XACML request as String - * @param simpleCache whether using simple cache or not - * @return XACML response as String - */ - private Object getFromCache(String request, boolean simpleCache) { - - if (pdpDecisionCacheEnable) { - - String tenantRequest = tenantId + "+" + request; - Object decision; - - - //There is no any local cache hereafter and always get from distribute cache if there. - /*if (DecisionInvalidationCache.getInstance().isInvalidate()) { - decisionCache.clearCache(); - simpleDecisionCache.clearCache(); - }*/ - - // Check whether the policy cache is invalidated, if so clear the decision cache. - if (EntitlementEngine.getInstance().getPolicyCache().isInvalidate()) { - if (log.isDebugEnabled()) { - log.debug("Policy Cache is invalidated. Clearing the decision cache."); - } - decisionCache.clear(); - simpleDecisionCache.clear(); - return null; - } - - if (simpleCache) { - decision = simpleDecisionCache.getFromCache(tenantRequest); - } else { - decision = decisionCache.getFromCache(tenantRequest); - } - return decision; - } - - if (log.isDebugEnabled()) { - log.debug("PDP Decision Caching is disabled"); - } - return null; - } - - /** - * put entry in to cache - * - * @param request XACML request as String - * @param response XACML response as String - * @param simpleCache whether using simple cache or not - */ - private void addToCache(String request, Object response, boolean simpleCache) { - if (pdpDecisionCacheEnable) { - String tenantRequest = tenantId + "+" + request; - if (simpleCache) { - simpleDecisionCache.addToCache(tenantRequest, response); - } else { - decisionCache.addToCache(tenantRequest, response); - } - } else { - if (log.isDebugEnabled()) { - log.debug("PDP Decision Caching is disabled"); - } - } - } - - /** - * Helper method to init engine - */ - private void setUpAttributeFinders() { - - // Creates carbon attribute finder instance and init it - carbonAttributeFinder = new CarbonAttributeFinder(tenantId); - carbonAttributeFinder.init(); - - // Now setup attribute finder modules for the current date/time and - // AttributeSelectors (selectors are optional, but this project does - // support a basic implementation) - CurrentEnvModule envAttributeModule = new CurrentEnvModule(); - SelectorModule selectorAttributeModule = new SelectorModule(); - - attributeModules.add(carbonAttributeFinder); - attributeModules.add(envAttributeModule); - attributeModules.add(selectorAttributeModule); - - for (AttributeFinderModule module : balana.getPdpConfig().getAttributeFinder().getModules()) { - if (module instanceof CurrentEnvModule || module instanceof SelectorModule) { - continue; - } - attributeModules.add(module); - } - } - - /** - * Helper method to init engine - */ - private void setUpResourceFinders() { - - carbonResourceFinder = new CarbonResourceFinder(tenantId); - carbonResourceFinder.init(); - resourceModules.add(carbonResourceFinder); - - for (ResourceFinderModule module : balana.getPdpConfig().getResourceFinder().getModules()) { - resourceModules.add(module); - } - } - - /** - * Returns instance of policy search - * - * @return PolicySearch - */ - public PolicySearch getPolicySearch() { - return policySearch; - } - - private void setUPPolicyFinder() { - - carbonPolicyFinder = new PolicyFinder(); - Set policyModules = new HashSet(); - CarbonPolicyFinder tmpCarbonPolicyFinder = new CarbonPolicyFinder(); - policyModules.add(tmpCarbonPolicyFinder); - carbonPolicyFinder.setModules(policyModules); - carbonPolicyFinder.init(); - - } - - /** - * Check reset cache state - */ - public void resetCacheInvalidateState() { - - if (policyCache != null) { - policyCache.resetCacheInvalidateState(); - } else { - log.error("Policy cache is null - Unable to reset cache invalidate state."); - } - } - - /** - * Checking the policy cache status before cache invalidation - */ - public void invalidatePolicyCache() { - - if (policyCache != null) { - policyCache.invalidateCache(); - } else { - log.error("Policy cache is null - Unable to invalidate cache."); - } - } - -} \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/ConfigPersistenceManager.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/ConfigPersistenceManager.java deleted file mode 100644 index 81126cf6817b..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/ConfigPersistenceManager.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.wso2.balana.combine.PolicyCombiningAlgorithm; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.EntitlementUtil; - -/** - * This interface supports the management of policy configuration data. - */ -public interface ConfigPersistenceManager { - - /** - * Gets the global policy combining algorithm. - * - * @return global policy combining algorithm. - */ - default PolicyCombiningAlgorithm getGlobalPolicyAlgorithm() { - - String algorithm = getGlobalPolicyAlgorithmName(); - return EntitlementUtil.resolveGlobalPolicyAlgorithm(algorithm); - } - - /** - * Gets the policy combining algorithm name. - * - * @return global policy combining algorithm name. - */ - String getGlobalPolicyAlgorithmName(); - - /** - * Sets the global policy combining algorithm. - * - * @param policyCombiningAlgorithm policy combining algorithm name. - * @return true if the policy combining algorithm is updated, false if the policy combining algorithm is added. - * @throws EntitlementException If an error occurs. - */ - void addOrUpdateGlobalPolicyAlgorithm(String policyCombiningAlgorithm) throws EntitlementException; -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/HybridConfigPersistenceManager.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/HybridConfigPersistenceManager.java deleted file mode 100644 index cc6cf4774cf7..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/HybridConfigPersistenceManager.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.persistence.cache.CacheBackedConfigDAO; - -/** - * HybridConfigPersistenceManager is a hybrid implementation of ConfigPersistenceManager. It uses both JDBC and Registry - * implementations to handle configuration data. Adding or updating a configuration will migrate the - * configuration to the database. - */ -public class HybridConfigPersistenceManager implements ConfigPersistenceManager { - - private final JDBCConfigPersistenceManager jdbcConfigPersistenceManager = new JDBCConfigPersistenceManager(); - private final RegistryConfigPersistenceManager registryConfigPersistenceManager = - new RegistryConfigPersistenceManager(); - private static final CacheBackedConfigDAO configDAO = CacheBackedConfigDAO.getInstance(); - private static final Log LOG = LogFactory.getLog(HybridConfigPersistenceManager.class); - - @Override - public String getGlobalPolicyAlgorithmName() { - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - String algorithm = null; - try { - algorithm = configDAO.getPolicyCombiningAlgorithm(tenantId); - } catch (EntitlementException e) { - LOG.debug(String.format("Error while getting Global Policy Combining Algorithm name from JDBC in tenant " + - "%s.", tenantId), e); - } - if (StringUtils.isBlank(algorithm)) { - algorithm = registryConfigPersistenceManager.getGlobalPolicyAlgorithmName(); - } - return algorithm; - } - - @Override - public void addOrUpdateGlobalPolicyAlgorithm(String policyCombiningAlgorithm) throws EntitlementException { - - jdbcConfigPersistenceManager.addOrUpdateGlobalPolicyAlgorithm(policyCombiningAlgorithm); - if (registryConfigPersistenceManager.isGlobalPolicyAlgorithmExist()) { - try { - registryConfigPersistenceManager.deleteGlobalPolicyAlgorithm(); - } catch (EntitlementException e) { - LOG.debug("Error while deleting global policy combining algorithm from registry", e); - } - } - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/HybridPAPStatusDataHandler.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/HybridPAPStatusDataHandler.java deleted file mode 100644 index 64d3ca6d7e7b..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/HybridPAPStatusDataHandler.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.PAPStatusDataHandler; -import org.wso2.carbon.identity.entitlement.SimplePAPStatusDataHandler; -import org.wso2.carbon.identity.entitlement.dto.StatusHolder; - -import java.util.Arrays; -import java.util.List; -import java.util.Properties; - -/** - * HybridPAPStatusDataHandler is a hybrid implementation of PAPStatusDataHandler. It uses both JDBC and Registry - * implementations to handle status data. If the status trail is maintained in the registry, it will be continued. - * Otherwise, the status trail will be persisted in the database. - */ -public class HybridPAPStatusDataHandler implements PAPStatusDataHandler { - - private final JDBCSimplePAPStatusDataHandler jdbcSimplePAPStatusDataHandler = new JDBCSimplePAPStatusDataHandler(); - private final SimplePAPStatusDataHandler registrySimplePAPStatusDataHandler = new SimplePAPStatusDataHandler(); - - @Override - public void init(Properties properties) { - - jdbcSimplePAPStatusDataHandler.init(properties); - registrySimplePAPStatusDataHandler.init(properties); - } - - @Override - public void handle(String about, String key, List statusHolders) throws EntitlementException { - - // TODO: migrate the retrieved registry status trail to DB - List regStatusHoldersList = - Arrays.asList(registrySimplePAPStatusDataHandler.getStatusData(about, key, null, "*")); - if (regStatusHoldersList.isEmpty()) { - jdbcSimplePAPStatusDataHandler.handle(about, key, statusHolders); - } else { - registrySimplePAPStatusDataHandler.handle(about, key, statusHolders); - } - } - - @Override - public StatusHolder[] getStatusData(String about, String key, String type, String searchString) - throws EntitlementException { - - StatusHolder[] statusHolders = jdbcSimplePAPStatusDataHandler.getStatusData(about, key, type, searchString); - if (statusHolders.length == 0) { - statusHolders = registrySimplePAPStatusDataHandler.getStatusData(about, key, type, searchString); - } - return statusHolders; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/HybridPolicyPersistenceManager.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/HybridPolicyPersistenceManager.java deleted file mode 100644 index a00fca6eae5b..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/HybridPolicyPersistenceManager.java +++ /dev/null @@ -1,400 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.apache.commons.lang.StringUtils; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.EntitlementUtil; -import org.wso2.carbon.identity.entitlement.dto.AttributeDTO; -import org.wso2.carbon.identity.entitlement.dto.PolicyDTO; -import org.wso2.carbon.identity.entitlement.dto.PolicyStoreDTO; -import org.wso2.carbon.identity.entitlement.policy.finder.AbstractPolicyFinderModule; -import org.wso2.carbon.identity.entitlement.policy.finder.PolicyFinderModule; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import static org.wso2.carbon.identity.entitlement.PDPConstants.MODULE_NAME; - -/** - * HybridPolicyPersistenceManager is a hybrid implementation of PolicyPersistenceManager. It uses both JDBC and Registry - * implementations to handle policy data. If the policy is already in the registry, it will be maintained there, - * including new versions. New policies will be persisted in the database. - */ -public class HybridPolicyPersistenceManager extends AbstractPolicyFinderModule implements PolicyPersistenceManager { - - private final JDBCPolicyPersistenceManager jdbcPolicyPersistenceManager = new JDBCPolicyPersistenceManager(); - private final RegistryPolicyPersistenceManager registryPolicyPersistenceManager = - new RegistryPolicyPersistenceManager(); - - @Override - public void init(Properties properties) { - - jdbcPolicyPersistenceManager.init(properties); - registryPolicyPersistenceManager.init(properties); - } - - /** - * Checks the data source of the policy and proceeds with add or update. If registry already contains older - * versions of the policy, new versions are created there. - * - * @param policy policy. - * @param isFromPapAction true if the operation originated from a PAP action, false if it is from a PDP action. - * @throws EntitlementException If an error occurs. - */ - @Override - public void addOrUpdatePolicy(PolicyDTO policy, boolean isFromPapAction) throws EntitlementException { - - if (registryPolicyPersistenceManager.isPolicyExistsInPap(policy.getPolicyId())) { - registryPolicyPersistenceManager.addOrUpdatePolicy(policy, isFromPapAction); - } else { - jdbcPolicyPersistenceManager.addOrUpdatePolicy(policy, isFromPapAction); - } - } - - /** - * Gets the requested policy from DB or registry. - * - * @param policyId policy ID. - * @return policyDTO object. - * @throws EntitlementException If an error occurs. - */ - @Override - public PolicyDTO getPAPPolicy(String policyId) throws EntitlementException { - - PolicyDTO policyDTO = jdbcPolicyPersistenceManager.getPAPPolicy(policyId); - if (policyDTO == null) { - policyDTO = registryPolicyPersistenceManager.getPAPPolicy(policyId); - } - return policyDTO; - } - - /** - * Gets the requested policy lists from both DB and registry to create the complete policy ID list. - * - * @param policyIds policy ID list. - * @return policyDTO. - * @throws EntitlementException If an error occurs. - */ - @Override - public List getPAPPolicies(List policyIds) throws EntitlementException { - - List policyDTOs = jdbcPolicyPersistenceManager.getPAPPolicies(policyIds); - List regPolicyDTOs = registryPolicyPersistenceManager.getPAPPolicies(policyIds); - return EntitlementUtil.mergeLists(policyDTOs, regPolicyDTOs); - } - - /** - * Gets the requested policy version from DB or registry as per the existence. - * - * @param policyId policy ID. - * @param version policy version. - * @return policyDTO object. - * @throws EntitlementException If an error occurs. - */ - @Override - public PolicyDTO getPolicy(String policyId, String version) throws EntitlementException { - - if (jdbcPolicyPersistenceManager.isPolicyExistsInPap(policyId)) { - return jdbcPolicyPersistenceManager.getPolicy(policyId, version); - } else { - return registryPolicyPersistenceManager.getPolicy(policyId, version); - } - } - - /** - * Gets all versions of the given policy ID. If an empty array is returned, tries to retrieve the versions form - * registry. - * - * @param policyId policy ID. - * @return array of policy versions. - */ - @Override - public String[] getVersions(String policyId) { - - String[] versions = jdbcPolicyPersistenceManager.getVersions(policyId); - if (versions.length == 0) { - versions = registryPolicyPersistenceManager.getVersions(policyId); - } - return versions; - } - - /** - * Gets the name of the module. - * - * @return name as String. - */ - @Override - public String getModuleName() { - - return MODULE_NAME; - } - - /** - * Gets the published policy for the given policy ID from DB. If null, queries the registry. - * - * @param policyId policy id as a string value. - * @return policy as string. - */ - @Override - public String getPolicy(String policyId) { - - String policy = jdbcPolicyPersistenceManager.getPolicy(policyId); - if (policy == null) { - policy = registryPolicyPersistenceManager.getPolicy(policyId); - } - return policy; - } - - /** - * Gets the policy order from DB or registry. - * - * @param policyId policy id as a string value. - * @return policy order. - */ - @Override - public int getPolicyOrder(String policyId) { - - if (jdbcPolicyPersistenceManager.isPolicyExist(policyId)) { - return jdbcPolicyPersistenceManager.getPolicyOrder(policyId); - } else { - return registryPolicyPersistenceManager.getPolicyOrder(policyId); - } - } - - /** - * Gets all supported active, published policies from both DB and registry. - * If policy ordering is supported by the module itself, these policies must be ordered. - * - * @return array of policies as Strings. - */ - @Override - public String[] getActivePolicies() { - - String[] dbActivePolicies = jdbcPolicyPersistenceManager.getActivePolicies(); - String[] regActivePolicies = registryPolicyPersistenceManager.getActivePolicies(); - return EntitlementUtil.mergeLists(Arrays.asList(dbActivePolicies), - Arrays.asList(regActivePolicies)).toArray(new String[0]); - } - - /** - * Gets all supported ordered policy ids from both DB and registry. - * If policy ordering is supported by the module itself, these policy ids must be ordered. - * - * @return array of policy ids as Strings. - */ - @Override - public String[] getOrderedPolicyIdentifiers() { - - String[] dbPolicyIds = jdbcPolicyPersistenceManager.getOrderedPolicyIdentifiers(); - String[] regPolicyIds = registryPolicyPersistenceManager.getOrderedPolicyIdentifiers(); - return EntitlementUtil.mergeLists(Arrays.asList(dbPolicyIds), Arrays.asList(regPolicyIds)) - .toArray(new String[0]); - } - - /** - * Gets all published policy ids from both DB and registry. - * - * @return array of policy ids as Strings. - */ - @Override - public String[] getPolicyIdentifiers() { - - String[] dbPolicyIds = jdbcPolicyPersistenceManager.getPolicyIdentifiers(); - String[] regPolicyIds = registryPolicyPersistenceManager.getPolicyIdentifiers(); - return EntitlementUtil.mergeLists(Arrays.asList(dbPolicyIds), Arrays.asList(regPolicyIds)) - .toArray(new String[0]); - } - - /** - * Gets reference policy for the given policy ID from DB or registry. - * - * @param policyId policy id as String value. - * @return reference policy as String. - */ - @Override - public String getReferencedPolicy(String policyId) { - - String policy = jdbcPolicyPersistenceManager.getReferencedPolicy(policyId); - if (policy == null) { - policy = registryPolicyPersistenceManager.getReferencedPolicy(policyId); - } - return policy; - } - - /** - * Gets attributes that are used for policy searching from both DB and registry. - * - * @param identifier unique identifier to separate out search attributes. - * @param givenAttribute pre-given attributes to retrieve other attributes. - * @return return search attributes based on a given policy, Map of policy id with search attributes. - */ - @Override - public Map> getSearchAttributes(String identifier, Set givenAttribute) { - - Map> searchAttributes = - jdbcPolicyPersistenceManager.getSearchAttributes(identifier, givenAttribute); - Map> regSearchAttributes = - registryPolicyPersistenceManager.getSearchAttributes(identifier, givenAttribute); - for (Map.Entry> entry : regSearchAttributes.entrySet()) { - searchAttributes.putIfAbsent(entry.getKey(), entry.getValue()); - } - return searchAttributes; - } - - /** - * Gets support attribute searching scheme of the module. - * - * @return return scheme identifier value. - */ - @Override - public int getSupportedSearchAttributesScheme() { - - return PolicyFinderModule.COMBINATIONS_BY_CATEGORY_AND_PARAMETER; - } - - /** - * Lists all PAP policy IDs from both DB and registry. - * - * @return list of policy IDs. - * @throws EntitlementException If an error occurs. - */ - @Override - public List listPolicyIds() throws EntitlementException { - - List policyIds = jdbcPolicyPersistenceManager.listPolicyIds(); - List regPolicyIds = registryPolicyPersistenceManager.listPolicyIds(); - return EntitlementUtil.mergeLists(policyIds, regPolicyIds); - } - - /** - * Removes the given policy from PAP from either DB or registry according to the existence. - * - * @param policyId policy ID. - * @throws EntitlementException If an error occurs. - */ - @Override - public void removePolicy(String policyId) throws EntitlementException { - - if (jdbcPolicyPersistenceManager.isPolicyExistsInPap(policyId)) { - jdbcPolicyPersistenceManager.removePolicy(policyId); - } else { - registryPolicyPersistenceManager.removePolicy(policyId); - } - } - - /** - * Publishes the given policy in either DB or registry according to the existence. - * - * @param policy policy to be published. - * @throws EntitlementException If an error occurs. - */ - @Override - public void addPolicy(PolicyStoreDTO policy) throws EntitlementException { - - if (policy == null || StringUtils.isBlank(policy.getPolicyId())) { - throw new EntitlementException("Policy and policy id can not be null"); - } - if (jdbcPolicyPersistenceManager.isPolicyExistsInPap(policy.getPolicyId())) { - jdbcPolicyPersistenceManager.addPolicy(policy); - } else { - registryPolicyPersistenceManager.addPolicy(policy); - } - } - - /** - * Updates the policy in either DB or registry according to the existence. - * - * @param policy policy. - * @throws EntitlementException If an error occurs. - */ - @Override - public void updatePolicy(PolicyStoreDTO policy) throws EntitlementException { - - if (policy == null || StringUtils.isBlank(policy.getPolicyId())) { - throw new EntitlementException("Policy and policy id can not be null"); - } - if (jdbcPolicyPersistenceManager.isPolicyExistsInPap(policy.getPolicyId())) { - jdbcPolicyPersistenceManager.updatePolicy(policy); - } else { - registryPolicyPersistenceManager.updatePolicy(policy); - } - } - - /** - * Checks whether the given policy is published or not. - * - * @param policyId policy ID. - * @return whether the given policy is published or not. - */ - @Override - public boolean isPolicyExist(String policyId) { - - return jdbcPolicyPersistenceManager.isPolicyExist(policyId) || - registryPolicyPersistenceManager.isPolicyExist(policyId); - } - - /** - * Gets the requested published policy from either DB or registry. - * - * @param policyId policy ID. - * @return requested policy. - */ - @Override - public PolicyStoreDTO getPublishedPolicy(String policyId) { - - PolicyStoreDTO policyDTO = jdbcPolicyPersistenceManager.getPublishedPolicy(policyId); - if (policyDTO == null || policyDTO.getPolicy() == null) { - policyDTO = registryPolicyPersistenceManager.getPublishedPolicy(policyId); - } - return policyDTO; - } - - /** - * Lists all published policy IDs from both DB and registry. - * - * @return list of published policy IDs. - * @throws EntitlementException If an error occurs. - */ - @Override - public List listPublishedPolicyIds() throws EntitlementException { - - List dbPolicyIds = jdbcPolicyPersistenceManager.listPublishedPolicyIds(); - List regPolicyIds = registryPolicyPersistenceManager.listPublishedPolicyIds(); - return EntitlementUtil.mergeLists(dbPolicyIds, regPolicyIds); - } - - /** - * Un-publishes the policy from either DB or registry according to the existence. - * - * @param policyId policy ID. - */ - @Override - public boolean deletePolicy(String policyId) { - - if (jdbcPolicyPersistenceManager.isPolicyExist(policyId)) { - return jdbcPolicyPersistenceManager.deletePolicy(policyId); - } else { - return registryPolicyPersistenceManager.deletePolicy(policyId); - } - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/HybridSubscriberPersistenceManager.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/HybridSubscriberPersistenceManager.java deleted file mode 100644 index 911ba0b3b378..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/HybridSubscriberPersistenceManager.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.EntitlementUtil; -import org.wso2.carbon.identity.entitlement.dto.PublisherDataHolder; - -import java.util.List; - -/** - * HybridSubscriberPersistenceManager is a hybrid implementation of SubscriberPersistenceManager. It uses both JDBC and - * Registry implementations. All new subscribers will be added to the database, while existing subscribers will be - * maintained in the registry. - */ -public class HybridSubscriberPersistenceManager implements SubscriberPersistenceManager { - - private final JDBCSubscriberPersistenceManager jdbcSubscriberPersistenceManager = - new JDBCSubscriberPersistenceManager(); - private final RegistrySubscriberPersistenceManager registrySubscriberPersistenceManager = - new RegistrySubscriberPersistenceManager(); - - @Override - public void addSubscriber(PublisherDataHolder holder) throws EntitlementException { - - String subscriberId = EntitlementUtil.resolveSubscriberId(holder); - if (subscriberId == null) { - throw new EntitlementException("Subscriber Id can not be null"); - } - if (registrySubscriberPersistenceManager.isSubscriberExists(subscriberId)) { - throw new EntitlementException("Subscriber ID already exists"); - } - jdbcSubscriberPersistenceManager.addSubscriber(holder); - } - - @Override - public PublisherDataHolder getSubscriber(String subscriberId, boolean shouldDecryptSecrets) - throws EntitlementException { - - if (jdbcSubscriberPersistenceManager.isSubscriberExists(subscriberId)) { - return jdbcSubscriberPersistenceManager.getSubscriber(subscriberId, shouldDecryptSecrets); - } - return registrySubscriberPersistenceManager.getSubscriber(subscriberId, shouldDecryptSecrets); - } - - @Override - public List listSubscriberIds(String filter) throws EntitlementException { - - List subscriberIds = jdbcSubscriberPersistenceManager.listSubscriberIds(filter); - List registrySubscriberIds = registrySubscriberPersistenceManager.listSubscriberIds(filter); - return EntitlementUtil.mergeLists(subscriberIds, registrySubscriberIds); - } - - @Override - public void updateSubscriber(PublisherDataHolder holder) throws EntitlementException { - - String subscriberId = EntitlementUtil.resolveSubscriberId(holder); - if (jdbcSubscriberPersistenceManager.isSubscriberExists(subscriberId)) { - jdbcSubscriberPersistenceManager.updateSubscriber(holder); - } else { - registrySubscriberPersistenceManager.updateSubscriber(holder); - } - } - - @Override - public void removeSubscriber(String subscriberId) throws EntitlementException { - - if (jdbcSubscriberPersistenceManager.isSubscriberExists(subscriberId)) { - jdbcSubscriberPersistenceManager.removeSubscriber(subscriberId); - } else { - registrySubscriberPersistenceManager.removeSubscriber(subscriberId); - } - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/JDBCConfigPersistenceManager.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/JDBCConfigPersistenceManager.java deleted file mode 100644 index cff7aa02c94a..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/JDBCConfigPersistenceManager.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.persistence.cache.CacheBackedConfigDAO; - -import static org.wso2.carbon.identity.entitlement.PDPConstants.Algorithms.DENY_OVERRIDES; - -/** - * This class handles the JDBC operations related to the global policy combining algorithm. - */ -public class JDBCConfigPersistenceManager implements ConfigPersistenceManager { - - private static final Log LOG = LogFactory.getLog(JDBCConfigPersistenceManager.class); - private static final CacheBackedConfigDAO configDAO = CacheBackedConfigDAO.getInstance(); - - /** - * Gets the policy combining algorithm name of the PDP. - * - * @return policy combining algorithm name. - */ - @Override - public String getGlobalPolicyAlgorithmName() { - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - String algorithm = null; - try { - algorithm = configDAO.getPolicyCombiningAlgorithm(tenantId); - } catch (EntitlementException e) { - LOG.debug(String.format("Error while getting Global Policy Combining Algorithm name from JDBC in tenant " + - "%s. Default algorithm name will be returned.", tenantId), e); - } - if (StringUtils.isBlank(algorithm)) { - algorithm = DENY_OVERRIDES; - } - - return algorithm; - } - - /** - * Persists the policy combining algorithm into the data store. - * - * @param policyCombiningAlgorithm policy combining algorithm name to persist. - * @return true if the policy combining algorithm is updated, false if the policy combining algorithm is added. - * @throws EntitlementException throws if fails. - */ - @Override - public void addOrUpdateGlobalPolicyAlgorithm(String policyCombiningAlgorithm) throws EntitlementException { - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - - // Check the existence of the algorithm - String algorithm = null; - try { - algorithm = configDAO.getPolicyCombiningAlgorithm(tenantId); - } catch (EntitlementException e) { - LOG.debug(String.format("Error while getting Global Policy Combining Algorithm name from JDBC in tenant " + - "%s.", tenantId), e); - } - if (StringUtils.isBlank(algorithm)) { - configDAO.insertPolicyCombiningAlgorithm(policyCombiningAlgorithm, tenantId); - } else { - configDAO.updatePolicyCombiningAlgorithm(policyCombiningAlgorithm, tenantId); - } - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/JDBCPolicyPersistenceManager.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/JDBCPolicyPersistenceManager.java deleted file mode 100644 index 0af4f81778fd..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/JDBCPolicyPersistenceManager.java +++ /dev/null @@ -1,658 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.apache.axiom.om.OMElement; -import org.apache.axiom.om.util.AXIOMUtil; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.EntitlementUtil; -import org.wso2.carbon.identity.entitlement.PDPConstants; -import org.wso2.carbon.identity.entitlement.PolicyOrderComparator; -import org.wso2.carbon.identity.entitlement.dto.AttributeDTO; -import org.wso2.carbon.identity.entitlement.dto.PolicyDTO; -import org.wso2.carbon.identity.entitlement.dto.PolicyStoreDTO; -import org.wso2.carbon.identity.entitlement.pap.store.PAPPolicyStoreManager; -import org.wso2.carbon.identity.entitlement.persistence.cache.CacheBackedPolicyDAO; -import org.wso2.carbon.identity.entitlement.policy.PolicyAttributeBuilder; -import org.wso2.carbon.identity.entitlement.policy.finder.AbstractPolicyFinderModule; -import org.wso2.carbon.identity.entitlement.policy.finder.PolicyFinderModule; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Date; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import javax.xml.stream.XMLStreamException; - -import static org.wso2.carbon.identity.entitlement.PDPConstants.MODULE_NAME; - -/** - * This class handles the policy operations in the JDBC data store. - */ -public class JDBCPolicyPersistenceManager extends AbstractPolicyFinderModule implements PolicyPersistenceManager { - - private static final Log LOG = LogFactory.getLog(JDBCPolicyPersistenceManager.class); - private static final String ERROR_RETRIEVING_POLICIES_FROM_POLICY_FINDER = "Policies can not be retrieved from " + - "the policy finder module"; - private final int maxVersions; - private static final CacheBackedPolicyDAO policyDAO = CacheBackedPolicyDAO.getInstance(); - - public JDBCPolicyPersistenceManager() { - - maxVersions = EntitlementUtil.getMaxNoOfPolicyVersions(); - } - - @Override - public void init(Properties properties) { - - // Nothing to initialize - } - - /** - * Adds or updates the given PAP policy. - * - * @param policy policy. - * @param isFromPapAction true if the operation originated from a PAP action, false if it is from a PDP action. - * @throws EntitlementException If an error occurs. - */ - @Override - public void addOrUpdatePolicy(PolicyDTO policy, boolean isFromPapAction) throws EntitlementException { - - // In the JDBC impl we use this method only to add a new policy version - if (!isFromPapAction) { - return; - } - - String policyId = policy.getPolicyId(); - if (StringUtils.isBlank(policyId)) { - throw new EntitlementException("Invalid Entitlement Policy. Policy or policyId can not be Null"); - } - boolean newPolicy = false; - OMElement omElement = null; - - String version = createVersion(policy); - policy.setVersion(version); - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Creating entitlement policy %s version %s", policyId, version)); - } - - if (StringUtils.isNotBlank(policy.getPolicy())) { - newPolicy = true; - } - - // Find policy type - String policyType = null; - if (StringUtils.isNotBlank(policy.getPolicyType())) { - policyType = policy.getPolicyType(); - } else { - try { - if (newPolicy) { - omElement = AXIOMUtil.stringToOM(policy.getPolicy()); - policyType = omElement.getLocalName(); - } - } catch (XMLStreamException e) { - policyType = PDPConstants.POLICY_ELEMENT; - LOG.warn("Policy Type can not be found. Default type is set"); - } - } - policy.setPolicyType(policyType); - - // Trim policy editor type - String policyEditorType = null; - if (StringUtils.isNotBlank(policy.getPolicyEditor())) { - policyEditorType = policy.getPolicyEditor().trim(); - } - policy.setPolicyEditor(policyEditorType); - - // Resolve policy references and policy set references of the policy - if (omElement != null) { - Iterator iterator1 = omElement.getChildrenWithLocalName(PDPConstants.POLICY_REFERENCE); - List policyReferences = new ArrayList<>(); - while (iterator1.hasNext()) { - OMElement policyReference = (OMElement) iterator1.next(); - policyReferences.add(policyReference.getText()); - } - policy.setPolicyIdReferences(policyReferences.toArray(new String[0])); - - Iterator iterator2 = omElement.getChildrenWithLocalName(PDPConstants.POLICY_SET_REFERENCE); - List policySetReferences = new ArrayList<>(); - while (iterator2.hasNext()) { - OMElement policySetReference = (OMElement) iterator2.next(); - policySetReferences.add(policySetReference.getText()); - } - policy.setPolicySetIdReferences(policySetReferences.toArray(new String[0])); - } - - // Find policy attributes - List attributeDTOs = null; - if (StringUtils.isNotBlank(policy.getPolicy()) && EntitlementUtil.isPolicyMetadataStoringEnabled()) { - PolicyAttributeBuilder policyAttributeBuilder = new PolicyAttributeBuilder(policy.getPolicy()); - attributeDTOs = policyAttributeBuilder.getAttributesFromPolicy(); - } - if (attributeDTOs != null && !attributeDTOs.isEmpty()) { - policy.setAttributeDTOs(attributeDTOs.toArray(new AttributeDTO[0])); - } - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - policyDAO.insertPolicy(policy, tenantId); - } - - /** - * Gets the requested policy. - * - * @param policyId policy ID. - * @return policyDTO object. - * @throws EntitlementException If an error occurs. - */ - @Override - public PolicyDTO getPAPPolicy(String policyId) throws EntitlementException { - - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Retrieving entitlement policy %s", policyId)); - } - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - - return policyDAO.getPAPPolicy(policyId, tenantId); - } - - /** - * Gets the requested policy list. - *

    - * Note: The `policyIds` parameter is ignored. This method retrieves the full list of PAP policies from the database - * regardless of the provided policy IDs. - *

    - * - * @param policyIds A list of policy IDs. This parameter is ignored. - * @return policyDTO. - * @throws EntitlementException If an error occurs. - */ - @Override - public List getPAPPolicies(List policyIds) throws EntitlementException { - - LOG.debug("Retrieving all PAP entitlement policies"); - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - return policyDAO.getAllPAPPolicies(tenantId); - } - - /** - * Gets the requested policy version. Returns the latest version if version is not specified. - * - * @param policyId policy ID. - * @param version policy version. - * @return policyDTO object. - * @throws EntitlementException If an error occurs. - */ - @Override - public PolicyDTO getPolicy(String policyId, String version) throws EntitlementException { - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - - // Zero means current version - if (StringUtils.isBlank(version)) { - version = policyDAO.getLatestPolicyVersion(policyId, tenantId); - if (StringUtils.isBlank(version)) { - throw new EntitlementException("Invalid policy version"); - } - } - - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Retrieving entitlement policy %s for the given version %s", policyId, version)); - } - return policyDAO.getPapPolicyByVersion(policyId, version, tenantId); - } - - /** - * Gets all versions of the given policy ID. - * - * @param policyId policy ID. - * @return array of policy versions. - */ - @Override - public String[] getVersions(String policyId) { - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - List versions = policyDAO.getPolicyVersions(policyId, tenantId); - return versions.toArray(new String[0]); - } - - /** - * Lists all PAP policy IDs. - * - * @return list of policy IDs. - * @throws EntitlementException If an error occurs. - */ - @Override - public List listPolicyIds() throws EntitlementException { - - LOG.debug("Retrieving all entitlement policy IDs"); - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - return policyDAO.getPAPPolicyIds(tenantId); - } - - /** - * Removes the given policy from PAP. - * - * @param policyId policy ID. - * @throws EntitlementException If an error occurs. - */ - @Override - public void removePolicy(String policyId) throws EntitlementException { - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Removing entitlement policy %s", policyId)); - } - if (StringUtils.isBlank(policyId)) { - throw new EntitlementException("Invalid policy id. Policy id can not be null"); - } - policyDAO.deletePAPPolicy(policyId, tenantId); - } - - /** - * Gets the name of the module. - * - * @return name as String. - */ - @Override - public String getModuleName() { - - return MODULE_NAME; - } - - /** - * Gets the published policy for the given policy ID. - * - * @param policyId policy id as a string value. - * @return policy as string. - */ - @Override - public String getPolicy(String policyId) { - - PolicyStoreDTO dto = getPublishedPolicy(policyId); - return dto.getPolicy(); - } - - /** - * Gets the policy order. - * - * @param policyId policy id as a string value. - * @return policy order. - */ - @Override - public int getPolicyOrder(String policyId) { - - PolicyStoreDTO dto = getPublishedPolicy(policyId); - return dto.getPolicyOrder(); - } - - /** - * Gets all supported active, published policies. - * If policy ordering is supported by the module itself, these policies must be ordered. - * - * @return array of policies as Strings. - */ - @Override - public String[] getActivePolicies() { - - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Retrieving of Active policies has started at %s", new Date())); - } - - List policies = new ArrayList<>(); - - try { - PolicyStoreDTO[] policyDTOs = getAllPolicies(true, true); - for (PolicyStoreDTO dto : policyDTOs) { - if (StringUtils.isNotBlank(dto.getPolicy())) { - policies.add(dto.getPolicy()); - } - } - } catch (EntitlementException e) { - LOG.error(ERROR_RETRIEVING_POLICIES_FROM_POLICY_FINDER, e); - } - - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Retrieving of Active policies has finished at %s", new Date())); - } - - return policies.toArray(new String[0]); - } - - /** - * Gets all supported ordered policy ids. - * If policy ordering is supported by the module itself, these policy ids must be ordered. - * - * @return array of policy ids as Strings. - */ - @Override - public String[] getOrderedPolicyIdentifiers() { - - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Retrieving of Ordered Policy Ids has started at %s", new Date())); - } - - List policies = new ArrayList<>(); - - try { - PolicyStoreDTO[] policyDTOs = getAllPolicies(false, true); - for (PolicyStoreDTO dto : policyDTOs) { - if (StringUtils.isNotBlank(dto.getPolicy())) { - policies.add(dto.getPolicyId()); - } - } - } catch (EntitlementException e) { - LOG.error(ERROR_RETRIEVING_POLICIES_FROM_POLICY_FINDER, e); - } - - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Retrieving of Ordered Policy Ids is finished at %s", new Date())); - } - - return policies.toArray(new String[0]); - } - - /** - * Gets all published policy ids. - * - * @return array of policy ids as Strings. - */ - @Override - public String[] getPolicyIdentifiers() { - - String[] policyIds = null; - try { - policyIds = listPublishedPolicyIds().toArray(new String[0]); - } catch (EntitlementException e) { - LOG.error("Policy identifiers can not be retrieved from the policy finder module", e); - } - return policyIds; - } - - /** - * Gets reference policy for the given policy ID. - * Reference policy can not be with PDP policy store, may be in some external policy store. - * Therefore, a new method has been added to retrieve reference policies. - * - * @param policyId policy id as String value. - * @return reference policy as String. - */ - @Override - public String getReferencedPolicy(String policyId) { - - // Retrieve policies that are not active - PolicyStoreDTO dto = getPublishedPolicy(policyId); - if (dto != null && StringUtils.isNotBlank(dto.getPolicy()) && !dto.isActive()) { - return dto.getPolicy(); - } - return null; - } - - /** - * Gets attributes that are used for policy searching. - * - * @param identifier unique identifier to separate out search attributes. - * @param givenAttribute pre-given attributes to retrieve other attributes. - * @return return search attributes based on a given policy, Map of policy id with search attributes. - */ - @Override - public Map> getSearchAttributes(String identifier, Set givenAttribute) { - - try { - PolicyStoreDTO[] policyDTOs = getAllPolicies(true, true); - List policyDTOList = new ArrayList<>(); - for (PolicyStoreDTO policyStoreDTO : policyDTOs) { - PolicyDTO policyDTO = getPAPPolicy(policyStoreDTO.getPolicyId()); - policyDTOList.add(policyDTO); - } - if (policyDTOs.length > 0) { - return EntitlementUtil.getAttributesFromPolicies(policyDTOList.toArray(new PolicyDTO[0])); - } - } catch (EntitlementException e) { - LOG.error(ERROR_RETRIEVING_POLICIES_FROM_POLICY_FINDER, e); - } - return Collections.emptyMap(); - } - - /** - * Gets support attribute searching scheme of the module. - * - * @return return scheme identifier value. - */ - @Override - public int getSupportedSearchAttributesScheme() { - - return PolicyFinderModule.COMBINATIONS_BY_CATEGORY_AND_PARAMETER; - } - - /** - * Publishes the given policy. - * - * @param policy policy to be published. - * @throws EntitlementException If an error occurs. - */ - @Override - public void addPolicy(PolicyStoreDTO policy) throws EntitlementException { - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - - if (policy == null || StringUtils.isBlank(policy.getPolicyId())) { - throw new EntitlementException("Policy and policy id can not be null"); - } - if (StringUtils.isBlank(policy.getVersion())) { - throw new EntitlementException(String.format("Cannot publish policy %s. Invalid policy version.", - policy.getPolicyId())); - } - policyDAO.insertOrUpdatePolicy(policy, tenantId); - } - - /** - * Updates the policy. - * - * @param policy policy. - * @throws EntitlementException If an error occurs. - */ - @Override - public void updatePolicy(PolicyStoreDTO policy) throws EntitlementException { - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - if (policy == null || StringUtils.isBlank(policy.getPolicyId())) { - throw new EntitlementException("Policy and policy id can not be null"); - } - - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Updating policy %s", policy.getPolicyId())); - } - if (policy.isSetActive() != policy.isSetOrder()) { - if (StringUtils.isBlank(policy.getVersion())) { - // Get published version - int version = policyDAO.getPublishedVersion(policy, tenantId); - if (version == -1) { - throw new EntitlementException(String.format("Cannot update policy %s. Invalid policy version.", - policy.getPolicyId())); - } - policy.setVersion(String.valueOf(version)); - } - policyDAO.updateActiveStatusAndOrder(policy, tenantId); - } else { - addPolicy(policy); - } - } - - /** - * Checks whether the given policy is published or not. - * - * @param policyId policy ID. - * @return whether the given policy is published or not. - */ - @Override - public boolean isPolicyExist(String policyId) { - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - if (StringUtils.isBlank(policyId)) { - return false; - } - return policyDAO.isPolicyPublished(policyId, tenantId); - } - - /** - * Gets the requested published policy. - * - * @param policyId policy ID. - * @return requested policy. - */ - @Override - public PolicyStoreDTO getPublishedPolicy(String policyId) { - - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Retrieving entitlement policy %s", policyId)); - } - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - - PolicyStoreDTO dto = policyDAO.getPDPPolicy(policyId, tenantId); - if (dto != null) { - return dto; - } - return new PolicyStoreDTO(); - } - - /** - * Lists all published policy IDs. - * - * @return list of published policy IDs. - * @throws EntitlementException If an error occurs. - */ - @Override - public List listPublishedPolicyIds() throws EntitlementException { - - LOG.debug("Retrieving all PDP entitlement policy ids"); - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - return policyDAO.getPublishedPolicyIds(tenantId); - } - - /** - * Un-publishes the policy. - * - * @param policyId policy ID. - */ - @Override - public boolean deletePolicy(String policyId) { - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - - if (StringUtils.isBlank(policyId)) { - return false; - } - return policyDAO.unpublishPolicy(policyId, tenantId); - } - - /** - * Checks the existence of the policy in PAP - * - * @param policyId policy ID. - * @return whether the policy exists in PAP or not. - */ - public boolean isPolicyExistsInPap(String policyId) { - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - - if (policyId == null || policyId.trim().isEmpty()) { - return false; - } - return policyDAO.isPAPPolicyExists(policyId, tenantId); - } - - /** - * Creates policy versions. - * - * @param policyDTO policyDTO. - * @return version. - * @throws EntitlementException throws, if fails. - */ - private String createVersion(PolicyDTO policyDTO) throws EntitlementException { - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - PAPPolicyStoreManager manager = new PAPPolicyStoreManager(); - String version = "0"; - - if (manager.isExistPolicy(policyDTO.getPolicyId())) { - PolicyDTO dto = manager.getLightPolicy(policyDTO.getPolicyId()); - version = dto.getVersion(); - } - - int versionInt = Integer.parseInt(version); - - // Check whether this is larger than max version - if (versionInt > maxVersions) { - // delete the older version - int olderVersion = versionInt - maxVersions; - policyDAO.deletePAPPolicyVersion(policyDTO.getPolicyId(), olderVersion, tenantId); - } - - // New version - version = Integer.toString(versionInt + 1); - return version; - } - - /** - * Reads all ordered and active policies as PolicyDTO. - * - * @param active only return active policies. Else return all policies. - * @param order return ordered policy. - * @return Array of PolicyDTO. - * @throws EntitlementException If an error occurs. - */ - private PolicyStoreDTO[] getAllPolicies(boolean active, boolean order) throws EntitlementException { - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - PolicyStoreDTO[] policies; - policies = policyDAO.getAllPDPPolicies(tenantId); - - if (policies.length == 0) { - return new PolicyStoreDTO[0]; - } - List policyDTOList = new ArrayList<>(); - for (PolicyStoreDTO policy : policies) { - if (active) { - if (policy.isActive()) { - policyDTOList.add(policy); - } - } else { - policyDTOList.add(policy); - } - } - - PolicyStoreDTO[] policyDTOs = policyDTOList.toArray(new PolicyStoreDTO[0]); - - if (order) { - Arrays.sort(policyDTOs, new PolicyOrderComparator()); - } - return policyDTOs; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/JDBCSimplePAPStatusDataHandler.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/JDBCSimplePAPStatusDataHandler.java deleted file mode 100644 index 9746ea046b5a..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/JDBCSimplePAPStatusDataHandler.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.apache.commons.logging.Log; -import org.wso2.carbon.CarbonConstants; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.identity.central.log.mgt.utils.LoggerUtils; -import org.wso2.carbon.identity.core.util.IdentityUtil; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.EntitlementUtil; -import org.wso2.carbon.identity.entitlement.PAPStatusDataHandler; -import org.wso2.carbon.identity.entitlement.common.EntitlementConstants; -import org.wso2.carbon.identity.entitlement.dto.StatusHolder; -import org.wso2.carbon.identity.entitlement.persistence.dao.StatusDAO; - -import java.util.List; -import java.util.Properties; - -/** - * This class handles the status data of the policies in the JDBC data store. - */ -public class JDBCSimplePAPStatusDataHandler implements PAPStatusDataHandler { - - private static final Log AUDIT_LOG = CarbonConstants.AUDIT_LOG; - private static final String AUDIT_MESSAGE - = "Initiator : %s | Action : %s | Target : %s | Data : { %s } | Result : %s "; - private int maxRecords; - private static final StatusDAO statusDAO = new StatusDAO(); - - /** - * init entitlement status data handler module. - * - * @param properties properties. - */ - @Override - public void init(Properties properties) { - - maxRecords = EntitlementUtil.getMaxNoOfStatusRecords(); - } - - /** - * Handles the status data. - * - * @param about whether the status is about a policy or publisher. - * @param key key value of the status. - * @param statusHolders StatusHolder. - * @throws EntitlementException throws, if fails to handle. - */ - @Override - public void handle(String about, String key, List statusHolders) throws EntitlementException { - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - // If the action is DELETE_POLICY, delete the policy or the subscriber status - for (StatusHolder holder : statusHolders) { - if (EntitlementConstants.StatusTypes.DELETE_POLICY.equals(holder.getType())) { - statusDAO.deleteStatusTrail(about, key, tenantId); - return; - } - } - amendStatusTrail(about, key, statusHolders, tenantId); - } - - /** - * Returns status data. - * - * @param about indicates what is related with this admin status action. - * @param key key value of the status. - * @param type admin action type. - * @param searchString search string for StatusHolder. - * @return An array of StatusHolder. - * @throws EntitlementException if fails. - */ - @Override - public StatusHolder[] getStatusData(String about, String key, String type, String searchString) - throws EntitlementException { - - String statusAboutType = EntitlementConstants.Status.ABOUT_POLICY.equals(about) - ? EntitlementConstants.Status.ABOUT_POLICY - : EntitlementConstants.Status.ABOUT_SUBSCRIBER; - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - List holders = statusDAO.getStatus(key, statusAboutType, tenantId); - // TODO: sort and return according to maxRecords - return EntitlementUtil.filterStatus(holders, searchString, about, type); - } - - private void amendStatusTrail(String about, String key, List statusHolders, int tenantId) - throws EntitlementException { - - boolean useLastStatusOnly = Boolean.parseBoolean( - IdentityUtil.getProperty(EntitlementConstants.PROP_USE_LAST_STATUS_ONLY)); - - if (statusHolders != null && !statusHolders.isEmpty()) { - - if (useLastStatusOnly) { - // Delete all the previous statuses - statusDAO.deleteStatusTrail(about, key, tenantId); - auditAction(statusHolders.toArray(new StatusHolder[0])); - } - - // Add new status to the database - statusDAO.insertStatus(about, key, statusHolders, tenantId); - - if (!useLastStatusOnly) { - statusDAO.deleteExcessStatusData(about, key, tenantId, maxRecords); - } - } - } - - private void auditAction(StatusHolder[] statusHolders) { - - if (statusHolders != null) { - for (StatusHolder statusHolder : statusHolders) { - if (statusHolder != null) { - String initiator = statusHolder.getUser(); - if (LoggerUtils.isLogMaskingEnable) { - initiator = LoggerUtils.getMaskedContent(initiator); - } - String action = statusHolder.getType(); - String key = statusHolder.getKey(); - String target = statusHolder.getTarget(); - String targetAction = statusHolder.getTargetAction(); - String result = "FAILURE"; - if (statusHolder.isSuccess()) { - result = "SUCCESS"; - } - String auditData = String.format("\"Key\" : \"%s\" , \"Target Action\" : \"%s\"", - key, targetAction); - - AUDIT_LOG.info(String.format(AUDIT_MESSAGE, initiator, action, target, auditData, result)); - } - } - } - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/JDBCSubscriberPersistenceManager.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/JDBCSubscriberPersistenceManager.java deleted file mode 100644 index 4fd14ea90307..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/JDBCSubscriberPersistenceManager.java +++ /dev/null @@ -1,246 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.core.util.CryptoException; -import org.wso2.carbon.core.util.CryptoUtil; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.EntitlementUtil; -import org.wso2.carbon.identity.entitlement.common.EntitlementConstants; -import org.wso2.carbon.identity.entitlement.dto.PublisherDataHolder; -import org.wso2.carbon.identity.entitlement.dto.PublisherPropertyDTO; -import org.wso2.carbon.identity.entitlement.persistence.cache.CacheBackedSubscriberDAO; - -import java.util.ArrayList; -import java.util.List; - -/** - * This class handles the JDBC operations of the subscribers in the data store. - */ -public class JDBCSubscriberPersistenceManager implements SubscriberPersistenceManager { - - private static final Log LOG = LogFactory.getLog(JDBCSubscriberPersistenceManager.class); - private static final String ERROR_SUBSCRIBER_ID_NULL = "Subscriber Id can not be null"; - private static final CacheBackedSubscriberDAO subscriberDAO = CacheBackedSubscriberDAO.getInstance(); - - /** - * Gets the requested subscriber. - * - * @param subscriberId subscriber ID. - * @param shouldDecryptSecrets whether the subscriber should get returned with secret(decrypted) values or not. - * @return publisher data holder. - * @throws EntitlementException If an error occurs. - */ - @Override - public PublisherDataHolder getSubscriber(String subscriberId, boolean shouldDecryptSecrets) - throws EntitlementException { - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - - PublisherDataHolder publisherDataHolder = subscriberDAO.getSubscriber(subscriberId, tenantId); - if (publisherDataHolder == null) { - throw new EntitlementException("No Subscriber is defined for the given Id"); - } - if (shouldDecryptSecrets) { - decryptSecretProperties(publisherDataHolder.getPropertyDTOs()); - } - return publisherDataHolder; - } - - /** - * Gets all subscriber IDs. - * - * @param filter search string. - * @return list of subscriber IDs. - * @throws EntitlementException If an error occurs. - */ - @Override - public List listSubscriberIds(String filter) throws EntitlementException { - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - List subscriberIdList = subscriberDAO.getSubscriberIds(tenantId); - return EntitlementUtil.filterSubscribers(subscriberIdList, filter); - } - - /** - * Adds a subscriber. - * - * @param holder publisher data holder. - * @throws EntitlementException If an error occurs. - */ - @Override - public void addSubscriber(PublisherDataHolder holder) throws EntitlementException { - - String subscriberId = EntitlementUtil.resolveSubscriberId(holder); - if (subscriberId == null) { - throw new EntitlementException(ERROR_SUBSCRIBER_ID_NULL); - } - PublisherPropertyDTO[] propertyDTOsWithEncryptedSecrets = encryptSecretProperties(holder.getPropertyDTOs()); - holder.setPropertyDTOs(propertyDTOsWithEncryptedSecrets); - - if (isSubscriberExists(subscriberId)) { - throw new EntitlementException("Subscriber ID already exists"); - } - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - subscriberDAO.insertSubscriber(subscriberId, holder, tenantId); - } - - /** - * Updates a subscriber. - * - * @param holder publisher data holder. - * @throws EntitlementException If an error occurs. - */ - @Override - public void updateSubscriber(PublisherDataHolder holder) throws EntitlementException { - - String subscriberId = EntitlementUtil.resolveSubscriberId(holder); - if (subscriberId == null) { - throw new EntitlementException(ERROR_SUBSCRIBER_ID_NULL); - } - - if (isSubscriberExists(subscriberId)) { - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - PublisherDataHolder oldHolder = getSubscriber(subscriberId, false); - String updatedModuleName = getUpdatedModuleName(holder, oldHolder); - PublisherPropertyDTO[] updatedPropertyDTOs = getUpdatedPropertyDTOs(holder, oldHolder); - PublisherPropertyDTO[] propertyDTOsWithEncryptedSecrets = encryptSecretProperties(updatedPropertyDTOs); - subscriberDAO.updateSubscriber(subscriberId, updatedModuleName, propertyDTOsWithEncryptedSecrets, tenantId); - } else { - throw new EntitlementException("Subscriber ID does not exist; update cannot be done"); - } - } - - /** - * Removes the subscriber of the given subscriber ID. - * - * @param subscriberId subscriber ID. - * @throws EntitlementException If an error occurs. - */ - @Override - public void removeSubscriber(String subscriberId) throws EntitlementException { - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - - if (StringUtils.isBlank(subscriberId)) { - throw new EntitlementException(ERROR_SUBSCRIBER_ID_NULL); - } - - if (EntitlementConstants.PDP_SUBSCRIBER_ID.equals(subscriberId.trim())) { - throw new EntitlementException("Cannot delete PDP publisher"); - } - - subscriberDAO.deleteSubscriber(subscriberId, tenantId); - } - - /** - * Checks whether a subscriber exists. - * - * @param subscriberId subscriber ID. - * @return whether the subscriber exists or not. - * @throws EntitlementException If an error occurs. - */ - public boolean isSubscriberExists(String subscriberId) throws EntitlementException { - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - return subscriberDAO.isSubscriberExists(subscriberId, tenantId); - } - - private String getUpdatedModuleName(PublisherDataHolder holder, PublisherDataHolder oldHolder) { - - if (holder == null || oldHolder == null) { - return null; - } - if (!oldHolder.getModuleName().equalsIgnoreCase(holder.getModuleName())) { - return holder.getModuleName(); - } - return null; - } - - private PublisherPropertyDTO[] getUpdatedPropertyDTOs(PublisherDataHolder holder, PublisherDataHolder oldHolder) { - - if (holder == null || oldHolder == null) { - return new PublisherPropertyDTO[0]; - } - List updatedPropertyDTOs = new ArrayList<>(); - for (PublisherPropertyDTO newPropertyDTO : holder.getPropertyDTOs()) { - if (StringUtils.isNotBlank(newPropertyDTO.getId()) && StringUtils.isNotBlank(newPropertyDTO.getValue())) { - - PublisherPropertyDTO oldPropertyDTO = oldHolder.getPropertyDTO(newPropertyDTO.getId()); - if (oldPropertyDTO == null || !oldPropertyDTO.getValue().equalsIgnoreCase(newPropertyDTO.getValue())) { - updatedPropertyDTOs.add(newPropertyDTO); - } - } - } - return updatedPropertyDTOs.toArray(new PublisherPropertyDTO[0]); - } - - /** - * Sets the base64 encoded secret value of the secret subscriber properties. - * - * @param propertyDTOs list of subscriber properties. - */ - private PublisherPropertyDTO[] encryptSecretProperties(PublisherPropertyDTO[] propertyDTOs) - throws EntitlementException { - - if (propertyDTOs == null) { - return new PublisherPropertyDTO[0]; - } - List updatedPropertyDTOs = new ArrayList<>(); - for (PublisherPropertyDTO propertyDTO : propertyDTOs) { - if (propertyDTO.isSecret()) { - try { - String encryptedValue = CryptoUtil.getDefaultCryptoUtil() - .encryptAndBase64Encode(propertyDTO.getValue().getBytes()); - propertyDTO.setValue(encryptedValue); - } catch (CryptoException e) { - throw new EntitlementException("Error while encrypting secret value of subscriber. Update cannot " + - "proceed.", e); - } - } - updatedPropertyDTOs.add(propertyDTO); - } - return updatedPropertyDTOs.toArray(new PublisherPropertyDTO[0]); - } - - /** - * Decrypts the secret values of the subscriber properties. - * - * @param properties list of subscriber properties - */ - // TODO: check if we can use common secret table or a separate table - private void decryptSecretProperties(PublisherPropertyDTO[] properties) { - - for (PublisherPropertyDTO dto : properties) { - if (dto.isSecret()) { - try { - String password = new String(CryptoUtil.getDefaultCryptoUtil() - .base64DecodeAndDecrypt(dto.getValue())); - dto.setValue(password); - } catch (CryptoException e) { - LOG.error("Error while decrypting secret value of subscriber.", e); - } - } - } - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/PersistenceManagerConstants.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/PersistenceManagerConstants.java deleted file mode 100644 index 7ab67344f842..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/PersistenceManagerConstants.java +++ /dev/null @@ -1,314 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -/** - * DB related constant values. - */ -public class PersistenceManagerConstants { - - private PersistenceManagerConstants() { - - } - - public static final String LIMIT = "LIMIT"; - public static final String KEY = "KEY"; - public static final String STATUS_COUNT = "COUNT"; - - public static class EntitlementTableColumns { - - private EntitlementTableColumns() { - - } - - // IDN_XACML_POLICY table - public static final String POLICY_ID = "POLICY_ID"; - public static final String VERSION = "VERSION"; - public static final String TENANT_ID = "TENANT_ID"; - public static final String LAST_MODIFIED_TIME = "LAST_MODIFIED_TIME"; - public static final String LAST_MODIFIED_USER = "LAST_MODIFIED_USER"; - public static final String IS_ACTIVE = "IS_ACTIVE"; - public static final String POLICY_ORDER = "POLICY_ORDER"; - public static final String POLICY_TYPE = "POLICY_TYPE"; - public static final String POLICY_EDITOR = "POLICY_EDITOR"; - public static final String POLICY = "POLICY"; - public static final String IS_IN_PAP = "IS_IN_PAP"; - public static final String IS_IN_PDP = "IS_IN_PDP"; - - // IDN_XACML_POLICY_EDITOR_DATA table - public static final String EDITOR_DATA_ORDER = "DATA_ORDER"; - public static final String EDITOR_DATA = "DATA"; - - // IDN_XACML_POLICY_ATTRIBUTE table - public static final String ATTRIBUTE_ID = "ATTRIBUTE_ID"; - public static final String ATTRIBUTE_VALUE = "ATTRIBUTE_VALUE"; - public static final String DATA_TYPE = "DATA_TYPE"; - public static final String CATEGORY = "CATEGORY"; - - // IDN_XACML_POLICY_REFERENCE table - public static final String REFERENCE = "REFERENCE"; - - // IDN_XACML_POLICY_SET_REFERENCE table - public static final String SET_REFERENCE = "SET_REFERENCE"; - - // IDN_XACML_SUBSCRIBER table - public static final String SUBSCRIBER_ID = "SUBSCRIBER_ID"; - public static final String ENTITLEMENT_MODULE_NAME = "ENTITLEMENT_MODULE_NAME"; - - // IDN_XACML_SUBSCRIBER_PROPERTY table - public static final String PROPERTY_ID = "PROPERTY_ID"; - public static final String DISPLAY_NAME = "DISPLAY_NAME"; - public static final String IS_REQUIRED = "IS_REQUIRED"; - public static final String DISPLAY_ORDER = "DISPLAY_ORDER"; - public static final String IS_SECRET = "IS_SECRET"; - public static final String MODULE = "PROPERTY_MODULE"; - public static final String PROPERTY_VALUE = "PROPERTY_VALUE"; - - // IDN_XACML_POLICY_STATUS and IDN_XACML_SUBSCRIBER_STATUS tables - public static final String STATUS_TYPE = "TYPE"; - public static final String IS_SUCCESS = "IS_SUCCESS"; - public static final String USER = "USERNAME"; - public static final String TARGET = "TARGET"; - public static final String TARGET_ACTION = "TARGET_ACTION"; - public static final String LOGGED_AT = "LOGGED_AT"; - public static final String MESSAGE = "MESSAGE"; - public static final String POLICY_VERSION = "POLICY_VERSION"; - - // IDN_XACML_CONFIG table - public static final String CONFIG_KEY = "CONFIG_KEY"; - public static final String CONFIG_VALUE = "CONFIG_VALUE"; - } - - public static class DatabaseTypes { - - private DatabaseTypes() { - - } - - public static final String MYSQL = "MySQL"; - public static final String MSSQL = "Microsoft SQL Server"; - public static final String ORACLE = "ORACLE"; - public static final String MARIADB = "MariaDB"; - public static final String DB2 = "DB2"; - public static final String H2 = "H2"; - public static final String POSTGRES = "PostgreSQL"; - } - - /** - * SQL queries for XACML policy storage and management. - */ - public static class SQLQueries { - - private SQLQueries() { - - } - - // TODO: revisit all queries using constants like, IN_PAP, IN_PDP, INACTIVE and check if they can be embedded - /** - * DB queries related to PAP policy store. - */ - public static final String CREATE_PAP_POLICY_SQL = "INSERT INTO IDN_XACML_POLICY (POLICY_ID, VERSION, " + - " IS_IN_PDP, IS_IN_PAP, POLICY, IS_ACTIVE, POLICY_TYPE, POLICY_EDITOR, POLICY_ORDER, " + - "LAST_MODIFIED_TIME, LAST_MODIFIED_USER, TENANT_ID) VALUES (:POLICY_ID;, :VERSION;, :IS_IN_PDP;, " + - ":IS_IN_PAP;, :POLICY;, :IS_ACTIVE;, :POLICY_TYPE;, :POLICY_EDITOR;, :POLICY_ORDER;, " + - ":LAST_MODIFIED_TIME;, :LAST_MODIFIED_USER;, :TENANT_ID;)"; - public static final String CREATE_PAP_POLICY_REFS_SQL = "INSERT INTO IDN_XACML_POLICY_REFERENCE " + - "(REFERENCE, POLICY_ID, VERSION, TENANT_ID) VALUES (:REFERENCE;, :POLICY_ID;, :VERSION;, :TENANT_ID;)"; - public static final String CREATE_PAP_POLICY_SET_REFS_SQL = "INSERT INTO IDN_XACML_POLICY_SET_REFERENCE " + - "(SET_REFERENCE, POLICY_ID, VERSION, TENANT_ID) VALUES (:SET_REFERENCE;, :POLICY_ID;, :VERSION;, " + - ":TENANT_ID;)"; - public static final String CREATE_PAP_POLICY_ATTRIBUTES_SQL = "INSERT INTO IDN_XACML_POLICY_ATTRIBUTE " + - "(ATTRIBUTE_ID, ATTRIBUTE_VALUE, DATA_TYPE, CATEGORY, POLICY_ID, VERSION, TENANT_ID) VALUES " + - "(:ATTRIBUTE_ID;, :ATTRIBUTE_VALUE;, :DATA_TYPE;, :CATEGORY;, :POLICY_ID;, :VERSION;, :TENANT_ID;)"; - public static final String CREATE_PAP_POLICY_EDITOR_DATA_SQL = "INSERT INTO IDN_XACML_POLICY_EDITOR_DATA " + - "(DATA_ORDER, DATA, POLICY_ID, VERSION, TENANT_ID) VALUES (:DATA_ORDER;, :DATA;, :POLICY_ID;, " + - ":VERSION;, :TENANT_ID;)"; - public static final String GET_PAP_POLICY_IDS_SQL = "SELECT DISTINCT POLICY_ID FROM IDN_XACML_POLICY WHERE " + - "IS_IN_PAP= :IS_IN_PAP; AND TENANT_ID= :TENANT_ID;"; - public static final String GET_PAP_POLICY_SQL = - "SELECT POLICY_ID, VERSION, LAST_MODIFIED_TIME, LAST_MODIFIED_USER, IS_ACTIVE, POLICY_ORDER, " + - "POLICY_TYPE, POLICY_EDITOR, POLICY, TENANT_ID FROM IDN_XACML_POLICY WHERE " + - "IS_IN_PAP = :IS_IN_PAP; AND POLICY_ID = :POLICY_ID; AND VERSION = (SELECT MAX(VERSION) " + - "FROM IDN_XACML_POLICY WHERE POLICY_ID = :POLICY_ID; AND TENANT_ID= :TENANT_ID;) " + - "AND TENANT_ID = :TENANT_ID;"; - public static final String GET_PAP_POLICY_REFS_SQL = "SELECT REFERENCE FROM IDN_XACML_POLICY_REFERENCE " + - "WHERE POLICY_ID=:POLICY_ID; AND VERSION=:VERSION; AND TENANT_ID=:TENANT_ID;"; - public static final String GET_PAP_POLICY_SET_REFS_SQL = - "SELECT SET_REFERENCE FROM IDN_XACML_POLICY_SET_REFERENCE WHERE " + - "POLICY_ID=:POLICY_ID; AND VERSION=:VERSION; AND TENANT_ID=:TENANT_ID;"; - public static final String GET_PAP_POLICY_EDITOR_DATA_SQL = - "SELECT DATA_ORDER, DATA FROM IDN_XACML_POLICY_EDITOR_DATA WHERE POLICY_ID=:POLICY_ID; AND " + - "VERSION=:VERSION; AND TENANT_ID=:TENANT_ID;"; - public static final String GET_PAP_POLICY_META_DATA_SQL = "SELECT ATTRIBUTE_ID, ATTRIBUTE_VALUE, DATA_TYPE, " + - "CATEGORY FROM IDN_XACML_POLICY_ATTRIBUTE WHERE POLICY_ID=:POLICY_ID; AND VERSION=:VERSION; " + - "AND TENANT_ID=:TENANT_ID;"; - public static final String GET_PAP_POLICY_BY_VERSION_SQL = "SELECT POLICY_ID, LAST_MODIFIED_TIME, " + - "LAST_MODIFIED_USER, IS_ACTIVE, POLICY_ORDER, POLICY_TYPE, POLICY_EDITOR, POLICY, VERSION, TENANT_ID " + - "FROM IDN_XACML_POLICY WHERE IS_IN_PAP = :IS_IN_PAP; AND POLICY_ID = :POLICY_ID; AND " + - "VERSION = :VERSION; AND TENANT_ID = :TENANT_ID;"; - public static final String GET_ALL_PAP_POLICIES_SQL = "SELECT t1.POLICY_ID, t1.VERSION, t1" + - ".LAST_MODIFIED_TIME, t1.LAST_MODIFIED_USER, t1.IS_ACTIVE, t1.POLICY_ORDER, t1.POLICY_TYPE, " + - "t1.POLICY_EDITOR, t1.POLICY, t1.TENANT_ID FROM IDN_XACML_POLICY t1 WHERE t1.IS_IN_PAP = :IS_IN_PAP; " + - "AND t1.VERSION =(SELECT MAX(VERSION) FROM IDN_XACML_POLICY t2 WHERE " + - "t2.POLICY_ID = t1.POLICY_ID AND t2.TENANT_ID = :TENANT_ID;) AND t1.TENANT_ID = :TENANT_ID;"; - public static final String DELETE_PAP_POLICY_SQL = "UPDATE IDN_XACML_POLICY SET IS_IN_PAP=:IS_IN_PAP; " + - "WHERE IS_IN_PDP=:IS_IN_PDP; AND POLICY_ID=:POLICY_ID; AND TENANT_ID=:TENANT_ID;"; - public static final String DELETE_PAP_POLICY_BY_VERSION_SQL = - "UPDATE IDN_XACML_POLICY SET IS_IN_PAP=:IS_IN_PAP; " + - "WHERE POLICY_ID=:POLICY_ID; AND VERSION=:VERSION; AND TENANT_ID=:TENANT_ID;"; - public static final String DELETE_UNPUBLISHED_POLICY_VERSIONS_SQL = "DELETE FROM IDN_XACML_POLICY " + - "WHERE IS_IN_PDP=:IS_IN_PDP; AND POLICY_ID=:POLICY_ID; AND TENANT_ID=:TENANT_ID;"; - public static final String DELETE_POLICY_SQL = - "DELETE FROM IDN_XACML_POLICY WHERE POLICY_ID=:POLICY_ID; AND TENANT_ID=:TENANT_ID;"; - public static final String DELETE_POLICY_VERSION_SQL = - "DELETE FROM IDN_XACML_POLICY WHERE POLICY_ID=:POLICY_ID; " + - "AND VERSION=:VERSION; AND TENANT_ID=:TENANT_ID;"; - - /** - * DB queries related to PDP policy store. - */ - public static final String CREATE_POLICY_COMBINING_ALGORITHM_SQL = "INSERT INTO IDN_XACML_CONFIG " + - "(CONFIG_KEY, CONFIG_VALUE, TENANT_ID) VALUES (:CONFIG_KEY;, :CONFIG_VALUE;, :TENANT_ID;)"; - public static final String GET_POLICY_PDP_PRESENCE_SQL = "SELECT POLICY_ID FROM IDN_XACML_POLICY WHERE " + - "IS_IN_PDP=:IS_IN_PDP; AND POLICY_ID=:POLICY_ID; AND TENANT_ID=:TENANT_ID;"; - public static final String GET_POLICY_PAP_PRESENCE_SQL = "SELECT POLICY_ID FROM IDN_XACML_POLICY WHERE " + - "IS_IN_PAP=:IS_IN_PAP; AND POLICY_ID=:POLICY_ID; AND TENANT_ID=:TENANT_ID;"; - public static final String GET_PDP_POLICY_SQL = - "SELECT POLICY, POLICY_ORDER, IS_ACTIVE, VERSION FROM IDN_XACML_POLICY WHERE IS_IN_PDP=:IS_IN_PDP; " + - "AND POLICY_ID=:POLICY_ID; AND TENANT_ID=:TENANT_ID;"; - public static final String GET_POLICY_PDP_PRESENCE_BY_VERSION_SQL = "SELECT POLICY_ID FROM IDN_XACML_POLICY " + - "WHERE IS_IN_PDP=:IS_IN_PDP; AND POLICY_ID=:POLICY_ID; AND VERSION=:VERSION; AND TENANT_ID=:TENANT_ID;"; - public static final String GET_ALL_PDP_POLICIES_SQL = "SELECT POLICY_ID, POLICY, POLICY_ORDER, IS_ACTIVE, " + - "VERSION FROM IDN_XACML_POLICY WHERE IS_IN_PDP=:IS_IN_PDP; AND TENANT_ID=:TENANT_ID;"; - public static final String GET_PDP_POLICY_IDS_SQL = "SELECT DISTINCT POLICY_ID FROM IDN_XACML_POLICY WHERE " + - "IS_IN_PDP=:IS_IN_PDP; AND TENANT_ID=:TENANT_ID;"; - public static final String GET_PUBLISHED_POLICY_VERSION_SQL = "SELECT VERSION FROM IDN_XACML_POLICY WHERE " + - "IS_IN_PDP=:IS_IN_PDP; AND POLICY_ID=:POLICY_ID; AND TENANT_ID=:TENANT_ID;"; - public static final String GET_ACTIVE_STATUS_AND_ORDER_SQL = "SELECT IS_ACTIVE, POLICY_ORDER FROM " + - "IDN_XACML_POLICY WHERE IS_IN_PDP=:IS_IN_PDP; AND POLICY_ID=:POLICY_ID; AND TENANT_ID=:TENANT_ID;"; - public static final String GET_POLICY_COMBINING_ALGORITHM_SQL = - "SELECT CONFIG_VALUE FROM IDN_XACML_CONFIG WHERE CONFIG_KEY=:CONFIG_KEY; AND TENANT_ID=:TENANT_ID;"; - public static final String UPDATE_ACTIVE_STATUS_SQL = - "UPDATE IDN_XACML_POLICY SET IS_ACTIVE=:IS_ACTIVE; WHERE POLICY_ID=:POLICY_ID; AND " + - "VERSION=:VERSION; AND TENANT_ID=:TENANT_ID;"; - public static final String UPDATE_ORDER_SQL = "UPDATE IDN_XACML_POLICY SET POLICY_ORDER=:POLICY_ORDER; WHERE " + - "POLICY_ID=:POLICY_ID; AND VERSION=:VERSION; AND TENANT_ID=:TENANT_ID;"; - public static final String DELETE_PUBLISHED_VERSIONS_SQL = - "UPDATE IDN_XACML_POLICY SET IS_IN_PDP=:IS_IN_PDP;, IS_ACTIVE=:IS_ACTIVE;, POLICY_ORDER=:POLICY_ORDER;" + - " WHERE IS_IN_PDP=:IS_IN_PDP_1; AND POLICY_ID=:POLICY_ID; AND TENANT_ID=:TENANT_ID;"; - public static final String PUBLISH_POLICY_VERSION_SQL = - "UPDATE IDN_XACML_POLICY SET IS_IN_PDP=:IS_IN_PDP; WHERE POLICY_ID=:POLICY_ID; " + - "AND VERSION=:VERSION; AND TENANT_ID=:TENANT_ID;"; - public static final String RESTORE_ACTIVE_STATUS_AND_ORDER_SQL = "UPDATE IDN_XACML_POLICY SET " + - "IS_ACTIVE=:IS_ACTIVE;, POLICY_ORDER=:POLICY_ORDER; WHERE POLICY_ID=:POLICY_ID; AND " + - "VERSION=:VERSION; AND TENANT_ID=:TENANT_ID;"; - public static final String UPDATE_POLICY_COMBINING_ALGORITHM_SQL = "UPDATE IDN_XACML_CONFIG SET " + - "CONFIG_VALUE=:CONFIG_VALUE; WHERE CONFIG_KEY=:CONFIG_KEY; AND TENANT_ID=:TENANT_ID;"; - public static final String DELETE_UNUSED_POLICY_SQL = - "DELETE FROM IDN_XACML_POLICY WHERE IS_IN_PAP=:IS_IN_PAP; AND IS_IN_PDP=:IS_IN_PDP; AND " + - "POLICY_ID=:POLICY_ID; AND TENANT_ID=:TENANT_ID; "; - - /** - * DB queries related to subscribers. - */ - public static final String CREATE_SUBSCRIBER_SQL = - "INSERT INTO IDN_XACML_SUBSCRIBER (SUBSCRIBER_ID, ENTITLEMENT_MODULE_NAME, TENANT_ID) VALUES " + - "(:SUBSCRIBER_ID;, :ENTITLEMENT_MODULE_NAME;, :TENANT_ID;)"; - public static final String CREATE_SUBSCRIBER_PROPERTIES_SQL = "INSERT INTO IDN_XACML_SUBSCRIBER_PROPERTY " + - "(PROPERTY_ID, DISPLAY_NAME, PROPERTY_VALUE, IS_REQUIRED, DISPLAY_ORDER, IS_SECRET, " + - "PROPERTY_MODULE, SUBSCRIBER_ID, TENANT_ID) VALUES (:PROPERTY_ID;, :DISPLAY_NAME;, :PROPERTY_VALUE;, " + - ":IS_REQUIRED;, :DISPLAY_ORDER;, :IS_SECRET;, :PROPERTY_MODULE;, :SUBSCRIBER_ID;, :TENANT_ID;)"; - public static final String GET_SUBSCRIBER_EXISTENCE_SQL = "SELECT SUBSCRIBER_ID FROM IDN_XACML_SUBSCRIBER " + - "WHERE SUBSCRIBER_ID=:SUBSCRIBER_ID; AND TENANT_ID=:TENANT_ID;"; - public static final String GET_SUBSCRIBER_SQL = "SELECT s.SUBSCRIBER_ID, s.ENTITLEMENT_MODULE_NAME, s.TENANT_ID, " + - "p.PROPERTY_ID, p.DISPLAY_NAME, p.PROPERTY_VALUE, p.IS_REQUIRED, p.DISPLAY_ORDER, p.IS_SECRET, " + - "p.PROPERTY_MODULE FROM IDN_XACML_SUBSCRIBER s INNER JOIN " + - "IDN_XACML_SUBSCRIBER_PROPERTY p ON s.SUBSCRIBER_ID = p.SUBSCRIBER_ID AND s.TENANT_ID = p.TENANT_ID " + - "WHERE s.SUBSCRIBER_ID = :SUBSCRIBER_ID; AND s.TENANT_ID = :TENANT_ID;"; - public static final String GET_SUBSCRIBER_IDS_SQL = "SELECT SUBSCRIBER_ID FROM IDN_XACML_SUBSCRIBER " + - "WHERE TENANT_ID=:TENANT_ID;"; - public static final String UPDATE_SUBSCRIBER_MODULE_SQL = "UPDATE IDN_XACML_SUBSCRIBER " + - "SET ENTITLEMENT_MODULE_NAME=:ENTITLEMENT_MODULE_NAME; WHERE " + - "SUBSCRIBER_ID=:SUBSCRIBER_ID; AND TENANT_ID=:TENANT_ID;"; - public static final String UPDATE_SUBSCRIBER_PROPERTIES_SQL = "UPDATE IDN_XACML_SUBSCRIBER_PROPERTY SET " + - "PROPERTY_VALUE=:PROPERTY_VALUE; WHERE PROPERTY_ID=:PROPERTY_ID; AND SUBSCRIBER_ID=:SUBSCRIBER_ID; AND " + - "TENANT_ID=:TENANT_ID;"; - public static final String DELETE_SUBSCRIBER_SQL = "DELETE FROM IDN_XACML_SUBSCRIBER WHERE " + - "SUBSCRIBER_ID=:SUBSCRIBER_ID; AND TENANT_ID=:TENANT_ID;"; - - /** - * DB queries related to status. - */ - public static final String CREATE_POLICY_STATUS_SQL = "INSERT INTO IDN_XACML_POLICY_STATUS (TYPE, IS_SUCCESS, " + - "USERNAME, TARGET, TARGET_ACTION, LOGGED_AT, MESSAGE, POLICY_ID, POLICY_VERSION, TENANT_ID) " + - "VALUES (:TYPE;, :IS_SUCCESS;, :USERNAME;, :TARGET;, :TARGET_ACTION;, :LOGGED_AT;, :MESSAGE;, " + - ":KEY;, :VERSION;, :TENANT_ID;)"; - public static final String CREATE_SUBSCRIBER_STATUS_SQL = "INSERT INTO IDN_XACML_SUBSCRIBER_STATUS " + - "(TYPE, IS_SUCCESS, USERNAME, TARGET, TARGET_ACTION, LOGGED_AT, MESSAGE, SUBSCRIBER_ID, " + - "TENANT_ID) VALUES (:TYPE;, :IS_SUCCESS;, :USERNAME;, :TARGET;, :TARGET_ACTION;, :LOGGED_AT;, " + - ":MESSAGE;, :KEY;, :TENANT_ID;)"; - public static final String GET_POLICY_STATUS_SQL = "SELECT POLICY_ID, TYPE, IS_SUCCESS, USERNAME, TARGET, " + - "TARGET_ACTION, LOGGED_AT, MESSAGE, POLICY_VERSION FROM IDN_XACML_POLICY_STATUS WHERE POLICY_ID=:KEY; " + - "AND TENANT_ID=:TENANT_ID;"; - public static final String GET_SUBSCRIBER_STATUS_SQL = - "SELECT SUBSCRIBER_ID, TYPE, IS_SUCCESS, USERNAME, TARGET, TARGET_ACTION, LOGGED_AT, MESSAGE FROM " + - "IDN_XACML_SUBSCRIBER_STATUS WHERE SUBSCRIBER_ID=:KEY; AND TENANT_ID=:TENANT_ID;"; - public static final String GET_POLICY_STATUS_COUNT_SQL = - "SELECT COUNT(POLICY_ID) AS COUNT FROM IDN_XACML_POLICY_STATUS WHERE POLICY_ID=:KEY; AND " + - "TENANT_ID=:TENANT_ID;"; - public static final String GET_SUBSCRIBER_STATUS_COUNT_SQL = "SELECT COUNT(SUBSCRIBER_ID) AS COUNT FROM " + - "IDN_XACML_SUBSCRIBER_STATUS WHERE SUBSCRIBER_ID=:KEY; AND TENANT_ID=:TENANT_ID;"; - public static final String DELETE_POLICY_STATUS_SQL = "DELETE FROM IDN_XACML_POLICY_STATUS WHERE POLICY_ID=:KEY; " + - "AND TENANT_ID=:TENANT_ID;"; - public static final String DELETE_SUBSCRIBER_STATUS_SQL = "DELETE FROM IDN_XACML_SUBSCRIBER_STATUS WHERE " + - "SUBSCRIBER_ID=:KEY; AND TENANT_ID=:TENANT_ID;"; - public static final String DELETE_OLD_POLICY_STATUSES_MYSQL = "DELETE FROM IDN_XACML_POLICY_STATUS WHERE " + - "ID IN (SELECT ID FROM IDN_XACML_POLICY_STATUS WHERE POLICY_ID= :KEY; AND " + - "TENANT_ID= :TENANT_ID; ORDER BY LOGGED_AT ASC, ID ASC LIMIT :LIMIT;)"; - public static final String DELETE_OLD_SUBSCRIBER_STATUSES_MYSQL = - "DELETE FROM IDN_XACML_SUBSCRIBER_STATUS WHERE ID " + - "IN (SELECT ID FROM IDN_XACML_SUBSCRIBER_STATUS WHERE SUBSCRIBER_ID= :KEY; AND " + - "TENANT_ID= :TENANT_ID; ORDER BY LOGGED_AT ASC, ID ASC LIMIT :LIMIT;)"; - public static final String DELETE_OLD_POLICY_STATUSES_MSSQL = - "DELETE FROM IDN_XACML_POLICY_STATUS WHERE ID IN (SELECT ID FROM IDN_XACML_POLICY_STATUS WHERE " + - "POLICY_ID = :KEY; AND TENANT_ID = :TENANT_ID; ORDER BY LOGGED_AT ASC, ID ASC OFFSET 0 ROWS " + - "FETCH NEXT :LIMIT; ROWS ONLY)"; - public static final String DELETE_OLD_SUBSCRIBER_STATUSES_MSSQL = - "DELETE FROM IDN_XACML_SUBSCRIBER_STATUS WHERE ID IN (SELECT ID FROM IDN_XACML_SUBSCRIBER_STATUS WHERE " + - "SUBSCRIBER_ID= :KEY; AND TENANT_ID=:TENANT_ID; ORDER BY LOGGED_AT ASC, ID ASC OFFSET 0 " + - "ROWS FETCH NEXT :LIMIT; ROWS ONLY)"; - public static final String DELETE_OLD_POLICY_STATUSES_ORACLE = - "DELETE FROM IDN_XACML_POLICY_STATUS WHERE ID IN" + - " (SELECT ID FROM (SELECT ID FROM IDN_XACML_POLICY_STATUS WHERE POLICY_ID= :KEY; AND" + - " TENANT_ID=:TENANT_ID; ORDER BY LOGGED_AT ASC, ID ASC) WHERE ROWNUM <= :LIMIT;)"; - public static final String DELETE_OLD_SUBSCRIBER_STATUSES_ORACLE = - "DELETE FROM IDN_XACML_SUBSCRIBER_STATUS WHERE ID " + - "IN (SELECT ID FROM (SELECT ID FROM IDN_XACML_SUBSCRIBER_STATUS WHERE SUBSCRIBER_ID= :KEY; " + - "AND TENANT_ID=:TENANT_ID; ORDER BY LOGGED_AT ASC, ID ASC) WHERE ROWNUM <= :LIMIT;)"; - - /** - * DB queries related to policy version management. - */ - public static final String GET_LATEST_POLICY_VERSION_SQL = - "SELECT MAX(VERSION) AS VERSION FROM IDN_XACML_POLICY " + - "WHERE IS_IN_PAP=:IS_IN_PAP; AND POLICY_ID=:POLICY_ID; AND TENANT_ID=:TENANT_ID;"; - public static final String GET_POLICY_VERSIONS_SQL = "SELECT VERSION FROM IDN_XACML_POLICY WHERE " + - "IS_IN_PAP=:IS_IN_PAP; AND POLICY_ID=:POLICY_ID; AND TENANT_ID=:TENANT_ID;"; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/PersistenceManagerFactory.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/PersistenceManagerFactory.java deleted file mode 100644 index 6d42169b43e2..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/PersistenceManagerFactory.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.apache.commons.lang.StringUtils; -import org.wso2.carbon.identity.core.util.IdentityUtil; -import org.wso2.carbon.identity.entitlement.PAPStatusDataHandler; -import org.wso2.carbon.identity.entitlement.SimplePAPStatusDataHandler; - -import static org.wso2.carbon.identity.entitlement.PDPConstants.POLICY_STORAGE_CONFIG; - -public class PersistenceManagerFactory { - - private static String POLICY_STORAGE_TYPE = IdentityUtil.getProperty(POLICY_STORAGE_CONFIG); - private static final String HYBRID = "hybrid"; - private static final String REGISTRY = "registry"; - - private PersistenceManagerFactory() { - - } - - public static PolicyPersistenceManager getPolicyPersistenceManager() { - - PolicyPersistenceManager defaultPolicyPersistenceManager = new JDBCPolicyPersistenceManager(); - if (StringUtils.isNotBlank(POLICY_STORAGE_TYPE)) { - switch (POLICY_STORAGE_TYPE) { - case HYBRID: - return new HybridPolicyPersistenceManager(); - case REGISTRY: - return new RegistryPolicyPersistenceManager(); - default: - return defaultPolicyPersistenceManager; - } - } - return defaultPolicyPersistenceManager; - } - - public static ConfigPersistenceManager getConfigPersistenceManager() { - - ConfigPersistenceManager defaultConfigPersistenceManager = new JDBCConfigPersistenceManager(); - if (StringUtils.isNotBlank(POLICY_STORAGE_TYPE)) { - switch (POLICY_STORAGE_TYPE) { - case HYBRID: - return new HybridConfigPersistenceManager(); - case REGISTRY: - return new RegistryConfigPersistenceManager(); - default: - return defaultConfigPersistenceManager; - } - } - return defaultConfigPersistenceManager; - } - - public static SubscriberPersistenceManager getSubscriberPersistenceManager() { - - SubscriberPersistenceManager defaultSubscriberPersistenceManager = new JDBCSubscriberPersistenceManager(); - if (StringUtils.isNotBlank(POLICY_STORAGE_TYPE)) { - switch (POLICY_STORAGE_TYPE) { - case HYBRID: - return new HybridSubscriberPersistenceManager(); - case REGISTRY: - return new RegistrySubscriberPersistenceManager(); - default: - return defaultSubscriberPersistenceManager; - } - } - return defaultSubscriberPersistenceManager; - } - - public static PAPStatusDataHandler getPAPStatusDataHandler() { - - PAPStatusDataHandler defaultPAPStatusDataHandler = new JDBCSimplePAPStatusDataHandler(); - if (StringUtils.isNotBlank(POLICY_STORAGE_TYPE)) { - switch (POLICY_STORAGE_TYPE) { - case HYBRID: - return new HybridPAPStatusDataHandler(); - case REGISTRY: - return new SimplePAPStatusDataHandler(); - default: - return defaultPAPStatusDataHandler; - } - } - return defaultPAPStatusDataHandler; - } -} - diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/PolicyPersistenceManager.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/PolicyPersistenceManager.java deleted file mode 100644 index 4a5b9026bc86..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/PolicyPersistenceManager.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.dto.PolicyDTO; -import org.wso2.carbon.identity.entitlement.dto.PolicyStoreDTO; -import org.wso2.carbon.identity.entitlement.policy.store.PolicyStoreManageModule; - -import java.util.List; - -/** - * This interface supports the management of XACML policies. - */ -public interface PolicyPersistenceManager extends PolicyStoreManageModule { - - /** - * Adds or updates the given policy. - * - * @param policy policy - * @param isFromPapAction true if the operation originated from a PAP action, false if it is from a PDP action. - * @throws EntitlementException If an error occurs - */ - void addOrUpdatePolicy(PolicyDTO policy, boolean isFromPapAction) throws EntitlementException; - - /** - * Gets the requested policy. - * - * @param policyId policy ID - * @return policyDTO - * @throws EntitlementException If an error occurs - */ - PolicyDTO getPAPPolicy(String policyId) throws EntitlementException; - - /** - * Gets the requested policy list. - * - * @param policyIds policy ID list - * @return policyDTO - * @throws EntitlementException If an error occurs - */ - List getPAPPolicies(List policyIds) throws EntitlementException; - - /** - * Gets the requested policy version. - * - * @param policyId policy ID - * @param version policy version - * @return requested policy - * @throws EntitlementException If an error occurs - */ - PolicyDTO getPolicy(String policyId, String version) throws EntitlementException; - - /** - * Gets all versions of the given policy ID. - * - * @param policyId policy ID - * @return array of policy versions - */ - String[] getVersions(String policyId); - - /** - * Lists all PAP policy IDs. - * - * @return list of policy IDs - * @throws EntitlementException If an error occurs - */ - List listPolicyIds() throws EntitlementException; - - /** - * Removes the given policy. - * - * @param policyId policy ID - * @throws EntitlementException If an error occurs - */ - void removePolicy(String policyId) throws EntitlementException; - - /** - * Gets the requested published policy. - * - * @param policyId policy ID - * @return requested policy - */ - PolicyStoreDTO getPublishedPolicy(String policyId); - - /** - * Lists all published policy IDs. - * - * @return list of published policy IDs - * @throws EntitlementException If an error occurs - */ - List listPublishedPolicyIds() throws EntitlementException; -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/RegistryConfigPersistenceManager.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/RegistryConfigPersistenceManager.java deleted file mode 100644 index 0884d07bceb2..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/RegistryConfigPersistenceManager.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.PDPConstants; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; -import org.wso2.carbon.registry.core.Collection; -import org.wso2.carbon.registry.core.Registry; -import org.wso2.carbon.registry.core.exceptions.RegistryException; - -import static org.wso2.carbon.identity.entitlement.PDPConstants.GLOBAL_POLICY_COMBINING_ALGORITHM; - -/** - * This implementation handles the Global Policy Combining Algorithm management in the Registry. - */ -public class RegistryConfigPersistenceManager implements ConfigPersistenceManager { - - // The logger that is used for all messages - private static final Log LOG = LogFactory.getLog(RegistryConfigPersistenceManager.class); - private static final String POLICY_DATA_COLLECTION = PDPConstants.ENTITLEMENT_POLICY_DATA; - private final Registry registry; - - public RegistryConfigPersistenceManager() { - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - registry = EntitlementServiceComponent.getGovernanceRegistry(tenantId); - } - - /** - * Sets the global policy combining algorithm. - * - * @param policyCombiningAlgorithm policy combining algorithm name. - * @return true if the policy combining algorithm is updated, false if the policy combining algorithm is added. - * @throws EntitlementException If an error occurs. - */ - @Override - public void addOrUpdateGlobalPolicyAlgorithm(String policyCombiningAlgorithm) throws EntitlementException { - - try { - Collection policyCollection; - if (registry.resourceExists(POLICY_DATA_COLLECTION)) { - policyCollection = (Collection) registry.get(POLICY_DATA_COLLECTION); - } else { - policyCollection = registry.newCollection(); - } - policyCollection.setProperty(GLOBAL_POLICY_COMBINING_ALGORITHM, policyCombiningAlgorithm); - registry.put(POLICY_DATA_COLLECTION, policyCollection); - } catch (RegistryException e) { - throw new EntitlementException("Error while updating global policy combining algorithm in policy store", e); - } - } - - /** - * Gets the policy combining algorithm name. - * - * @return global policy combining algorithm name - */ - @Override - public String getGlobalPolicyAlgorithmName() { - - String algorithm = getGlobalPolicyAlgorithmValue(); - - // set default - if (algorithm == null) { - algorithm = PDPConstants.Algorithms.DENY_OVERRIDES; - } - - return algorithm; - } - - private String getGlobalPolicyAlgorithmValue() { - - String algorithm = null; - try { - if (registry.resourceExists(POLICY_DATA_COLLECTION)) { - Collection collection = (Collection) registry.get(POLICY_DATA_COLLECTION); - algorithm = collection.getProperty(GLOBAL_POLICY_COMBINING_ALGORITHM); - } - } catch (RegistryException e) { - if (LOG.isDebugEnabled()) { - LOG.debug(e); - } - } - return algorithm; - } - - /** - * Deletes the global policy combining algorithm. - * - * @throws EntitlementException If an error occurs - */ - public void deleteGlobalPolicyAlgorithm() throws EntitlementException { - - try { - if (registry.resourceExists(POLICY_DATA_COLLECTION)) { - registry.delete(POLICY_DATA_COLLECTION); - } - } catch (RegistryException e) { - throw new EntitlementException("Error while deleting global policy combining algorithm in policy store", e); - } - } - - boolean isGlobalPolicyAlgorithmExist() { - - return getGlobalPolicyAlgorithmValue() != null; - - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/RegistryPolicyPersistenceManager.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/RegistryPolicyPersistenceManager.java deleted file mode 100644 index d6f15b17b607..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/RegistryPolicyPersistenceManager.java +++ /dev/null @@ -1,1245 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.apache.axiom.om.OMElement; -import org.apache.axiom.om.util.AXIOMUtil; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.balana.AbstractPolicy; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.EntitlementUtil; -import org.wso2.carbon.identity.entitlement.PDPConstants; -import org.wso2.carbon.identity.entitlement.PolicyOrderComparator; -import org.wso2.carbon.identity.entitlement.dto.AttributeDTO; -import org.wso2.carbon.identity.entitlement.dto.PolicyDTO; -import org.wso2.carbon.identity.entitlement.dto.PolicyStoreDTO; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; -import org.wso2.carbon.identity.entitlement.pap.PAPPolicyReader; -import org.wso2.carbon.identity.entitlement.policy.PolicyAttributeBuilder; -import org.wso2.carbon.identity.entitlement.policy.finder.AbstractPolicyFinderModule; -import org.wso2.carbon.identity.entitlement.policy.finder.PolicyFinderModule; -import org.wso2.carbon.registry.core.Collection; -import org.wso2.carbon.registry.core.Registry; -import org.wso2.carbon.registry.core.RegistryConstants; -import org.wso2.carbon.registry.core.Resource; -import org.wso2.carbon.registry.core.exceptions.RegistryException; -import org.wso2.carbon.registry.core.exceptions.ResourceNotFoundException; -import org.wso2.carbon.registry.core.utils.RegistryUtils; - -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Date; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Properties; -import java.util.Set; - -import javax.xml.stream.XMLStreamException; - -import static org.wso2.carbon.identity.entitlement.PDPConstants.MODULE_NAME; - -/** - * This implementation handles the XACML policy management in the Registry. - */ -public class RegistryPolicyPersistenceManager extends AbstractPolicyFinderModule implements PolicyPersistenceManager { - - // The logger that is used for all messages - private static final Log LOG = LogFactory.getLog(RegistryPolicyPersistenceManager.class); - private static final String KEY_VALUE_POLICY_META_DATA = "policyMetaData"; - private static final String POLICY_STORE_PATH = "policyStorePath"; - private static final String DEFAULT_POLICY_STORE_PATH = "/repository/identity/entitlement/policy/pdp/"; - private static final String INVALID_POLICY_VERSION = "Invalid policy version"; - private static final String ERROR_RETRIEVING_POLICIES_FROM_POLICY_FINDER = - "Policies can not be retrieved from registry policy finder module"; - private static final String INVALID_ENTITLEMENT_POLICY = "Trying to access an entitlement policy %s which does " + - "not exist"; - private static final String ERROR_PUBLISHING_POLICY = "Error while publishing policy"; - private String policyStorePath; - private final int maxVersions; - - public RegistryPolicyPersistenceManager() { - - maxVersions = EntitlementUtil.getMaxNoOfPolicyVersions(); - } - - @Override - public void init(Properties properties) { - - policyStorePath = properties.getProperty(POLICY_STORE_PATH); - if (policyStorePath == null) { - policyStorePath = DEFAULT_POLICY_STORE_PATH; - } - } - - /** - * Adds or updates the given PAP policy. - * - * @param policy policy. - * @param isFromPapAction true if the operation originated from a PAP action, false if it is from a PDP action. - * @throws EntitlementException If an error occurs - */ - @Override - public void addOrUpdatePolicy(PolicyDTO policy, boolean isFromPapAction) throws EntitlementException { - - if (isFromPapAction) { - String version = createVersion(policy); - policy.setVersion(version); - addOrUpdatePAPPolicy(policy, policy.getVersion(), PDPConstants.ENTITLEMENT_POLICY_VERSION + - policy.getPolicyId() + RegistryConstants.PATH_SEPARATOR); - } - addOrUpdatePAPPolicy(policy, policy.getPolicyId(), PDPConstants.ENTITLEMENT_POLICY_PAP); - } - - /** - * Gets the requested policy. - * - * @param policyId policy ID - * @return policyDTO - * @throws EntitlementException If an error occurs - */ - @Override - public PolicyDTO getPAPPolicy(String policyId) throws EntitlementException { - - String path = PDPConstants.ENTITLEMENT_POLICY_PAP + policyId; - return getPolicyDTO(policyId, path); - } - - /** - * Gets the requested policy list. - * - * @param policyIds policy ID list - * @return policyDTO - * @throws EntitlementException If an error occurs - */ - @Override - public List getPAPPolicies(List policyIds) throws EntitlementException { - - if (policyIds == null || policyIds.isEmpty()) { - return new ArrayList<>(); - } - List policyDTOs = new ArrayList<>(); - for (String policyId : policyIds) { - policyDTOs.add(getPAPPolicy(policyId)); - } - return policyDTOs; - } - - /** - * Gets the requested policy version. - * - * @param policyId policy ID - * @param version policy version - * @return policyDTO - * @throws EntitlementException If an error occurs - */ - @Override - public PolicyDTO getPolicy(String policyId, String version) throws EntitlementException { - - // Zero indicates the current version - if (version == null || version.trim().isEmpty()) { - try { - Registry registry = getRegistry(); - Collection collection = (Collection) registry.get(PDPConstants.ENTITLEMENT_POLICY_VERSION + policyId); - if (collection != null) { - version = collection.getProperty(PDPConstants.POLICY_VERSION); - } - } catch (RegistryException e) { - throw new EntitlementException(INVALID_POLICY_VERSION, e); - } - } - - String collection = PDPConstants.ENTITLEMENT_POLICY_VERSION + policyId + RegistryConstants.PATH_SEPARATOR; - String path = collection + version; - PolicyDTO dto = getPolicyDTO(policyId, path); - - if (dto == null) { - throw new EntitlementException(INVALID_POLICY_VERSION); - } - return dto; - } - - /** - * Gets all versions of the given policy ID. - * - * @param policyId policy ID - * @return array of policy versions - */ - @Override - public String[] getVersions(String policyId) { - - List versions = new ArrayList<>(); - Collection collection = null; - try { - try { - Registry registry = getRegistry(); - collection = (Collection) registry.get(PDPConstants.ENTITLEMENT_POLICY_VERSION + policyId); - } catch (ResourceNotFoundException e) { - // ignore - } - if (collection != null && collection.getChildren() != null) { - String[] children = collection.getChildren(); - for (String child : children) { - versions.add(RegistryUtils.getResourceName(child)); - } - } - } catch (RegistryException e) { - LOG.error(String.format("Error while retrieving policy versions for policy %s", policyId), e); - } - return versions.toArray(new String[0]); - - } - - /** - * Gets the name of the module. - * - * @return name as String - */ - @Override - public String getModuleName() { - - return MODULE_NAME; - } - - /** - * Gets the policy for the given policy ID. - * - * @param policyId policy id as a string value - * @return policy as string - */ - @Override - public String getPolicy(String policyId) { - - PolicyStoreDTO dto = getPublishedPolicy(policyId); - return dto.getPolicy(); - } - - /** - * Gets the policy order. - * - * @param policyId policy id as a string value - * @return policy order - */ - @Override - public int getPolicyOrder(String policyId) { - - PolicyStoreDTO dto = getPublishedPolicy(policyId); - return dto.getPolicyOrder(); - } - - /** - * Gets all supported active policies. - * If policy ordering is supported by the module itself, these policies must be ordered. - * - * @return array of policies as Strings - */ - @Override - public String[] getActivePolicies() { - - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Retrieving of Active policies are started at %s", new Date())); - } - - List policies = new ArrayList<>(); - - try { - PolicyStoreDTO[] policyDTOs = getAllPolicies(true, true); - for (PolicyStoreDTO dto : policyDTOs) { - if (dto.getPolicy() != null) { - policies.add(dto.getPolicy()); - } - } - } catch (EntitlementException e) { - LOG.error(ERROR_RETRIEVING_POLICIES_FROM_POLICY_FINDER, e); - } - - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Retrieving of Active policies are finished at %s", new Date())); - } - - return policies.toArray(new String[0]); - } - - /** - * Gets all supported policy ids. - * If policy ordering is supported by the module itself, these policy ids must be ordered. - * - * @return array of policy ids as Strings - */ - @Override - public String[] getOrderedPolicyIdentifiers() { - - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Retrieving of Order Policy Ids are started at %s ", new Date())); - } - - List policies = new ArrayList<>(); - - try { - PolicyStoreDTO[] policyDTOs = getAllPolicies(false, true); - for (PolicyStoreDTO dto : policyDTOs) { - if (dto.getPolicy() != null) { - policies.add(dto.getPolicyId()); - } - } - } catch (EntitlementException e) { - LOG.error(ERROR_RETRIEVING_POLICIES_FROM_POLICY_FINDER, e); - } - - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Retrieving of Order Policy Ids are finished at %s ", new Date())); - } - - return policies.toArray(new String[0]); - - } - - /** - * Gets all policy ids. - * - * @return array of policy ids as Strings - */ - @Override - public String[] getPolicyIdentifiers() { - - String[] policyIds = null; - try { - policyIds = listPublishedPolicyIds().toArray(new String[0]); - } catch (EntitlementException e) { - LOG.error("Policy identifiers can not be retrieved from registry policy finder module", e); - } - return policyIds; - } - - /** - * Gets reference policy for the given policy ID. - * Reference policy can not be with PDP policy store, may be in some external policy store. - * Therefore, a new method has been added to retrieve reference policies. - * - * @param policyId policy id as String value - * @return reference policy as String - */ - @Override - public String getReferencedPolicy(String policyId) { - - // Retrieves for policies that are not active - PolicyStoreDTO dto = getPublishedPolicy(policyId); - if (dto != null && dto.getPolicy() != null && !dto.isActive()) { - return dto.getPolicy(); - } - - return null; - } - - /** - * Gets attributes that are used for policy searching. - * - * @param identifier unique identifier to separate out search attributes - * @param givenAttribute pre-given attributes to retrieve other attributes - * @return return search attributes based on a given policy, Map of policy id with search attributes. - */ - @Override - public Map> getSearchAttributes(String identifier, Set givenAttribute) { - - try { - PolicyStoreDTO[] policyDTOs = getAllPolicies(true, true); - List policyIds = new ArrayList<>(); - for (PolicyStoreDTO policyStoreDTO : policyDTOs) { - policyIds.add(policyStoreDTO.getPolicyId()); - } - List policyDTOList = getPAPPolicies(policyIds); - if (policyDTOs.length > 0) { - return EntitlementUtil.getAttributesFromPolicies(policyDTOList.toArray(new PolicyDTO[0])); - } - } catch (EntitlementException e) { - LOG.error(ERROR_RETRIEVING_POLICIES_FROM_POLICY_FINDER, e); - } - - return Collections.emptyMap(); - } - - /** - * Gets support attribute searching scheme of the module. - * - * @return return scheme identifier value - */ - @Override - public int getSupportedSearchAttributesScheme() { - - return PolicyFinderModule.COMBINATIONS_BY_CATEGORY_AND_PARAMETER; - } - - /** - * Lists all PAP policy IDs. - * - * @return list of policy IDs - * @throws EntitlementException If an error occurs - */ - @Override - public List listPolicyIds() throws EntitlementException { - - String path = PDPConstants.ENTITLEMENT_POLICY_PAP; - return listAllPolicyIds(path); - - } - - /** - * Removes the given policy from PAP. - * - * @param policyId policy ID - * @throws EntitlementException If an error occurs - */ - @Override - public void removePolicy(String policyId) throws EntitlementException { - - String path; - - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Removing entitlement policy %s", policyId)); - } - - try { - path = PDPConstants.ENTITLEMENT_POLICY_PAP + policyId; - Registry registry = getRegistry(); - if (!registry.resourceExists(path)) { - if (LOG.isDebugEnabled()) { - LOG.debug(String.format(INVALID_ENTITLEMENT_POLICY, policyId)); - } - return; - } - registry.delete(path); - - // Removes versions - if (registry.resourceExists(PDPConstants.ENTITLEMENT_POLICY_VERSION + policyId)) { - registry.delete(PDPConstants.ENTITLEMENT_POLICY_VERSION + policyId); - } - - } catch (RegistryException e) { - throw new EntitlementException(String.format("Error while removing policy %s from PAP policy store", - policyId), e); - } - - } - - /** - * Publishes the given policy. - * - * @param policy policy to be published - * @throws EntitlementException If an error occurs - */ - @Override - public void addPolicy(PolicyStoreDTO policy) throws EntitlementException { - - String policyPath; - Collection policyCollection; - Resource resource; - String papPath; - Resource papResource; - - if (policy == null || StringUtils.isBlank(policy.getPolicyId())) { - throw new EntitlementException("Policy can not be null"); - } - - try { - - // Restricts publishing policies that are not in PAP - papPath = PDPConstants.ENTITLEMENT_POLICY_PAP + policy.getPolicyId(); - Registry registry = getRegistry(); - if (!registry.resourceExists(papPath)) { - throw new EntitlementException("Policies that are not included in the PAP, cannot be published"); - } - - // Publishes policy to PDP - if (registry.resourceExists(policyStorePath)) { - policyCollection = (Collection) registry.get(policyStorePath); - } else { - policyCollection = registry.newCollection(); - } - registry.put(policyStorePath, policyCollection); - - policyPath = policyStorePath + policy.getPolicyId(); - if (registry.resourceExists(policyPath)) { - resource = registry.get(policyPath); - } else { - resource = registry.newResource(); - } - - if (policy.getPolicy() != null && !policy.getPolicy().trim().isEmpty()) { - resource.setContent(policy.getPolicy()); - resource.setMediaType(PDPConstants.REGISTRY_MEDIA_TYPE); - AttributeDTO[] attributeDTOs = policy.getAttributeDTOs(); - if (attributeDTOs != null && EntitlementUtil.isPolicyMetadataStoringEnabled()) { - setAttributesAsProperties(attributeDTOs, resource); - } - } - if (policy.isSetActive()) { - resource.setProperty("active", Boolean.toString(policy.isActive())); - } - if (policy.isSetOrder()) { - int order = policy.getPolicyOrder(); - if (order > 0) { - resource.setProperty("order", Integer.toString(order)); - } - } - if (resource.getContent() == null) { - LOG.info(String.format("Prevented adding null content to resource %s", policyPath)); - return; - } - // Store policy metadata based on the configured property. - if (!EntitlementUtil.isPolicyMetadataStoringEnabled()) { - for (Map.Entry entry : resource.getProperties().entrySet()) { - if (entry.getKey().toString().startsWith(PDPConstants.POLICY_META_DATA)) { - resource.getProperties().remove(entry.getKey()); - } - } - } - registry.put(policyPath, resource); - - // Updates the relevant resource in version store - String version = policy.getVersion(); - if (version == null || version.trim().isEmpty()) { - try { - Collection collection = (Collection) registry.get(PDPConstants.ENTITLEMENT_POLICY_VERSION + - policy.getPolicyId()); - if (collection != null) { - version = collection.getProperty(PDPConstants.POLICY_VERSION); - } - } catch (RegistryException e) { - throw new EntitlementException(INVALID_POLICY_VERSION, e); - } - } - String versionCollectionPath = PDPConstants.ENTITLEMENT_POLICY_VERSION + policy.getPolicyId() + - RegistryConstants.PATH_SEPARATOR; - String versionPolicyPath = PDPConstants.ENTITLEMENT_POLICY_VERSION + policy.getPolicyId() + - RegistryConstants.PATH_SEPARATOR + version; - updateResource(policy, versionCollectionPath, versionPolicyPath); - - // If the publishing version is the latest version, updates the relevant resource in PAP - if (registry.resourceExists(papPath)) { - papResource = registry.get(papPath); - if (Objects.equals(papResource.getProperty(PDPConstants.POLICY_VERSION), version)) { - updateResource(policy, PDPConstants.ENTITLEMENT_POLICY_PAP, papPath); - } - } - - } catch (RegistryException e) { - throw new EntitlementException(ERROR_PUBLISHING_POLICY, e); - } - } - - @Override - public void updatePolicy(PolicyStoreDTO policy) throws EntitlementException { - - if (LOG.isDebugEnabled() && policy != null) { - LOG.debug(String.format("Updating policy %s", policy.getPolicyId())); - } - addPolicy(policy); - } - - /** - * Checks whether the given policy is published or not. - * - * @param policyId policy ID - * @return whether the given policy is published or not - */ - @Override - public boolean isPolicyExist(String policyId) { - - String policyPath; - if (policyId == null || policyId.trim().isEmpty()) { - return false; - } - try { - Registry registry = getRegistry(); - policyPath = policyStorePath + policyId; - return registry.resourceExists(policyPath); - } catch (RegistryException e) { - //ignore - return false; - } - } - - /** - * Gets the requested published policy. - * - * @param policyId policy ID - * @return requested policy - */ - @Override - public PolicyStoreDTO getPublishedPolicy(String policyId) { - - try { - Resource resource; - resource = getPolicyResource(policyId); - if (resource == null) { - return new PolicyStoreDTO(); - } - return readPolicy(resource); - } catch (EntitlementException e) { - LOG.error(String.format("Error while retrieving PDP policy : %s", policyId), e); - return new PolicyStoreDTO(); - } - - } - - /** - * Lists all published policy IDs. - * - * @return list of published policy IDs - * @throws EntitlementException If an error occurs - */ - @Override - public List listPublishedPolicyIds() throws EntitlementException { - - return listAllPolicyIds(policyStorePath); - } - - /** - * Un-publishes the policy. - * - * @param policyId policy ID - */ - @Override - public boolean deletePolicy(String policyId) { - - String policyPath; - - if (policyId == null || policyId.trim().isEmpty()) { - return false; - } - - try { - Registry registry = getRegistry(); - // Removes from PDP - policyPath = policyStorePath + policyId; - registry.delete(policyPath); - return true; - } catch (RegistryException e) { - LOG.error(e); - return false; - } - } - - /** - * Checks the existence of the policy in PAP - * - * @param policyId policy ID. - * @return whether the policy exists in PAP or not. - */ - public boolean isPolicyExistsInPap(String policyId) { - - String path = PDPConstants.ENTITLEMENT_POLICY_PAP + policyId; - try { - Registry registry = getRegistry(); - return registry.resourceExists(path); - } catch (RegistryException e) { - LOG.error("Error while checking the existence of the policy in PAP", e); - return false; - } - } - - /** - * Adds or updates the given policy to PAP. - * - * @param policy policyDTO - * @param policyId policyID - * @param policyPath registry destination path - * @throws EntitlementException If an error occurs - */ - private void addOrUpdatePAPPolicy(PolicyDTO policy, String policyId, String policyPath) - throws EntitlementException { - - String path; - Resource resource; - boolean newPolicy = false; - OMElement omElement = null; - - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Creating or updating entitlement policy %s", policyId)); - } - - if (policyId == null) { - throw new EntitlementException("Invalid Entitlement Policy. Policy or policyId can not be Null"); - } - - try { - path = policyPath + policyId; - Registry registry = getRegistry(); - if (registry.resourceExists(path)) { - resource = registry.get(path); - } else { - resource = registry.newResource(); - } - - Collection policyCollection; - if (registry.resourceExists(policyPath)) { - policyCollection = (Collection) registry.get(policyPath); - } else { - policyCollection = registry.newCollection(); - } - - if (policy.getPolicyOrder() > 0) { - String noOfPolicies = policyCollection.getProperty(PDPConstants.MAX_POLICY_ORDER); - if (noOfPolicies != null && Integer.parseInt(noOfPolicies) < policy.getPolicyOrder()) { - policyCollection.setProperty(PDPConstants.MAX_POLICY_ORDER, - Integer.toString(policy.getPolicyOrder())); - registry.put(policyPath, policyCollection); - } - resource.setProperty(PDPConstants.POLICY_ORDER, Integer.toString(policy.getPolicyOrder())); - } else { - String previousOrder = resource.getProperty(PDPConstants.POLICY_ORDER); - if (previousOrder == null) { - if (policyCollection != null) { - int policyOrder = 1; - String noOfPolicies = policyCollection.getProperty(PDPConstants.MAX_POLICY_ORDER); - if (noOfPolicies != null) { - policyOrder = policyOrder + Integer.parseInt(noOfPolicies); - } - policyCollection.setProperty(PDPConstants.MAX_POLICY_ORDER, Integer.toString(policyOrder)); - resource.setProperty(PDPConstants.POLICY_ORDER, Integer.toString(policyOrder)); - } - registry.put(policyPath, policyCollection); - } - } - - if (StringUtils.isNotBlank(policy.getPolicy())) { - resource.setContent(policy.getPolicy()); - newPolicy = true; - PolicyAttributeBuilder policyAttributeBuilder = new PolicyAttributeBuilder(policy.getPolicy()); - Properties properties = policyAttributeBuilder.getPolicyMetaDataFromPolicy(); - // Store policy metadata based on the configured property. - if (EntitlementUtil.isPolicyMetadataStoringEnabled()) { - for (Object keyObject : properties.keySet()) { - String key = keyObject.toString(); - resource.setProperty(key, properties.get(key).toString()); - } - } - } - - resource.setProperty(PDPConstants.ACTIVE_POLICY, Boolean.toString(policy.isActive())); - resource.setProperty(PDPConstants.PROMOTED_POLICY, Boolean.toString(policy.isPromote())); - - if (policy.getVersion() != null) { - resource.setProperty(PDPConstants.POLICY_VERSION, policy.getVersion()); - } - resource.setProperty(PDPConstants.LAST_MODIFIED_TIME, Long.toString(System.currentTimeMillis())); - resource.setProperty(PDPConstants.LAST_MODIFIED_USER, - CarbonContext.getThreadLocalCarbonContext().getUsername()); - - if (policy.getPolicyType() != null && !policy.getPolicyType().trim().isEmpty()) { - resource.setProperty(PDPConstants.POLICY_TYPE, policy.getPolicyType()); - } else { - try { - if (newPolicy) { - omElement = AXIOMUtil.stringToOM(policy.getPolicy()); - resource.setProperty(PDPConstants.POLICY_TYPE, omElement.getLocalName()); - } - } catch (XMLStreamException e) { - policy.setPolicyType(PDPConstants.POLICY_ELEMENT); - LOG.warn("Policy Type can not be found. Default type is set"); - } - } - - if (omElement != null) { - Iterator iterator1 = omElement.getChildrenWithLocalName(PDPConstants.POLICY_REFERENCE); - if (iterator1 != null) { - String policyReferences = ""; - while (iterator1.hasNext()) { - OMElement policyReference = (OMElement) iterator1.next(); - if (!"".equals(policyReferences)) { - policyReferences = policyReferences + PDPConstants.ATTRIBUTE_SEPARATOR + - policyReference.getText(); - } else { - policyReferences = policyReference.getText(); - } - } - resource.setProperty(PDPConstants.POLICY_REFERENCE, policyReferences); - } - - Iterator iterator2 = omElement.getChildrenWithLocalName(PDPConstants.POLICY_SET_REFERENCE); - if (iterator2 != null) { - String policySetReferences = ""; - while (true) { - assert iterator1 != null; - if (!iterator1.hasNext()) { - break; - } - OMElement policySetReference = (OMElement) iterator2.next(); - if (!"".equals(policySetReferences)) { - policySetReferences = policySetReferences + PDPConstants.ATTRIBUTE_SEPARATOR + - policySetReference.getText(); - } else { - policySetReferences = policySetReference.getText(); - } - } - resource.setProperty(PDPConstants.POLICY_SET_REFERENCE, policySetReferences); - } - } - - // Before writing basic policy editor metadata as properties, deletes any properties related to them - String policyEditor = resource.getProperty(PDPConstants.POLICY_EDITOR_TYPE); - if (newPolicy && policyEditor != null) { - resource.removeProperty(PDPConstants.POLICY_EDITOR_TYPE); - } - - // Writes policy metadata that is used for basic policy editor - if (policy.getPolicyEditor() != null && !policy.getPolicyEditor().trim().isEmpty()) { - resource.setProperty(PDPConstants.POLICY_EDITOR_TYPE, policy.getPolicyEditor().trim()); - } - String[] policyMetaData = policy.getPolicyEditorData(); - if (policyMetaData != null && policyMetaData.length > 0) { - String basicPolicyEditorMetaDataAmount = - resource.getProperty(PDPConstants.BASIC_POLICY_EDITOR_META_DATA_AMOUNT); - if (newPolicy && basicPolicyEditorMetaDataAmount != null) { - int amount = Integer.parseInt(basicPolicyEditorMetaDataAmount); - for (int i = 0; i < amount; i++) { - resource.removeProperty(PDPConstants.BASIC_POLICY_EDITOR_META_DATA + i); - } - resource.removeProperty(PDPConstants.BASIC_POLICY_EDITOR_META_DATA_AMOUNT); - } - - int i = 0; - for (String policyData : policyMetaData) { - if (policyData != null && !policyData.isEmpty()) { - resource.setProperty(PDPConstants.BASIC_POLICY_EDITOR_META_DATA + i, policyData); - } - i++; - } - resource.setProperty(PDPConstants.BASIC_POLICY_EDITOR_META_DATA_AMOUNT, Integer.toString(i)); - } - // Store policy metadata based on the configured property. - if (!EntitlementUtil.isPolicyMetadataStoringEnabled()) { - for (Map.Entry entry : resource.getProperties().entrySet()) { - if (entry.getKey().toString().startsWith(PDPConstants.POLICY_META_DATA)) { - resource.getProperties().remove(entry.getKey()); - } - } - } - - registry.put(path, resource); - - } catch (RegistryException e) { - throw new EntitlementException( - String.format("Error while adding or updating entitlement policy %s in policy store", policyId), e); - } - } - - /** - * Creates a new policy version. - * - * @param policyDTO policy - * @return new policy version - */ - private String createVersion(PolicyDTO policyDTO) { - - String version = "0"; - - try { - Collection collection = null; - Registry registry = getRegistry(); - try { - collection = (Collection) registry.get(PDPConstants.ENTITLEMENT_POLICY_VERSION + - policyDTO.getPolicyId()); - } catch (ResourceNotFoundException e) { - // ignore - } - - if (collection != null) { - version = collection.getProperty(PDPConstants.POLICY_VERSION); - } else { - collection = registry.newCollection(); - collection.setProperty(PDPConstants.POLICY_VERSION, "1"); - registry.put(PDPConstants.ENTITLEMENT_POLICY_VERSION + policyDTO.getPolicyId(), collection); - } - - int versionInt = Integer.parseInt(version); - String policyPath = PDPConstants.ENTITLEMENT_POLICY_VERSION + policyDTO.getPolicyId() + - RegistryConstants.PATH_SEPARATOR; - - // Checks whether the version is larger than the maximum version - if (versionInt > maxVersions) { - // Deletes the older version - int olderVersion = versionInt - maxVersions; - if (registry.resourceExists(policyPath + olderVersion)) { - registry.delete(policyPath + olderVersion); - } - } - - // Creates the new version - version = Integer.toString(versionInt + 1); - policyDTO.setVersion(version); - - // Sets the new version - collection.setProperty("version", version); - registry.put(PDPConstants.ENTITLEMENT_POLICY_VERSION + policyDTO.getPolicyId(), collection); - - } catch (RegistryException e) { - LOG.error("Error while creating a new version for the policy", e); - } - return version; - } - - /** - * Creates a property object which contains the policy metadata. - * - * @param attributeDTOs list of AttributeDTO - * @param resource registry resource - */ - private void setAttributesAsProperties(AttributeDTO[] attributeDTOs, Resource resource) { - - int attributeElementNo = 0; - if (attributeDTOs != null) { - for (AttributeDTO attributeDTO : attributeDTOs) { - resource.setProperty(KEY_VALUE_POLICY_META_DATA + attributeElementNo, - attributeDTO.getCategory() + "," + - attributeDTO.getAttributeValue() + "," + - attributeDTO.getAttributeId() + "," + - attributeDTO.getAttributeDataType()); - attributeElementNo++; - } - } - } - - /** - * Gets the requested policy from PAP. - * - * @param policyId policy ID - * @return policyDTO - * @throws EntitlementException If an error occurs - */ - private PolicyDTO getPolicyDTO(String policyId, String path) throws EntitlementException { - - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Retrieving entitlement policy %s", policyId)); - } - - try { - Registry registry = getRegistry(); - if (!registry.resourceExists(path)) { - if (LOG.isDebugEnabled()) { - LOG.debug(String.format(INVALID_ENTITLEMENT_POLICY, policyId)); - } - return null; - } - - Resource resource = registry.get(path); - if (resource == null) { - return null; - } - - PolicyDTO dto = new PolicyDTO(); - dto.setPolicyId(policyId); - dto.setPolicy(new String((byte[]) resource.getContent(), StandardCharsets.UTF_8)); - dto.setActive(Boolean.parseBoolean(resource.getProperty(PDPConstants.ACTIVE_POLICY))); - String policyOrder = resource.getProperty(PDPConstants.POLICY_ORDER); - if (policyOrder != null) { - dto.setPolicyOrder(Integer.parseInt(policyOrder)); - } else { - dto.setPolicyOrder(0); - } - - String version = resource.getProperty(PDPConstants.POLICY_VERSION); - if (version != null) { - dto.setVersion(version); - } - String lastModifiedTime = resource.getProperty(PDPConstants.LAST_MODIFIED_TIME); - if (lastModifiedTime != null) { - dto.setLastModifiedTime(lastModifiedTime); - } - String lastModifiedUser = resource.getProperty(PDPConstants.LAST_MODIFIED_USER); - if (lastModifiedUser != null) { - dto.setLastModifiedUser(lastModifiedUser); - } - dto.setPolicyType(resource.getProperty(PDPConstants.POLICY_TYPE)); - - String policyReferences = resource.getProperty(PDPConstants.POLICY_REFERENCE); - if (policyReferences != null && !policyReferences.trim().isEmpty()) { - dto.setPolicyIdReferences(policyReferences.split(PDPConstants.ATTRIBUTE_SEPARATOR)); - } - - String policySetReferences = resource.getProperty(PDPConstants.POLICY_SET_REFERENCE); - if (policySetReferences != null && !policySetReferences.trim().isEmpty()) { - dto.setPolicySetIdReferences(policySetReferences.split(PDPConstants.ATTRIBUTE_SEPARATOR)); - } - - dto.setPolicyEditor(resource.getProperty(PDPConstants.POLICY_EDITOR_TYPE)); - String basicPolicyEditorMetaDataAmount = - resource.getProperty(PDPConstants.BASIC_POLICY_EDITOR_META_DATA_AMOUNT); - if (basicPolicyEditorMetaDataAmount != null) { - int amount = Integer.parseInt(basicPolicyEditorMetaDataAmount); - String[] basicPolicyEditorMetaData = new String[amount]; - for (int i = 0; i < amount; i++) { - basicPolicyEditorMetaData[i] = resource.getProperty(PDPConstants.BASIC_POLICY_EDITOR_META_DATA + i); - } - dto.setPolicyEditorData(basicPolicyEditorMetaData); - } - PolicyAttributeBuilder policyAttributeBuilder = new PolicyAttributeBuilder(); - dto.setAttributeDTOs( - policyAttributeBuilder.getPolicyMetaDataFromRegistryProperties(resource.getProperties())); - - return dto; - - } catch (RegistryException e) { - throw new EntitlementException("Error while retrieving entitlement policy PAP policy store", e); - } - - } - - /** - * Returns given policy as a registry resource. - * - * @param policyId policy id - * @return policy as a registry resource - * @throws EntitlementException If an error occurs - */ - private Resource getPolicyResource(String policyId) throws EntitlementException { - - String path; - - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Retrieving entitlement policy %s", policyId)); - } - - try { - path = policyStorePath + policyId; - Registry registry = getRegistry(); - if (!registry.resourceExists(path)) { - if (LOG.isDebugEnabled()) { - LOG.debug(String.format(INVALID_ENTITLEMENT_POLICY, policyId)); - } - return null; - } - return registry.get(path); - } catch (RegistryException e) { - throw new EntitlementException(String.format("Error while retrieving entitlement policy : %s", policyId), - e); - } - } - - /** - * Reads All ordered active policies as PolicyDTO. - * - * @param active only return active policies - * @param order return ordered policy - * @return Array of PolicyDTO - * @throws EntitlementException If an error occurs - */ - private PolicyStoreDTO[] getAllPolicies(boolean active, boolean order) throws EntitlementException { - - Resource[] resources; - resources = getAllPolicyResource(); - - if (resources.length == 0) { - return new PolicyStoreDTO[0]; - } - List policyDTOList = new ArrayList<>(); - for (Resource resource : resources) { - PolicyStoreDTO policyDTO = readPolicy(resource); - if (active) { - if (policyDTO.isActive()) { - policyDTOList.add(policyDTO); - } - } else { - policyDTOList.add(policyDTO); - } - } - - PolicyStoreDTO[] policyDTOs = policyDTOList.toArray(new PolicyStoreDTO[0]); - - if (order) { - Arrays.sort(policyDTOs, new PolicyOrderComparator()); - } - return policyDTOs; - } - - /** - * Returns all the policies as registry resources. - * - * @return policies as Resource[] - * @throws EntitlementException If an error occurs - */ - private Resource[] getAllPolicyResource() throws EntitlementException { - - String path; - Collection collection; - List resources = new ArrayList<>(); - String[] children; - - LOG.debug("Retrieving all entitlement policies"); - try { - path = policyStorePath; - Registry registry = getRegistry(); - if (!registry.resourceExists(path)) { - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Invalid policy store path %s", path)); - } - return new Resource[0]; - } - collection = (Collection) registry.get(path); - children = collection.getChildren(); - - for (String aChildren : children) { - resources.add(registry.get(aChildren)); - } - - } catch (RegistryException e) { - throw new EntitlementException("Error while retrieving entitlement policies", e); - } - - return resources.toArray(new Resource[0]); - } - - /** - * Gets all policy IDs. - * - * @param path policy registry path - * @return list of policy IDs - * @throws EntitlementException If an error occurs - */ - private List listAllPolicyIds(String path) throws EntitlementException { - - Collection collection; - String[] children; - List resources = new ArrayList<>(); - - LOG.debug("Retrieving all entitlement policy ids"); - try { - Registry registry = getRegistry(); - if (!registry.resourceExists(path)) { - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Invalid policy path %s", path)); - } - return Collections.emptyList(); - } - collection = (Collection) registry.get(path); - children = collection.getChildren(); - for (String child : children) { - String id = child.substring(child.lastIndexOf(RegistryConstants.PATH_SEPARATOR) + 1); - resources.add(id); - } - - } catch (RegistryException e) { - throw new EntitlementException("Error while retrieving entitlement policy resources", e); - } - - return resources; - } - - /** - * Reads PolicyDTO for given registry resource. - * - * @param resource Registry resource - * @return PolicyDTO - * @throws EntitlementException If an error occurs - */ - private PolicyStoreDTO readPolicy(Resource resource) throws EntitlementException { - - String policy; - AbstractPolicy absPolicy; - PolicyStoreDTO dto; - - try { - if (resource.getContent() == null) { - throw new EntitlementException("Error while loading entitlement policy. Policy content is null"); - } - policy = new String((byte[]) resource.getContent(), StandardCharsets.UTF_8); - absPolicy = PAPPolicyReader.getInstance(null).getPolicy(policy); - dto = new PolicyStoreDTO(); - dto.setPolicyId(absPolicy.getId().toASCIIString()); - dto.setPolicy(policy); - String policyOrder = resource.getProperty("order"); - if (policyOrder != null) { - dto.setPolicyOrder(Integer.parseInt(policyOrder)); - } else { - dto.setPolicyOrder(0); - } - String policyActive = resource.getProperty("active"); - if (policyActive != null) { - dto.setActive(Boolean.parseBoolean(policyActive)); - } - PolicyAttributeBuilder policyAttributeBuilder = new PolicyAttributeBuilder(); - dto.setAttributeDTOs(policyAttributeBuilder. - getPolicyMetaDataFromRegistryProperties(resource.getProperties())); - return dto; - } catch (RegistryException e) { - throw new EntitlementException("Error while loading entitlement policy", e); - } - } - - /** - * Updates the given registry resource. - * - * @param policy publishing policy - * @param collectionPath registry collection path - * @param policyPath registry resource path - * @throws EntitlementException If an error occurs - */ - private void updateResource(PolicyStoreDTO policy, String collectionPath, String policyPath) - throws EntitlementException { - - Collection policyCollection; - Resource resource; - - try { - Registry registry = getRegistry(); - policyCollection = (Collection) registry.get(collectionPath); - resource = registry.get(policyPath); - - if (policy.isSetActive()) { - resource.setProperty(PDPConstants.ACTIVE_POLICY, Boolean.toString(policy.isActive())); - } - if (policy.isSetOrder()) { - int order = policy.getPolicyOrder(); - if (order > 0) { - if (Objects.equals(collectionPath, PDPConstants.ENTITLEMENT_POLICY_PAP)) { - String noOfPolicies = policyCollection.getProperty(PDPConstants.MAX_POLICY_ORDER); - if (noOfPolicies != null && Integer.parseInt(noOfPolicies) < order) { - policyCollection.setProperty(PDPConstants.MAX_POLICY_ORDER, Integer.toString(order)); - registry.put(PDPConstants.ENTITLEMENT_POLICY_PAP, policyCollection); - } - } - resource.setProperty(PDPConstants.POLICY_ORDER, Integer.toString(order)); - } - } - - if (policy.isSetOrder() || policy.isSetActive()) { - resource.setProperty(PDPConstants.LAST_MODIFIED_TIME, Long.toString(System.currentTimeMillis())); - resource.setProperty(PDPConstants.LAST_MODIFIED_USER, - CarbonContext.getThreadLocalCarbonContext().getUsername()); - } - - registry.put(policyPath, resource); - - } catch (RegistryException e) { - throw new EntitlementException(ERROR_PUBLISHING_POLICY, e); - } - } - - private Registry getRegistry() { - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - return EntitlementServiceComponent.getGovernanceRegistry(tenantId); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/RegistrySubscriberPersistenceManager.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/RegistrySubscriberPersistenceManager.java deleted file mode 100644 index 7c5d29d5e065..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/RegistrySubscriberPersistenceManager.java +++ /dev/null @@ -1,335 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.core.util.CryptoException; -import org.wso2.carbon.core.util.CryptoUtil; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.EntitlementUtil; -import org.wso2.carbon.identity.entitlement.PDPConstants; -import org.wso2.carbon.identity.entitlement.common.EntitlementConstants; -import org.wso2.carbon.identity.entitlement.dto.PublisherDataHolder; -import org.wso2.carbon.identity.entitlement.dto.PublisherPropertyDTO; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; -import org.wso2.carbon.registry.core.Collection; -import org.wso2.carbon.registry.core.Registry; -import org.wso2.carbon.registry.core.RegistryConstants; -import org.wso2.carbon.registry.core.Resource; -import org.wso2.carbon.registry.core.exceptions.RegistryException; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import static org.wso2.carbon.identity.entitlement.PDPConstants.SUBSCRIBER_ID; - -/** - * This implementation handles the subscriber management in the Registry. - */ -public class RegistrySubscriberPersistenceManager implements SubscriberPersistenceManager { - - // The logger that is used for all messages - private static final Log LOG = LogFactory.getLog(RegistrySubscriberPersistenceManager.class); - private final Registry registry; - - public RegistrySubscriberPersistenceManager() { - - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - this.registry = EntitlementServiceComponent.getGovernanceRegistry(tenantId); - } - - /** - * Adds a subscriber. - * - * @param holder publisher data holder - * @throws EntitlementException If an error occurs - */ - @Override - public void addSubscriber(PublisherDataHolder holder) throws EntitlementException { - - persistSubscriber(holder, false); - } - - /** - * Gets the requested subscriber. - * - * @param subscriberId subscriber ID - * @param shouldDecryptSecrets whether the subscriber should get returned with secret(decrypted) values or not - * @return publisher data holder - * @throws EntitlementException If an error occurs - */ - @Override - public PublisherDataHolder getSubscriber(String subscriberId, boolean shouldDecryptSecrets) - throws EntitlementException { - - try { - if (registry.resourceExists(PDPConstants.ENTITLEMENT_POLICY_PUBLISHER + - RegistryConstants.PATH_SEPARATOR + subscriberId)) { - Resource resource = registry.get(PDPConstants.ENTITLEMENT_POLICY_PUBLISHER + - RegistryConstants.PATH_SEPARATOR + subscriberId); - - return getPublisherDataHolder(resource, shouldDecryptSecrets); - } - } catch (RegistryException e) { - throw new EntitlementException("Error while retrieving subscriber detail of id : " + subscriberId, e); - } - - throw new EntitlementException("No Subscriber is defined for the given Id"); - - } - - /** - * Gets all subscriber IDs. - * - * @param filter search string - * @return list of subscriber IDs - * @throws EntitlementException If an error occurs - */ - @Override - public List listSubscriberIds(String filter) throws EntitlementException { - - try { - if (registry.resourceExists(PDPConstants.ENTITLEMENT_POLICY_PUBLISHER + - RegistryConstants.PATH_SEPARATOR)) { - Resource resource = registry.get(PDPConstants.ENTITLEMENT_POLICY_PUBLISHER + - RegistryConstants.PATH_SEPARATOR); - Collection collection = (Collection) resource; - List list = new ArrayList<>(); - if (collection.getChildCount() > 0) { - for (String path : collection.getChildren()) { - Resource childResource = registry.get(path); - if (childResource != null && childResource.getProperty(SUBSCRIBER_ID) != null) { - list.add(childResource.getProperty(SUBSCRIBER_ID)); - } - } - } - return EntitlementUtil.filterSubscribers(list, filter); - } - } catch (RegistryException e) { - throw new EntitlementException("Error while retrieving subscriber ids", e); - } - return Collections.emptyList(); - } - - /** - * Updates a subscriber. - * - * @param holder publisher data holder - * @throws EntitlementException If an error occurs - */ - @Override - public void updateSubscriber(PublisherDataHolder holder) throws EntitlementException { - - persistSubscriber(holder, true); - } - - /** - * Removes the subscriber of the given subscriber ID. - * - * @param subscriberId subscriber ID - * @throws EntitlementException If an error occurs - */ - @Override - public void removeSubscriber(String subscriberId) throws EntitlementException { - - String subscriberPath; - - if (subscriberId == null) { - throw new EntitlementException("Subscriber Id can not be null"); - } - - if (EntitlementConstants.PDP_SUBSCRIBER_ID.equals(subscriberId.trim())) { - throw new EntitlementException("Can not delete PDP publisher"); - } - - try { - subscriberPath = PDPConstants.ENTITLEMENT_POLICY_PUBLISHER + - RegistryConstants.PATH_SEPARATOR + subscriberId; - - if (registry.resourceExists(subscriberPath)) { - registry.delete(subscriberPath); - } - } catch (RegistryException e) { - throw new EntitlementException("Error while deleting subscriber details", e); - } - } - - /** - * Checks whether a subscriber exists. - * - * @param subscriberId subscriber ID. - * @return whether the subscriber exists or not. - * @throws EntitlementException If an error occurs. - */ - public boolean isSubscriberExists(String subscriberId) throws EntitlementException { - - try { - return registry.resourceExists(PDPConstants.ENTITLEMENT_POLICY_PUBLISHER + - RegistryConstants.PATH_SEPARATOR + subscriberId); - } catch (RegistryException e) { - throw new EntitlementException("Error while checking subscriber existence", e); - } - } - - /** - * Adds or updates a subscriber. - * - * @param holder publisher data holder - * @param isUpdate whether the operation is an update or an addition - * @throws EntitlementException If an error occurs - */ - private void persistSubscriber(PublisherDataHolder holder, boolean isUpdate) throws EntitlementException { - - Collection policyCollection; - String subscriberPath; - String subscriberId = EntitlementUtil.resolveSubscriberId(holder); - if (subscriberId == null) { - throw new EntitlementException("Subscriber Id can not be null"); - } - - try { - if (registry.resourceExists(PDPConstants.ENTITLEMENT_POLICY_PUBLISHER)) { - policyCollection = registry.newCollection(); - registry.put(PDPConstants.ENTITLEMENT_POLICY_PUBLISHER, policyCollection); - } - - subscriberPath = PDPConstants.ENTITLEMENT_POLICY_PUBLISHER + - RegistryConstants.PATH_SEPARATOR + subscriberId; - - Resource resource; - - PublisherDataHolder oldHolder = null; - if (registry.resourceExists(subscriberPath)) { - if (isUpdate) { - resource = registry.get(subscriberPath); - oldHolder = getPublisherDataHolder(resource, false); - } else { - throw new EntitlementException("Subscriber ID already exists"); - } - } else { - resource = registry.newResource(); - } - - populateProperties(holder, oldHolder, resource); - registry.put(subscriberPath, resource); - - } catch (RegistryException e) { - throw new EntitlementException("Error while persisting subscriber details", e); - } - } - - /** - * Populate subscriber properties. - * - * @param holder subscriber data holder - * @param oldHolder old publisher data holder - * @param resource registry resource - */ - private void populateProperties(PublisherDataHolder holder, PublisherDataHolder oldHolder, Resource resource) - throws EntitlementException { - - PublisherPropertyDTO[] propertyDTOs = holder.getPropertyDTOs(); - for (PublisherPropertyDTO dto : propertyDTOs) { - if (StringUtils.isNotBlank(dto.getId()) && StringUtils.isNotBlank(dto.getValue())) { - ArrayList list = new ArrayList<>(); - if (dto.isSecret()) { - PublisherPropertyDTO propertyDTO = null; - if (oldHolder != null) { - propertyDTO = oldHolder.getPropertyDTO(dto.getId()); - } - if (propertyDTO == null || !propertyDTO.getValue().equalsIgnoreCase(dto.getValue())) { - try { - String encryptedValue = CryptoUtil.getDefaultCryptoUtil(). - encryptAndBase64Encode(dto.getValue().getBytes()); - dto.setValue(encryptedValue); - } catch (CryptoException e) { - throw new EntitlementException("Error while encrypting secret value of subscriber. Update" + - " cannot proceed.", e); - } - } - } - list.add(dto.getValue()); - list.add(dto.getDisplayName()); - list.add(Integer.toString(dto.getDisplayOrder())); - list.add(Boolean.toString(dto.isRequired())); - list.add(Boolean.toString(dto.isSecret())); - resource.setProperty(dto.getId(), list); - } - } - resource.setProperty(PublisherDataHolder.MODULE_NAME, holder.getModuleName()); - } - - private PublisherDataHolder getPublisherDataHolder(Resource resource, boolean returnSecrets) { - - List propertyDTOs = new ArrayList<>(); - String moduleName = null; - if (resource != null && resource.getProperties() != null) { - Properties properties = resource.getProperties(); - for (Map.Entry entry : properties.entrySet()) { - PublisherPropertyDTO dto = new PublisherPropertyDTO(); - dto.setId((String) entry.getKey()); - Object value = entry.getValue(); - if (value instanceof ArrayList) { - List list = (ArrayList) entry.getValue(); - if (!list.isEmpty() && list.get(0) != null) { - dto.setValue((String) list.get(0)); - - if (list.size() > 1 && list.get(1) != null) { - dto.setDisplayName((String) list.get(1)); - } - if (list.size() > 2 && list.get(2) != null) { - dto.setDisplayOrder(Integer.parseInt((String) list.get(2))); - } - if (list.size() > 3 && list.get(3) != null) { - dto.setRequired(Boolean.parseBoolean((String) list.get(3))); - } - if (list.size() > 4 && list.get(4) != null) { - dto.setSecret(Boolean.parseBoolean((String) list.get(4))); - } - - if (dto.isSecret() && returnSecrets) { - String password = dto.getValue(); - try { - password = new String(CryptoUtil.getDefaultCryptoUtil(). - base64DecodeAndDecrypt(dto.getValue())); - } catch (CryptoException e) { - LOG.error(e); - // ignore - } - dto.setValue(password); - } - } - } - if (PublisherDataHolder.MODULE_NAME.equals(dto.getId())) { - moduleName = dto.getValue(); - continue; - } - - propertyDTOs.add(dto); - } - } - return new PublisherDataHolder(propertyDTOs, moduleName); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/SubscriberPersistenceManager.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/SubscriberPersistenceManager.java deleted file mode 100644 index 196014879c48..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/SubscriberPersistenceManager.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.dto.PublisherDataHolder; - -import java.util.List; - -/** - * This interface supports the management of subscribers. - */ -public interface SubscriberPersistenceManager { - - /** - * Adds a subscriber. - * - * @param holder publisher data holder - * @throws EntitlementException If an error occurs - */ - void addSubscriber(PublisherDataHolder holder) throws EntitlementException; - - /** - * Gets the requested subscriber. - * - * @param subscriberId subscriber ID - * @param shouldDecryptSecrets whether the subscriber should get returned with secret(decrypted) values or not - * @return publisher data holder - * @throws EntitlementException If an error occurs - */ - PublisherDataHolder getSubscriber(String subscriberId, boolean shouldDecryptSecrets) throws EntitlementException; - - /** - * Lists all subscriber IDs. - * - * @param filter search string - * @return list of subscriber IDs - * @throws EntitlementException If an error occurs - */ - List listSubscriberIds(String filter) throws EntitlementException; - - /** - * Updates a subscriber. - * - * @param holder publisher data holder - * @throws EntitlementException If an error occurs - */ - void updateSubscriber(PublisherDataHolder holder) throws EntitlementException; - - /** - * Removes the subscriber of the given subscriber ID. - * - * @param subscriberId subscriber ID - * @throws EntitlementException If an error occurs - */ - void removeSubscriber(String subscriberId) throws EntitlementException; -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/cache/CacheBackedConfigDAO.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/cache/CacheBackedConfigDAO.java deleted file mode 100644 index 0e19ae496ff2..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/cache/CacheBackedConfigDAO.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence.cache; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.PDPConstants; -import org.wso2.carbon.identity.entitlement.cache.ConfigCache; -import org.wso2.carbon.identity.entitlement.persistence.dao.ConfigDAO; - -public class CacheBackedConfigDAO extends ConfigDAO { - - private static final Log LOG = LogFactory.getLog(CacheBackedConfigDAO.class); - private final ConfigCache configCache = ConfigCache.getInstance(); - private static final CacheBackedConfigDAO instance = new CacheBackedConfigDAO(); - - private CacheBackedConfigDAO() { - - } - - public static CacheBackedConfigDAO getInstance() { - - return instance; - } - - @Override - public String getPolicyCombiningAlgorithm(int tenantId) throws EntitlementException { - - String algorithm = configCache.getValueFromCache(PDPConstants.GLOBAL_POLICY_COMBINING_ALGORITHM, tenantId); - if (algorithm != null) { - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Cache hit in ConfigCache for policy combining algorithm for tenant: %s", - tenantId)); - } - return algorithm; - } - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Cache miss in ConfigCache for policy combining algorithm for tenant: %s", - tenantId)); - } - algorithm = super.getPolicyCombiningAlgorithm(tenantId); - configCache.addToCache(PDPConstants.GLOBAL_POLICY_COMBINING_ALGORITHM, algorithm, tenantId); - - return algorithm; - } - - @Override - public void insertPolicyCombiningAlgorithm(String policyCombiningAlgorithm, int tenantId) - throws EntitlementException { - - super.insertPolicyCombiningAlgorithm(policyCombiningAlgorithm, tenantId); - configCache.addToCache(PDPConstants.GLOBAL_POLICY_COMBINING_ALGORITHM, policyCombiningAlgorithm, tenantId); - } - - @Override - public void updatePolicyCombiningAlgorithm(String policyCombiningAlgorithm, int tenantId) - throws EntitlementException { - - super.updatePolicyCombiningAlgorithm(policyCombiningAlgorithm, tenantId); - configCache.addToCache(PDPConstants.GLOBAL_POLICY_COMBINING_ALGORITHM, policyCombiningAlgorithm, tenantId); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/cache/CacheBackedPolicyDAO.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/cache/CacheBackedPolicyDAO.java deleted file mode 100644 index c1b59c1b45dd..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/cache/CacheBackedPolicyDAO.java +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence.cache; - -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.cache.PapPolicyCache; -import org.wso2.carbon.identity.entitlement.cache.PapPolicyListCache; -import org.wso2.carbon.identity.entitlement.cache.PdpPolicyCache; -import org.wso2.carbon.identity.entitlement.cache.PdpPolicyListCache; -import org.wso2.carbon.identity.entitlement.dto.PolicyDTO; -import org.wso2.carbon.identity.entitlement.dto.PolicyStoreDTO; -import org.wso2.carbon.identity.entitlement.persistence.dao.PolicyDAO; - -import java.util.ArrayList; -import java.util.List; - -public class CacheBackedPolicyDAO extends PolicyDAO { - - private static final Log LOG = LogFactory.getLog(CacheBackedPolicyDAO.class); - private final PapPolicyCache papPolicyCache = PapPolicyCache.getInstance(); - private final PapPolicyListCache papPolicyListCache = PapPolicyListCache.getInstance(); - private final PdpPolicyCache pdpPolicyCache = PdpPolicyCache.getInstance(); - private final PdpPolicyListCache pdpPolicyListCache = PdpPolicyListCache.getInstance(); - private static final String PAP_POLICY_LIST_CACHE_KEY = "PAP_POLICY_LIST_CACHE_KEY"; - private static final String PDP_POLICY_LIST_CACHE_KEY = "PDP_POLICY_LIST_CACHE_KEY"; - - private static final CacheBackedPolicyDAO instance = new CacheBackedPolicyDAO(); - - private CacheBackedPolicyDAO() { - - } - - public static CacheBackedPolicyDAO getInstance() { - - return instance; - } - - @Override - public void insertPolicy(PolicyDTO policy, int tenantId) throws EntitlementException { - - super.insertPolicy(policy, tenantId); - papPolicyCache.addToCache(policy.getPolicyId(), policy, tenantId); - papPolicyListCache.clearCacheEntry(PAP_POLICY_LIST_CACHE_KEY, tenantId); - } - - @Override - public PolicyDTO getPAPPolicy(String policyId, int tenantId) throws EntitlementException { - - PolicyDTO policy = papPolicyCache.getValueFromCache(policyId, tenantId); - if (policy != null) { - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Cache hit in PapPolicyCache for policy: %s for tenant: %s", - policyId, tenantId)); - } - return policy; - } - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Cache miss in PapPolicyCache for policy: %s for tenant: %s", policyId, tenantId)); - } - policy = super.getPAPPolicy(policyId, tenantId); - papPolicyCache.addToCache(policyId, policy, tenantId); - return policy; - } - - @Override - public List getAllPAPPolicies(int tenantId) throws EntitlementException { - - List policies = papPolicyListCache.getValueFromCache(PAP_POLICY_LIST_CACHE_KEY, tenantId); - if (policies != null) { - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Cache hit in PapPolicyListCache for policies for tenant: %s", tenantId)); - } - return policies; - } - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Cache miss in PapPolicyListCache for policies for tenant: %s", tenantId)); - } - policies = super.getAllPAPPolicies(tenantId); - papPolicyListCache.addToCache(PAP_POLICY_LIST_CACHE_KEY, (ArrayList) policies, tenantId); - return policies; - } - - @Override - public void deletePAPPolicy(String policyId, int tenantId) throws EntitlementException { - - super.deletePAPPolicy(policyId, tenantId); - papPolicyCache.clearCacheEntry(policyId, tenantId); - papPolicyListCache.clearCacheEntry(PAP_POLICY_LIST_CACHE_KEY, tenantId); - } - - @Override - public PolicyStoreDTO getPDPPolicy(String policyId, int tenantId) { - - PolicyStoreDTO policy = pdpPolicyCache.getValueFromCache(policyId, tenantId); - if (policy != null) { - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Cache hit in PdpPolicyCache for policy: %s for tenant: %s", - policyId, tenantId)); - } - return policy; - } - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Cache miss in PdpPolicyCache for policy: %s for tenant: %s", policyId, tenantId)); - } - policy = super.getPDPPolicy(policyId, tenantId); - pdpPolicyCache.addToCache(policyId, policy, tenantId); - return policy; - } - - @Override - public PolicyStoreDTO[] getAllPDPPolicies(int tenantId) throws EntitlementException { - - PolicyStoreDTO[] policies = pdpPolicyListCache.getValueFromCache(PDP_POLICY_LIST_CACHE_KEY, tenantId); - if (policies != null) { - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Cache hit in PdpPolicyListCache for policies for tenant: %s", tenantId)); - } - return policies; - } - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Cache miss in PdpPolicyListCache for policies for tenant: %s", tenantId)); - } - policies = super.getAllPDPPolicies(tenantId); - pdpPolicyListCache.addToCache(PDP_POLICY_LIST_CACHE_KEY, policies, tenantId); - return policies; - } - - @Override - public void insertOrUpdatePolicy(PolicyStoreDTO policy, int tenantId) throws EntitlementException { - - super.insertOrUpdatePolicy(policy, tenantId); - pdpPolicyCache.addToCache(policy.getPolicyId(), policy, tenantId); - pdpPolicyListCache.clearCacheEntry(PDP_POLICY_LIST_CACHE_KEY, tenantId); - papPolicyCache.clearCacheEntry(policy.getPolicyId(), tenantId); - papPolicyListCache.clearCacheEntry(PAP_POLICY_LIST_CACHE_KEY, tenantId); - } - - @Override - public void updateActiveStatusAndOrder(PolicyStoreDTO policy, int tenantId) throws EntitlementException { - - super.updateActiveStatusAndOrder(policy, tenantId); - pdpPolicyCache.clearCacheEntry(policy.getPolicyId(), tenantId); - pdpPolicyListCache.clearCacheEntry(PDP_POLICY_LIST_CACHE_KEY, tenantId); - papPolicyCache.clearCacheEntry(policy.getPolicyId(), tenantId); - papPolicyListCache.clearCacheEntry(PAP_POLICY_LIST_CACHE_KEY, tenantId); - } - - @Override - public int getPublishedVersion(PolicyStoreDTO policy, int tenantId) throws EntitlementException { - - String policyId = policy.getPolicyId(); - PolicyStoreDTO cachedPolicy = pdpPolicyCache.getValueFromCache(policyId, tenantId); - if (cachedPolicy != null) { - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Cache hit in PdpPolicyCache for policy: %s for tenant: %s", - policyId, tenantId)); - } - return Integer.parseInt(cachedPolicy.getVersion()); - } - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Cache miss in PdpPolicyCache for policy: %s for tenant: %s", policyId, tenantId)); - } - return super.getPublishedVersion(policy, tenantId); - } - - @Override - public boolean unpublishPolicy(String policyId, int tenantId) { - - boolean isSuccess = super.unpublishPolicy(policyId, tenantId); - pdpPolicyCache.clearCacheEntry(policyId, tenantId); - pdpPolicyListCache.clearCacheEntry(PDP_POLICY_LIST_CACHE_KEY, tenantId); - papPolicyCache.clearCacheEntry(policyId, tenantId); - papPolicyListCache.clearCacheEntry(PAP_POLICY_LIST_CACHE_KEY, tenantId); - return isSuccess; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/cache/CacheBackedSubscriberDAO.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/cache/CacheBackedSubscriberDAO.java deleted file mode 100644 index c8bc9bbd01fb..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/cache/CacheBackedSubscriberDAO.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence.cache; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.cache.SubscriberCache; -import org.wso2.carbon.identity.entitlement.cache.SubscriberIdListCache; -import org.wso2.carbon.identity.entitlement.dto.PublisherDataHolder; -import org.wso2.carbon.identity.entitlement.dto.PublisherPropertyDTO; -import org.wso2.carbon.identity.entitlement.persistence.dao.SubscriberDAO; - -import java.util.ArrayList; -import java.util.List; - -public class CacheBackedSubscriberDAO extends SubscriberDAO { - - private static final Log LOG = LogFactory.getLog(CacheBackedSubscriberDAO.class); - private final SubscriberCache subscriberCache = SubscriberCache.getInstance(); - private final SubscriberIdListCache subscriberIdListCache = SubscriberIdListCache.getInstance(); - private static final String SUBSCRIBER_ID_LIST_CACHE_KEY = "SUBSCRIBER_ID_LIST_CACHE_KEY"; - private static final CacheBackedSubscriberDAO instance = new CacheBackedSubscriberDAO(); - - private CacheBackedSubscriberDAO() { - - } - - public static CacheBackedSubscriberDAO getInstance() { - - return instance; - } - - @Override - public PublisherDataHolder getSubscriber(String subscriberId, int tenantId) throws EntitlementException { - - PublisherDataHolder subscriber = subscriberCache.getValueFromCache(subscriberId, tenantId); - if (subscriber != null) { - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Cache hit in SubscriberCache for subscriber: %s for tenant: %s", - subscriberId, tenantId)); - } - return subscriber; - } - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Cache miss in SubscriberCache for subscriber: %s for tenant: %s", - subscriberId, tenantId)); - } - subscriber = super.getSubscriber(subscriberId, tenantId); - subscriberCache.addToCache(subscriberId, subscriber, tenantId); - return subscriber; - } - - @Override - public List getSubscriberIds(int tenantId) throws EntitlementException { - - List subscriberIds = subscriberIdListCache.getValueFromCache(SUBSCRIBER_ID_LIST_CACHE_KEY, tenantId); - if (subscriberIds != null) { - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Cache hit in SubscriberIdListCache for subscriber ids for tenant: %s", - tenantId)); - } - return subscriberIds; - } - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Cache miss in SubscriberIdListCache for subscriber ids for tenant: %s", tenantId)); - } - subscriberIds = super.getSubscriberIds(tenantId); - subscriberIdListCache.addToCache(SUBSCRIBER_ID_LIST_CACHE_KEY, (ArrayList) subscriberIds, tenantId); - return subscriberIds; - } - - @Override - public void insertSubscriber(String subscriberId, PublisherDataHolder holder, int tenantId) - throws EntitlementException { - - super.insertSubscriber(subscriberId, holder, tenantId); - subscriberCache.addToCache(subscriberId, holder, tenantId); - subscriberIdListCache.clearCacheEntry(SUBSCRIBER_ID_LIST_CACHE_KEY, tenantId); - } - - @Override - public void updateSubscriber(String subscriberId, String updatedModuleName, - PublisherPropertyDTO[] updatedPropertyDTOS, int tenantId) - throws EntitlementException { - - super.updateSubscriber(subscriberId, updatedModuleName, updatedPropertyDTOS, tenantId); - subscriberCache.clearCacheEntry(subscriberId, tenantId); - } - - @Override - public void deleteSubscriber(String subscriberId, int tenantId) throws EntitlementException { - - super.deleteSubscriber(subscriberId, tenantId); - subscriberCache.clearCacheEntry(subscriberId, tenantId); - subscriberIdListCache.clearCacheEntry(SUBSCRIBER_ID_LIST_CACHE_KEY, tenantId); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/dao/ConfigDAO.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/dao/ConfigDAO.java deleted file mode 100644 index 4504d3821da4..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/dao/ConfigDAO.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence.dao; - -import org.wso2.carbon.database.utils.jdbc.NamedPreparedStatement; -import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.PDPConstants; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; - -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.CONFIG_KEY; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.CONFIG_VALUE; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.TENANT_ID; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.CREATE_POLICY_COMBINING_ALGORITHM_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.GET_POLICY_COMBINING_ALGORITHM_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.UPDATE_POLICY_COMBINING_ALGORITHM_SQL; - -/** - * This class handles the JDBC operations related to the global policy combining algorithm. - */ -public class ConfigDAO { - - /** - * Get the policy combining algorithm from the data store. - * - * @return policy combining algorithm. - */ - public String getPolicyCombiningAlgorithm(int tenantId) throws EntitlementException { - - String algorithm = null; - try (Connection connection = IdentityDatabaseUtil.getDBConnection(false)) { - try (NamedPreparedStatement getPolicyCombiningAlgoPrepStmt = new NamedPreparedStatement(connection, - GET_POLICY_COMBINING_ALGORITHM_SQL)) { - getPolicyCombiningAlgoPrepStmt.setString(CONFIG_KEY, PDPConstants.GLOBAL_POLICY_COMBINING_ALGORITHM); - getPolicyCombiningAlgoPrepStmt.setInt(TENANT_ID, tenantId); - try (ResultSet rs = getPolicyCombiningAlgoPrepStmt.executeQuery()) { - if (rs.next()) { - algorithm = rs.getString(CONFIG_VALUE); - } - } - } - } catch (SQLException e) { - throw new EntitlementException( - "Error while getting Global Policy Combining Algorithm from policy data store.", e); - } - return algorithm; - } - - /** - * Set the policy combining algorithm in the data store. - * - * @param policyCombiningAlgorithm policy combining algorithm to set. - * @param tenantId tenant id. - * @throws EntitlementException throws if fails. - */ - public void insertPolicyCombiningAlgorithm(String policyCombiningAlgorithm, int tenantId) - throws EntitlementException { - - try (Connection connection = IdentityDatabaseUtil.getDBConnection(false)) { - try (NamedPreparedStatement setPolicyCombiningAlgoPrepStmt = new NamedPreparedStatement(connection, - CREATE_POLICY_COMBINING_ALGORITHM_SQL)) { - setPolicyCombiningAlgoPrepStmt.setString(CONFIG_KEY, PDPConstants.GLOBAL_POLICY_COMBINING_ALGORITHM); - setPolicyCombiningAlgoPrepStmt.setString(CONFIG_VALUE, policyCombiningAlgorithm); - setPolicyCombiningAlgoPrepStmt.setInt(TENANT_ID, tenantId); - setPolicyCombiningAlgoPrepStmt.executeUpdate(); - } - } catch (SQLException e) { - throw new EntitlementException("Error while adding global policy combining algorithm in policy store", e); - } - } - - /** - * Update the policy combining algorithm in the data store. - * - * @param policyCombiningAlgorithm policy combining algorithm to update. - * @param tenantId tenant id. - * @throws EntitlementException throws if fails. - */ - public void updatePolicyCombiningAlgorithm(String policyCombiningAlgorithm, int tenantId) - throws EntitlementException { - - try (Connection connection = IdentityDatabaseUtil.getDBConnection(false)) { - try (NamedPreparedStatement setPolicyCombiningAlgoPrepStmt = new NamedPreparedStatement(connection, - UPDATE_POLICY_COMBINING_ALGORITHM_SQL)) { - setPolicyCombiningAlgoPrepStmt.setString(CONFIG_KEY, PDPConstants.GLOBAL_POLICY_COMBINING_ALGORITHM); - setPolicyCombiningAlgoPrepStmt.setString(CONFIG_VALUE, policyCombiningAlgorithm); - setPolicyCombiningAlgoPrepStmt.setInt(TENANT_ID, tenantId); - setPolicyCombiningAlgoPrepStmt.executeUpdate(); - } - } catch (SQLException e) { - throw new EntitlementException("Error while updating global policy combining algorithm in policy store", e); - } - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/dao/PolicyDAO.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/dao/PolicyDAO.java deleted file mode 100644 index b45200275486..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/dao/PolicyDAO.java +++ /dev/null @@ -1,1031 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence.dao; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.database.utils.jdbc.NamedPreparedStatement; -import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.EntitlementUtil; -import org.wso2.carbon.identity.entitlement.dto.AttributeDTO; -import org.wso2.carbon.identity.entitlement.dto.PolicyDTO; -import org.wso2.carbon.identity.entitlement.dto.PolicyStoreDTO; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.List; -import java.util.TimeZone; - -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.ATTRIBUTE_ID; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.ATTRIBUTE_VALUE; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.CATEGORY; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.DATA_TYPE; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.EDITOR_DATA; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.EDITOR_DATA_ORDER; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.IS_ACTIVE; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.IS_IN_PAP; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.IS_IN_PDP; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.LAST_MODIFIED_TIME; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.LAST_MODIFIED_USER; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.POLICY; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.POLICY_EDITOR; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.POLICY_ID; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.POLICY_ORDER; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.POLICY_TYPE; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.REFERENCE; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.SET_REFERENCE; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.TENANT_ID; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.VERSION; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.CREATE_PAP_POLICY_ATTRIBUTES_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.CREATE_PAP_POLICY_EDITOR_DATA_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.CREATE_PAP_POLICY_REFS_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.CREATE_PAP_POLICY_SET_REFS_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.CREATE_PAP_POLICY_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.DELETE_PAP_POLICY_BY_VERSION_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.DELETE_PAP_POLICY_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.DELETE_POLICY_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.DELETE_POLICY_VERSION_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.DELETE_PUBLISHED_VERSIONS_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.DELETE_UNPUBLISHED_POLICY_VERSIONS_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.DELETE_UNUSED_POLICY_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.GET_ACTIVE_STATUS_AND_ORDER_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.GET_ALL_PAP_POLICIES_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.GET_ALL_PDP_POLICIES_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.GET_LATEST_POLICY_VERSION_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.GET_PAP_POLICY_BY_VERSION_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.GET_PAP_POLICY_EDITOR_DATA_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.GET_PAP_POLICY_IDS_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.GET_PAP_POLICY_META_DATA_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.GET_PAP_POLICY_REFS_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.GET_PAP_POLICY_SET_REFS_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.GET_PAP_POLICY_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.GET_PDP_POLICY_IDS_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.GET_PDP_POLICY_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.GET_POLICY_PAP_PRESENCE_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.GET_POLICY_PDP_PRESENCE_BY_VERSION_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.GET_POLICY_PDP_PRESENCE_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.GET_POLICY_VERSIONS_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.GET_PUBLISHED_POLICY_VERSION_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.PUBLISH_POLICY_VERSION_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.RESTORE_ACTIVE_STATUS_AND_ORDER_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.UPDATE_ACTIVE_STATUS_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.UPDATE_ORDER_SQL; - -import static java.time.ZoneOffset.UTC; - -/** - * This class handles the JDBC operations related to the policies. - */ -public class PolicyDAO { - - private static final Log LOG = LogFactory.getLog(PolicyDAO.class); - private static final String IS_IN_PDP_1 = "IS_IN_PDP_1"; - private static final boolean IN_PAP = true; - private static final boolean IN_PDP = true; - private static final boolean INACTIVE = false; - private static final int DEFAULT_POLICY_ORDER = 0; - private static final String ERROR_RETRIEVING_PAP_POLICY = - "Error while retrieving entitlement policy %s from the PAP policy store"; - - /** - * Insert a policy to PAP. - * - * @param policy policy. - */ - public void insertPolicy(PolicyDTO policy, int tenantId) throws EntitlementException { - - Connection connection = IdentityDatabaseUtil.getDBConnection(true); - try { - - insertPolicy(connection, policy, tenantId); - insertPolicyReferences(connection, policy, tenantId); - if (policy.getAttributeDTOs() != null && EntitlementUtil.isPolicyMetadataStoringEnabled()) { - insertPolicyAttributes(connection, policy, tenantId); - } - insertPolicyEditorData(connection, policy, tenantId); - IdentityDatabaseUtil.commitTransaction(connection); - - } catch (SQLException e) { - IdentityDatabaseUtil.rollbackTransaction(connection); - throw new EntitlementException("Error while adding or updating entitlement policy in policy store", e); - } finally { - IdentityDatabaseUtil.closeConnection(connection); - } - } - - /** - * Delete the given policy version from the PAP. - * - * @param policyId policyId. - * @param version version. - * @throws EntitlementException throws, if fails. - */ - public void deletePAPPolicyVersion(String policyId, int version, int tenantId) throws EntitlementException { - - Connection connection = IdentityDatabaseUtil.getDBConnection(true); - - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Removing policy version %s %s", policyId, version)); - } - try (NamedPreparedStatement findPDPPresencePrepStmt = new NamedPreparedStatement(connection, - GET_POLICY_PDP_PRESENCE_BY_VERSION_SQL); - NamedPreparedStatement removePolicyFromPAPPrepStmt = new NamedPreparedStatement(connection, - DELETE_PAP_POLICY_BY_VERSION_SQL); - NamedPreparedStatement removePolicyPrepStmt = new NamedPreparedStatement(connection, - DELETE_POLICY_VERSION_SQL)) { - - // Find whether the policy is published or not - findPDPPresencePrepStmt.setBoolean(IS_IN_PDP, IN_PDP); - findPDPPresencePrepStmt.setString(POLICY_ID, policyId); - findPDPPresencePrepStmt.setInt(VERSION, version); - findPDPPresencePrepStmt.setInt(TENANT_ID, tenantId); - try (ResultSet resultSet = findPDPPresencePrepStmt.executeQuery()) { - - if (resultSet.next()) { - // Remove the policy version from the PAP (It is still present in PDP) - removePolicyFromPAPPrepStmt.setBoolean(IS_IN_PAP, !IN_PAP); - removePolicyFromPAPPrepStmt.setString(POLICY_ID, policyId); - removePolicyFromPAPPrepStmt.setInt(VERSION, version); - removePolicyFromPAPPrepStmt.setInt(TENANT_ID, tenantId); - removePolicyFromPAPPrepStmt.executeUpdate(); - } else { - // Remove the policy version from the database - removePolicyPrepStmt.setString(POLICY_ID, policyId); - removePolicyPrepStmt.setInt(VERSION, version); - removePolicyPrepStmt.setInt(TENANT_ID, tenantId); - removePolicyPrepStmt.executeUpdate(); - } - } - IdentityDatabaseUtil.commitTransaction(connection); - - } catch (SQLException e) { - IdentityDatabaseUtil.rollbackTransaction(connection); - throw new EntitlementException(String.format("Error while removing policy version %s %s from PAP policy " + - "store", policyId, version), e); - } finally { - IdentityDatabaseUtil.closeConnection(connection); - } - } - - /** - * Get a policy from PAP. - * - * @param policyId policyId. - * @throws EntitlementException throws, if fails. - */ - public PolicyDTO getPAPPolicy(String policyId, int tenantId) throws EntitlementException { - - try (Connection connection = IdentityDatabaseUtil.getDBConnection(false)) { - try (NamedPreparedStatement prepStmt = new NamedPreparedStatement(connection, GET_PAP_POLICY_SQL)) { - prepStmt.setBoolean(IS_IN_PAP, IN_PAP); - prepStmt.setString(POLICY_ID, policyId); - prepStmt.setInt(TENANT_ID, tenantId); - - try (ResultSet policy = prepStmt.executeQuery()) { - if (policy.next()) { - return getPolicyDTO(policy, connection); - } - return null; - } - } - } catch (SQLException e) { - throw new EntitlementException(String.format(ERROR_RETRIEVING_PAP_POLICY, policyId), e); - } - } - - /** - * Get all PAP policies. - * - * @param tenantId tenant ID. - * @return list of policy DTOs. - */ - public List getAllPAPPolicies(int tenantId) throws EntitlementException { - - List policyDTOs = new ArrayList<>(); - try (Connection connection = IdentityDatabaseUtil.getDBConnection(false)) { - try (NamedPreparedStatement prepStmt = new NamedPreparedStatement(connection, GET_ALL_PAP_POLICIES_SQL)) { - prepStmt.setBoolean(IS_IN_PAP, IN_PAP); - prepStmt.setInt(TENANT_ID, tenantId); - - try (ResultSet policies = prepStmt.executeQuery()) { - while (policies.next()) { - policyDTOs.add(getPolicyDTO(policies, connection)); - } - } - } - } catch (SQLException e) { - throw new EntitlementException("Error while retrieving entitlement policies from the PAP policy store", e); - } - return policyDTOs; - } - - /** - * Get the latest policy version. - * - * @param policyId policy ID. - * @param tenantId tenant ID. - * @throws EntitlementException throws, if fails. - */ - public String getLatestPolicyVersion(String policyId, int tenantId) throws EntitlementException { - - try (Connection connection = IdentityDatabaseUtil.getDBConnection(false)) { - try (NamedPreparedStatement prepStmt = new NamedPreparedStatement(connection, - GET_LATEST_POLICY_VERSION_SQL)) { - prepStmt.setBoolean(IS_IN_PAP, IN_PAP); - prepStmt.setString(POLICY_ID, policyId); - prepStmt.setInt(TENANT_ID, tenantId); - - try (ResultSet latestVersion = prepStmt.executeQuery()) { - if (latestVersion.next()) { - return String.valueOf(latestVersion.getInt(VERSION)); - } - return null; - } - } - } catch (SQLException e) { - throw new EntitlementException(String.format("Error retrieving the latest version of the policy %s", - policyId), e); - } - } - - /** - * Get the policy by version. - * - * @param policyId policy ID. - * @param version version. - * @param tenantId tenant ID. - * @throws EntitlementException throws, if fails. - */ - public PolicyDTO getPapPolicyByVersion(String policyId, String version, int tenantId) throws EntitlementException { - - try (Connection connection = IdentityDatabaseUtil.getDBConnection(false)) { - try (NamedPreparedStatement prepStmt = new NamedPreparedStatement(connection, - GET_PAP_POLICY_BY_VERSION_SQL)) { - prepStmt.setBoolean(IS_IN_PAP, IN_PAP); - prepStmt.setString(POLICY_ID, policyId); - prepStmt.setInt(VERSION, Integer.parseInt(version)); - prepStmt.setInt(TENANT_ID, tenantId); - - try (ResultSet policy = prepStmt.executeQuery()) { - if (policy.next()) { - return getPolicyDTO(policy, connection); - } else { - throw new EntitlementException( - String.format("No policy with the given policyID %s and version %s exists", policyId, - version)); - } - } - } - } catch (SQLException e) { - throw new EntitlementException(String.format(ERROR_RETRIEVING_PAP_POLICY, policyId), e); - } - } - - /** - * Get all the versions of the policy. - * - * @param policyId policy ID. - * @param tenantId tenant ID. - * @return latest version of the policy. - */ - public List getPolicyVersions(String policyId, int tenantId) { - - List versions = new ArrayList<>(); - - try (Connection connection = IdentityDatabaseUtil.getDBConnection(false)) { - try (NamedPreparedStatement prepStmt = new NamedPreparedStatement(connection, GET_POLICY_VERSIONS_SQL)) { - prepStmt.setBoolean(IS_IN_PAP, IN_PAP); - prepStmt.setString(POLICY_ID, policyId); - prepStmt.setInt(TENANT_ID, tenantId); - - try (ResultSet versionsSet = prepStmt.executeQuery()) { - while (versionsSet.next()) { - versions.add(String.valueOf(versionsSet.getInt(VERSION))); - } - } - } - } catch (SQLException e) { - LOG.error(String.format("Error while retrieving policy versions for policy %s", policyId), e); - } - return versions; - } - - /** - * Get PAP policy ids. - * - * @param tenantId tenant ID. - * @return list of policy IDs. - * @throws EntitlementException If an error occurs. - */ - public List getPAPPolicyIds(int tenantId) throws EntitlementException { - - List policies = new ArrayList<>(); - - try (Connection connection = IdentityDatabaseUtil.getDBConnection(false)) { - try (NamedPreparedStatement prepStmt = new NamedPreparedStatement(connection, GET_PAP_POLICY_IDS_SQL)) { - prepStmt.setBoolean(IS_IN_PAP, IN_PAP); - prepStmt.setInt(TENANT_ID, tenantId); - - try (ResultSet policyIds = prepStmt.executeQuery()) { - while (policyIds.next()) { - policies.add(policyIds.getString(POLICY_ID)); - } - if (policies.isEmpty()) { - LOG.debug("No PAP policies found"); - } - return policies; - } - } - } catch (SQLException e) { - throw new EntitlementException( - "Error while retrieving entitlement policy identifiers from PAP policy store", e); - } - } - - /** - * Delete a policy from PAP. - * - * @param policyId policy ID. - * @param tenantId tenant ID. - * @throws EntitlementException If an error occurs. - */ - public void deletePAPPolicy(String policyId, int tenantId) throws EntitlementException { - - Connection connection = IdentityDatabaseUtil.getDBConnection(true); - try { - if (isPolicyPublished(policyId, tenantId)) { - try (NamedPreparedStatement removePolicyByIdAndVersionPrepStmt = new NamedPreparedStatement(connection, - DELETE_UNPUBLISHED_POLICY_VERSIONS_SQL); - NamedPreparedStatement removePolicyFromPAPPrepStmt = new NamedPreparedStatement(connection, - DELETE_PAP_POLICY_SQL)) { - - // Remove the unpublished versions of the policy from the database - removePolicyByIdAndVersionPrepStmt.setBoolean(IS_IN_PDP, !IN_PDP); - removePolicyByIdAndVersionPrepStmt.setString(POLICY_ID, policyId); - removePolicyByIdAndVersionPrepStmt.setInt(TENANT_ID, tenantId); - removePolicyByIdAndVersionPrepStmt.executeUpdate(); - - // Remove the published version of the policy from the PAP (It is still present in PDP) - removePolicyFromPAPPrepStmt.setBoolean(IS_IN_PAP, !IN_PAP); - removePolicyFromPAPPrepStmt.setBoolean(IS_IN_PDP, IN_PDP); - removePolicyFromPAPPrepStmt.setString(POLICY_ID, policyId); - removePolicyFromPAPPrepStmt.setInt(TENANT_ID, tenantId); - removePolicyFromPAPPrepStmt.executeUpdate(); - } - } else { - try (NamedPreparedStatement removePolicyPrepStmt = new NamedPreparedStatement(connection, - DELETE_POLICY_SQL)) { - // Remove the policy from the database - removePolicyPrepStmt.setString(POLICY_ID, policyId); - removePolicyPrepStmt.setInt(TENANT_ID, tenantId); - removePolicyPrepStmt.executeUpdate(); - } - } - - IdentityDatabaseUtil.commitTransaction(connection); - - } catch (SQLException e) { - IdentityDatabaseUtil.rollbackTransaction(connection); - throw new EntitlementException( - String.format("Error while removing policy %s from PAP policy store", policyId), e); - } finally { - IdentityDatabaseUtil.closeConnection(connection); - } - } - - /** - * Check the existence of the policy in PAP. - * - * @param policyId policy ID. - * @param tenantId tenant ID. - * @return whether the policy exists in PAP or not. - */ - public boolean isPAPPolicyExists(String policyId, int tenantId) { - - try (Connection connection = IdentityDatabaseUtil.getDBConnection(false)) { - try (NamedPreparedStatement getPolicyPublishStatus = new NamedPreparedStatement(connection, - GET_POLICY_PAP_PRESENCE_SQL)) { - getPolicyPublishStatus.setBoolean(IS_IN_PAP, IN_PAP); - getPolicyPublishStatus.setString(POLICY_ID, policyId); - getPolicyPublishStatus.setInt(TENANT_ID, tenantId); - - try (ResultSet rs = getPolicyPublishStatus.executeQuery()) { - return rs.next(); - } - } - } catch (SQLException e) { - LOG.error(String.format("Error while checking the existence of the policy %s.", policyId), e); - return false; - } - } - - /** - * Get the published policy from PDP. - * - * @param policyId policy ID. - * @param tenantId tenant ID. - * @return latest version of the policy. - */ - public PolicyStoreDTO getPDPPolicy(String policyId, int tenantId) { - - try (Connection connection = IdentityDatabaseUtil.getDBConnection(false)) { - try (NamedPreparedStatement prepStmt = new NamedPreparedStatement(connection, GET_PDP_POLICY_SQL)) { - prepStmt.setBoolean(IS_IN_PDP, IN_PDP); - prepStmt.setString(POLICY_ID, policyId); - prepStmt.setInt(TENANT_ID, tenantId); - - try (ResultSet resultSet = prepStmt.executeQuery()) { - if (resultSet.next()) { - PolicyStoreDTO dto = new PolicyStoreDTO(); - String policyString = resultSet.getString(POLICY); - int version = resultSet.getInt(VERSION); - AttributeDTO[] attributes = getPolicyAttributes(connection, tenantId, policyId, version); - - dto.setPolicyId(policyId); - dto.setPolicy(policyString); - dto.setPolicyOrder(resultSet.getInt(POLICY_ORDER)); - dto.setActive(resultSet.getBoolean(IS_ACTIVE)); - dto.setVersion(String.valueOf(version)); - dto.setAttributeDTOs(attributes); - return dto; - } - } - } - } catch (SQLException e) { - LOG.error(String.format("Error while retrieving PDP policy %s", policyId), e); - } - return null; - } - - /** - * Returns all the published policies as PolicyDTOs. - * - * @return policies as PolicyDTO[]. - * @throws EntitlementException throws if fails. - */ - public PolicyStoreDTO[] getAllPDPPolicies(int tenantId) throws EntitlementException { - - List policies = new ArrayList<>(); - - LOG.debug("Retrieving all PDP entitlement policies"); - try (Connection connection = IdentityDatabaseUtil.getDBConnection(false)) { - try (NamedPreparedStatement prepStmt = new NamedPreparedStatement(connection, GET_ALL_PDP_POLICIES_SQL)) { - prepStmt.setBoolean(IS_IN_PDP, IN_PDP); - prepStmt.setInt(TENANT_ID, tenantId); - - try (ResultSet policySet = prepStmt.executeQuery()) { - while (policySet.next()) { - String policy = policySet.getString(POLICY); - String policyId = policySet.getString(POLICY_ID); - int version = policySet.getInt(VERSION); - AttributeDTO[] attributes = getPolicyAttributes(connection, tenantId, policyId, version); - - PolicyStoreDTO dto = new PolicyStoreDTO(); - dto.setPolicyId(policyId); - dto.setPolicy(policy); - dto.setPolicyOrder(policySet.getInt(POLICY_ORDER)); - dto.setActive(policySet.getBoolean(IS_ACTIVE)); - dto.setVersion(String.valueOf(version)); - dto.setAttributeDTOs(attributes); - policies.add(dto); - } - return policies.toArray(new PolicyStoreDTO[0]); - } - } - } catch (SQLException e) { - throw new EntitlementException("Error while retrieving PDP policies", e); - } - } - - /** - * DAO method to get PDP policy ids. - * - * @param tenantId tenant ID. - * @throws EntitlementException If an error occurs. - */ - public List getPublishedPolicyIds(int tenantId) throws EntitlementException { - - List policyIds = new ArrayList<>(); - try (Connection connection = IdentityDatabaseUtil.getDBConnection(false)) { - try (NamedPreparedStatement prepStmt = new NamedPreparedStatement(connection, GET_PDP_POLICY_IDS_SQL)) { - prepStmt.setBoolean(IS_IN_PDP, IN_PDP); - prepStmt.setInt(TENANT_ID, tenantId); - - try (ResultSet resultSet = prepStmt.executeQuery()) { - while (resultSet.next()) { - policyIds.add(resultSet.getString(POLICY_ID)); - } - return policyIds; - } - } - } catch (SQLException e) { - throw new EntitlementException("Error while retrieving PDP policy ids", e); - } - } - - /** - * Publish a new policy version. For inserts, `isSetActive()` and `isSetOrder()` will be true. For updates, both - * will be false. - * - * @param policy policy. - * @param tenantId tenant ID. - * @throws EntitlementException If an error occurs. - */ - public void insertOrUpdatePolicy(PolicyStoreDTO policy, int tenantId) throws EntitlementException { - - Connection connection = IdentityDatabaseUtil.getDBConnection(true); - try { - int version = Integer.parseInt(policy.getVersion()); - if (policy.isSetActive()) { - updateActiveStatus(connection, policy, version, tenantId); - } - if (policy.isSetOrder() && policy.getPolicyOrder() > 0) { - updateOrder(connection, policy, version, tenantId); - } - - boolean previousActive = false; - int previousOrder = 0; - if (!policy.isSetActive() && !policy.isSetOrder()) { - // Get active status and order of the previously published policy version. - try (NamedPreparedStatement getActiveStatusAndOrderPrepStmt = new NamedPreparedStatement(connection, - GET_ACTIVE_STATUS_AND_ORDER_SQL)) { - getActiveStatusAndOrderPrepStmt.setBoolean(IS_IN_PDP, IN_PDP); - getActiveStatusAndOrderPrepStmt.setString(POLICY_ID, policy.getPolicyId()); - getActiveStatusAndOrderPrepStmt.setInt(TENANT_ID, tenantId); - try (ResultSet rs = getActiveStatusAndOrderPrepStmt.executeQuery()) { - if (rs.next()) { - previousActive = rs.getBoolean(IS_ACTIVE); - previousOrder = rs.getInt(POLICY_ORDER); - } - } - } - - // Remove previously published versions of the policy. - try (NamedPreparedStatement updatePublishStatusPrepStmt = new NamedPreparedStatement(connection, - DELETE_PUBLISHED_VERSIONS_SQL)) { - updatePublishStatusPrepStmt.setBoolean(IS_IN_PDP, !IN_PDP); - updatePublishStatusPrepStmt.setBoolean(IS_ACTIVE, INACTIVE); - updatePublishStatusPrepStmt.setInt(POLICY_ORDER, DEFAULT_POLICY_ORDER); - updatePublishStatusPrepStmt.setBoolean(IS_IN_PDP_1, IN_PDP); - updatePublishStatusPrepStmt.setString(POLICY_ID, policy.getPolicyId()); - updatePublishStatusPrepStmt.setInt(TENANT_ID, tenantId); - updatePublishStatusPrepStmt.executeUpdate(); - } - - // When removing previously published versions, - // If the policy has been already removed from PAP, remove the policy from the database. - try (NamedPreparedStatement removePolicyPrepStmt = new NamedPreparedStatement(connection, - DELETE_UNUSED_POLICY_SQL)) { - removePolicyPrepStmt.setBoolean(IS_IN_PAP, !IN_PAP); - removePolicyPrepStmt.setBoolean(IS_IN_PDP, !IN_PDP); - removePolicyPrepStmt.setString(POLICY_ID, policy.getPolicyId()); - removePolicyPrepStmt.setInt(TENANT_ID, tenantId); - removePolicyPrepStmt.executeUpdate(); - } - } - - // Publish the given version of the policy - publishPolicyVersion(policy, tenantId, connection, version); - - // If this is an update, keep the previous active status and order - if (!policy.isSetActive() && !policy.isSetOrder()) { - try (NamedPreparedStatement updatePolicyStatusAndOrderPrepStmt = new NamedPreparedStatement(connection, - RESTORE_ACTIVE_STATUS_AND_ORDER_SQL)) { - updatePolicyStatusAndOrderPrepStmt.setBoolean(IS_ACTIVE, previousActive); - updatePolicyStatusAndOrderPrepStmt.setInt(POLICY_ORDER, previousOrder); - updatePolicyStatusAndOrderPrepStmt.setString(POLICY_ID, policy.getPolicyId()); - updatePolicyStatusAndOrderPrepStmt.setInt(VERSION, version); - updatePolicyStatusAndOrderPrepStmt.setInt(TENANT_ID, tenantId); - updatePolicyStatusAndOrderPrepStmt.executeUpdate(); - } - } - IdentityDatabaseUtil.commitTransaction(connection); - - } catch (SQLException e) { - IdentityDatabaseUtil.rollbackTransaction(connection); - throw new EntitlementException("Error while publishing policy", e); - } finally { - IdentityDatabaseUtil.closeConnection(connection); - } - } - - /** - * Update the active status or order of a published policy. - * - * @param policy policy. - * @param tenantId tenant ID. - * @throws EntitlementException If an error occurs. - */ - public void updateActiveStatusAndOrder(PolicyStoreDTO policy, int tenantId) throws EntitlementException { - - try (Connection connection = IdentityDatabaseUtil.getDBConnection(false)) { - int version = Integer.parseInt(policy.getVersion()); - if (policy.isSetActive()) { - updateActiveStatus(connection, policy, version, tenantId); - } - if (policy.isSetOrder() && policy.getPolicyOrder() > 0) { - updateOrder(connection, policy, version, tenantId); - } - } catch (SQLException | EntitlementException e) { - throw new EntitlementException(String.format("Error while publishing policy %s", policy.getPolicyId()), e); - } - } - - /** - * Get the version of a published policy. - * - * @param policy policy. - * @param tenantId tenant ID. - * @throws EntitlementException throws, if fails. - */ - public int getPublishedVersion(PolicyStoreDTO policy, int tenantId) throws EntitlementException { - - try (Connection connection = IdentityDatabaseUtil.getDBConnection(true)) { - try (NamedPreparedStatement getPublishedVersionPrepStmt = new NamedPreparedStatement(connection, - GET_PUBLISHED_POLICY_VERSION_SQL)) { - getPublishedVersionPrepStmt.setBoolean(IS_IN_PDP, IN_PDP); - getPublishedVersionPrepStmt.setString(POLICY_ID, policy.getPolicyId()); - getPublishedVersionPrepStmt.setInt(TENANT_ID, tenantId); - try (ResultSet rs = getPublishedVersionPrepStmt.executeQuery()) { - if (rs.next()) { - return rs.getInt(VERSION); - } - } - } - } catch (SQLException e) { - throw new EntitlementException(String.format("Error while getting published version of policy %s", - policy.getPolicyId())); - } - return -1; - } - - /** - * Unpublish the given policy from PDP. - * - * @param policyId policy ID. - * @param tenantId tenant ID. - * @return whether the policy version is deleted or not. - */ - public boolean unpublishPolicy(String policyId, int tenantId) { - - Connection connection = IdentityDatabaseUtil.getDBConnection(true); - try (NamedPreparedStatement demotePolicyPrepStmt = new NamedPreparedStatement(connection, - DELETE_PUBLISHED_VERSIONS_SQL); - NamedPreparedStatement removePolicyPrepStmt = new NamedPreparedStatement(connection, - DELETE_UNUSED_POLICY_SQL)) { - // Remove the published state of the given policy (Remove from PDP) - demotePolicyPrepStmt.setBoolean(IS_IN_PDP, !IN_PDP); - demotePolicyPrepStmt.setBoolean(IS_ACTIVE, INACTIVE); - demotePolicyPrepStmt.setInt(POLICY_ORDER, DEFAULT_POLICY_ORDER); - demotePolicyPrepStmt.setBoolean(IS_IN_PDP_1, IN_PDP); - demotePolicyPrepStmt.setString(POLICY_ID, policyId); - demotePolicyPrepStmt.setInt(TENANT_ID, tenantId); - demotePolicyPrepStmt.executeUpdate(); - - // If the policy has been already removed from PAP, remove the policy from the database - removePolicyPrepStmt.setBoolean(IS_IN_PAP, !IN_PAP); - removePolicyPrepStmt.setBoolean(IS_IN_PDP, !IN_PDP); - removePolicyPrepStmt.setString(POLICY_ID, policyId); - removePolicyPrepStmt.setInt(TENANT_ID, tenantId); - removePolicyPrepStmt.executeUpdate(); - - IdentityDatabaseUtil.commitTransaction(connection); - return true; - } catch (SQLException e) { - IdentityDatabaseUtil.rollbackTransaction(connection); - LOG.error(String.format("Error while demoting policy %s", policyId), e); - return false; - } finally { - IdentityDatabaseUtil.closeConnection(connection); - } - } - - /** - * Check if the policy is published. - * - * @param policyId policy ID. - * @param tenantId tenant ID. - * @return whether the policy is published or not. - */ - public boolean isPolicyPublished(String policyId, int tenantId) { - - try (Connection connection = IdentityDatabaseUtil.getDBConnection(false)) { - try (NamedPreparedStatement prepStmt = new NamedPreparedStatement(connection, - GET_POLICY_PDP_PRESENCE_SQL)) { - prepStmt.setBoolean(IS_IN_PDP, IN_PDP); - prepStmt.setString(POLICY_ID, policyId); - prepStmt.setInt(TENANT_ID, tenantId); - - try (ResultSet rs = prepStmt.executeQuery()) { - return rs.next(); - } - } - } catch (SQLException e) { - LOG.error(String.format("Error while checking the published status of the policy %s", policyId), e); - return false; - } - } - - private List getPolicyReferences(Connection connection, int tenantId, String policyId, int version) - throws SQLException { - - List policyReferences = new ArrayList<>(); - try (NamedPreparedStatement getPolicyRefsPrepStmt = new NamedPreparedStatement(connection, - GET_PAP_POLICY_REFS_SQL)) { - getPolicyRefsPrepStmt.setString(POLICY_ID, policyId); - getPolicyRefsPrepStmt.setInt(VERSION, version); - getPolicyRefsPrepStmt.setInt(TENANT_ID, tenantId); - try (ResultSet policyRefs = getPolicyRefsPrepStmt.executeQuery()) { - while (policyRefs.next()) { - policyReferences.add( - policyRefs.getString(REFERENCE)); - } - } - return policyReferences; - } - } - - private List getPolicySetReferences(Connection connection, int tenantId, String policyId, int version) - throws SQLException { - - List policySetReferences = new ArrayList<>(); - try (NamedPreparedStatement getPolicySetRefsPrepStmt = new NamedPreparedStatement(connection, - GET_PAP_POLICY_SET_REFS_SQL)) { - - getPolicySetRefsPrepStmt.setString(POLICY_ID, policyId); - getPolicySetRefsPrepStmt.setInt(VERSION, version); - getPolicySetRefsPrepStmt.setInt(TENANT_ID, tenantId); - try (ResultSet policySetRefs = getPolicySetRefsPrepStmt.executeQuery()) { - while (policySetRefs.next()) { - policySetReferences.add( - policySetRefs.getString(SET_REFERENCE)); - } - } - return policySetReferences; - } - } - - private String[] getPolicyEditorData(Connection connection, int tenantId, String policyId, int version) - throws SQLException { - - try (NamedPreparedStatement getPolicyEditorDataPrepStmt = new NamedPreparedStatement(connection, - GET_PAP_POLICY_EDITOR_DATA_SQL)) { - getPolicyEditorDataPrepStmt.setString(POLICY_ID, policyId); - getPolicyEditorDataPrepStmt.setInt(VERSION, version); - getPolicyEditorDataPrepStmt.setInt(TENANT_ID, tenantId); - - try (ResultSet editorMetadata = getPolicyEditorDataPrepStmt.executeQuery()) { - - List basicPolicyEditorMetaDataList = new ArrayList<>(); - if (editorMetadata != null) { - while (editorMetadata.next()) { - int dataOrder = editorMetadata.getInt(EDITOR_DATA_ORDER); - while (basicPolicyEditorMetaDataList.size() <= dataOrder) { - basicPolicyEditorMetaDataList.add(null); - } - basicPolicyEditorMetaDataList.set(dataOrder, editorMetadata.getString(EDITOR_DATA)); - } - } - return basicPolicyEditorMetaDataList.toArray(new String[0]); - } - } - } - - private AttributeDTO[] getPolicyAttributes(Connection connection, int tenantId, String policyId, int version) - throws SQLException { - - List attributeDTOs = new ArrayList<>(); - try (NamedPreparedStatement getPolicyMetaDataPrepStmt = - new NamedPreparedStatement(connection, GET_PAP_POLICY_META_DATA_SQL)) { - getPolicyMetaDataPrepStmt.setString(POLICY_ID, policyId); - getPolicyMetaDataPrepStmt.setInt(VERSION, version); - getPolicyMetaDataPrepStmt.setInt(TENANT_ID, tenantId); - - try (ResultSet metadata = getPolicyMetaDataPrepStmt.executeQuery()) { - while (metadata.next()) { - AttributeDTO attributeDTO = new AttributeDTO(); - attributeDTO.setCategory(metadata.getString(CATEGORY)); - attributeDTO.setAttributeValue(metadata.getString(ATTRIBUTE_VALUE)); - attributeDTO.setAttributeId(metadata.getString(ATTRIBUTE_ID)); - attributeDTO.setAttributeDataType(metadata.getString(DATA_TYPE)); - attributeDTOs.add(attributeDTO); - } - } - } - return attributeDTOs.toArray(new AttributeDTO[0]); - } - - private void insertPolicy(Connection connection, PolicyDTO policy, int tenantId) throws SQLException { - - try (NamedPreparedStatement createPolicyPrepStmt = new NamedPreparedStatement(connection, - CREATE_PAP_POLICY_SQL)) { - - createPolicyPrepStmt.setString(POLICY_ID, policy.getPolicyId()); - createPolicyPrepStmt.setInt(VERSION, Integer.parseInt(policy.getVersion())); - createPolicyPrepStmt.setBoolean(IS_IN_PDP, !IN_PDP); - createPolicyPrepStmt.setBoolean(IS_IN_PAP, IN_PAP); - createPolicyPrepStmt.setString(POLICY, policy.getPolicy()); - createPolicyPrepStmt.setBoolean(IS_ACTIVE, policy.isActive()); - createPolicyPrepStmt.setString(POLICY_TYPE, policy.getPolicyType()); - createPolicyPrepStmt.setString(POLICY_EDITOR, policy.getPolicyEditor()); - createPolicyPrepStmt.setInt(POLICY_ORDER, DEFAULT_POLICY_ORDER); - createPolicyPrepStmt.setTimeStamp(LAST_MODIFIED_TIME, new Timestamp(System.currentTimeMillis()), - Calendar.getInstance(TimeZone.getTimeZone(UTC))); - createPolicyPrepStmt.setString(LAST_MODIFIED_USER, - CarbonContext.getThreadLocalCarbonContext().getUsername()); - createPolicyPrepStmt.setInt(TENANT_ID, tenantId); - - createPolicyPrepStmt.executeUpdate(); - } - } - - private void insertPolicyReferences(Connection connection, PolicyDTO policy, int tenantId) - throws SQLException { - - String[] policyIdReferences = policy.getPolicyIdReferences(); - String[] policySetIdReferences = policy.getPolicySetIdReferences(); - - try (NamedPreparedStatement createPolicyReferencesPrepStmt = new NamedPreparedStatement(connection, - CREATE_PAP_POLICY_REFS_SQL); - NamedPreparedStatement createPolicySetReferencesPrepStmt = new NamedPreparedStatement(connection, - CREATE_PAP_POLICY_SET_REFS_SQL)) { - - for (String policyIdReference : policyIdReferences) { - createPolicyReferencesPrepStmt.setString(REFERENCE, policyIdReference); - createPolicyReferencesPrepStmt.setString(POLICY_ID, policy.getPolicyId()); - createPolicyReferencesPrepStmt.setInt(VERSION, Integer.parseInt(policy.getVersion())); - createPolicyReferencesPrepStmt.setInt(TENANT_ID, tenantId); - createPolicyReferencesPrepStmt.addBatch(); - } - createPolicyReferencesPrepStmt.executeBatch(); - - for (String policySetReference : policySetIdReferences) { - createPolicySetReferencesPrepStmt.setString(SET_REFERENCE, policySetReference); - createPolicySetReferencesPrepStmt.setString(POLICY_ID, policy.getPolicyId()); - createPolicySetReferencesPrepStmt.setInt(VERSION, Integer.parseInt(policy.getVersion())); - createPolicySetReferencesPrepStmt.setInt(TENANT_ID, tenantId); - createPolicySetReferencesPrepStmt.addBatch(); - } - createPolicySetReferencesPrepStmt.executeBatch(); - } - } - - private void insertPolicyAttributes(Connection connection, PolicyDTO policy, int tenantId) throws SQLException { - - try (NamedPreparedStatement createAttributesPrepStmt = new NamedPreparedStatement(connection, - CREATE_PAP_POLICY_ATTRIBUTES_SQL)) { - - AttributeDTO[] attributeDTOs = policy.getAttributeDTOs(); - for (AttributeDTO attributeDTO : attributeDTOs) { - - createAttributesPrepStmt.setString(ATTRIBUTE_ID, attributeDTO.getAttributeId()); - createAttributesPrepStmt.setString(ATTRIBUTE_VALUE, attributeDTO.getAttributeValue()); - createAttributesPrepStmt.setString(DATA_TYPE, attributeDTO.getAttributeDataType()); - createAttributesPrepStmt.setString(CATEGORY, attributeDTO.getCategory()); - createAttributesPrepStmt.setString(POLICY_ID, policy.getPolicyId()); - createAttributesPrepStmt.setInt(VERSION, Integer.parseInt(policy.getVersion())); - createAttributesPrepStmt.setInt(TENANT_ID, tenantId); - createAttributesPrepStmt.addBatch(); - } - createAttributesPrepStmt.executeBatch(); - } - } - - private void insertPolicyEditorData(Connection connection, PolicyDTO policy, int tenantId) throws SQLException { - - // Find policy meta data - String[] policyMetaData = policy.getPolicyEditorData(); - if (policyMetaData != null && policyMetaData.length > 0) { - try (NamedPreparedStatement createPolicyEditorDataPrepStmt = new NamedPreparedStatement(connection, - CREATE_PAP_POLICY_EDITOR_DATA_SQL)) { - int index = 0; - for (String policyData : policyMetaData) { - createPolicyEditorDataPrepStmt.setInt(EDITOR_DATA_ORDER, index); - createPolicyEditorDataPrepStmt.setString(EDITOR_DATA, policyData); - createPolicyEditorDataPrepStmt.setString(POLICY_ID, policy.getPolicyId()); - createPolicyEditorDataPrepStmt.setInt(VERSION, Integer.parseInt(policy.getVersion())); - createPolicyEditorDataPrepStmt.setInt(TENANT_ID, tenantId); - - createPolicyEditorDataPrepStmt.addBatch(); - index++; - } - createPolicyEditorDataPrepStmt.executeBatch(); - } - } - } - - private void updateOrder(Connection connection, PolicyStoreDTO policy, int version, int tenantId) - throws EntitlementException { - - try (NamedPreparedStatement updateOrderPrepStmt = new NamedPreparedStatement(connection, - UPDATE_ORDER_SQL)) { - int order = policy.getPolicyOrder(); - updateOrderPrepStmt.setInt(POLICY_ORDER, order); - updateOrderPrepStmt.setString(POLICY_ID, policy.getPolicyId()); - updateOrderPrepStmt.setInt(VERSION, version); - updateOrderPrepStmt.setInt(TENANT_ID, tenantId); - updateOrderPrepStmt.executeUpdate(); - IdentityDatabaseUtil.closeStatement(updateOrderPrepStmt); - } catch (SQLException e) { - throw new EntitlementException( - String.format("Error while updating policy order of policy %s", policy.getPolicyId()), e); - } - } - - private void updateActiveStatus(Connection connection, PolicyStoreDTO policy, int version, int tenantId) - throws EntitlementException { - - try (NamedPreparedStatement updateActiveStatusPrepStmt = new NamedPreparedStatement(connection, - UPDATE_ACTIVE_STATUS_SQL)) { - updateActiveStatusPrepStmt.setBoolean(IS_ACTIVE, policy.isActive()); - updateActiveStatusPrepStmt.setString(POLICY_ID, policy.getPolicyId()); - updateActiveStatusPrepStmt.setInt(VERSION, version); - updateActiveStatusPrepStmt.setInt(TENANT_ID, tenantId); - updateActiveStatusPrepStmt.executeUpdate(); - IdentityDatabaseUtil.closeStatement(updateActiveStatusPrepStmt); - } catch (SQLException e) { - throw new EntitlementException( - String.format("Error while enabling or disabling policy %s", policy.getPolicyId()), e); - } - } - - private void publishPolicyVersion(PolicyStoreDTO policy, int tenantId, Connection connection, int version) - throws SQLException { - - try (NamedPreparedStatement publishPolicyPrepStmt = new NamedPreparedStatement(connection, - PUBLISH_POLICY_VERSION_SQL)) { - publishPolicyPrepStmt.setBoolean(IS_IN_PDP, IN_PDP); - publishPolicyPrepStmt.setString(POLICY_ID, policy.getPolicyId()); - publishPolicyPrepStmt.setInt(VERSION, version); - publishPolicyPrepStmt.setInt(TENANT_ID, tenantId); - publishPolicyPrepStmt.executeUpdate(); - } - } - - /** - * Returns given policy version as a PolicyDTO. - * - * @param policy policy. - * @return policy as a PolicyDTO. - * @throws SQLException throws, if fails. - */ - private PolicyDTO getPolicyDTO(ResultSet policy, Connection connection) throws SQLException { - - String policyId = policy.getString(POLICY_ID); - String version = String.valueOf(policy.getInt(VERSION)); - int tenantId = policy.getInt(TENANT_ID); - - PolicyDTO dto = new PolicyDTO(); - dto.setPolicyId(policyId); - dto.setVersion(version); - dto.setLastModifiedTime(String.valueOf(policy.getTimestamp(LAST_MODIFIED_TIME).getTime())); - dto.setLastModifiedUser(policy.getString(LAST_MODIFIED_USER)); - dto.setActive(policy.getBoolean(IS_ACTIVE)); - dto.setPolicyOrder(policy.getInt(POLICY_ORDER)); - dto.setPolicyType(policy.getString(POLICY_TYPE)); - dto.setPolicyEditor(policy.getString(POLICY_EDITOR)); - dto.setPolicy(policy.getString(POLICY)); - - // Get policy references - List policyReferences = getPolicyReferences(connection, tenantId, policyId, Integer.parseInt(version)); - dto.setPolicyIdReferences(policyReferences.toArray(new String[0])); - - // Get policy set references - List policySetReferences = - getPolicySetReferences(connection, tenantId, policyId, Integer.parseInt(version)); - dto.setPolicySetIdReferences(policySetReferences.toArray(new String[0])); - - // Get policy editor data - String[] basicPolicyEditorMetaData = - getPolicyEditorData(connection, tenantId, policyId, Integer.parseInt(version)); - dto.setPolicyEditorData(basicPolicyEditorMetaData); - - // Get policy metadata - AttributeDTO[] attributeDTOs = getPolicyAttributes(connection, tenantId, policyId, Integer.parseInt(version)); - dto.setAttributeDTOs(attributeDTOs); - - return dto; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/dao/StatusDAO.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/dao/StatusDAO.java deleted file mode 100644 index 4d1d7cf10278..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/dao/StatusDAO.java +++ /dev/null @@ -1,302 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence.dao; - -import org.wso2.carbon.database.utils.jdbc.NamedPreparedStatement; -import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.common.EntitlementConstants; -import org.wso2.carbon.identity.entitlement.dto.StatusHolder; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.TimeZone; - -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.DatabaseTypes.DB2; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.DatabaseTypes.H2; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.DatabaseTypes.MARIADB; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.DatabaseTypes.MSSQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.DatabaseTypes.MYSQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.DatabaseTypes.ORACLE; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.DatabaseTypes.POSTGRES; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.IS_SUCCESS; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.LOGGED_AT; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.MESSAGE; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.POLICY_ID; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.POLICY_VERSION; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.STATUS_TYPE; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.SUBSCRIBER_ID; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.TARGET; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.TARGET_ACTION; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.TENANT_ID; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.USER; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.VERSION; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.KEY; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.LIMIT; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.CREATE_POLICY_STATUS_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.CREATE_SUBSCRIBER_STATUS_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.DELETE_OLD_POLICY_STATUSES_MSSQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.DELETE_OLD_POLICY_STATUSES_MYSQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.DELETE_OLD_POLICY_STATUSES_ORACLE; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.DELETE_OLD_SUBSCRIBER_STATUSES_MSSQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.DELETE_OLD_SUBSCRIBER_STATUSES_MYSQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.DELETE_OLD_SUBSCRIBER_STATUSES_ORACLE; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.DELETE_POLICY_STATUS_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.DELETE_SUBSCRIBER_STATUS_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.GET_POLICY_STATUS_COUNT_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.GET_POLICY_STATUS_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.GET_SUBSCRIBER_STATUS_COUNT_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.GET_SUBSCRIBER_STATUS_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.STATUS_COUNT; - -import static java.time.ZoneOffset.UTC; - -/** - * This class handles the JDBC operations related to the status data. - */ -public class StatusDAO { - - /** - * Delete all status records. - * - * @param about whether the status is about a policy or publisher. - * @param key key value of the status. - * @throws EntitlementException if fails to delete. - */ - public void deleteStatusTrail(String about, String key, int tenantId) throws EntitlementException { - - String query = EntitlementConstants.Status.ABOUT_POLICY.equals(about) ? - DELETE_POLICY_STATUS_SQL : DELETE_SUBSCRIBER_STATUS_SQL; - try (Connection connection = IdentityDatabaseUtil.getDBConnection(false)) { - try (NamedPreparedStatement deleteStatusPrepStmt = new NamedPreparedStatement(connection, query)) { - deleteStatusPrepStmt.setString(KEY, key); - deleteStatusPrepStmt.setInt(TENANT_ID, tenantId); - deleteStatusPrepStmt.executeUpdate(); - } - } catch (SQLException e) { - throw new EntitlementException("Error while deleting policy status", e); - } - } - - /** - * Get the status records. - * - * @param key key value of the status. - * @param about whether the status is about a policy or publisher. - * @param tenantId tenant id. - * @return list of status holders. - * @throws EntitlementException if fails to get status. - */ - public List getStatus(String key, String about, int tenantId) throws EntitlementException { - - List statusHolders = new ArrayList<>(); - String query = EntitlementConstants.Status.ABOUT_POLICY.equals(about) - ? GET_POLICY_STATUS_SQL - : GET_SUBSCRIBER_STATUS_SQL; - - try (Connection connection = IdentityDatabaseUtil.getDBConnection(false)) { - try (NamedPreparedStatement getStatusPrepStmt = new NamedPreparedStatement(connection, query)) { - getStatusPrepStmt.setString(KEY, key); - getStatusPrepStmt.setInt(TENANT_ID, tenantId); - try (ResultSet statusSet = getStatusPrepStmt.executeQuery()) { - while (statusSet.next()) { - StatusHolder statusHolder = new StatusHolder(about); - statusHolder.setType(statusSet.getString(STATUS_TYPE)); - statusHolder.setSuccess(statusSet.getBoolean(IS_SUCCESS)); - statusHolder.setUser(statusSet.getString(USER)); - statusHolder.setTarget(statusSet.getString(TARGET)); - statusHolder.setTargetAction(statusSet.getString(TARGET_ACTION)); - statusHolder.setTimeInstance(String.valueOf(statusSet.getTimestamp(LOGGED_AT).getTime())); - statusHolder.setMessage(statusSet.getString(MESSAGE)); - - if (EntitlementConstants.Status.ABOUT_POLICY.equals(about)) { - statusHolder.setKey(statusSet.getString(POLICY_ID)); - int version = statusSet.getInt(POLICY_VERSION); - if (version != -1) { - statusHolder.setVersion(Integer.toString(version)); - } - } else { - statusHolder.setKey(statusSet.getString(SUBSCRIBER_ID)); - } - statusHolders.add(statusHolder); - } - } - return statusHolders; - } - } catch (SQLException e) { - throw new EntitlementException("Error while retrieving policy status", e); - } - } - - /** - * Insert status records. - * - * @param about whether the status is about a policy or publisher. - * @param key key value of the status. - * @param statusHolders list of status holders. - * @param tenantId tenant id. - * @throws EntitlementException if fails to insert status. - */ - public void insertStatus(String about, String key, List statusHolders, int tenantId) - throws EntitlementException { - - String query = EntitlementConstants.Status.ABOUT_POLICY.equals(about) - ? CREATE_POLICY_STATUS_SQL - : CREATE_SUBSCRIBER_STATUS_SQL; - - try (Connection connection = IdentityDatabaseUtil.getDBConnection(false)) { - try (NamedPreparedStatement addStatusPrepStmt = new NamedPreparedStatement(connection, query)) { - for (StatusHolder statusHolder : statusHolders) { - - int version = -1; - if (statusHolder.getVersion() != null) { - version = Integer.parseInt(statusHolder.getVersion()); - } - - addStatusPrepStmt.setString(KEY, key); - addStatusPrepStmt.setString(STATUS_TYPE, statusHolder.getType()); - addStatusPrepStmt.setBoolean(IS_SUCCESS, statusHolder.isSuccess()); - addStatusPrepStmt.setString(USER, statusHolder.getUser()); - addStatusPrepStmt.setString(TARGET, statusHolder.getTarget()); - addStatusPrepStmt.setString(TARGET_ACTION, statusHolder.getTargetAction()); - addStatusPrepStmt.setString(MESSAGE, statusHolder.getMessage()); - addStatusPrepStmt.setTimeStamp(LOGGED_AT, new Timestamp(System.currentTimeMillis()), - Calendar.getInstance(TimeZone.getTimeZone(UTC))); - if (EntitlementConstants.Status.ABOUT_POLICY.equals(about)) { - addStatusPrepStmt.setInt(VERSION, version); - } - addStatusPrepStmt.setInt(TENANT_ID, tenantId); - - addStatusPrepStmt.addBatch(); - } - addStatusPrepStmt.executeBatch(); - } - } catch (SQLException e) { - throw new EntitlementException("Error while persisting policy status", e); - } - } - - /** - * Delete excess status records (if surpassing maximum, excess number of old records are deleted). - * - * @param about whether the status is about a policy or publisher. - * @param key key value of the status. - * @param tenantId tenant id. - * @throws EntitlementException if fails to delete. - */ - public void deleteExcessStatusData(String about, String key, int tenantId, int maxRecords) - throws EntitlementException { - - Connection connection = IdentityDatabaseUtil.getDBConnection(true); - try { - // Get the existing status count - int statusCount = getStatusCount(connection, about, key, tenantId); - - // Delete old status data if the count exceeds the maximum records - if (statusCount > maxRecords) { - int statusCountToDelete = statusCount - maxRecords; - deleteStatus(connection, about, key, statusCountToDelete, tenantId); - } - IdentityDatabaseUtil.commitTransaction(connection); - } catch (SQLException e) { - IdentityDatabaseUtil.rollbackTransaction(connection); - throw new EntitlementException("Error while deleting surplus policy status", e); - } finally { - IdentityDatabaseUtil.closeConnection(connection); - } - } - - private void deleteStatus(Connection connection, String about, String key, int statusCountToDelete, int tenantId) - throws SQLException, EntitlementException { - - String query = resolveDeleteStatusQuery(connection, about); - try (NamedPreparedStatement deleteOldRecordsPrepStmt = new NamedPreparedStatement(connection, query)) { - deleteOldRecordsPrepStmt.setString(KEY, key); - deleteOldRecordsPrepStmt.setInt(TENANT_ID, tenantId); - deleteOldRecordsPrepStmt.setInt(LIMIT, statusCountToDelete); - deleteOldRecordsPrepStmt.executeUpdate(); - } - } - - private int getStatusCount(Connection connection, String about, String key, int tenantId) - throws EntitlementException { - - int statusCount = 0; - - String query = EntitlementConstants.Status.ABOUT_POLICY.equals(about) - ? GET_POLICY_STATUS_COUNT_SQL - : GET_SUBSCRIBER_STATUS_COUNT_SQL; - - try (NamedPreparedStatement getStatusCountPrepStmt = new NamedPreparedStatement(connection, query)) { - getStatusCountPrepStmt.setString(KEY, key); - getStatusCountPrepStmt.setInt(TENANT_ID, tenantId); - try (ResultSet count = getStatusCountPrepStmt.executeQuery()) { - if (count.next()) { - statusCount = count.getInt(STATUS_COUNT); - } - } - } catch (SQLException e) { - throw new EntitlementException("Error while getting policy status count", e); - } - return statusCount; - } - - private String resolveDeleteStatusQuery(Connection connection, String about) - throws SQLException, EntitlementException { - - String databaseProductName = connection.getMetaData().getDatabaseProductName(); - - Map policyQueries = new HashMap<>(); - policyQueries.put(MYSQL, DELETE_OLD_POLICY_STATUSES_MYSQL); - policyQueries.put(MARIADB, DELETE_OLD_POLICY_STATUSES_MYSQL); - policyQueries.put(H2, DELETE_OLD_POLICY_STATUSES_MYSQL); - policyQueries.put(MSSQL, DELETE_OLD_POLICY_STATUSES_MSSQL); - policyQueries.put(ORACLE, DELETE_OLD_POLICY_STATUSES_ORACLE); - policyQueries.put(POSTGRES, DELETE_OLD_POLICY_STATUSES_MYSQL); - policyQueries.put(DB2, DELETE_OLD_POLICY_STATUSES_MYSQL); - - Map subscriberQueries = new HashMap<>(); - subscriberQueries.put(MYSQL, DELETE_OLD_SUBSCRIBER_STATUSES_MYSQL); - subscriberQueries.put(MARIADB, DELETE_OLD_SUBSCRIBER_STATUSES_MYSQL); - subscriberQueries.put(H2, DELETE_OLD_SUBSCRIBER_STATUSES_MYSQL); - subscriberQueries.put(MSSQL, DELETE_OLD_SUBSCRIBER_STATUSES_MSSQL); - subscriberQueries.put(ORACLE, DELETE_OLD_SUBSCRIBER_STATUSES_ORACLE); - subscriberQueries.put(POSTGRES, DELETE_OLD_POLICY_STATUSES_MYSQL); - subscriberQueries.put(DB2, DELETE_OLD_POLICY_STATUSES_MYSQL); - - String query; - if (EntitlementConstants.Status.ABOUT_POLICY.equals(about)) { - query = policyQueries.get(databaseProductName); - } else { - query = subscriberQueries.get(databaseProductName); - } - - if (query == null) { - throw new EntitlementException("Database driver could not be identified or not supported."); - } - return query; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/dao/SubscriberDAO.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/dao/SubscriberDAO.java deleted file mode 100644 index d0572e667b51..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/persistence/dao/SubscriberDAO.java +++ /dev/null @@ -1,279 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence.dao; - -import org.apache.commons.lang.ArrayUtils; -import org.apache.commons.lang.StringUtils; -import org.wso2.carbon.database.utils.jdbc.NamedPreparedStatement; -import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.dto.PublisherDataHolder; -import org.wso2.carbon.identity.entitlement.dto.PublisherPropertyDTO; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.DISPLAY_NAME; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.DISPLAY_ORDER; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.ENTITLEMENT_MODULE_NAME; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.IS_REQUIRED; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.IS_SECRET; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.MODULE; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.PROPERTY_ID; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.PROPERTY_VALUE; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.SUBSCRIBER_ID; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.EntitlementTableColumns.TENANT_ID; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.CREATE_SUBSCRIBER_PROPERTIES_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.CREATE_SUBSCRIBER_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.DELETE_SUBSCRIBER_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.GET_SUBSCRIBER_EXISTENCE_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.GET_SUBSCRIBER_IDS_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.GET_SUBSCRIBER_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.UPDATE_SUBSCRIBER_MODULE_SQL; -import static org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerConstants.SQLQueries.UPDATE_SUBSCRIBER_PROPERTIES_SQL; - -/** - * This class handles the JDBC operations of the subscribers in the data store. - */ -public class SubscriberDAO { - - /** - * Get the requested subscriber. - * - * @param subscriberId subscriber ID. - * @param tenantId tenant ID. - * @return publisher data holder. - * @throws EntitlementException If an error occurs. - */ - public PublisherDataHolder getSubscriber(String subscriberId, int tenantId) - throws EntitlementException { - - List propertyDTOList = new ArrayList<>(); - String moduleName = null; - - try (Connection connection = IdentityDatabaseUtil.getDBConnection(false); - NamedPreparedStatement preparedStmt = new NamedPreparedStatement(connection, GET_SUBSCRIBER_SQL)) { - - preparedStmt.setString(SUBSCRIBER_ID, subscriberId); - preparedStmt.setInt(TENANT_ID, tenantId); - - try (ResultSet resultSet = preparedStmt.executeQuery()) { - if (resultSet.next()) { - do { - PublisherPropertyDTO dto = new PublisherPropertyDTO(); - - dto.setId(resultSet.getString(PROPERTY_ID)); - dto.setValue(resultSet.getString(PROPERTY_VALUE)); - dto.setDisplayName(resultSet.getString(DISPLAY_NAME)); - dto.setDisplayOrder(resultSet.getInt(DISPLAY_ORDER)); - dto.setRequired(resultSet.getBoolean(IS_REQUIRED)); - dto.setSecret(resultSet.getBoolean(IS_SECRET)); - dto.setModule(resultSet.getString(MODULE)); - propertyDTOList.add(dto); - - if (StringUtils.isBlank(moduleName)) { - moduleName = resultSet.getString(ENTITLEMENT_MODULE_NAME); - } - - } while (resultSet.next()); - } else { - return null; - } - } - } catch (SQLException e) { - throw new EntitlementException(String.format("Error while retrieving subscriber details of id : %s", - subscriberId), e); - } - - return new PublisherDataHolder(propertyDTOList, moduleName); - } - - /** - * Get all subscriber IDs. - * - * @param tenantId tenant ID. - * @return list of subscriber IDs. - * @throws EntitlementException If an error occurs. - */ - public List getSubscriberIds(int tenantId) throws EntitlementException { - - List subscriberIdList = new ArrayList<>(); - - try (Connection connection = IdentityDatabaseUtil.getDBConnection(false); - NamedPreparedStatement preparedStmt = new NamedPreparedStatement(connection, GET_SUBSCRIBER_IDS_SQL)) { - - preparedStmt.setInt(TENANT_ID, tenantId); - try (ResultSet subscriberIds = preparedStmt.executeQuery()) { - while (subscriberIds.next()) { - subscriberIdList.add(subscriberIds.getString(SUBSCRIBER_ID)); - } - } - - } catch (SQLException e) { - throw new EntitlementException("Error while retrieving subscriber ids", e); - } - return subscriberIdList; - } - - /** - * Insert a subscriber. - * - * @param subscriberId subscriber ID. - * @param holder publisher data holder. - * @param tenantId tenant ID. - * @throws EntitlementException If an error occurs. - */ - public void insertSubscriber(String subscriberId, PublisherDataHolder holder, int tenantId) - throws EntitlementException { - - Connection connection = IdentityDatabaseUtil.getDBConnection(true); - try (NamedPreparedStatement createSubscriberPrepStmt = new NamedPreparedStatement(connection, - CREATE_SUBSCRIBER_SQL); - NamedPreparedStatement createSubscriberPropertiesPrepStmt = new NamedPreparedStatement(connection, - CREATE_SUBSCRIBER_PROPERTIES_SQL)) { - - createSubscriberPrepStmt.setString(SUBSCRIBER_ID, subscriberId); - createSubscriberPrepStmt.setString(ENTITLEMENT_MODULE_NAME, holder.getModuleName()); - createSubscriberPrepStmt.setInt(TENANT_ID, tenantId); - createSubscriberPrepStmt.executeUpdate(); - - for (PublisherPropertyDTO dto : holder.getPropertyDTOs()) { - if (dto.getId() != null && StringUtils.isNotBlank(dto.getValue())) { - - createSubscriberPropertiesPrepStmt.setString(PROPERTY_ID, dto.getId()); - createSubscriberPropertiesPrepStmt.setString(DISPLAY_NAME, dto.getDisplayName()); - createSubscriberPropertiesPrepStmt.setString(PROPERTY_VALUE, dto.getValue()); - createSubscriberPropertiesPrepStmt.setBoolean(IS_REQUIRED, dto.isRequired()); - createSubscriberPropertiesPrepStmt.setInt(DISPLAY_ORDER, dto.getDisplayOrder()); - createSubscriberPropertiesPrepStmt.setBoolean(IS_SECRET, dto.isSecret()); - createSubscriberPropertiesPrepStmt.setString(MODULE, dto.getModule()); - createSubscriberPropertiesPrepStmt.setString(SUBSCRIBER_ID, subscriberId); - createSubscriberPropertiesPrepStmt.setInt(TENANT_ID, tenantId); - - createSubscriberPropertiesPrepStmt.addBatch(); - } - } - createSubscriberPropertiesPrepStmt.executeBatch(); - IdentityDatabaseUtil.commitTransaction(connection); - } catch (SQLException e) { - IdentityDatabaseUtil.rollbackTransaction(connection); - throw new EntitlementException("Error while inserting subscriber details", e); - } finally { - IdentityDatabaseUtil.closeConnection(connection); - } - } - - /** - * Update a subscriber. - * - * @param subscriberId subscriber ID. - * @param updatedModuleName updated module name. - * @param updatedPropertyDTOS updated property DTOs. - * @param tenantId tenant ID. - * @throws EntitlementException If an error occurs. - */ - public void updateSubscriber(String subscriberId, String updatedModuleName, - PublisherPropertyDTO[] updatedPropertyDTOS, int tenantId) - throws EntitlementException { - - Connection connection = IdentityDatabaseUtil.getDBConnection(true); - try { - // Update the module name of an existing subscriber - if (StringUtils.isNotBlank(updatedModuleName)) { - try (NamedPreparedStatement updateSubscriberPrepStmt = new NamedPreparedStatement(connection, - UPDATE_SUBSCRIBER_MODULE_SQL)) { - updateSubscriberPrepStmt.setString(ENTITLEMENT_MODULE_NAME, updatedModuleName); - updateSubscriberPrepStmt.setString(SUBSCRIBER_ID, subscriberId); - updateSubscriberPrepStmt.setInt(TENANT_ID, tenantId); - updateSubscriberPrepStmt.executeUpdate(); - } - } - - // Update the property values of an existing subscriber - if (ArrayUtils.isNotEmpty(updatedPropertyDTOS)) { - try (NamedPreparedStatement updateSubscriberPropertiesPrepStmt = new NamedPreparedStatement(connection, - UPDATE_SUBSCRIBER_PROPERTIES_SQL)) { - for (PublisherPropertyDTO dto : updatedPropertyDTOS) { - updateSubscriberPropertiesPrepStmt.setString(PROPERTY_VALUE, dto.getValue()); - updateSubscriberPropertiesPrepStmt.setString(PROPERTY_ID, dto.getId()); - updateSubscriberPropertiesPrepStmt.setString(SUBSCRIBER_ID, subscriberId); - updateSubscriberPropertiesPrepStmt.setInt(TENANT_ID, tenantId); - updateSubscriberPropertiesPrepStmt.addBatch(); - } - updateSubscriberPropertiesPrepStmt.executeBatch(); - } - } - IdentityDatabaseUtil.commitTransaction(connection); - } catch (SQLException e) { - IdentityDatabaseUtil.rollbackTransaction(connection); - throw new EntitlementException("Error while updating subscriber details", e); - } finally { - IdentityDatabaseUtil.closeConnection(connection); - } - } - - /** - * Delete a subscriber. - * - * @param subscriberId subscriber ID. - * @param tenantId tenant ID. - * @throws EntitlementException If an error occurs. - */ - public void deleteSubscriber(String subscriberId, int tenantId) throws EntitlementException { - - try (Connection connection = IdentityDatabaseUtil.getDBConnection(false); - NamedPreparedStatement preparedStmt = new NamedPreparedStatement(connection, DELETE_SUBSCRIBER_SQL)) { - - preparedStmt.setString(SUBSCRIBER_ID, subscriberId); - preparedStmt.setInt(TENANT_ID, tenantId); - preparedStmt.executeUpdate(); - - } catch (SQLException e) { - throw new EntitlementException("Error while deleting subscriber details", e); - } - } - - /** - * Check whether a subscriber exists. - * - * @param subscriberId subscriber ID. - * @param tenantId tenant ID. - * @return whether the subscriber exists or not. - * @throws EntitlementException If an error occurs. - */ - public boolean isSubscriberExists(String subscriberId, int tenantId) throws EntitlementException { - - try (Connection connection = IdentityDatabaseUtil.getDBConnection(false)) { - try (NamedPreparedStatement findSubscriberExistencePrepStmt = new NamedPreparedStatement(connection, - GET_SUBSCRIBER_EXISTENCE_SQL)) { - findSubscriberExistencePrepStmt.setString(SUBSCRIBER_ID, subscriberId); - findSubscriberExistencePrepStmt.setInt(TENANT_ID, tenantId); - - try (ResultSet resultSet = findSubscriberExistencePrepStmt.executeQuery()) { - return resultSet.next(); - } - } - } catch (SQLException e) { - throw new EntitlementException("Error while checking subscriber existence", e); - } - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pip/AbstractPIPAttributeFinder.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pip/AbstractPIPAttributeFinder.java deleted file mode 100644 index f377d36246e9..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pip/AbstractPIPAttributeFinder.java +++ /dev/null @@ -1,309 +0,0 @@ -/* -* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.pip; - -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.balana.XACMLConstants; -import org.wso2.balana.attr.AttributeValue; -import org.wso2.balana.attr.BagAttribute; -import org.wso2.balana.attr.StringAttribute; -import org.wso2.balana.cond.EvaluationResult; -import org.wso2.balana.ctx.EvaluationCtx; -import org.wso2.carbon.CarbonConstants; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.identity.application.common.model.ApplicationBasicInfo; -import org.wso2.carbon.identity.application.common.model.RoleV2; -import org.wso2.carbon.identity.entitlement.PDPConstants; -import org.wso2.carbon.identity.entitlement.cache.PIPAbstractAttributeCache; -import org.wso2.carbon.identity.entitlement.internal.EntitlementConfigHolder; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; -import org.wso2.carbon.user.core.UserCoreConstants; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.List; -import java.util.Properties; -import java.util.Set; -import java.util.stream.Collectors; - -/** - * Abstract implementation of the PIPAttributeFinder. - */ -public abstract class AbstractPIPAttributeFinder implements PIPAttributeFinder { - - private static final Log log = LogFactory.getLog(AbstractPIPAttributeFinder.class); - protected int tenantId; - private PIPAbstractAttributeCache abstractAttributeFinderCache = null; - private boolean isAbstractAttributeCachingEnabled = false; - - /** - * This is the overloaded simplify version of the getAttributeValues() method. Any one who extends the - * AbstractPIPAttributeFinder can implement this method and get use of the default - * implementation of the getAttributeValues() method which has been implemented within - * AbstractPIPAttributeFinder class - * - * @param subject Name of the subject the returned attributes should apply to. - * @param resource The name of the resource the subject is trying to access. - * @param action The name of the action the subject is trying to execute on resource - * @param environment The name of the environment the subject is trying to access the resource - * @param attributeId The unique id of the required attribute. - * @param issuer The attribute issuer. - * @return Returns a Set of Strings that represent the attribute - * values. - * @throws Exception throws if fails - */ - public abstract Set getAttributeValues(String subject, String resource, String action, - String environment, String attributeId, String issuer) - throws Exception; - - - @Override - public Set getAttributeValues(URI attributeType, URI attributeId, URI category, - String issuer, EvaluationCtx evaluationCtx) throws Exception { - - EvaluationResult subject; - String subjectId = null; - EvaluationResult resource; - String resourceId = null; - EvaluationResult action; - String actionId = null; - EvaluationResult environment; - String environmentId = null; - Set attributeValues = null; - - tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - - subject = evaluationCtx.getAttribute(new URI(StringAttribute.identifier), new URI( - PDPConstants.SUBJECT_ID_DEFAULT), issuer, new URI(XACMLConstants.SUBJECT_CATEGORY)); - if (subject != null && subject.getAttributeValue() != null && - subject.getAttributeValue().isBag()) { - BagAttribute bagAttribute = (BagAttribute) subject.getAttributeValue(); - if (bagAttribute.size() > 0) { - subjectId = ((AttributeValue) bagAttribute.iterator().next()).encode(); - if (log.isDebugEnabled()) { - log.debug(String.format("Finding attributes for the subject %1$s", - subjectId)); - } - } - } - - resource = evaluationCtx.getAttribute(new URI(StringAttribute.identifier), new URI( - PDPConstants.RESOURCE_ID_DEFAULT), issuer, new URI(XACMLConstants.RESOURCE_CATEGORY)); - if (resource != null && resource.getAttributeValue() != null && - resource.getAttributeValue().isBag()) { - BagAttribute bagAttribute = (BagAttribute) resource.getAttributeValue(); - if (bagAttribute.size() > 0) { - resourceId = ((AttributeValue) bagAttribute.iterator().next()).encode(); - if (log.isDebugEnabled()) { - log.debug(String.format("Finding attributes for the resource %1$s", - resourceId)); - } - } - } - - action = evaluationCtx.getAttribute(new URI(StringAttribute.identifier), new URI( - PDPConstants.ACTION_ID_DEFAULT), issuer, new URI(XACMLConstants.ACTION_CATEGORY)); - if (action != null && action.getAttributeValue() != null && - action.getAttributeValue().isBag()) { - BagAttribute bagAttribute = (BagAttribute) action.getAttributeValue(); - if (bagAttribute.size() > 0) { - actionId = ((AttributeValue) bagAttribute.iterator().next()).encode(); - if (log.isDebugEnabled()) { - log.debug(String.format("Finding attributes for the action %1$s", - actionId)); - } - } - } - - environment = evaluationCtx.getAttribute(new URI(StringAttribute.identifier), new URI( - PDPConstants.ENVIRONMENT_ID_DEFAULT), issuer, new URI(XACMLConstants.ENT_CATEGORY)); - if (environment != null && environment.getAttributeValue() != null && - environment.getAttributeValue().isBag()) { - BagAttribute bagAttribute = (BagAttribute) environment.getAttributeValue(); - if (bagAttribute.size() > 0) { - environmentId = ((AttributeValue) bagAttribute.iterator().next()).encode(); - if (log.isDebugEnabled()) { - log.debug(String.format("Finding attributes for the environment %1$s", - environmentId)); - } - } - } - - String key = null; - - if (isAbstractAttributeCachingEnabled) { - key = (subjectId != null ? subjectId : "") + (resourceId != null ? resourceId : "") + - (environmentId != null ? environmentId : "") + (attributeId != null ? attributeId : "") + - (issuer != null ? issuer : "") + - (actionId != null ? actionId : ""); - - attributeValues = abstractAttributeFinderCache.getFromCache(tenantId, key); - if (log.isDebugEnabled()) { - log.debug("Retrieving attributes from cache, tenantId: " + tenantId + ", key: " + key); - } - } - - if (attributeValues == null) { - if (log.isDebugEnabled()) { - log.debug("Carbon Attribute Cache Miss"); - } - attributeValues = getAttributeValues(subjectId, resourceId, actionId, environmentId, - attributeId.toString(), issuer); - // Resolve application roles. - if (UserCoreConstants.INTERNAL_ROLES_CLAIM.equals(attributeId.toString()) && - !CarbonConstants.ENABLE_LEGACY_AUTHZ_RUNTIME) { - String spName = getServiceProviderName(issuer, evaluationCtx); - String spTenantDomain = getServiceProviderTenantDomain(issuer, evaluationCtx); - if (StringUtils.isNotBlank(spName) && StringUtils.isNotBlank(spTenantDomain)) { - Set roleNames = getAssociatedRolesOfApplication(spName, spTenantDomain); - if (roleNames != null && !roleNames.isEmpty()) { - attributeValues = attributeValues.stream().filter(roleNames::contains).collect( - Collectors.toSet()); - } - } - } - if (isAbstractAttributeCachingEnabled && key != null) { - if (attributeValues != null && !attributeValues.isEmpty()) { - abstractAttributeFinderCache.addToCache(tenantId, key, attributeValues); - } - } - } else { - if (log.isDebugEnabled()) { - log.debug("Carbon Attribute Cache Hit"); - } - } - - return attributeValues; - - } - - @Override - public boolean overrideDefaultCache() { - - if (abstractAttributeFinderCache == null) { - Properties properties = EntitlementServiceComponent.getEntitlementConfig().getEngineProperties(); - if ("true".equals(properties.getProperty(PDPConstants.ATTRIBUTE_CACHING))) { - int attributeCachingInterval = -1; - String cacheInterval = properties.getProperty(PDPConstants.ATTRIBUTE_CACHING_INTERVAL); - if (cacheInterval != null) { - try { - attributeCachingInterval = Integer.parseInt(cacheInterval.trim()); - } catch (Exception e) { - //ignore - } - } - abstractAttributeFinderCache = new PIPAbstractAttributeCache(attributeCachingInterval); - isAbstractAttributeCachingEnabled = true; - } - } else { - return true; - } - - return isAbstractAttributeCachingEnabled; - } - - /** - * Get roles associated with the application. - * - * @param spName Service provider name. - * @param spTenantDomain Service provider tenant domain. - * @return Set of roles - * @throws Exception if fails to get roles. - */ - private Set getAssociatedRolesOfApplication(String spName, String spTenantDomain) throws Exception { - - ApplicationBasicInfo applicationBasicInfo = EntitlementConfigHolder.getInstance() - .getApplicationManagementService().getApplicationBasicInfoByName(spName, spTenantDomain); - List roles = EntitlementConfigHolder.getInstance() - .getApplicationManagementService() - .getAssociatedRolesOfApplication(applicationBasicInfo.getApplicationResourceId(), - spTenantDomain); - return roles.stream().map(RoleV2::getName).map( - this::appendInternalDomain).collect(Collectors.toSet()); - } - - /** - * Get name of the service provider. - * - * @param issuer The attribute issuer. - * @param evaluationCtx EvaluationCtx which encapsulates the XACML request. - * @return Set of roles - * @throws URISyntaxException if fails to get service provider name. - */ - private String getServiceProviderName(String issuer, EvaluationCtx evaluationCtx) throws URISyntaxException { - - String spName = null; - EvaluationResult result = evaluationCtx.getAttribute(new URI(StringAttribute.identifier), - new URI(PDPConstants.SERVICE_PROVIDER_NAME), issuer, - new URI(PDPConstants.SERVICE_PROVIDER)); - if (result != null && result.getAttributeValue() != null && result.getAttributeValue().isBag()) { - BagAttribute bagAttribute = (BagAttribute) result.getAttributeValue(); - if (bagAttribute.size() > 0) { - spName = ((AttributeValue) bagAttribute.iterator().next()).encode(); - } - } - return spName; - } - - /** - * Get tenant domain of the service provider. - * - * @param issuer The attribute issuer. - * @param evaluationCtx EvaluationCtx which encapsulates the XACML request. - * @return Set of roles - * @throws URISyntaxException if fails to get service provider tenant domain. - */ - private String getServiceProviderTenantDomain(String issuer, EvaluationCtx evaluationCtx) - throws URISyntaxException { - - String spTenantDomain = null; - EvaluationResult result = evaluationCtx.getAttribute(new URI(StringAttribute.identifier), - new URI(PDPConstants.SERVICE_PROVIDER_TENANT_DOMAIN), issuer, - new URI(PDPConstants.SERVICE_PROVIDER)); - if (result != null && result.getAttributeValue() != null && result.getAttributeValue().isBag()) { - BagAttribute bagAttribute = (BagAttribute) result.getAttributeValue(); - if (bagAttribute.size() > 0) { - spTenantDomain = ((AttributeValue) bagAttribute.iterator().next()).encode(); - } - } - return spTenantDomain; - } - - private String appendInternalDomain(String roleName) { - - if (!roleName.contains(UserCoreConstants.DOMAIN_SEPARATOR)) { - return UserCoreConstants.INTERNAL_DOMAIN + UserCoreConstants.DOMAIN_SEPARATOR + roleName; - } - return roleName; - } - - @Override - public void clearCache() { - if (abstractAttributeFinderCache != null) { - abstractAttributeFinderCache.clearCache(); - } - } - - @Override - public void clearCache(String[] attributeId) { - } - -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pip/AbstractPIPResourceFinder.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pip/AbstractPIPResourceFinder.java deleted file mode 100644 index 4913a43996dc..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pip/AbstractPIPResourceFinder.java +++ /dev/null @@ -1,153 +0,0 @@ -/* -* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.pip; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.wso2.balana.XACMLConstants; -import org.wso2.balana.attr.AttributeValue; -import org.wso2.balana.attr.BagAttribute; -import org.wso2.balana.attr.StringAttribute; -import org.wso2.balana.cond.EvaluationResult; -import org.wso2.balana.ctx.EvaluationCtx; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.identity.entitlement.EntitlementUtil; -import org.wso2.carbon.identity.entitlement.PDPConstants; -import org.wso2.carbon.identity.entitlement.cache.EntitlementBaseCache; -import org.wso2.carbon.identity.entitlement.cache.IdentityCacheEntry; -import org.wso2.carbon.identity.entitlement.cache.IdentityCacheKey; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; - -import java.net.URI; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Properties; -import java.util.Set; - -/** - * Abstract implementation of the PIPResourceFinder. - */ -public abstract class AbstractPIPResourceFinder implements PIPResourceFinder { - - private static final Log log = LogFactory.getLog(CarbonAttributeFinder.class); - private EntitlementBaseCache abstractResourceCache = null; - private boolean isAbstractResourceCacheEnabled = false; - private int tenantId; - - /** - * This is the overloaded simplify version of the findDescendantResources() method. Any one who extends the - * AbstractPIPResourceFinder can implement this method and get use of the default - * implementation of the findDescendantResources() method which has been implemented within - * AbstractPIPResourceFinder class - * - * @param parentResourceId parent resource value - * @param environmentId environment name - * @return Returns a Set of Strings that represent the descendant resources - * @throws Exception throws if any failure is occurred - */ - public abstract Set findDescendantResources(String parentResourceId, String environmentId) - throws Exception; - - @Override - public Set findDescendantResources(String parentResourceId, EvaluationCtx context) - throws Exception { - - EvaluationResult environment; - String environmentId = null; - Set resourceNames = null; - - NodeList children = context.getRequestRoot().getChildNodes(); - for (int i = 0; i < children.getLength(); i++) { - Node child = children.item(i); - if (child != null) { - if (PDPConstants.ENVIRONMENT_ELEMENT.equals(child.getLocalName())) { - if (child.getChildNodes() != null && child.getChildNodes().getLength() > 0) { - environment = context.getAttribute(new URI(StringAttribute.identifier), - new URI(PDPConstants.ENVIRONMENT_ID_DEFAULT), null, - new URI(XACMLConstants.ENT_CATEGORY)); - if (environment != null && environment.getAttributeValue() != null && - environment.getAttributeValue().isBag()) { - BagAttribute attr = (BagAttribute) environment.getAttributeValue(); - environmentId = ((AttributeValue) attr.iterator().next()).encode(); - } - } - } - } - } - - if (isAbstractResourceCacheEnabled) { - IdentityCacheKey cacheKey; - String key = PDPConstants.RESOURCE_DESCENDANTS + parentResourceId + - (environmentId != null ? environmentId : ""); - tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - cacheKey = new IdentityCacheKey(tenantId, key); - IdentityCacheEntry cacheEntry = (IdentityCacheEntry) abstractResourceCache.getValueFromCache(cacheKey); - if (cacheEntry != null) { - String[] values = cacheEntry.getCacheEntryArray(); - resourceNames = new HashSet(Arrays.asList(values)); - if (log.isDebugEnabled()) { - log.debug("Carbon Resource Cache Hit"); - } - } - - if (resourceNames != null) { - resourceNames = findDescendantResources(parentResourceId, environmentId); - if (log.isDebugEnabled()) { - log.debug("Carbon Resource Cache Miss"); - } - if (resourceNames != null && !resourceNames.isEmpty()) { - cacheEntry = new IdentityCacheEntry(resourceNames.toArray(new String[resourceNames.size()])); - abstractResourceCache.addToCache(cacheKey, cacheEntry); - } - } - } else { - resourceNames = findDescendantResources(parentResourceId, environmentId); - } - - return resourceNames; - } - - @Override - public boolean overrideDefaultCache() { - Properties properties = EntitlementServiceComponent.getEntitlementConfig().getEngineProperties(); - if ("true".equals(properties.getProperty(PDPConstants.RESOURCE_CACHING))) { - abstractResourceCache = EntitlementUtil - .getCommonCache(PDPConstants.PIP_ABSTRACT_RESOURCE_CACHE); - isAbstractResourceCacheEnabled = true; - return true; - } else { - return false; - } - } - - @Override - public void clearCache() { - if (abstractResourceCache != null) { - abstractResourceCache.clear(); - } - } - - @Override - public Set findChildResources(String parentResourceId, EvaluationCtx context) - throws Exception { - return null; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pip/CarbonAttributeFinder.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pip/CarbonAttributeFinder.java deleted file mode 100644 index 6b946b5f7d27..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pip/CarbonAttributeFinder.java +++ /dev/null @@ -1,323 +0,0 @@ -/* -* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.pip; - -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.balana.ParsingException; -import org.wso2.balana.attr.AttributeValue; -import org.wso2.balana.attr.BagAttribute; -import org.wso2.balana.cond.EvaluationResult; -import org.wso2.balana.ctx.Attribute; -import org.wso2.balana.ctx.EvaluationCtx; -import org.wso2.balana.ctx.Status; -import org.wso2.balana.finder.AttributeFinderModule; -import org.wso2.balana.xacml3.Attributes; -import org.wso2.carbon.identity.entitlement.EntitlementUtil; -import org.wso2.carbon.identity.entitlement.PDPConstants; -import org.wso2.carbon.identity.entitlement.cache.PIPAttributeCache; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; -import org.wso2.carbon.identity.entitlement.pdp.EntitlementEngine; - -import javax.xml.transform.TransformerException; -import java.io.ByteArrayOutputStream; -import java.io.OutputStream; -import java.net.URI; -import java.net.URISyntaxException; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -/** - * CarbonAttributeFinder registers with sun-xacml engine as an AttributeFinderModule and delegate - * functionality to the attribute handlers registered with it self. - *

    - * Whenever the XACML engine finds a missing attribute in the XACML request - it will call the - * findAttribute() method of this class. - */ -public class CarbonAttributeFinder extends AttributeFinderModule { - - private Map> attrFinders = new HashMap>(); - private static final Log log = LogFactory.getLog(CarbonAttributeFinder.class); - private PIPAttributeCache attributeFinderCache = null; - protected int tenantId; - - public CarbonAttributeFinder(int tenantId) { - this.tenantId = tenantId; - } - - /** - * Registers PIP attribute handlers with the PDP against their supported attributes. This PIP - * attribute handlers are picked from pip-config.xml file - which should be inside - * [CARBON_HOME]\repository\conf. - */ - public void init() { - Map designators = EntitlementServiceComponent.getEntitlementConfig() - .getDesignators(); - Properties properties = EntitlementServiceComponent.getEntitlementConfig().getEngineProperties(); - if ("true".equals(properties.getProperty(PDPConstants.ATTRIBUTE_CACHING))) { - int attributeCachingInterval = -1; - String cacheInterval = properties.getProperty(PDPConstants.ATTRIBUTE_CACHING_INTERVAL); - if (cacheInterval != null) { - try { - attributeCachingInterval = Integer.parseInt(cacheInterval.trim()); - } catch (Exception e) { - //ignore - } - } - attributeFinderCache = new PIPAttributeCache(attributeCachingInterval); - } - // clear decision cache - if (designators != null && !designators.isEmpty()) { - Set pipAttributeFinders = designators.keySet(); - for (Iterator iterator = pipAttributeFinders.iterator(); iterator.hasNext(); ) { - PIPAttributeFinder pipAttributeFinder = (PIPAttributeFinder) iterator.next(); - Set attrs = pipAttributeFinder.getSupportedAttributes(); - if (attrs != null) { - for (Iterator attrsIter = attrs.iterator(); attrsIter.hasNext(); ) { - String attr = (String) attrsIter.next(); - if (attrFinders.containsKey(attr)) { - List finders = attrFinders.get(attr); - if (!finders.contains(pipAttributeFinder)) { - finders.add(pipAttributeFinder); - if (log.isDebugEnabled()) { - log.debug(String - .format("PIP attribute handler %1$s registered for the " + - "supported attribute %2$s", - pipAttributeFinder.getClass(), attr)); - } - } - } else { - List finders = new ArrayList(); - finders.add(pipAttributeFinder); - attrFinders.put(attr, finders); - if (log.isDebugEnabled()) { - log.debug(String - .format("PIP attribute handler %1$s registered for the supported " + - "attribute %2$s", - pipAttributeFinder.getClass(), attr)); - } - } - } - } - } - } - } - - /* - * (non-Javadoc) - * - * @see org.wso2.balana.finder.AttributeFinderModule#findAttribute(java.net.URI, java.net.URI, - * java.net.URI, java.net.URI, org.wso2.balana.EvaluationCtx, int) - */ - public EvaluationResult findAttribute(URI attributeType, URI attributeId, String issuer, - URI category, EvaluationCtx context) { - - List attrBag = new ArrayList(); - // Get the list of attribute finders who are registered with this particular attribute. - - - List finders = null; - - if (StringUtils.isNotBlank(category.toString())) { - finders = attrFinders.get(category.toString()); - if (log.isDebugEnabled()) { - log.debug("No attribute designators defined for the category " + category.toString()); - } - } - - if (CollectionUtils.isEmpty(finders)) { - finders = attrFinders.get(attributeId.toString()); - if (CollectionUtils.isEmpty(finders)) { - if (log.isDebugEnabled()) { - log.debug("No attribute designators defined for the attribute " + attributeId.toString()); - } - return new EvaluationResult(BagAttribute.createEmptyBag(attributeType)); - - } - } - - try { - - for (Iterator iterator = finders.iterator(); iterator.hasNext(); ) { - PIPAttributeFinder pipAttributeFinder = (PIPAttributeFinder) iterator.next(); - if (log.isDebugEnabled()) { - log.debug(String.format( - "Finding attributes with the PIP attribute handler %1$s", - pipAttributeFinder.getClass())); - } - - Set attrs = null; - String key = null; - - if (attributeFinderCache != null && !pipAttributeFinder.overrideDefaultCache()) { - - key = "[" + attributeType.toString() + "][" + attributeId.toString() + "][" + category.toString() + - "][" + encodeContext(context) + "]"; - - if (issuer != null) { - key += "[" + issuer + "]"; - } - - if (key != null) { - if (log.isDebugEnabled()) { - log.debug("Retrieving attributes from cache, tenantId: " + tenantId + ", key: " + key); - } - attrs = attributeFinderCache.getFromCache(tenantId, key); - } - } - - if (attrs == null) { - attrs = pipAttributeFinder.getAttributeValues(attributeType, attributeId, category, - issuer, context); - if (attributeFinderCache != null && key != null - && !pipAttributeFinder.overrideDefaultCache()) { - attributeFinderCache.addToCache(tenantId, key, attrs); - } - } - - if (attrs != null) { - for (Iterator iterAttr = attrs.iterator(); iterAttr.hasNext(); ) { - final String attr = (String) iterAttr.next(); - AttributeValue attribute = EntitlementUtil. - getAttributeValue(attr, attributeType.toString()); - attrBag.add(attribute); - if (log.isDebugEnabled()) { - log.debug("Attribute added to the attributeBag: \'" + attr + "\'"); - } - } - } - } - } catch (ParsingException e) { - log.error("Error while parsing attribute values from EvaluationCtx : ", e); - ArrayList code = new ArrayList(); - code.add(Status.STATUS_MISSING_ATTRIBUTE); - Status status = new Status(code, - "Error while parsing attribute values from EvaluationCtx : " + e.getMessage()); - return new EvaluationResult(status); - } catch (ParseException e) { - e.printStackTrace(); - log.error("Error while parsing attribute values from EvaluationCtx : ", e); - ArrayList code = new ArrayList(); - code.add(Status.STATUS_MISSING_ATTRIBUTE); - Status status = new Status(code, - "Error while parsing attribute values from EvaluationCtx : " + e.getMessage()); - return new EvaluationResult(status); - } catch (URISyntaxException e) { - log.error("Error while parsing attribute values from EvaluationCtx : ", e); - ArrayList code = new ArrayList(); - code.add(Status.STATUS_MISSING_ATTRIBUTE); - Status status = new Status(code, - "Error while parsing attribute values from EvaluationCtx :" + e.getMessage()); - return new EvaluationResult(status); - } catch (Exception e) { - log.error("Error while retrieving attribute values from PIP attribute finder : ", e); - ArrayList code = new ArrayList(); - code.add(Status.STATUS_MISSING_ATTRIBUTE); - Status status = new Status(code, "Error while retrieving attribute values from PIP" - + " attribute finder : " + e.getMessage()); - return new EvaluationResult(status); - } - return new EvaluationResult(new BagAttribute(attributeType, attrBag)); - } - - /* - * (non-Javadoc) - * - * @see org.wso2.balana.finder.AttributeFinderModule#isDesignatorSupported() - */ - public boolean isDesignatorSupported() { - return true; - } - - - /* - * (non-Javadoc) - * - * @see org.wso2.balana.finder.AttributeFinderModule#getSupportedIds() - */ - public Set getSupportedIds() { - return null; - } - - /** - * Registers PIP attribute handlers are initialized when the server is start-up. This method can - * be used to refresh all attribute finders internally. refreshSupportedAttribute() method must be - * implemented within the PIP attribute finder to perform this operation. Also this uses to find newly - * defined attributes, attribute caches are would not be cleared. - * - * @throws Exception throws then initialization of attribute finders are failed - */ - private void refreshAttributeFindersForNewAttributeId() throws Exception { - Map designators = EntitlementServiceComponent.getEntitlementConfig() - .getDesignators(); - if (designators != null && !designators.isEmpty()) { - Set> attributeFinders = designators.entrySet(); - for (Map.Entry attributeFinder : attributeFinders) { - attributeFinder.getKey().init(attributeFinder.getValue()); - } - init(); - } - } - - - /** - * Clears attribute cache - */ - public void clearAttributeCache() { - if (attributeFinderCache != null) { - attributeFinderCache.clearCache(); - // clear decision cache - EntitlementEngine.getInstance().clearDecisionCache(); - } - } - - /** - * Converts DOM object to String. This is a helper method for creating cache key - * - * @param evaluationCtx EvaluationCtx - * @return String Object - * @throws TransformerException Exception throws if fails - */ - private String encodeContext(EvaluationCtx evaluationCtx) throws TransformerException { - OutputStream stream = new ByteArrayOutputStream(); - evaluationCtx.getRequestCtx().encode(stream); - String rowContext = stream.toString(); - String contextWithAttributeValues = rowContext + "]["; - - StringBuilder builder = new StringBuilder(); - for (Attributes attributes : evaluationCtx.getRequestCtx().getAttributesSet()) { - builder.append(""); - for (Attribute attribute : attributes.getAttributes()) { - attribute.encode(builder); - } - builder.append(""); - } - contextWithAttributeValues += builder.toString(); - - return contextWithAttributeValues; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pip/CarbonResourceFinder.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pip/CarbonResourceFinder.java deleted file mode 100644 index 09bfa7911b06..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pip/CarbonResourceFinder.java +++ /dev/null @@ -1,273 +0,0 @@ -/* -* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.pip; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.w3c.dom.Node; -import org.wso2.balana.attr.AttributeValue; -import org.wso2.balana.ctx.EvaluationCtx; -import org.wso2.balana.finder.ResourceFinderModule; -import org.wso2.balana.finder.ResourceFinderResult; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.EntitlementUtil; -import org.wso2.carbon.identity.entitlement.PDPConstants; -import org.wso2.carbon.identity.entitlement.cache.EntitlementBaseCache; -import org.wso2.carbon.identity.entitlement.cache.IdentityCacheEntry; -import org.wso2.carbon.identity.entitlement.cache.IdentityCacheKey; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; - -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; -import java.io.StringWriter; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -/** - * CarbonResourceFinder implements the ResourceFinderModule in the sum-xacml. This class would find - * children and descendant resources in the Registry resources which is running on the WSO2 Identity - * Server - */ - -public class CarbonResourceFinder extends ResourceFinderModule { - - private static final Log log = LogFactory.getLog(CarbonResourceFinder.class); - boolean isResourceCachingEnabled = false; - private int tenantId; - private Set resourceFinders = new HashSet(); - //private Cache resourceCache = null; - private EntitlementBaseCache resourceCache = null; - - public CarbonResourceFinder(int tenantId) { - this.tenantId = tenantId; - } - - /** - * initializes the Carbon resource finder by listing the registered resource finders - */ - public void init() { - Map resourceConfigs = EntitlementServiceComponent.getEntitlementConfig() - .getResourceFinders(); - - if (resourceConfigs != null && !resourceConfigs.isEmpty()) { - resourceFinders = resourceConfigs.keySet(); - } - Properties properties = EntitlementServiceComponent.getEntitlementConfig().getEngineProperties(); - if ("true".equals(properties.getProperty(PDPConstants.RESOURCE_CACHING))) { - resourceCache = EntitlementUtil - .getCommonCache(PDPConstants.PIP_RESOURCE_CACHE); - isResourceCachingEnabled = true; - } - } - - @Override - public boolean isChildSupported() { - return true; - } - - @Override - public boolean isDescendantSupported() { - return true; - } - - @Override - public ResourceFinderResult findDescendantResources(AttributeValue parentResourceId, - EvaluationCtx context) { - - ResourceFinderResult resourceFinderResult = null; - Set resources = null; - String dataType = parentResourceId.getType().toString(); - - for (PIPResourceFinder finder : resourceFinders) { - try { - Set resourceNames = null; - if (isResourceCachingEnabled && !finder.overrideDefaultCache()) { - IdentityCacheKey cacheKey = null; - String key = PDPConstants.RESOURCE_DESCENDANTS + parentResourceId.encode() + - domToString(context.getRequestRoot()); - cacheKey = new IdentityCacheKey(tenantId, key); - IdentityCacheEntry cacheEntry = (IdentityCacheEntry) resourceCache.getValueFromCache(cacheKey); - if (cacheEntry != null) { - String[] values = cacheEntry.getCacheEntryArray(); - resourceNames = new HashSet(Arrays.asList(values)); - if (log.isDebugEnabled()) { - log.debug("Carbon Resource Cache Hit"); - } - } - - if (resourceNames != null) { - resourceNames = finder.findDescendantResources(parentResourceId.encode(), context); - if (log.isDebugEnabled()) { - log.debug("Carbon Resource Cache Miss"); - } - cacheEntry = new IdentityCacheEntry(resourceNames.toArray(new String[resourceNames.size()])); - resourceCache.addToCache(cacheKey, cacheEntry); - } - } else { - resourceNames = finder.findDescendantResources(parentResourceId.encode(), context); - } - - if (resourceNames != null && !resourceNames.isEmpty()) { - resources = new HashSet(); - for (String resourceName : resourceNames) { - resources.add(EntitlementUtil.getAttributeValue(resourceName, dataType)); - } - } - } catch (EntitlementException e) { - log.error("Error while finding descendant resources", e); - } catch (TransformerException e) { - log.error("Error while finding descendant resources", e); - } catch (Exception e) { - log.error("Error while finding descendant resources", e); - } - } - - if (resources != null) { - resourceFinderResult = new ResourceFinderResult(resources); - } else { - resourceFinderResult = new ResourceFinderResult(); - } - - return resourceFinderResult; - } - - @Override - public ResourceFinderResult findChildResources(AttributeValue parentResourceId, - EvaluationCtx context) { - ResourceFinderResult resourceFinderResult = null; - Set resources = null; - String dataType = parentResourceId.getType().toString(); - - for (PIPResourceFinder finder : resourceFinders) { - try { - Set resourceNames = null; - if (isResourceCachingEnabled && !finder.overrideDefaultCache()) { - IdentityCacheKey cacheKey = null; - String key = PDPConstants.RESOURCE_CHILDREN + parentResourceId.encode() + - domToString(context.getRequestRoot()); - cacheKey = new IdentityCacheKey(tenantId, key); - IdentityCacheEntry cacheEntry = (IdentityCacheEntry) resourceCache.getValueFromCache(cacheKey); - if (cacheEntry != null) { - String cacheEntryString = cacheEntry.getCacheEntry(); - String[] attributes = cacheEntryString.split(PDPConstants.ATTRIBUTE_SEPARATOR); - if (attributes != null && attributes.length > 0) { - List list = Arrays.asList(attributes); - resourceNames = new HashSet(list); - } - if (log.isDebugEnabled()) { - log.debug("Carbon Resource Cache Hit"); - } - } else { - resourceNames = finder.findChildResources(parentResourceId.encode(), context); - if (log.isDebugEnabled()) { - log.debug("Carbon Resource Cache Miss"); - } - String cacheEntryString = ""; - if (resourceNames != null && resourceNames.size() > 0) { - for (String attribute : resourceNames) { - if (cacheEntryString.equals("")) { - cacheEntryString = attribute; - } else { - cacheEntryString = cacheEntryString + PDPConstants.ATTRIBUTE_SEPARATOR + attribute; - } - } - } - cacheEntry = new IdentityCacheEntry(cacheEntryString); - resourceCache.addToCache(cacheKey, cacheEntry); - } - } else { - resourceNames = finder.findChildResources(parentResourceId.encode(), context); - } - - if (resourceNames != null && !resourceNames.isEmpty()) { - resources = new HashSet(); - for (String resourceName : resourceNames) { - resources.add(EntitlementUtil.getAttributeValue(resourceName, dataType)); - } - } - } catch (EntitlementException e) { - log.error("Error while finding child resources", e); - } catch (TransformerException e) { - log.error("Error while finding child resources", e); - } catch (Exception e) { - log.error("Error while finding child resources", e); - } - } - - if (resources != null) { - resourceFinderResult = new ResourceFinderResult(resources); - } else { - resourceFinderResult = new ResourceFinderResult(); - } - - return resourceFinderResult; - } - - /** - * Disables resource Caches - */ - public void disableAttributeCache() { - resourceCache = null; - } - - /** - * Enables resource caches - */ - public void enableAttributeCache() { - resourceCache = EntitlementUtil - .getCommonCache(PDPConstants.PIP_RESOURCE_CACHE); - } - - /** - * Clears attribute cache - */ - public void clearAttributeCache() { - if (resourceCache != null) { - resourceCache.clear(); - if (log.isDebugEnabled()) { - log.debug("Resource cache is cleared for tenant " + tenantId); - } - } - } - - /** - * Converts DOM object to String. This is a helper method for creating cache key - * - * @param node Node value - * @return String Object - * @throws javax.xml.transform.TransformerException Exception throws if fails - */ - private String domToString(Node node) throws TransformerException { - TransformerFactory transFactory = TransformerFactory.newInstance(); - Transformer transformer = transFactory.newTransformer(); - StringWriter buffer = new StringWriter(); - transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); - transformer.transform(new DOMSource(node), - new StreamResult(buffer)); - return buffer.toString(); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pip/DefaultAttributeFinder.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pip/DefaultAttributeFinder.java deleted file mode 100644 index 6da46e3a5ecf..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pip/DefaultAttributeFinder.java +++ /dev/null @@ -1,214 +0,0 @@ -/* -* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.pip; - -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.balana.attr.AttributeValue; -import org.wso2.balana.attr.BagAttribute; -import org.wso2.balana.attr.StringAttribute; -import org.wso2.balana.cond.EvaluationResult; -import org.wso2.balana.ctx.EvaluationCtx; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.identity.core.util.IdentityCoreConstants; -import org.wso2.carbon.identity.entitlement.PDPConstants; -import org.wso2.carbon.user.api.ClaimManager; -import org.wso2.carbon.user.api.ClaimMapping; -import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.user.core.UserCoreConstants; -import org.wso2.carbon.utils.multitenancy.MultitenantUtils; - -import java.net.URI; -import java.util.HashSet; -import java.util.Properties; -import java.util.Set; -import java.util.StringTokenizer; - -/** - * DefaultAttributeFinder talks to the underlying user store to read user attributes. - * DefaultAttributeFinder is by default registered for all the claims defined under - * http://wso2.org/claims dialect. - */ -public class DefaultAttributeFinder extends AbstractPIPAttributeFinder { - - private static final Log log = LogFactory.getLog(DefaultAttributeFinder.class); - private Set supportedAttrs = new HashSet(); - private boolean mapFederatedUsersToLocal = false; - private static final String MAP_FEDERATED_USERS_TO_LOCAL = "MapFederatedUsersToLocal"; - private static final String FEDERATED_USER_DOMAIN = "FEDERATED"; - - /** - * Loads all the claims defined under http://wso2.org/claims dialect. - * - * @throws Exception - */ - public void init(Properties properties) throws Exception { - - mapFederatedUsersToLocal = Boolean.parseBoolean(properties.getProperty(MAP_FEDERATED_USERS_TO_LOCAL)); - if (log.isDebugEnabled()) { - log.debug("DefaultAttributeFinder is initialized successfully"); - } - } - - @Override - public String getModuleName() { - return "Default Attribute Finder"; - } - - /** - * This method is introduced in order to check whether the user is local or federated. If it is a - * federated user, obtaining user attributes from userstore will be prevented. - * - * @param attributeType The type of the required attribute. - * @param attributeId The unique id of the required attribute. - * @param category The category of the required attribute. - * @param issuer The attribute issuer. - * @param evaluationCtx The evaluation context object. - * @return return the set of values for the required attribute. - * @throws Exception throws if fails. - */ - @Override - public Set getAttributeValues(URI attributeType, URI attributeId, URI category, - String issuer, EvaluationCtx evaluationCtx) throws Exception { - - Set values = null; - EvaluationResult userType = evaluationCtx.getAttribute(new URI(StringAttribute.identifier), new URI( - PDPConstants.USER_TYPE_ID), issuer, new URI(PDPConstants.USER_CATEGORY)); - String userTypeId = null; - if (userType != null && userType.getAttributeValue() != null && userType.getAttributeValue().isBag()) { - BagAttribute bagAttribute = (BagAttribute) userType.getAttributeValue(); - if (bagAttribute.size() > 0) { - userTypeId = ((AttributeValue) bagAttribute.iterator().next()).encode(); - if (log.isDebugEnabled()) { - log.debug(String.format("The user type of the user is %s", userTypeId)); - } - } - } - - if (!StringUtils.equalsIgnoreCase(userTypeId, FEDERATED_USER_DOMAIN)) { - // If the user is not a federated user, user attributes should be be populated from local userstore. - values = super.getAttributeValues(attributeType, attributeId, category, issuer, evaluationCtx); - } else if (mapFederatedUsersToLocal) { - // If the user is federated and the MapFederatedToLocal config is enabled, then populate user attributes - // from userstore. - values = super.getAttributeValues(attributeType, attributeId, category, issuer, evaluationCtx); - } - return values; - } - /* - * (non-Javadoc) - * - * @see - * org.wso2.carbon.identity.entitlement.pip.PIPAttributeFinder#getAttributeValues(java.lang. - * String, java.lang.String, java.lang.String) - */ - public Set getAttributeValues(String subjectId, String resourceId, String actionId, - String environmentId, String attributeId, String issuer) throws Exception { - Set values = new HashSet(); - - if (log.isDebugEnabled()) { - log.debug("Retrieving attribute values of subjectId \'" + subjectId + "\'with attributeId \'" + - attributeId + "\'"); - } - if (StringUtils.isEmpty(subjectId)) { - if (log.isDebugEnabled()) { - log.debug("subjectId value is null or empty. Returning empty attribute set"); - } - return values; - } - subjectId = MultitenantUtils.getTenantAwareUsername(subjectId); - if (UserCoreConstants.ClaimTypeURIs.ROLE.equals(attributeId)) { - if (log.isDebugEnabled()) { - log.debug("Looking for roles via DefaultAttributeFinder"); - } - String[] roles = CarbonContext.getThreadLocalCarbonContext().getUserRealm().getUserStoreManager() - .getRoleListOfUser(subjectId); - if (roles != null && roles.length > 0) { - for (String role : roles) { - if (log.isDebugEnabled()) { - log.debug(String.format("User %1$s belongs to the Role %2$s", subjectId, - role)); - } - values.add(role); - } - } - } else { - String claimValue = null; - try { - claimValue = CarbonContext.getThreadLocalCarbonContext().getUserRealm(). - getUserStoreManager().getUserClaimValue(subjectId, attributeId, null); - if (log.isDebugEnabled()) { - log.debug("Claim \'" + claimValue + "\' retrieved for attributeId \'" + attributeId + "\' " + - "for subjectId \'" + subjectId + "\'"); - } - } catch (UserStoreException e) { - if(e.getMessage().startsWith(IdentityCoreConstants.USER_NOT_FOUND)){ - if(log.isDebugEnabled()){ - log.debug("User: " + subjectId + " not found in user store"); - } - } else { - throw e; - } - } - if (claimValue == null && log.isDebugEnabled()) { - log.debug(String.format("Request attribute %1$s not found", attributeId)); - } - // Fix for multiple claim values - if (claimValue != null) { - String claimSeparator = CarbonContext.getThreadLocalCarbonContext().getUserRealm(). - getRealmConfiguration().getUserStoreProperty(IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR); - if (StringUtils.isBlank(claimSeparator)) { - claimSeparator = IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR_DEFAULT; - } - if (claimValue.contains(claimSeparator)) { - StringTokenizer st = new StringTokenizer(claimValue, claimSeparator); - while (st.hasMoreElements()) { - String attributeValue = st.nextElement().toString(); - if (StringUtils.isNotBlank(attributeValue)) { - values.add(attributeValue); - } - } - } else { - values.add(claimValue); - } - } - } - return values; - } - - /* - * (non-Javadoc) - * - * @see org.wso2.carbon.identity.entitlement.pip.PIPAttributeFinder#getSupportedAttributes() - */ - public Set getSupportedAttributes() { - try { - ClaimManager claimManager = CarbonContext.getThreadLocalCarbonContext().getUserRealm().getClaimManager(); - ClaimMapping[] claims = claimManager - .getAllClaimMappings(UserCoreConstants.DEFAULT_CARBON_DIALECT); - for (ClaimMapping claim : claims) { - supportedAttrs.add(claim.getClaim().getClaimUri()); - } - } catch (Exception e) { - //ignore - } - return supportedAttrs; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pip/DefaultResourceFinder.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pip/DefaultResourceFinder.java deleted file mode 100644 index de671ed648a2..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pip/DefaultResourceFinder.java +++ /dev/null @@ -1,109 +0,0 @@ -/* -* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.pip; - -import org.wso2.balana.ctx.EvaluationCtx; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; -import org.wso2.carbon.registry.api.Resource; -import org.wso2.carbon.registry.core.Collection; -import org.wso2.carbon.registry.core.Registry; -import org.wso2.carbon.registry.core.exceptions.RegistryException; - -import java.util.HashSet; -import java.util.Properties; -import java.util.Set; - -/** - * This is the default implementation of the PIPResourceFinder. DefaultResourceFinder finds the resources - * of the underline registry - */ -public class DefaultResourceFinder implements PIPResourceFinder { - - private Registry registry; - - @Override - public void init(Properties properties) throws Exception { - - } - - @Override - public String getModuleName() { - return "Default Resource Finder"; - } - - @Override - public Set findDescendantResources(String parentResourceId, EvaluationCtx context) throws Exception { - Set resourceSet = new HashSet(); - registry = EntitlementServiceComponent.getRegistryService().getSystemRegistry(CarbonContext. - getThreadLocalCarbonContext().getTenantId()); - if (registry.resourceExists(parentResourceId)) { - Resource resource = registry.get(parentResourceId); - if (resource instanceof Collection) { - Collection collection = (Collection) resource; - String[] resources = collection.getChildren(); - for (String res : resources) { - resourceSet.add(res); - getChildResources(res, resourceSet); - } - } else { - return null; - } - } - return resourceSet; - } - - @Override - public Set findChildResources(String parentResourceId, EvaluationCtx context) throws Exception { - return null; - } - - @Override - public boolean overrideDefaultCache() { - return false; - } - - @Override - public void clearCache() { - - } - - /** - * This helps to find resources un a recursive manner - * - * @param parentResource parent resource Name - * @param childResources child resource set - * @return child resource set - * @throws RegistryException throws - */ - private Set getChildResources(String parentResource, Set childResources) - throws RegistryException { - - Resource resource = registry.get(parentResource); - if (resource instanceof Collection) { - Collection collection = (Collection) resource; - String[] resources = collection.getChildren(); - for (String res : resources) { - childResources.add(res); - getChildResources(res, childResources); - } - } - return childResources; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pip/PIPAttributeFinder.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pip/PIPAttributeFinder.java deleted file mode 100644 index dfe1f2dc1579..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pip/PIPAttributeFinder.java +++ /dev/null @@ -1,97 +0,0 @@ -/* -* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.pip; - -import org.wso2.balana.ctx.EvaluationCtx; - -import java.net.URI; -import java.util.Properties; -import java.util.Set; - -/** - * To register a PIP attribute handler with the PDP against their supported attributes - you need to - * implement this interface and add an entry to pip-config.xml file - which should be inside - * [CARBON_HOME]\repository\conf. PIPAttributeFinder will be fired by CarbonAttributeFinder whenever - * it finds an attribute supported by this module. - */ -public interface PIPAttributeFinder { - - /** - * initializes the Attribute finder module - * - * @param properties properties, that need to initialize the module. These properties can be - * defined in pip-config.xml file - * @throws Exception throws when initialization is failed - */ - public void init(Properties properties) throws Exception; - - /** - * gets name of this module - * - * @return name as String - */ - public String getModuleName(); - - /** - * Will be fired by CarbonAttributeFinder whenever it finds an attribute supported by this - * module. This method has given the flexibility for users to implement more advance use cases - * within PIP attribute finder. Here PIP attribute finder have been given access for EvaluationCtx - * which encapsulates the XACML request. - * - * @param attributeType - * @param attributeId The unique id of the required attribute. - * @param category Category of the subject - * @param issuer The attribute issuer. - * @param context EvaluationCtx which encapsulates the XACML request. - * @return Returns a Set of Strings that represent the attribute - * values. - * @throws Exception throws, if fails - */ - public Set getAttributeValues(URI attributeType, URI attributeId, URI category, - String issuer, EvaluationCtx context) throws Exception; - - /** - * Returns a Set of Strings that represent the attributeIds handled by - * this module, or null if this module doesn't handle any specific attributeIds. A return value - * of null means that this module will not handle any attributes. - * - * @return Set of Strings that represent the attributeIds - */ - public Set getSupportedAttributes(); - - /** - * This is to inform whether to ignore caching of attributes registered for this attribute finer - * or not. - * - * @return True/False - */ - public boolean overrideDefaultCache(); - - /** - * Clears the entire cache. - */ - public void clearCache(); - - /** - * Clears only the cached attribute by name. - * - * @param attributeId attributeId that needs to be cleared - */ - public void clearCache(String[] attributeId); -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pip/PIPExtension.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pip/PIPExtension.java deleted file mode 100644 index c7e038b51184..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pip/PIPExtension.java +++ /dev/null @@ -1,48 +0,0 @@ -/* -* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.pip; - -import org.wso2.balana.ctx.AbstractRequestCtx; - -import java.util.Properties; - -/** - * PIPExtensions will be fired for each and every XACML request - which will give a handle to the - * incoming request. - */ -public interface PIPExtension { - - /** - * initializes the PIPExtension module - * - * @param properties properties, that need to initialize the module. These properties can be - * defined in entitlement-config.xml file - * @throws Exception throws when initialization is failed - */ - public void init(Properties properties) throws Exception; - - /** - * Gives a handle to the XACML request built. Can be used to carry out custom checks or updates - * before sending to the PDP. - * - * @param request Incoming XACML request. - */ - public void update(AbstractRequestCtx request); - -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pip/PIPResourceFinder.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pip/PIPResourceFinder.java deleted file mode 100644 index 00f89706d02a..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/pip/PIPResourceFinder.java +++ /dev/null @@ -1,82 +0,0 @@ -/* -* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.pip; - -import org.wso2.balana.ctx.EvaluationCtx; - -import java.util.Properties; -import java.util.Set; - -/** - * To register a PIP resource finder with the PDP. you need to implement this interface and - * add an entry to pip-config.xml file (by specifying the full qualified class name, under "ResourceFinders") - * which can be found at [CARBON_HOME]\repository\conf. - * PIPResourceFinder will be fired by CarbonAttributeFinder whenever it wants to find a child or - * descendant resources for a given resource value . - */ -public interface PIPResourceFinder { - - /** - * initializes the Resource finder module - * - * @param properties properties, that need to initialize the module. These properties can be - * defined in pip-config.xml file - * @throws Exception throws when initialization is failed - */ - public void init(Properties properties) throws Exception; - - /** - * gets name of this module - * - * @return name as String - */ - public String getModuleName(); - - /** - * Will be fired by CarbonResourceFinder whenever it wants to find a child resources - * - * @param parentResourceId parent resource value - * @param context EvaluationCtx which encapsulates the XACML request. - * @return Returns a Set of Strings that represent the child resources - * @throws Exception throws if any failure is occurred - */ - public Set findChildResources(String parentResourceId, EvaluationCtx context) throws Exception; - - /** - * Will be fired by CarbonResourceFinder whenever it wants to find a descendant resources - * - * @param parentResourceId parent resource value - * @param context EvaluationCtx which encapsulates the XACML request. - * @return Returns a Set of Strings that represent the descendant resources - * @throws Exception throws if any failure is occurred - */ - public Set findDescendantResources(String parentResourceId, EvaluationCtx context) throws Exception; - - /** - * This is to inform whether to ignore caching of descendant and child resources in carbon level - * - * @return True/False - */ - public boolean overrideDefaultCache(); - - /** - * Clears the entire cache. - */ - public void clearCache(); -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/PolicyAttributeBuilder.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/PolicyAttributeBuilder.java deleted file mode 100644 index 619488c18089..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/PolicyAttributeBuilder.java +++ /dev/null @@ -1,1062 +0,0 @@ -/* -* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.policy; - -import org.apache.axiom.om.OMElement; -import org.apache.axiom.om.util.AXIOMUtil; -import org.wso2.balana.XACMLConstants; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.EntitlementUtil; -import org.wso2.carbon.identity.entitlement.PDPConstants; -import org.wso2.carbon.identity.entitlement.dto.AttributeDTO; - -import javax.xml.namespace.QName; -import javax.xml.stream.XMLStreamException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Properties; - - -/** - * This class phrase the xml representation of policy and build the policy meta data such as - * resource names, subject names action names and environment names, attribute ids and data types. - */ -public class PolicyAttributeBuilder { - - private String policy; - - private int version; - - public PolicyAttributeBuilder() { - - } - - /** - * @param policy policy as a String - */ - public PolicyAttributeBuilder(String policy) { - this.policy = policy; - String version = EntitlementUtil.getPolicyVersion(policy); - if (XACMLConstants.XACML_1_0_IDENTIFIER.equals(version)) { - this.version = XACMLConstants.XACML_VERSION_1_0; - } else if (XACMLConstants.XACML_2_0_IDENTIFIER.equals(version)) { - this.version = XACMLConstants.XACML_VERSION_2_0; - } else { - this.version = XACMLConstants.XACML_VERSION_3_0; - } - } - - /** - * This creates properties object which contains the policy meta data. - * - * @return properties object which contains the policy meta data - * @throws EntitlementException throws - */ - public Properties getPolicyMetaDataFromPolicy() throws EntitlementException { - - List attributeDTOs = new ArrayList(); - try { - attributeDTOs = createPolicyMetaData(policy, attributeDTOs); - } catch (EntitlementException e) { - throw new EntitlementException("Can not create Policy MetaData for given policy"); - } - - int attributeElementNo = 0; - Properties properties = new Properties(); - - if (attributeDTOs != null) { - for (AttributeDTO attributeDTO : attributeDTOs) { - properties.setProperty(PDPConstants.POLICY_META_DATA + attributeElementNo, - attributeDTO.getCategory() + PDPConstants.ATTRIBUTE_SEPARATOR + - attributeDTO.getAttributeValue() + PDPConstants.ATTRIBUTE_SEPARATOR + - attributeDTO.getAttributeId() + PDPConstants.ATTRIBUTE_SEPARATOR + - attributeDTO.getAttributeDataType()); - attributeElementNo++; - } - } - return properties; - } - - /** - * This creates the attributes from registry property values - * - * @param properties Properties object read from registry resource - * @return attributes as AttributeDTO[] object - */ - public AttributeDTO[] getPolicyMetaDataFromRegistryProperties(Properties properties) { - - List attributeDTOs = new ArrayList(); - if (properties != null && !properties.isEmpty()) { - for (int attributeElementNo = 0; attributeElementNo < properties.size(); ) { - List attributeList = (ArrayList) properties.get(PDPConstants.POLICY_META_DATA + - attributeElementNo); - if (attributeList != null && attributeList.get(0) != null) { - String[] attributeData = attributeList.get(0).toString(). - split(PDPConstants.ATTRIBUTE_SEPARATOR); - if (attributeData.length == PDPConstants.POLICY_META_DATA_ARRAY_LENGTH) { - AttributeDTO attributeDTO = new AttributeDTO(); - attributeDTO.setCategory(attributeData[0]); - attributeDTO.setAttributeValue(attributeData[1]); - attributeDTO.setAttributeId(attributeData[2]); - attributeDTO.setAttributeDataType(attributeData[3]); - attributeDTOs.add(attributeDTO); - } - } - attributeElementNo++; - } - } - - return attributeDTOs.toArray(new AttributeDTO[attributeDTOs.size()]); - } - - /** - * This creates the OMElement from the policy xml and create the the meta data for hole policy - * - * @param policy policy as a String - * @param attributeDTOs object which holds the policy meta data in String format - * @return list of AttributeDTO object which holds the policy meta data in String format - * @throws EntitlementException throws if OMElement can not be created - */ - public List createPolicyMetaData(String policy, - List attributeDTOs) throws EntitlementException { - - OMElement omElement; - - try { - omElement = AXIOMUtil.stringToOM(policy); - } catch (XMLStreamException e) { - throw new EntitlementException("Policy xml can not be converted to OMElement"); - } - - if (omElement != null) { - Iterator iterator1 = omElement.getChildrenWithLocalName(PDPConstants. - TARGET_ELEMENT); - while (iterator1.hasNext()) { - OMElement targetElement = (OMElement) iterator1.next(); - if (version == XACMLConstants.XACML_VERSION_3_0) { - createMetaDataFromXACML3TargetElement(targetElement, attributeDTOs); - } else { - createMetaDataFromTargetElement(targetElement, attributeDTOs); - } - } - - Iterator iterator2 = omElement.getChildrenWithLocalName(PDPConstants. - RULE_ELEMENT); - while (iterator2.hasNext()) { - OMElement targetElement = (OMElement) iterator2.next(); - createMetaDataFromRuleElement(targetElement, attributeDTOs); - } - - Iterator iterator3 = omElement.getChildrenWithLocalName(PDPConstants. - POLICY_ELEMENT); - while (iterator3.hasNext()) { - OMElement targetElement = (OMElement) iterator3.next(); - createPolicyMetaData(targetElement.toString(), attributeDTOs); - } - } - - return attributeDTOs; - } - - /** - * This extract policy meta data from target element in the policy - * - * @param omElement target element as an OMElement - * @param attributeDTOs list of AttributeDTO object which holds the policy meta data - * in String format - * @return list of AttributeDTO object which holds the policy meta data in String format - */ - public List createMetaDataFromTargetElement(OMElement omElement, - List attributeDTOs) { - - if (omElement != null) { - - Iterator iterator1 = omElement. - getChildrenWithLocalName(PDPConstants.RESOURCE_ELEMENT + "s"); - while (iterator1.hasNext()) { - OMElement resourceElements = (OMElement) iterator1.next(); - - Iterator iterator2 = resourceElements. - getChildrenWithLocalName(PDPConstants.RESOURCE_ELEMENT); - while (iterator2.hasNext()) { - OMElement resourceElement = (OMElement) iterator2.next(); - - Iterator iterator3 = resourceElement. - getChildrenWithLocalName(PDPConstants.RESOURCE_ELEMENT + - PDPConstants.MATCH_ELEMENT); - - while (iterator3.hasNext()) { - OMElement resourceMatch = (OMElement) iterator3.next(); - List attributeDTOList = - createMetaDataFromMatchElement(resourceMatch, - PDPConstants.RESOURCE_ELEMENT); - for (AttributeDTO attributeDTO : attributeDTOList) { - attributeDTOs.add(attributeDTO); - } - } - } - } - - Iterator iterator4 = omElement. - getChildrenWithLocalName(PDPConstants.SUBJECT_ELEMENT + "s"); - while (iterator4.hasNext()) { - OMElement resourceElements = (OMElement) iterator4.next(); - - Iterator iterator2 = resourceElements. - getChildrenWithLocalName(PDPConstants.SUBJECT_ELEMENT); - while (iterator2.hasNext()) { - OMElement resourceElement = (OMElement) iterator2.next(); - - Iterator iterator3 = resourceElement. - getChildrenWithLocalName(PDPConstants.SUBJECT_ELEMENT + - PDPConstants.MATCH_ELEMENT); - - while (iterator3.hasNext()) { - OMElement resourceMatch = (OMElement) iterator3.next(); - List attributeDTOList = - createMetaDataFromMatchElement(resourceMatch, - PDPConstants.SUBJECT_ELEMENT); - for (AttributeDTO attributeDTO : attributeDTOList) { - attributeDTOs.add(attributeDTO); - } - } - } - - } - - Iterator iterator5 = omElement. - getChildrenWithLocalName(PDPConstants.ACTION_ELEMENT + "s"); - - while (iterator5.hasNext()) { - OMElement resourceElements = (OMElement) iterator5.next(); - - Iterator iterator2 = resourceElements. - getChildrenWithLocalName(PDPConstants.ACTION_ELEMENT); - while (iterator2.hasNext()) { - OMElement resourceElement = (OMElement) iterator2.next(); - - Iterator iterator3 = resourceElement. - getChildrenWithLocalName(PDPConstants.ACTION_ELEMENT + - PDPConstants.MATCH_ELEMENT); - - while (iterator3.hasNext()) { - OMElement resourceMatch = (OMElement) iterator3.next(); - List attributeDTOList = - createMetaDataFromMatchElement(resourceMatch, - PDPConstants.ACTION_ELEMENT); - for (AttributeDTO attributeDTO : attributeDTOList) { - attributeDTOs.add(attributeDTO); - } - } - } - - } - - Iterator iterator6 = omElement. - getChildrenWithLocalName(PDPConstants.ENVIRONMENT_ELEMENT + "s"); - - while (iterator6.hasNext()) { - OMElement resourceElements = (OMElement) iterator6.next(); - - Iterator iterator2 = resourceElements. - getChildrenWithLocalName(PDPConstants.ENVIRONMENT_ELEMENT); - while (iterator2.hasNext()) { - OMElement resourceElement = (OMElement) iterator2.next(); - - Iterator iterator3 = resourceElement. - getChildrenWithLocalName(PDPConstants.ENVIRONMENT_ELEMENT + - PDPConstants.MATCH_ELEMENT); - - while (iterator3.hasNext()) { - OMElement resourceMatch = (OMElement) iterator3.next(); - - List attributeDTOList = - createMetaDataFromMatchElement(resourceMatch, - PDPConstants.ENVIRONMENT_ELEMENT); - for (AttributeDTO attributeDTO : attributeDTOList) { - attributeDTOs.add(attributeDTO); - } - } - } - - } - - } - - return attributeDTOs; - } - - - /** - * This extract policy meta data from target element in the policy - * - * @param omElement target element as an OMElement - * @param attributeDTOs list of AttributeDTO object which holds the policy meta data - * in String format - * @return list of AttributeDTO object which holds the policy meta data in String format - */ - public List createMetaDataFromXACML3TargetElement(OMElement omElement, - List attributeDTOs) { - - if (omElement != null) { - - Iterator iterator1 = omElement. - getChildrenWithLocalName(PDPConstants.ANY_OF); - while (iterator1.hasNext()) { - - OMElement anyOff = (OMElement) iterator1.next(); - - Iterator iterator2 = anyOff. - getChildrenWithLocalName(PDPConstants.ALL_OF); - - while (iterator2.hasNext()) { - OMElement allOf = (OMElement) iterator2.next(); - - Iterator iterator3 = allOf. - getChildrenWithLocalName(PDPConstants.MATCH_ELEMENT); - - while (iterator3.hasNext()) { - OMElement resourceMatch = (OMElement) iterator3.next(); - List attributeDTOList = - createMetaDataFromXACML3MatchElement(resourceMatch); - for (AttributeDTO attributeDTO : attributeDTOList) { - attributeDTOs.add(attributeDTO); - } - } - } - } - } - - return attributeDTOs; - } - - /** - * This extract policy meta data from match element in the policy - * - * @param omElement match element as an OMElement - * @param subElementName match element name - * @return AttributeValueDTO object which holds the policy meta data in String format - */ - public List createMetaDataFromMatchElement(OMElement omElement, - String subElementName) { - - List attributeDTOs = new ArrayList(); - String attributeId = null; - String dataType = null; - - if (omElement != null) { - Iterator iterator1 = omElement. - getChildrenWithLocalName(subElementName + PDPConstants.ATTRIBUTE_DESIGNATOR); - while (iterator1.hasNext()) { - OMElement attributeDesignator = (OMElement) iterator1.next(); - if (attributeDesignator != null) { - attributeId = attributeDesignator. - getAttributeValue(new QName(PDPConstants.ATTRIBUTE_ID)); - dataType = attributeDesignator. - getAttributeValue(new QName(PDPConstants.DATA_TYPE)); - } - } - - Iterator iterator2 = omElement. - getChildrenWithLocalName(PDPConstants.ATTRIBUTE_SELECTOR); - while (iterator2.hasNext()) { - OMElement attributeDesignator = (OMElement) iterator2.next(); - if (attributeDesignator != null) { - attributeId = attributeDesignator. - getAttributeValue(new QName(PDPConstants.REQUEST_CONTEXT_PATH)); - dataType = attributeDesignator. - getAttributeValue(new QName(PDPConstants.DATA_TYPE)); - } - } - - Iterator iterator3 = omElement. - getChildrenWithLocalName(PDPConstants.ATTRIBUTE_VALUE); - while (iterator3.hasNext()) { - OMElement attributeElement = (OMElement) iterator3.next(); - if (attributeElement != null) { - AttributeDTO attributeDTO = new AttributeDTO(); - attributeDTO.setAttributeValue(attributeElement.getText()); - attributeDTO.setAttributeId(attributeId); - attributeDTO.setAttributeDataType(dataType); - attributeDTO.setCategory(subElementName); - attributeDTOs.add(attributeDTO); - } - } - - } - return attributeDTOs; - } - - - /** - * This extract policy meta data from match element in the policy - * - * @param omElement match element as an OMElement - * @return AttributeValueDTO object which holds the policy meta data in String format - */ - public List createMetaDataFromXACML3MatchElement(OMElement omElement) { - - List attributeDTOs = new ArrayList(); - String attributeId = null; - String category = null; - - if (omElement != null) { - Iterator iterator1 = omElement. - getChildrenWithLocalName(PDPConstants.ATTRIBUTE_DESIGNATOR); - while (iterator1.hasNext()) { - OMElement attributeDesignator = (OMElement) iterator1.next(); - if (attributeDesignator != null) { - attributeId = attributeDesignator. - getAttributeValue(new QName(PDPConstants.ATTRIBUTE_ID)); - category = attributeDesignator. - getAttributeValue(new QName(PDPConstants.CATEGORY)); - } - } - - Iterator iterator3 = omElement. - getChildrenWithLocalName(PDPConstants.ATTRIBUTE_VALUE); - while (iterator3.hasNext()) { - OMElement attributeElement = (OMElement) iterator3.next(); - if (attributeElement != null) { - String dataType = attributeElement. - getAttributeValue(new QName(PDPConstants.DATA_TYPE)); - AttributeDTO attributeDTO = new AttributeDTO(); - attributeDTO.setAttributeValue(attributeElement.getText()); - attributeDTO.setAttributeId(attributeId); - attributeDTO.setAttributeDataType(dataType); - attributeDTO.setCategory(category); - attributeDTOs.add(attributeDTO); - } - } - } - return attributeDTOs; - } - - /** - * This extract policy meta data from apply element in the policy - * - * @param omElement apply element as an OMElement - * @param attributeDTOs list of AttributeDTO object which holds the policy meta data - * in String format - * @return list of AttributeDTO object which holds the policy meta data in String format - */ - public List createMetaDataFromApplyElement(OMElement omElement, - List attributeDTOs) { - - //TODO check with function id and decide whether search can be done or not - if (omElement != null) { - Iterator iterator1 = omElement. - getChildrenWithLocalName(PDPConstants.RESOURCE_ELEMENT + - PDPConstants.ATTRIBUTE_DESIGNATOR); - while (iterator1.hasNext()) { - OMElement attributeDesignator = (OMElement) iterator1.next(); - if (attributeDesignator != null) { - String attributeId = attributeDesignator. - getAttributeValue(new QName(PDPConstants.ATTRIBUTE_ID)); - String dataType = attributeDesignator. - getAttributeValue(new QName(PDPConstants.DATA_TYPE)); - List attributeValues = searchAttributeValues(omElement, - new ArrayList(), true); - if (attributeValues == null) { - AttributeDTO attributeDTO = new AttributeDTO(); - attributeDTO.setCategory(PDPConstants.UNKNOWN); - attributeDTO.setAttributeValue(PDPConstants.SEARCH_WARNING_MESSAGE1 + - " for " + PDPConstants.RESOURCE_ELEMENT + - " Designator Element "); - attributeDTOs.add(attributeDTO); - } else if (attributeValues.isEmpty()) { - AttributeDTO attributeDTO = new AttributeDTO(); - attributeDTO.setCategory(PDPConstants.UNKNOWN); - attributeDTO.setAttributeValue(PDPConstants.SEARCH_WARNING_MESSAGE2 + - " for " + PDPConstants.RESOURCE_ELEMENT + - " Designator Element "); - - } else { - for (String value : attributeValues) { - AttributeDTO attributeDTO = new AttributeDTO(); - attributeDTO.setAttributeValue(value); - attributeDTO.setAttributeDataType(dataType); - attributeDTO.setCategory(PDPConstants.RESOURCE_ELEMENT); - attributeDTO.setAttributeId(attributeId); - attributeDTOs.add(attributeDTO); - } - } - } - } - - Iterator iterator2 = omElement. - getChildrenWithLocalName(PDPConstants.SUBJECT_ELEMENT + - PDPConstants.ATTRIBUTE_DESIGNATOR); - while (iterator2.hasNext()) { - OMElement attributeDesignator = (OMElement) iterator2.next(); - if (attributeDesignator != null) { - String attributeId = attributeDesignator. - getAttributeValue(new QName(PDPConstants.ATTRIBUTE_ID)); - String dataType = attributeDesignator. - getAttributeValue(new QName(PDPConstants.DATA_TYPE)); - List attributeValues = searchAttributeValues(omElement, - new ArrayList(), true); - if (attributeValues == null) { - AttributeDTO attributeDTO = new AttributeDTO(); - attributeDTO.setCategory(PDPConstants.UNKNOWN); - attributeDTO.setAttributeValue(PDPConstants.SEARCH_WARNING_MESSAGE1 + - " for " + PDPConstants.RESOURCE_ELEMENT + - " Designator Element "); - - attributeDTOs.add(attributeDTO); - } else if (attributeValues.isEmpty()) { - AttributeDTO attributeDTO = new AttributeDTO(); - attributeDTO.setCategory(PDPConstants.UNKNOWN); - attributeDTO.setAttributeValue(PDPConstants.SEARCH_WARNING_MESSAGE2 + - " for " + PDPConstants.RESOURCE_ELEMENT + - " Designator Element "); - - } else { - for (String value : attributeValues) { - AttributeDTO attributeDTO = new AttributeDTO(); - attributeDTO.setAttributeValue(value); - attributeDTO.setAttributeDataType(dataType); - attributeDTO.setCategory(PDPConstants.SUBJECT_ELEMENT); - attributeDTO.setAttributeId(attributeId); - attributeDTOs.add(attributeDTO); - } - } - } - } - - Iterator iterator3 = omElement. - getChildrenWithLocalName(PDPConstants.ACTION_ELEMENT + - PDPConstants.ATTRIBUTE_DESIGNATOR); - while (iterator3.hasNext()) { - OMElement attributeDesignator = (OMElement) iterator3.next(); - if (attributeDesignator != null) { - String attributeId = attributeDesignator. - getAttributeValue(new QName(PDPConstants.ATTRIBUTE_ID)); - String dataType = attributeDesignator. - getAttributeValue(new QName(PDPConstants.DATA_TYPE)); - List attributeValues = searchAttributeValues(omElement, - new ArrayList(), true); - if (attributeValues == null) { - AttributeDTO attributeDTO = new AttributeDTO(); - attributeDTO.setCategory(PDPConstants.UNKNOWN); - attributeDTO.setAttributeValue(PDPConstants.SEARCH_WARNING_MESSAGE1 + - " for " + PDPConstants.RESOURCE_ELEMENT + - " Designator Element "); - - attributeDTOs.add(attributeDTO); - } else if (attributeValues.isEmpty()) { - AttributeDTO attributeDTO = new AttributeDTO(); - attributeDTO.setCategory(PDPConstants.UNKNOWN); - attributeDTO.setAttributeValue(PDPConstants.SEARCH_WARNING_MESSAGE2 + - " for " + PDPConstants.RESOURCE_ELEMENT + - " Designator Element "); - - } else { - for (String value : attributeValues) { - AttributeDTO attributeDTO = new AttributeDTO(); - attributeDTO.setAttributeValue(value); - attributeDTO.setAttributeDataType(dataType); - attributeDTO.setCategory(PDPConstants.ACTION_ELEMENT); - attributeDTO.setAttributeId(attributeId); - attributeDTOs.add(attributeDTO); - } - } - } - } - - Iterator iterator4 = omElement. - getChildrenWithLocalName(PDPConstants.ENVIRONMENT_ELEMENT + - PDPConstants.ATTRIBUTE_DESIGNATOR); - while (iterator4.hasNext()) { - OMElement attributeDesignator = (OMElement) iterator4.next(); - if (attributeDesignator != null) { - String attributeId = attributeDesignator. - getAttributeValue(new QName(PDPConstants.ATTRIBUTE_ID)); - String dataType = attributeDesignator. - getAttributeValue(new QName(PDPConstants.DATA_TYPE)); - List attributeValues = searchAttributeValues(omElement, - new ArrayList(), true); - if (attributeValues == null) { - AttributeDTO attributeDTO = new AttributeDTO(); - attributeDTO.setCategory(PDPConstants.UNKNOWN); - attributeDTO.setAttributeValue(PDPConstants.SEARCH_WARNING_MESSAGE1 + - " for " + PDPConstants.RESOURCE_ELEMENT + - " Designator Element "); - - attributeDTOs.add(attributeDTO); - } else if (attributeValues.isEmpty()) { - AttributeDTO attributeDTO = new AttributeDTO(); - attributeDTO.setCategory(PDPConstants.UNKNOWN); - attributeDTO.setAttributeValue(PDPConstants.SEARCH_WARNING_MESSAGE2 + - " for " + PDPConstants.RESOURCE_ELEMENT + - " Designator Element "); - - } else { - for (String value : attributeValues) { - AttributeDTO attributeDTO = new AttributeDTO(); - attributeDTO.setAttributeValue(value); - attributeDTO.setAttributeDataType(dataType); - attributeDTO.setCategory(PDPConstants.ENVIRONMENT_ELEMENT); - attributeDTO.setAttributeId(attributeId); - attributeDTOs.add(attributeDTO); - } - } - } - } - - Iterator iterator5 = omElement. - getChildrenWithLocalName(PDPConstants.ATTRIBUTE_SELECTOR); - while (iterator5.hasNext()) { - OMElement attributeSelector = (OMElement) iterator5.next(); - if (attributeSelector != null) { - String attributeId = attributeSelector. - getAttributeValue(new QName(PDPConstants.REQUEST_CONTEXT_PATH)); - String subElementName = attributeId; //TODO Fix finding element name from Xpath - String dataType = attributeSelector. - getAttributeValue(new QName(PDPConstants.DATA_TYPE)); - List attributeValues = searchAttributeValues(omElement, - new ArrayList(), true); - if (attributeValues == null) { - AttributeDTO attributeDTO = new AttributeDTO(); - attributeDTO.setCategory(PDPConstants.UNKNOWN); - attributeDTO.setAttributeValue(PDPConstants.SEARCH_WARNING_MESSAGE3); - - attributeDTOs.add(attributeDTO); - } else if (attributeValues.isEmpty()) { - AttributeDTO attributeDTO = new AttributeDTO(); - attributeDTO.setCategory(PDPConstants.UNKNOWN); - attributeDTO.setAttributeValue(PDPConstants.SEARCH_WARNING_MESSAGE3); - - } else { - for (String value : attributeValues) { - AttributeDTO attributeDTO = new AttributeDTO(); - attributeDTO.setAttributeValue(value); - attributeDTO.setAttributeDataType(dataType); - attributeDTO.setCategory(subElementName); - attributeDTO.setAttributeId(attributeId); - attributeDTOs.add(attributeDTO); - // Remove following after fixing XPath issues - attributeDTO.setCategory(PDPConstants.UNKNOWN); - attributeDTO.setAttributeValue(PDPConstants.SEARCH_WARNING_MESSAGE3); - } - } - } - } - - Iterator iterator6 = omElement. - getChildrenWithLocalName(PDPConstants.ATTRIBUTE_VALUE); - if (iterator6.hasNext()) { - List attributeValues = searchAttributeValues(omElement, new ArrayList(), false); - if (attributeValues == null) { - AttributeDTO attributeDTO = new AttributeDTO(); - attributeDTO.setCategory(PDPConstants.UNKNOWN); - attributeDTO.setAttributeValue(PDPConstants.SEARCH_WARNING_MESSAGE1 + - " for " + PDPConstants.RESOURCE_ELEMENT + - " Designator Element "); - attributeDTOs.add(attributeDTO); - } else if (attributeValues.isEmpty()) { - AttributeDTO attributeDTO = new AttributeDTO(); - attributeDTO.setCategory(PDPConstants.UNKNOWN); - attributeDTO.setAttributeValue(PDPConstants.SEARCH_WARNING_MESSAGE2 + - " for " + PDPConstants.RESOURCE_ELEMENT + - " Designator Element "); - } else { - for (String values : attributeValues) { - AttributeDTO attributeDTO = new AttributeDTO(); - attributeDTO.setAttributeValue(values); - Iterator iterator8 = omElement. - getChildrenWithLocalName(PDPConstants.APPLY_ELEMENT); - while (iterator8.hasNext()) { - OMElement applyElement = (OMElement) iterator8.next(); - if (version == XACMLConstants.XACML_VERSION_3_0) { - searchXACML3Designator(applyElement, attributeDTO); - } else { - searchDesignatorOrSelector(applyElement, attributeDTO); - } - } - if (attributeDTO.getCategory() != null || - "".equals(attributeDTO.getCategory())) { - attributeDTOs.add(attributeDTO); - } - } - } - } - - Iterator iterator7 = omElement.getChildrenWithLocalName(PDPConstants.APPLY_ELEMENT); - while (iterator7.hasNext()) { - OMElement applyElement = (OMElement) iterator7.next(); - createMetaDataFromApplyElement(applyElement, attributeDTOs); - } - } - return attributeDTOs; - } - - - /** - * This extract policy meta data from apply element in the policy - * - * @param omElement apply element as an OMElement - * @param attributeDTOs list of AttributeDTO object which holds the policy meta data - * in String format - * @return list of AttributeDTO object which holds the policy meta data in String format - */ - public List createMetaDataFromXACML3ApplyElement(OMElement omElement, - List attributeDTOs) { - - //TODO check with function id and decide whether search can be done or not - if (omElement != null) { - Iterator iterator1 = omElement. - getChildrenWithLocalName(PDPConstants.ATTRIBUTE_DESIGNATOR); - while (iterator1.hasNext()) { - OMElement attributeDesignator = (OMElement) iterator1.next(); - if (attributeDesignator != null) { - String attributeId = attributeDesignator. - getAttributeValue(new QName(PDPConstants.ATTRIBUTE_ID)); - String category = attributeDesignator. - getAttributeValue(new QName(PDPConstants.CATEGORY)); - String dataType = attributeDesignator. - getAttributeValue(new QName(PDPConstants.DATA_TYPE)); //TODO - List attributeValues = searchAttributeValues(omElement, - new ArrayList(), true); - if (attributeValues == null) { - AttributeDTO attributeDTO = new AttributeDTO(); - attributeDTO.setCategory(PDPConstants.UNKNOWN); - attributeDTO.setAttributeValue(PDPConstants.SEARCH_WARNING_MESSAGE1 + - " for " + PDPConstants.RESOURCE_ELEMENT + - " Designator Element "); - attributeDTOs.add(attributeDTO); - } else if (attributeValues.isEmpty()) { - AttributeDTO attributeDTO = new AttributeDTO(); - attributeDTO.setCategory(PDPConstants.UNKNOWN); - attributeDTO.setAttributeValue(PDPConstants.SEARCH_WARNING_MESSAGE2 + - " for " + PDPConstants.RESOURCE_ELEMENT + - " Designator Element "); - - } else { - for (String value : attributeValues) { - AttributeDTO attributeDTO = new AttributeDTO(); - attributeDTO.setAttributeValue(value); - attributeDTO.setAttributeDataType(dataType); - attributeDTO.setCategory(category); - attributeDTO.setAttributeId(attributeId); - attributeDTOs.add(attributeDTO); - } - } - } - } - - - Iterator iterator2 = omElement. - getChildrenWithLocalName(PDPConstants.ATTRIBUTE_VALUE); - if (iterator2.hasNext()) { - List attributeValues = searchAttributeValues(omElement, new ArrayList(), false); - if (attributeValues == null) { - AttributeDTO attributeDTO = new AttributeDTO(); - attributeDTO.setCategory(PDPConstants.UNKNOWN); - attributeDTO.setAttributeValue(PDPConstants.SEARCH_WARNING_MESSAGE1 + - " for " + PDPConstants.RESOURCE_ELEMENT + - " Designator Element "); - attributeDTOs.add(attributeDTO); - } else if (attributeValues.isEmpty()) { - AttributeDTO attributeDTO = new AttributeDTO(); - attributeDTO.setCategory(PDPConstants.UNKNOWN); - attributeDTO.setAttributeValue(PDPConstants.SEARCH_WARNING_MESSAGE2 + - " for " + PDPConstants.RESOURCE_ELEMENT + - " Designator Element "); - } else { - for (String values : attributeValues) { - AttributeDTO attributeDTO = new AttributeDTO(); - attributeDTO.setAttributeValue(values); - Iterator iterator8 = omElement. - getChildrenWithLocalName(PDPConstants.APPLY_ELEMENT); - while (iterator8.hasNext()) { - OMElement applyElement = (OMElement) iterator8.next(); - searchXACML3Designator(applyElement, attributeDTO); - } - if (attributeDTO.getCategory() != null || - "".equals(attributeDTO.getCategory())) { - attributeDTOs.add(attributeDTO); - } - } - } - } - - Iterator iterator7 = omElement.getChildrenWithLocalName(PDPConstants.APPLY_ELEMENT); - while (iterator7.hasNext()) { - OMElement applyElement = (OMElement) iterator7.next(); - createMetaDataFromXACML3ApplyElement(applyElement, attributeDTOs); - } - } - return attributeDTOs; - } - - /** - * This searches through attribute values in the attribute elements to extract the policy meta data - * - * @param omElement apply element as an OMElement - * @param values set of String objects - * @param searchDesignators states where, to find designators which are involved in creating - * attribute values - * @return AttributeValueDTO object which holds the policy meta data in String format - */ - public List searchAttributeValues(OMElement omElement, List values, - boolean searchDesignators) { - - if (values != null) { - Iterator iterator = omElement. - getChildrenWithLocalName(PDPConstants.ATTRIBUTE_VALUE); - while (iterator.hasNext()) { - OMElement attributeElement = (OMElement) iterator.next(); - if (attributeElement != null) { - String dataType = attributeElement. - getAttributeValue(new QName(PDPConstants.DATA_TYPE)); // TODO - values.add(attributeElement.getText()); - } - } - } - - Iterator iterator1 = omElement.getChildrenWithLocalName(PDPConstants.APPLY_ELEMENT); - while (iterator1.hasNext()) { - OMElement applyElement = (OMElement) iterator1.next(); - searchAttributeValues(applyElement, values, searchDesignators); - - AttributeDTO attributeDTO = new AttributeDTO(); - if (searchDesignators) { - if (version == XACMLConstants.XACML_VERSION_3_0) { - searchXACML3Designator(applyElement, attributeDTO); - } else { - searchDesignatorOrSelector(applyElement, attributeDTO); - } - } - if (attributeDTO.getCategory() != null || attributeDTO.getAttributeId() != null || - attributeDTO.getAttributeDataType() != null) { - values = null; - } - } - - return values; - } - - /** - * This searches through designator and selector values in the attribute elements to extract - * the policy meta data - * - * @param omElement apply element as an OMElement - * @param attributeDTO AttributeDTO object which holds the policy meta data in String format - * @return AttributeValueDTO object which holds the policy meta data in String format - */ - public AttributeDTO searchDesignatorOrSelector(OMElement omElement, - AttributeDTO attributeDTO) { - - - Iterator iterator1 = omElement. - getChildrenWithLocalName(PDPConstants.RESOURCE_ELEMENT + - PDPConstants.ATTRIBUTE_DESIGNATOR); - while (iterator1.hasNext()) { - OMElement attributeDesignator = (OMElement) iterator1.next(); - if (attributeDesignator != null) { - String attributeId = attributeDesignator. - getAttributeValue(new QName(PDPConstants.ATTRIBUTE_ID)); - String dataType = attributeDesignator. - getAttributeValue(new QName(PDPConstants.DATA_TYPE)); - attributeDTO.setAttributeDataType(dataType); - attributeDTO.setCategory(PDPConstants.RESOURCE_ELEMENT); - attributeDTO.setAttributeId(attributeId); - } - } - - Iterator iterator2 = omElement. - getChildrenWithLocalName(PDPConstants.SUBJECT_ELEMENT + - PDPConstants.ATTRIBUTE_DESIGNATOR); - while (iterator2.hasNext()) { - OMElement attributeDesignator = (OMElement) iterator2.next(); - if (attributeDesignator != null) { - String attributeId = attributeDesignator. - getAttributeValue(new QName(PDPConstants.ATTRIBUTE_ID)); - String dataType = attributeDesignator. - getAttributeValue(new QName(PDPConstants.DATA_TYPE)); - attributeDTO.setAttributeDataType(dataType); - attributeDTO.setCategory(PDPConstants.SUBJECT_ELEMENT); - attributeDTO.setAttributeId(attributeId); - } - } - - Iterator iterator3 = omElement. - getChildrenWithLocalName(PDPConstants.ACTION_ELEMENT + - PDPConstants.ATTRIBUTE_DESIGNATOR); - while (iterator3.hasNext()) { - OMElement attributeDesignator = (OMElement) iterator3.next(); - if (attributeDesignator != null) { - String attributeId = attributeDesignator. - getAttributeValue(new QName(PDPConstants.ATTRIBUTE_ID)); - String dataType = attributeDesignator. - getAttributeValue(new QName(PDPConstants.DATA_TYPE)); - attributeDTO.setAttributeDataType(dataType); - attributeDTO.setCategory(PDPConstants.ACTION_ELEMENT); - attributeDTO.setAttributeId(attributeId); - } - } - - Iterator iterator4 = omElement. - getChildrenWithLocalName(PDPConstants.ENVIRONMENT_ELEMENT + - PDPConstants.ATTRIBUTE_DESIGNATOR); - while (iterator4.hasNext()) { - OMElement attributeDesignator = (OMElement) iterator4.next(); - if (attributeDesignator != null) { - String attributeId = attributeDesignator. - getAttributeValue(new QName(PDPConstants.ATTRIBUTE_ID)); - String dataType = attributeDesignator. - getAttributeValue(new QName(PDPConstants.DATA_TYPE)); - attributeDTO.setAttributeDataType(dataType); - attributeDTO.setCategory(PDPConstants.ENVIRONMENT_ELEMENT); - attributeDTO.setAttributeId(attributeId); - } - } - - Iterator iterator5 = omElement. - getChildrenWithLocalName(PDPConstants.ATTRIBUTE_SELECTOR); - while (iterator5.hasNext()) { - OMElement attributeDesignator = (OMElement) iterator5.next(); - if (attributeDesignator != null) { - String attributeId = attributeDesignator. - getAttributeValue(new QName(PDPConstants.REQUEST_CONTEXT_PATH)); - String subElementName = attributeId; //TODO Fix finding element name from Xpath - String dataType = attributeDesignator. - getAttributeValue(new QName(PDPConstants.DATA_TYPE)); - attributeDTO.setAttributeDataType(dataType); - attributeDTO.setCategory(PDPConstants.UNKNOWN); - attributeDTO.setAttributeValue(PDPConstants.SEARCH_WARNING_MESSAGE3); - attributeDTO.setAttributeId(attributeId); - } - } - - return attributeDTO; - } - - /** - * This searches through designator and selector values in the attribute elements to extract - * the policy meta data - * - * @param omElement apply element as an OMElement - * @param attributeDTO AttributeDTO object which holds the policy meta data in String format - * @return AttributeValueDTO object which holds the policy meta data in String format - */ - public AttributeDTO searchXACML3Designator(OMElement omElement, - AttributeDTO attributeDTO) { - - Iterator iterator1 = omElement. - getChildrenWithLocalName(PDPConstants.ATTRIBUTE_DESIGNATOR); - while (iterator1.hasNext()) { - OMElement attributeDesignator = (OMElement) iterator1.next(); - if (attributeDesignator != null) { - String attributeId = attributeDesignator. - getAttributeValue(new QName(PDPConstants.ATTRIBUTE_ID)); - String category = attributeDesignator. - getAttributeValue(new QName(PDPConstants.CATEGORY)); - String dataType = attributeDesignator. - getAttributeValue(new QName(PDPConstants.DATA_TYPE)); - attributeDTO.setCategory(category); - attributeDTO.setAttributeId(attributeId); - attributeDTO.setAttributeDataType(dataType); - } - } - - return attributeDTO; - } - - /** - * This extract policy meta data from condition element in the policy - * - * @param omElement condition element as an OMElement - * @param attributeDTOs list of AttributeDTO object which holds the policy meta data - * in String format - * @return list of AttributeDTO object which holds the policy meta data in String format - */ - public List createMetaDataFromConditionElement(OMElement omElement, - List attributeDTOs) { - - Iterator iterator = omElement.getChildrenWithLocalName(PDPConstants.APPLY_ELEMENT); - if (iterator.hasNext()) { - if (version == XACMLConstants.XACML_VERSION_3_0) { - createMetaDataFromXACML3ApplyElement(omElement, attributeDTOs); - } else { - createMetaDataFromApplyElement(omElement, attributeDTOs); - } - } else { - AttributeDTO attributeDTO = new AttributeDTO(); - attributeDTO.setCategory(PDPConstants.UNKNOWN); - attributeDTO.setAttributeValue(PDPConstants.SEARCH_WARNING_MESSAGE4); - } - - // TODO currently only search meta data on Apply Element, support for other elements - return attributeDTOs; - } - - /** - * This extract policy meta data from each rule element in the policy - * - * @param omElement rule element as an OMElement - * @param attributeDTOs list of AttributeDTO object which holds the policy meta data - * in String format - * @return list of AttributeDTO object which holds the policy meta data in String format - */ - public List createMetaDataFromRuleElement(OMElement omElement, - List attributeDTOs) { - - if (omElement != null) { - - Iterator iterator1 = omElement.getChildrenWithLocalName(PDPConstants. - TARGET_ELEMENT); - while (iterator1.hasNext()) { - OMElement targetElement = (OMElement) iterator1.next(); - if (version == XACMLConstants.XACML_VERSION_3_0) { - createMetaDataFromXACML3TargetElement(targetElement, attributeDTOs); - } else { - createMetaDataFromTargetElement(targetElement, attributeDTOs); - } - } - - Iterator iterator2 = omElement.getChildrenWithLocalName(PDPConstants. - CONDITION_ELEMENT); - while (iterator2.hasNext()) { - OMElement conditionElement = (OMElement) iterator2.next(); - createMetaDataFromConditionElement(conditionElement, attributeDTOs); - } - } - - return attributeDTOs; - } - - /** - * This retrieves metadata attributes from the policy. - * - * @return attributeDTO list. - * @throws EntitlementException if an error occurs while retrieving attributes. - */ - public List getAttributesFromPolicy() throws EntitlementException { - - List attributeDTOs = new ArrayList<>(); - try { - return createPolicyMetaData(policy, attributeDTOs); - } catch (EntitlementException e) { - throw new EntitlementException("Can not create Policy MetaData for given policy"); - } - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/PolicyReader.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/PolicyReader.java deleted file mode 100644 index 4047bd366e61..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/PolicyReader.java +++ /dev/null @@ -1,200 +0,0 @@ -/* -* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.policy; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.wso2.balana.AbstractPolicy; -import org.wso2.balana.ParsingException; -import org.wso2.balana.Policy; -import org.wso2.balana.PolicySet; -import org.wso2.balana.finder.PolicyFinder; -import org.wso2.carbon.identity.core.util.IdentityUtil; -import org.xml.sax.ErrorHandler; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import java.io.ByteArrayInputStream; -import java.io.InputStream; - -public class PolicyReader implements ErrorHandler { - - // the standard attribute for specifying the XML schema language - private static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage"; - - // the standard identifier for the XML schema specification - private static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema"; - - // the standard attribute for specifying schema source - private static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource"; - // To enable attempted thread-safety using double-check locking - private static final Object lock = new Object(); - private static Log log = LogFactory.getLog(PolicyReader.class); - private static volatile PolicyReader reader; - // the builder used to create DOM documents - private DocumentBuilder builder; - - // policy finder module to find policies - private PolicyFinder policyFinder; - - private PolicyReader(PolicyFinder policyFinder) { - - this.policyFinder = policyFinder; - // create the factory - DocumentBuilderFactory factory = IdentityUtil.getSecuredDocumentBuilderFactory(); - factory.setIgnoringComments(true); - // now use the factory to create the document builder - try { - builder = factory.newDocumentBuilder(); - builder.setErrorHandler(this); - } catch (ParserConfigurationException pce) { - throw new IllegalArgumentException("Filed to setup repository: "); - } - } - - /** - * @param policyFinder - * @return - */ - public static PolicyReader getInstance(PolicyFinder policyFinder) { - if (reader == null) { - synchronized (lock) { - if (reader == null) { - reader = new PolicyReader(policyFinder); - } - } - } - return reader; - } - - /** - * @param policy - * @return - */ - public boolean isValidPolicy(String policy) { - InputStream stream = null; - try { - stream = new ByteArrayInputStream(policy.getBytes("UTF-8")); - handleDocument(builder.parse(stream)); - } catch (Exception e) { - return false; - } - return true; - } - - /** - * @param policy - * @return - */ - public synchronized AbstractPolicy getPolicy(String policy) { - InputStream stream = null; - try { - stream = new ByteArrayInputStream(policy.getBytes("UTF-8")); - return handleDocument(builder.parse(stream)); - } catch (Exception e) { - log.error("Error while parsing the policy", e); - return null; - } - } - - /** - * Reads policy target from the policy - * - * @param policy policy as a String - * @return target as PolicyTarget object - */ - public PolicyTarget getTarget(String policy) { - InputStream stream = null; - PolicyTarget policyTarget = new PolicyTarget(); - try { - stream = new ByteArrayInputStream(policy.getBytes("UTF-8")); - AbstractPolicy abstractPolicy = handleDocument(builder.parse(stream)); - policyTarget.setTarget(abstractPolicy.getTarget()); - policyTarget.setPolicyId(abstractPolicy.getId().toString()); - return policyTarget; - } catch (Exception e) { - log.error("Error while parsing the policy", e); - return null; - } - } - - /** - * @param doc - * @return - * @throws ParsingException - */ - private AbstractPolicy handleDocument(Document doc) throws ParsingException { - // handle the policy, if it's a known type - Element root = doc.getDocumentElement(); - String name = root.getLocalName(); - // see what type of policy this is - if (name.equals("Policy")) { - return Policy.getInstance(root); - } else if (name.equals("PolicySet")) { - return PolicySet.getInstance(root, policyFinder); - } else { - // this isn't a root type that we know how to handle - throw new ParsingException("Unknown root document type: " + name); - } - } - - /** - * {@inheritDoc} - */ - public void warning(SAXParseException exception) throws SAXException { - if (log.isWarnEnabled()) { - String message = null; - message = "Warning on line " + exception.getLineNumber() + ": " - + exception.getMessage(); - log.warn(message); - } - } - - /** - * {@inheritDoc} - */ - public void error(SAXParseException exception) throws SAXException { - if (log.isWarnEnabled()) { - log.warn("Error on line " + exception.getLineNumber() + ": " + exception.getMessage() - + " ... " + "Policy will not be available"); - } - - throw new SAXException("error parsing policy"); - } - - /** - * {@inheritDoc} - */ - public void fatalError(SAXParseException exception) throws SAXException { - if (log.isWarnEnabled()) { - log.warn("Fatal error on line " + exception.getLineNumber() + ": " - + exception.getMessage() + " ... " + "Policy will not be available"); - } - - throw new SAXException("fatal error parsing policy"); - } - - public PolicyFinder getPolicyFinder() { - return policyFinder; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/PolicyRequestBuilder.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/PolicyRequestBuilder.java deleted file mode 100644 index e6ae5fd10667..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/PolicyRequestBuilder.java +++ /dev/null @@ -1,77 +0,0 @@ -/* -* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.policy; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.wso2.carbon.identity.core.util.IdentityUtil; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.xml.sax.SAXException; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import java.io.ByteArrayInputStream; -import java.io.IOException; - -/** - * XACML request is built - */ -public class PolicyRequestBuilder { - - private static Log log = LogFactory.getLog(PolicyRequestBuilder.class); - - /** - * creates DOM representation of the XACML request - * - * @param request XACML request as a String object - * @return XACML request as a DOM element - * @throws EntitlementException throws, if fails - */ - public Element getXacmlRequest(String request) throws EntitlementException { - - ByteArrayInputStream inputStream; - DocumentBuilderFactory documentBuilderFactory; - Document doc; - DocumentBuilder documentBuilder; - - inputStream = new ByteArrayInputStream(request.getBytes()); - documentBuilderFactory = IdentityUtil.getSecuredDocumentBuilderFactory(); - - try { - - documentBuilder = documentBuilderFactory.newDocumentBuilder(); - doc = documentBuilder.parse(inputStream); - } catch (SAXException e) { - throw new EntitlementException("Error while creating DOM from XACML request"); - } catch (IOException e) { - throw new EntitlementException("Error while creating DOM from XACML request"); - } catch (ParserConfigurationException e) { - throw new EntitlementException("Error while creating DOM from XACML request"); - } finally { - try { - inputStream.close(); - } catch (IOException e) { - log.error("Error in closing input stream of XACML request"); - } - } - return doc.getDocumentElement(); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/PolicyTarget.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/PolicyTarget.java deleted file mode 100644 index f5411537272e..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/PolicyTarget.java +++ /dev/null @@ -1,56 +0,0 @@ -/* -* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.policy; - -import org.wso2.balana.AbstractTarget; - -/** - * This class encapsulates the policy target data with org.wso2.balana.Target and policyId - */ -public class PolicyTarget { - - private AbstractTarget target; - - private String policyId; - - public AbstractTarget getTarget() { - return target; - } - - public void setTarget(AbstractTarget target) { - this.target = target; - } - - public String getPolicyId() { - return policyId; - } - - public void setPolicyId(String policyId) { - this.policyId = policyId; - } - - @Override - public int hashCode() { - if (this.target != null) { - return target.encode().hashCode(); - } else { - return 0; - } - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/collection/DefaultPolicyCollection.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/collection/DefaultPolicyCollection.java deleted file mode 100644 index 52f5d57ee6b2..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/collection/DefaultPolicyCollection.java +++ /dev/null @@ -1,410 +0,0 @@ -/* - * Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.entitlement.policy.collection; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.balana.AbstractPolicy; -import org.wso2.balana.AbstractTarget; -import org.wso2.balana.MatchResult; -import org.wso2.balana.Policy; -import org.wso2.balana.PolicyReference; -import org.wso2.balana.PolicySet; -import org.wso2.balana.TargetMatch; -import org.wso2.balana.VersionConstraints; -import org.wso2.balana.XACMLConstants; -import org.wso2.balana.combine.PolicyCombiningAlgorithm; -import org.wso2.balana.ctx.EvaluationCtx; -import org.wso2.balana.ctx.Status; -import org.wso2.balana.xacml2.Target; -import org.wso2.balana.xacml2.TargetSection; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.EntitlementLRUCache; - -import java.io.Serializable; -import java.net.URI; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Properties; -import java.util.StringTokenizer; -import java.util.TreeSet; - -public class DefaultPolicyCollection implements PolicyCollection { - - // default target that matches anything, used in wrapping policies - private static final AbstractTarget target; - private static Log log = LogFactory.getLog(DefaultPolicyCollection.class); - /** - * This static initializer just sets up the default target, which is used by all wrapping policy - * sets. - */ - static { - target = new Target(new TargetSection(null, TargetMatch.SUBJECT, - XACMLConstants.XACML_VERSION_2_0), new TargetSection(null, TargetMatch.RESOURCE, - XACMLConstants.XACML_VERSION_2_0), new TargetSection(null, TargetMatch.ACTION, - XACMLConstants.XACML_VERSION_2_0), new TargetSection(null, TargetMatch.ENVIRONMENT, - XACMLConstants.XACML_VERSION_2_0)); - } - // the actual collection of policies - private LinkedHashMap> policies; - // the single instance of the comparator we'll use for managing versions - private VersionComparator versionComparator = new VersionComparator(); - // the optional combining algorithm used when wrapping multiple policies - private PolicyCombiningAlgorithm combiningAlg; - // the optional policy id used when wrapping multiple policies - private URI parentId; - private int maxInMemoryPolicies; - - ; - - /** - * Creates a new DefaultPolicyCollection that will return errors when multiple policies - * match for a given request. - * - * @param combiningAlg Policy combining Algorithm - * @param maxInMemoryPolicies maximum no of policies that keeps in memory - */ - public DefaultPolicyCollection(PolicyCombiningAlgorithm combiningAlg, int maxInMemoryPolicies) { - policies = new EntitlementLRUCache>(maxInMemoryPolicies); - this.maxInMemoryPolicies = maxInMemoryPolicies; - this.combiningAlg = combiningAlg; - } - - /** - * Creates a new DefaultPolicyCollection that will return errors when multiple policies - * match for a given request. - * - * @param combiningAlg Policy combining Algorithm - */ - public DefaultPolicyCollection(PolicyCombiningAlgorithm combiningAlg) { - policies = new LinkedHashMap>(); - this.combiningAlg = combiningAlg; - } - - /** - * Creates a new DefaultPolicyCollection that will create a new top-level PolicySet when - * multiple policies match for a given request. - * - * @param combiningAlg the algorithm to use in a new PolicySet when more than one policy applies - * @param parentPolicyId the identifier to use for the new PolicySet - */ - public DefaultPolicyCollection(PolicyCombiningAlgorithm combiningAlg, URI parentPolicyId) { - policies = new LinkedHashMap>(); - this.combiningAlg = combiningAlg; - this.parentId = parentPolicyId; - } - - @Override - public void init(Properties properties) throws Exception { - String parentIdProperty = properties.getProperty("parentId"); - if (parentIdProperty != null) { - parentId = new URI(parentIdProperty); - } - } - - /** - * Adds a new policy to the collection, and uses the policy's identifier as the reference - * identifier. If this identifier already exists in the collection, and this policy does not - * represent a new version of the policy, then the policy is not added. - * - * @param policy the policy to add - * @return true if the policy was added, false otherwise - */ - public boolean addPolicy(AbstractPolicy policy) { - return addPolicy(policy, policy.getId().toString()); - } - - /** - * *Adds a new policy to the collection using the given identifier as the reference identifier. - * If this identifier already exists in the collection, and this policy does not represent a new - * version of the policy, then the policy is not added. - * - * @param policy - * @param identifier - * @return - */ - public boolean addPolicy(AbstractPolicy policy, String identifier) { - if (policies.containsKey(identifier)) { - // this identifier is already is use, so see if this version is - // already in the set - TreeSet set = policies.get(identifier); - return set.add(policy); - } else { - // this identifier isn't already being used, so create a new - // set in the map for it, and add the policy - TreeSet set = new TreeSet(versionComparator); - policies.put(identifier, set); - return set.add(policy); - } - } - - /** - * Attempts to retrieve a policy based on the given context. If multiple policies match then - * this will either throw an exception or wrap the policies under a new PolicySet (depending on - * how this instance was constructed). If no policies match, then this will return null. See the - * comment in the class header about how this behaves when multiple versions of the same policy - * exist. - * - * @param context - * @return - * @throws EntitlementException - */ - public AbstractPolicy getEffectivePolicy(EvaluationCtx context) throws EntitlementException { - // setup a list of matching policies - ArrayList list = new ArrayList(); - // get an iterator over all the identifiers - Iterator> it = policies.values().iterator(); - - while (it.hasNext()) { - // for each identifier, get only the most recent policy - AbstractPolicy policy = it.next().first(); - - // see if we match - MatchResult match = policy.match(context); - int result = match.getResult(); - - // if there was an error, we stop right away - if (result == MatchResult.INDETERMINATE) { - log.error(match.getStatus().getMessage()); - throw new EntitlementException(match.getStatus().getMessage()); - } - - // if we matched, we keep track of the matching policy... - if (result == MatchResult.MATCH) { - // ...first checking if this is the first match and if - // we automatically nest policies - - if (log.isDebugEnabled()) { - log.debug("Matching XACML policy found " + policy.getId().toString()); - } - - if ((combiningAlg == null) && (list.size() > 0)) { - ArrayList code = new ArrayList(); - code.add(Status.STATUS_PROCESSING_ERROR); - Status status = new Status(code, "too many applicable top-level policies"); - //throw new EntitlementException(status); // TODO - } - - list.add(policy); - } - } - - // no errors happened during the search, so now take the right - // action based on how many policies we found - switch (list.size()) { - case 0: - if (log.isDebugEnabled()) { - log.debug("No matching XACML policy found"); - } - return null; - case 1: - return ((AbstractPolicy) (list.get(0))); - default: - return new PolicySet(parentId, combiningAlg, null, list); - } - } - - /** - * Get Policy using policyId - * - * @param policyId policyId as a URI - * @return AbstractPolicy - */ - public AbstractPolicy getPolicy(URI policyId) { - if (policies.containsKey(policyId.toString())) { - return policies.get(policyId.toString()).first(); - } - return null; - } - - /** - * Get Policy using policyId - * - * @param policyId policyId as a String - * @return AbstractPolicy - */ - public AbstractPolicy getPolicy(String policyId) { - if (policies.containsKey(policyId)) { - return policies.get(policyId).first(); - } - return null; - } - - /** - * get All policies - * - * @return LinkedHashMap of policies - */ - public LinkedHashMap> getPolicies() { - return policies; - } - - /** - * Get Policy or Policy Set for given applicable policies - * - * @param policies applicable policies as array list - * @return Policy or Policy Set as AbstractPolicy - * @throws EntitlementException throws if no policy combiningAlg is defined - */ - public AbstractPolicy getEffectivePolicy(ArrayList policies) throws EntitlementException { - - if ((combiningAlg == null) && (policies.size() > 0)) { - log.error("Too many applicable top-level policies"); - throw new EntitlementException("Too many applicable top-level policies"); - } - - switch (policies.size()) { - case 0: - if (log.isDebugEnabled()) { - log.debug("No matching XACML policy found"); - } - return null; - case 1: - return ((AbstractPolicy) (policies.get(0))); - default: - return new PolicySet(parentId, combiningAlg, target, policies); - } - } - - - /** - * Attempts to retrieve a policy based on the given identifier and other constraints. If there - * are multiple versions of the identified policy that meet the version constraints, then the - * most recent version is returned. - * - * @param identifier - * @param type - * @param constraints - * @return - */ - public AbstractPolicy getPolicy(URI identifier, int type, VersionConstraints constraints) { - - TreeSet set = policies.get(identifier.toString()); - - // if we don't know about this identifier then there's nothing to do - if (set == null) - return null; - - // walk through the set starting with the most recent version, looking - // for a match until we exhaust all known versions - Iterator it = set.iterator(); - while (it.hasNext()) { - AbstractPolicy policy = (AbstractPolicy) (it.next()); - if (constraints.meetsConstraint(policy.getVersion())) { - // we found a valid version, so see if it's the right kind, - // and if it is then we return it - if (type == PolicyReference.POLICY_REFERENCE) { - if (policy instanceof Policy) - return policy; - } else { - if (policy instanceof PolicySet) - return policy; - } - } - } - - // we didn't find a match - return null; - } - - @Override - public void setPolicyCombiningAlgorithm(PolicyCombiningAlgorithm algorithm) { - - } - - @Override - public int hashCode() { - int hash = 7; - hash = 31 * hash + (null == this.policies ? 0 : this.policies.hashCode()); - hash = 31 * hash + (null == this.combiningAlg ? 0 : this.combiningAlg.hashCode()); - return hash; - } - - /** - * A Comparator that is used within this class to maintain ordering amongst different versions - * of the same policy. Note that it actually maintains reverse-ordering, since we want to - * traverse the sets in decreasing, not increasing order. - *

    - * Note that this comparator is only used when there are multiple versions of the same policy, - * which in practice will probably happen far less (from this class' point of view) than - * additions or fetches. - */ - static class VersionComparator implements Serializable, Comparator { - - private static final long serialVersionUID = 1136846256293162005L; - - public int compare(AbstractPolicy o1, AbstractPolicy o2) { - // we swap the parameters so that sorting goes largest to smallest - String v1 = ((AbstractPolicy) o2).getVersion(); - String v2 = ((AbstractPolicy) o1).getVersion(); - - // do a quick check to see if the strings are equal (note that - // even if the strings aren't equal, the versions can still - // be equal) - if (v1.equals(v2)) - return 0; - - // setup tokenizers, and walk through both strings one set of - // numeric values at a time - StringTokenizer tok1 = new StringTokenizer(v1, "."); - StringTokenizer tok2 = new StringTokenizer(v2, "."); - - while (tok1.hasMoreTokens()) { - // if there's nothing left in tok2, then v1 is bigger - if (!tok2.hasMoreTokens()) - return 1; - - // get the next elements in the version, convert to numbers, - // and compare them (continuing with the loop only if the - // two values were equal) - int num1 = Integer.parseInt(tok1.nextToken()); - int num2 = Integer.parseInt(tok2.nextToken()); - - if (num1 > num2) - return 1; - - if (num1 < num2) - return -1; - } - - // if there's still something left in tok2, then it's bigger - if (tok2.hasMoreTokens()) - return -1; - - // if we got here it means both versions had the same number of - // elements and all the elements were equal, so the versions - // are in fact equal - return 0; - } - } -@Override - public boolean deletePolicy(String policyId) { - return false; - } -@Override - public LinkedHashMap getPolicyMap() { - return this.policies; - } - - @Override - public void setPolicyMap(LinkedHashMap policyMap) { - this.policies = policyMap ; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/collection/PolicyCollection.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/collection/PolicyCollection.java deleted file mode 100644 index 5271043a5251..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/collection/PolicyCollection.java +++ /dev/null @@ -1,93 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.policy.collection; - -import org.wso2.balana.AbstractPolicy; -import org.wso2.balana.VersionConstraints; -import org.wso2.balana.combine.PolicyCombiningAlgorithm; -import org.wso2.balana.ctx.EvaluationCtx; -import org.wso2.carbon.identity.entitlement.EntitlementException; - -import java.net.URI; -import java.util.LinkedHashMap; -import java.util.Properties; - -/** - * Policy collection for all the policies defined in entitlement engine. This collection is created - * by finding each and every policies that have been configured with each policy finder modules. - * There can be different implementation to maintain policies. - */ -public interface PolicyCollection { - - /** - * initializes policy finder collection - * - * @param properties Properties, that need to initialize the module - * @throws Exception throws when initialization is failed - */ - public void init(Properties properties) throws Exception; - - /** - * adds policy to policy collection - * - * @param policy policy as AbstractPolicy object of Balana - * @return whether policy is added successfully or not - */ - public boolean addPolicy(AbstractPolicy policy); - - /** - * returns the effective policy for given XACML request - * - * @param context XACML request ctx - * @return effective policy set as AbstractPolicy object of Balana - * @throws EntitlementException if any error, while policy is retrieved - */ - public AbstractPolicy getEffectivePolicy(EvaluationCtx context) throws EntitlementException; - - /** - * returns policy by given identifier - * - * @param identifier policy identifier - * @return policy as AbstractPolicy object of Balana - */ - public AbstractPolicy getPolicy(URI identifier); - - /** - * returns policy by identifier type and version - * - * @param identifier policy identifier - * @param type policy type whether policy or policy set - * @param constraints policy version constraints - * @return policy as AbstractPolicy object of Balana - */ - public AbstractPolicy getPolicy(URI identifier, int type, VersionConstraints constraints); - - /** - * sets global policy combining algorithm - * - * @param algorithm PolicyCombiningAlgorithm object of Balana - */ - public void setPolicyCombiningAlgorithm(PolicyCombiningAlgorithm algorithm); - - - public boolean deletePolicy(String policyId); - public LinkedHashMap getPolicyMap() ; - public void setPolicyMap(LinkedHashMap policyMap) ; - -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/collection/SimplePolicyCollection.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/collection/SimplePolicyCollection.java deleted file mode 100644 index fa34940272ac..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/collection/SimplePolicyCollection.java +++ /dev/null @@ -1,184 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.policy.collection; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.balana.AbstractPolicy; -import org.wso2.balana.MatchResult; -import org.wso2.balana.Policy; -import org.wso2.balana.PolicyReference; -import org.wso2.balana.PolicySet; -import org.wso2.balana.VersionConstraints; -import org.wso2.balana.combine.PolicyCombiningAlgorithm; -import org.wso2.balana.ctx.EvaluationCtx; -import org.wso2.carbon.identity.entitlement.EntitlementException; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Properties; - -/** - * simple implementation of Policy collection interface. This uses in-memory map to maintain policies - * policy versions are not maintained by this - */ -public class SimplePolicyCollection implements PolicyCollection { - - private static Log log = LogFactory.getLog(SimplePolicyCollection.class); - /** - * the actual collection of policies - * to maintain the order of the policies, LinkedHashMap has been used. - * Map with policy identifier policy as AbstractPolicy object - */ - private LinkedHashMap policyCollection = new LinkedHashMap(); - /** - * the optional combining algorithm used when wrapping multiple policies - * if no algorithm is defined, only one applicable algorithm is used - */ - private PolicyCombiningAlgorithm combiningAlg; - /** - * the optional policy id used when wrapping multiple policies - */ - private URI parentId; - - @Override - public void init(Properties properties) throws Exception { - String parentIdProperty = properties.getProperty("parentId"); - if (parentIdProperty != null) { - parentId = new URI(parentIdProperty); - } - } - - @Override - public boolean addPolicy(AbstractPolicy policy) { - return addPolicy(policy.getId(), policy); - } - - @Override - public AbstractPolicy getEffectivePolicy(EvaluationCtx context) throws EntitlementException { - - // setup a list of matching policies - ArrayList list = new ArrayList(); - - for (Map.Entry entry : policyCollection.entrySet()) { - - AbstractPolicy policy = entry.getValue(); - - // see if we match - MatchResult match = policy.match(context); - int result = match.getResult(); - - // if there was an error, we stop right away - if (result == MatchResult.INDETERMINATE) { - log.error(match.getStatus().getMessage()); - throw new EntitlementException(match.getStatus().getMessage()); - } - - // if we matched, we keep track of the matching policy... - if (result == MatchResult.MATCH) { - // ...first checking if this is the first match and if - // we automatically nest policies - - if (log.isDebugEnabled()) { - log.debug("Matching XACML policy found " + policy.getId().toString()); - } - - if ((combiningAlg == null) && (list.size() > 0)) { - log.error("Too many applicable top-level policies"); - throw new EntitlementException("Too many applicable top-level policies"); - } - - list.add(policy); - } - } - - // no errors happened during the search, so now take the right - // action based on how many policies we found - switch (list.size()) { - case 0: - if (log.isDebugEnabled()) { - log.debug("No matching XACML policy found"); - } - return null; - case 1: - return ((AbstractPolicy) (list.get(0))); - default: - return new PolicySet(parentId, combiningAlg, null, list); - } - - } - - @Override - public AbstractPolicy getPolicy(URI policyId) { - return policyCollection.get(policyId); - } - - @Override - public AbstractPolicy getPolicy(URI identifier, int type, VersionConstraints constraints) { - - AbstractPolicy policy = policyCollection.get(identifier); - - if (policy != null) { - // we found a valid version, so see if it's the right kind, - // and if it is then we return it - if (type == PolicyReference.POLICY_REFERENCE) { - if (policy instanceof Policy) { - return policy; - } - } else { - if (policy instanceof PolicySet) { - return policy; - } - } - } - - return null; - } - - private synchronized boolean addPolicy(URI identifier, AbstractPolicy policy) { - return policyCollection.put(identifier, policy) != null; - } - - @Override - public void setPolicyCombiningAlgorithm(PolicyCombiningAlgorithm algorithm) { - this.combiningAlg = algorithm; - } - - @Override - public boolean deletePolicy(String policyId) { - try { - return this.policyCollection.remove(new URI(policyId)) != null; - } catch (URISyntaxException ex) { - return false; - } - } - - @Override - public LinkedHashMap getPolicyMap() { - return this.policyCollection; - } - - @Override - public void setPolicyMap(LinkedHashMap policyMap) { - this.policyCollection = policyMap; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/finder/AbstractPolicyFinderModule.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/finder/AbstractPolicyFinderModule.java deleted file mode 100644 index 82f9617f56a6..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/finder/AbstractPolicyFinderModule.java +++ /dev/null @@ -1,143 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.policy.finder; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.entitlement.PolicyOrderComparator; -import org.wso2.carbon.identity.entitlement.dto.AttributeDTO; -import org.wso2.carbon.identity.entitlement.dto.PolicyStoreDTO; -import org.wso2.carbon.identity.entitlement.pap.EntitlementAdminEngine; -import org.wso2.carbon.identity.entitlement.pdp.EntitlementEngine; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Abstract implementation of a policy finder module. This can be easily extended by any module - * that support dynamic policy changes. - */ -public abstract class AbstractPolicyFinderModule implements PolicyFinderModule { - - private static Log log = LogFactory.getLog(AbstractPolicyFinderModule.class); - - /** - * This method must be called by the module when its policies are updated - */ - public static void invalidateCache(String policyId, String action) { - EntitlementEngine.getInstance().getPolicyCache().invalidateCache(policyId, action); - EntitlementEngine.getInstance().clearDecisionCache(); - EntitlementEngine.getInstance().getPolicySearch().getPolicySearchCache().invalidateCache(); - } - - public static void invalidateCache() { - EntitlementEngine.getInstance().clearDecisionCache(); - EntitlementEngine.getInstance().invalidatePolicyCache(); - EntitlementEngine.getInstance().getPolicySearch().getPolicySearchCache().invalidateCache(); - } - - @Override - public String[] getOrderedPolicyIdentifiers() { - - log.debug("Start retrieving ordered policy identifiers at : " + new Date()); - String[] policyIdentifiers = getPolicyIdentifiers(); - if (policyIdentifiers != null && !isPolicyOrderingSupport()) { - PolicyStoreDTO[] policyDTOs = EntitlementAdminEngine.getInstance(). - getPolicyStoreManager().getAllPolicyData(); - Arrays.sort(policyDTOs, new PolicyOrderComparator()); - List list = new ArrayList(); - List finalList = new ArrayList(); - // 1st put non -order items - list.addAll(Arrays.asList(policyIdentifiers)); - for (PolicyStoreDTO dto : policyDTOs) { - list.remove(dto.getPolicyId()); - finalList.add(dto.getPolicyId()); - } - finalList.addAll(list); - return finalList.toArray(new String[finalList.size()]); - } - log.debug("Finish retrieving ordered policy identifiers at : " + new Date()); - return policyIdentifiers; - } - - @Override - public String[] getActivePolicies() { - - log.debug("Start retrieving active policies at : " + new Date()); - List policies = new ArrayList(); - String[] policyIdentifiers = getOrderedPolicyIdentifiers(); - if (policyIdentifiers != null) { - for (String identifier : policyIdentifiers) { - if (!isPolicyDeActivationSupport()) { - PolicyStoreDTO data = EntitlementAdminEngine.getInstance(). - getPolicyDataStore().getPolicyData(identifier); - if (data != null && data.isActive()) { - String policy = getPolicy(identifier); - if (policy != null) { - policies.add(policy); - } - } - } else { - String policy = getPolicy(identifier); - if (policy != null) { - policies.add(policy); - } - } - } - } - log.debug("Finish retrieving active policies at : " + new Date()); - return policies.toArray(new String[policies.size()]); - - } - - @Override - public boolean isDefaultCategoriesSupported() { - return true; - } - - @Override - public boolean isPolicyOrderingSupport() { - return false; - } - - @Override - public boolean isPolicyDeActivationSupport() { - return false; - } - - @Override - public Map> getSearchAttributes(String identifier, - Set givenAttribute) { - return null; - } - - @Override - public int getSupportedSearchAttributesScheme() { - return 0; - } - - /** - * @return - */ - protected abstract String[] getPolicyIdentifiers(); -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/finder/CarbonPolicyFinder.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/finder/CarbonPolicyFinder.java deleted file mode 100644 index 1eeb1de7080a..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/finder/CarbonPolicyFinder.java +++ /dev/null @@ -1,358 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.policy.finder; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.balana.AbstractPolicy; -import org.wso2.balana.Policy; -import org.wso2.balana.PolicyMetaData; -import org.wso2.balana.PolicyReference; -import org.wso2.balana.PolicySet; -import org.wso2.balana.VersionConstraints; -import org.wso2.balana.combine.PolicyCombiningAlgorithm; -import org.wso2.balana.ctx.EvaluationCtx; -import org.wso2.balana.ctx.Status; -import org.wso2.balana.finder.PolicyFinder; -import org.wso2.balana.finder.PolicyFinderResult; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.PDPConstants; -import org.wso2.carbon.identity.entitlement.PolicyOrderComparator; -import org.wso2.carbon.identity.entitlement.cache.PolicyStatus; -import org.wso2.carbon.identity.entitlement.common.EntitlementConstants; -import org.wso2.carbon.identity.entitlement.persistence.ConfigPersistenceManager; -import org.wso2.carbon.identity.entitlement.dto.PolicyDTO; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; -import org.wso2.carbon.identity.entitlement.pap.EntitlementAdminEngine; -import org.wso2.carbon.identity.entitlement.pdp.EntitlementEngine; -import org.wso2.carbon.identity.entitlement.policy.PolicyReader; -import org.wso2.carbon.identity.entitlement.policy.collection.PolicyCollection; -import org.wso2.carbon.identity.entitlement.policy.collection.SimplePolicyCollection; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -/** - * Policy finder of the WSO2 entitlement engine. This an implementation of PolicyFinderModule - * of Balana engine. Extensions can be plugged with this. - */ -public class CarbonPolicyFinder extends org.wso2.balana.finder.PolicyFinderModule { - - private static Log log = LogFactory.getLog(CarbonPolicyFinder.class); - public PolicyReader policyReader; - private List finderModules = null; - private PolicyCollection policyCollection; - - private List policyCollectionOrder = new ArrayList(); - - private PolicyFinder finder; - /** - * this is a flag to keep whether init it has finished or not. - */ - private volatile boolean initFinish; - private LinkedHashMap policyReferenceCache = null; - private int maxReferenceCacheEntries = PDPConstants.MAX_NO_OF_IN_MEMORY_POLICIES; - - - @Override - public void init(PolicyFinder finder) { - initFinish = false; - this.finder = finder; - init(); - policyReferenceCache.clear(); - } - - private synchronized void init() { - - if (initFinish) { - return; - } - - log.info("Initializing of policy store is started at : " + new Date()); - - String maxEntries = EntitlementServiceComponent.getEntitlementConfig().getEngineProperties(). - getProperty(PDPConstants.MAX_POLICY_REFERENCE_ENTRIES); - - if (maxEntries != null) { - try { - maxReferenceCacheEntries = Integer.parseInt(maxEntries.trim()); - } catch (Exception e) { - //ignore - } - } - - policyReferenceCache = new LinkedHashMap() { - - @Override - protected boolean removeEldestEntry(Map.Entry eldest) { - // oldest entry of the cache would be removed when max cache size become, i.e 50 - return size() > maxReferenceCacheEntries; - } - - }; - - PolicyCombiningAlgorithm policyCombiningAlgorithm = null; - // get registered finder modules - Map finderModules = EntitlementServiceComponent. - getEntitlementConfig().getPolicyFinderModules(); - - if (finderModules != null) { - this.finderModules = new ArrayList(finderModules.keySet()); - } - - PolicyCollection tempPolicyCollection = null; - - // get policy collection - Map policyCollections = EntitlementServiceComponent. - getEntitlementConfig().getPolicyCollections(); - if (policyCollections != null && policyCollections.size() > 0) { - tempPolicyCollection = policyCollections.entrySet().iterator().next().getKey(); - } else { - tempPolicyCollection = new SimplePolicyCollection(); - } - - // get policy reader - policyReader = PolicyReader.getInstance(finder); - - if (this.finderModules != null && this.finderModules.size() > 0) { - // find policy combining algorithm. - - ConfigPersistenceManager configPersistenceManager = EntitlementAdminEngine.getInstance().getConfigPersistenceManager(); - policyCombiningAlgorithm = configPersistenceManager.getGlobalPolicyAlgorithm(); - - tempPolicyCollection.setPolicyCombiningAlgorithm(policyCombiningAlgorithm); - - for (PolicyFinderModule finderModule : this.finderModules) { - log.info("Start retrieving policies from " + finderModule + " at : " + new Date()); - String[] policies = finderModule.getActivePolicies(); - for (int a = 0; a < policies.length; a++) { - String policy = policies[a]; - AbstractPolicy abstractPolicy = policyReader.getPolicy(policy); - if (abstractPolicy != null) { - PolicyDTO policyDTO = new PolicyDTO(); - policyDTO.setPolicyId(abstractPolicy.getId().toString()); - policyDTO.setPolicyOrder(a); - policyCollectionOrder.add(policyDTO); - tempPolicyCollection.addPolicy(abstractPolicy); - } - } - log.info("Finish retrieving policies from " + finderModule + " at : " + new Date()); - } - } else { - log.warn("No Carbon policy finder modules are registered"); - - } - - policyCollection = tempPolicyCollection; - initFinish = true; - log.info("Initializing of policy store is finished at : " + new Date()); - } - - @Override - public String getIdentifier() { - return super.getIdentifier(); - } - - @Override - public boolean isRequestSupported() { - return true; - } - - @Override - public boolean isIdReferenceSupported() { - return true; - } - - - private void orderPolicyCache() { - LinkedHashMap policyMap = policyCollection.getPolicyMap(); - Collections.sort(policyCollectionOrder, new PolicyOrderComparator()); - LinkedHashMap newPolicyMap = new LinkedHashMap(); - Iterator policyDTOIterator = policyCollectionOrder.iterator(); - while (policyDTOIterator.hasNext()) { - try { - URI policyURI = new URI(policyDTOIterator.next().getPolicyId()); - newPolicyMap.put(policyURI, policyMap.get(policyURI)); - - } catch (URISyntaxException e) { - e.printStackTrace(); - } - } - } - - @Override - public PolicyFinderResult findPolicy(EvaluationCtx context) { - - if (EntitlementEngine.getInstance().getPolicyCache().isInvalidate()) { - - init(this.finder); - policyReferenceCache.clear(); - EntitlementEngine.getInstance().clearDecisionCache(); - EntitlementEngine.getInstance().resetCacheInvalidateState(); - if (log.isDebugEnabled()) { - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - log.debug("Invalidation cache message is received. " + - "Re-initialized policy finder module of current node and invalidate decision " + - "caching for tenantId : " + tenantId); - } - } else { - Collection policies = - EntitlementEngine.getInstance().getPolicyCache().getInvalidatedPolicies(); - if (policies != null) { - if (policies.size() > 0) { - synchronized (policies) { - boolean isReorder = false; - policyReferenceCache.clear(); - EntitlementEngine.getInstance().clearDecisionCache(); - for (PolicyStatus policyStatus : policies) { - - if (EntitlementConstants.PolicyPublish.ACTION_DELETE - .equals(policyStatus.getPolicyAction())) { - policyCollection.deletePolicy(policyStatus.getPolicyId()); - policyCollectionOrder.remove(new PolicyDTO(policyStatus.getPolicyId())); - } else if (EntitlementConstants.PolicyPublish.ACTION_UPDATE - .equals(policyStatus.getPolicyAction())) { - AbstractPolicy abstractPolicy = loadPolicy(policyStatus.getPolicyId()); - policyCollection.addPolicy(abstractPolicy); - } else if (EntitlementConstants.PolicyPublish.ACTION_CREATE - .equals(policyStatus.getPolicyAction())) { - AbstractPolicy abstractPolicy = loadPolicy(policyStatus.getPolicyId()); - policyCollection.addPolicy(abstractPolicy); - isReorder = true; - } else if (EntitlementConstants.PolicyPublish.ACTION_ORDER - .equals(policyStatus.getPolicyAction())) { - int order = getPolicyOrder(policyStatus.getPolicyId()); - if (order != -1) { - PolicyDTO policyDTO = new PolicyDTO(policyStatus.getPolicyId()); - if (policyCollectionOrder.indexOf(policyDTO) != -1) { - policyCollectionOrder.get(policyCollectionOrder.indexOf(policyDTO)) - .setPolicyOrder(order); - isReorder = true; - } - } - } - - } - if (isReorder) { - orderPolicyCache(); - } - policies.clear(); - } - - - } - } - } - - try { - AbstractPolicy policy = policyCollection.getEffectivePolicy(context); - if (policy == null) { - return new PolicyFinderResult(); - } else { - return new PolicyFinderResult(policy); - } - } catch (EntitlementException e) { - ArrayList code = new ArrayList(); - code.add(Status.STATUS_PROCESSING_ERROR); - Status status = new Status(code, e.getMessage()); - return new PolicyFinderResult(status); - } - } - - - private AbstractPolicy loadPolicy(String policyId) { - if (this.finderModules != null) { - for (PolicyFinderModule finderModule : this.finderModules) { - String policyString = finderModule.getPolicy(policyId); - if (policyString != null) { - AbstractPolicy policy = policyReader.getPolicy(policyString); - if (policy != null) { - return policy; - } - } - } - } - return null; - } - - private int getPolicyOrder(String policyId) { - int order = -1; - if (this.finderModules != null) { - - for (PolicyFinderModule finderModule : this.finderModules) { - if ((order = finderModule.getPolicyOrder(policyId)) != -1) { - break; - } - } - } - return order; - } - - @Override - public PolicyFinderResult findPolicy(URI idReference, int type, VersionConstraints constraints, - PolicyMetaData parentMetaData) { - - AbstractPolicy policy = policyReferenceCache.get(idReference); - - if (policy == null) { - if (this.finderModules != null) { - for (PolicyFinderModule finderModule : this.finderModules) { - String policyString = finderModule.getReferencedPolicy(idReference.toString()); - if (policyString != null) { - policy = policyReader.getPolicy(policyString); - if (policy != null) { - policyReferenceCache.put(idReference, policy); - break; - } - } - } - } - } - - if (policy != null) { - // we found a valid version, so see if it's the right kind, - // and if it is then we return it - if (type == PolicyReference.POLICY_REFERENCE) { - if (policy instanceof Policy) { - return new PolicyFinderResult(policy); - } - } else { - if (policy instanceof PolicySet) { - return new PolicyFinderResult(policy); - } - } - } - - return new PolicyFinderResult(); - } - - public void clearPolicyCache() { - EntitlementEngine.getInstance().getPolicyCache().clear(); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/finder/PolicyFinderModule.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/finder/PolicyFinderModule.java deleted file mode 100644 index a9147988da64..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/finder/PolicyFinderModule.java +++ /dev/null @@ -1,158 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.policy.finder; - -import org.wso2.carbon.identity.entitlement.dto.AttributeDTO; - -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -/** - * Policy manage module is a extension point where XACML policies can be stored and loaded in to the PDP - * from different sources. There can be more than one policy store modules. - */ -public interface PolicyFinderModule { - - /** - * Policy search is done by creating requests from all combinations of the attributes that is - * found by policy manage module - */ - public final static int ALL_COMBINATIONS = 0; - - /** - * Policy search is done by creating requests from combinations of category of the attributes that is - * found by policy manage module - */ - public final static int COMBINATIONS_BY_CATEGORY = 1; - - /** - * Policy search is done by creating requests from combinations of given parameter - * of the attributes that is found by policy manage module - */ - public final static int COMBINATIONS_BY_PARAMETER = 2; - - /** - * Policy search is done by creating requests from combinations of given parameter - * and category of the attributes that is found by policy manage module - */ - public final static int COMBINATIONS_BY_CATEGORY_AND_PARAMETER = 3; - - /** - * Policy search is done by creating requests from the attributes that is - * found by policy manage module - */ - public final static int NO_COMBINATIONS = 4; - - - /** - * initializes policy manage module - * - * @param properties Properties, that need to initialize the module - * @throws Exception throws when initialization is failed - */ - public void init(Properties properties) throws Exception; - - /** - * gets name of this module - * - * @return name as String - */ - public String getModuleName(); - - /** - * gets all supported active policies. policies are fetched as Strings. - * if policy ordering is supported by module itself, these policies must be ordered. - * - * @return array of policies as Strings - */ - public String[] getActivePolicies(); - - /** - * gets all supported policy ids by this module - * if policy ordering is supported by module itself, these policy ids must be ordered - * - * @return array of policy ids as Strings - */ - public String[] getOrderedPolicyIdentifiers(); - - /** - * gets policy for given policy Id - * - * @param policyId policy id as String value - * @return policy as String - */ - public String getPolicy(String policyId); - - - public int getPolicyOrder(String policyId); - - - /** - * gets reference policy for given policy Id - *

    - * reference policy can not be with PDP policy store, may be in some external policy store - * Therefore new method has been add for retrieve reference policies - * - * @param policyId policy id as String value - * @return reference policy as String - */ - public String getReferencedPolicy(String policyId); - - /** - * gets attributes that are used for policy searching - * - * @param identifier unique identifier to separate out search attributes - * @param givenAttribute pre-given attributes to retrieve other attributes - * @return return search attributes based on a given policy. Map of policy id with search attributes. - */ - public Map> getSearchAttributes(String identifier, - Set givenAttribute); - - /** - * gets support attribute searching scheme of this module - * - * @return return scheme identifier value - */ - public int getSupportedSearchAttributesScheme(); - - /** - * returns whether this module supports for default category of policies - * if means policies has been written based subject or users, resource, actions and environment - * - * @return whether supported or not - */ - public boolean isDefaultCategoriesSupported(); - - /** - * returns whether this module supports for policy ordering. - * - * @return whether supported or not - */ - public boolean isPolicyOrderingSupport(); - - /** - * returns whether this module supports for policy activation or de-activation. - * - * @return whether supported or not - */ - public boolean isPolicyDeActivationSupport(); - - -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/finder/registry/RegistryPolicyHandler.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/finder/registry/RegistryPolicyHandler.java deleted file mode 100644 index eba65f603795..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/finder/registry/RegistryPolicyHandler.java +++ /dev/null @@ -1,67 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.policy.finder.registry; - -import org.wso2.carbon.identity.entitlement.PDPConstants; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; -import org.wso2.carbon.identity.entitlement.policy.finder.AbstractPolicyFinderModule; -import org.wso2.carbon.registry.core.exceptions.RegistryException; -import org.wso2.carbon.registry.core.jdbc.handlers.Handler; -import org.wso2.carbon.registry.core.jdbc.handlers.RequestContext; - -import java.util.Properties; - -/** - * Registry policy handler - */ -public class RegistryPolicyHandler extends Handler { - - @Override - public void put(RequestContext requestContext) throws RegistryException { - super.put(requestContext); - Properties properties = EntitlementServiceComponent.getEntitlementConfig().getEngineProperties(); - boolean enableRegistryCacheClear = true ; - if(properties.getProperty(PDPConstants.PDP_REGISTRY_LEVEL_POLICY_CACHE_CLEAR)!=null){ - enableRegistryCacheClear = Boolean.parseBoolean(properties.getProperty(PDPConstants.PDP_REGISTRY_LEVEL_POLICY_CACHE_CLEAR)); - } - if(enableRegistryCacheClear) { - AbstractPolicyFinderModule.invalidateCache(); - } - - - } - - @Override - public void delete(RequestContext requestContext) throws RegistryException { - - super.delete(requestContext); - Properties properties = EntitlementServiceComponent.getEntitlementConfig().getEngineProperties(); - boolean enableRegistryCacheClear = true ; - if(properties.getProperty(PDPConstants.PDP_REGISTRY_LEVEL_POLICY_CACHE_CLEAR)!=null){ - enableRegistryCacheClear = Boolean.parseBoolean(properties.getProperty(PDPConstants.PDP_REGISTRY_LEVEL_POLICY_CACHE_CLEAR)); - } - if(enableRegistryCacheClear) { - AbstractPolicyFinderModule.invalidateCache(); - } - - } - - - -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/finder/registry/RegistryPolicyMediaTypeMatcher.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/finder/registry/RegistryPolicyMediaTypeMatcher.java deleted file mode 100644 index 3190821a300e..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/finder/registry/RegistryPolicyMediaTypeMatcher.java +++ /dev/null @@ -1,58 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.policy.finder.registry; - -import org.wso2.carbon.registry.core.Resource; -import org.wso2.carbon.registry.core.exceptions.RegistryException; -import org.wso2.carbon.registry.core.jdbc.handlers.RequestContext; -import org.wso2.carbon.registry.core.jdbc.handlers.filters.MediaTypeMatcher; - -/** - * Registry policy media type matcher - */ -public class RegistryPolicyMediaTypeMatcher extends MediaTypeMatcher { - - - @Override - public boolean handlePut(RequestContext requestContext) throws RegistryException { - Resource resource = requestContext.getResource(); - if (resource != null) { - String mType = resource.getMediaType(); - return mType != null && (invert != mType.equals(getMediaType())); - } - return false; - } - - @Override - public boolean handleDelete(RequestContext requestContext) throws RegistryException { - Resource resource = requestContext.getResource(); - if (resource != null) { - String mType = resource.getMediaType(); - return mType != null && (invert != mType.equals(getMediaType())); - } else if (requestContext.getResourcePath() != null) { - resource = requestContext.getRegistry().get(requestContext. - getResourcePath().getCompletePath()); - if (resource != null) { - String mType = resource.getMediaType(); - return mType != null && (invert != mType.equals(getMediaType())); - } - } - return false; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/publisher/AbstractPolicyPublisherModule.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/publisher/AbstractPolicyPublisherModule.java deleted file mode 100644 index 4a19ceb36eb4..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/publisher/AbstractPolicyPublisherModule.java +++ /dev/null @@ -1,195 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.policy.publisher; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.common.EntitlementConstants; -import org.wso2.carbon.identity.entitlement.dto.PolicyDTO; -import org.wso2.carbon.identity.entitlement.dto.PublisherDataHolder; -import org.wso2.carbon.identity.entitlement.dto.PublisherPropertyDTO; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -/** - * This is abstract implementation of PolicyPublisherModule. Here we have implemented the init() - * method. - * If you want to configure properties of a publisher module from management UI, - * you want to write your publisher module by extending this abstract class - * Then you can init() your module each time policy is published. - */ -public abstract class AbstractPolicyPublisherModule implements PolicyPublisherModule { - - protected static final String REQUIRED = "required"; - - protected static final String DISPLAY_NAME = "displayName"; - - protected static final String ORDER = "order"; - - protected static final String SECRET = "password"; - - private static Log log = LogFactory.getLog(AbstractPolicyPublisherModule.class); - - public void init(Properties properties) { - - List propertyDTOs = new ArrayList(); - - if (properties == null || properties.size() == 0) { - properties = loadProperties(); - } - - if (properties != null) { - for (Map.Entry entry : properties.entrySet()) { - - Map attributeMap; - - Object value = entry.getValue(); - if (value instanceof Map) { - attributeMap = (Map) value; - } else { - return; - } - - PublisherPropertyDTO dto = new PublisherPropertyDTO(); - dto.setModule(getModuleName()); - dto.setId((String) entry.getKey()); - if (attributeMap.get(DISPLAY_NAME) != null) { - dto.setDisplayName((String) attributeMap.get(DISPLAY_NAME)); - } else { - log.error("Invalid policy publisher configuration : Display name can not be null"); - } - if (attributeMap.get(ORDER) != null) { - dto.setDisplayOrder(Integer.parseInt((String) attributeMap.get(ORDER))); - } - if (attributeMap.get(REQUIRED) != null) { - dto.setRequired(Boolean.parseBoolean((String) attributeMap.get(REQUIRED))); - } - if (attributeMap.get(SECRET) != null) { - dto.setSecret(Boolean.parseBoolean((String) attributeMap.get(SECRET))); - } - propertyDTOs.add(dto); - } - } - - PublisherPropertyDTO preDefined1 = new PublisherPropertyDTO(); - preDefined1.setId(PolicyPublisher.SUBSCRIBER_ID); - preDefined1.setModule(getModuleName()); - preDefined1.setDisplayName(PolicyPublisher.SUBSCRIBER_DISPLAY_NAME); - preDefined1.setRequired(true); - preDefined1.setDisplayOrder(0); - propertyDTOs.add(preDefined1); - - PublisherDataHolder holder = new PublisherDataHolder(getModuleName()); - holder.setPropertyDTOs(propertyDTOs.toArray(new PublisherPropertyDTO[propertyDTOs.size()])); - EntitlementServiceComponent.getEntitlementConfig(). - addModulePropertyHolder(PolicyPublisherModule.class.getName(), holder); - - } - - @Override - public Properties loadProperties() { - return null; - } - - @Override - public void publish(PolicyDTO policyDTO, String action, boolean enabled, int order) throws EntitlementException { - - if (EntitlementConstants.PolicyPublish.ACTION_CREATE.equals(action)) { - policyDTO.setPolicyOrder(order); - policyDTO.setActive(enabled); - publishNew(policyDTO); - } else if (EntitlementConstants.PolicyPublish.ACTION_DELETE.equals(action)) { - delete(policyDTO); - } else if (EntitlementConstants.PolicyPublish.ACTION_UPDATE.equals(action)) { - update(policyDTO); - } else if (EntitlementConstants.PolicyPublish.ACTION_ENABLE.equals(action)) { - policyDTO.setActive(true); - enable(policyDTO); - } else if (EntitlementConstants.PolicyPublish.ACTION_DISABLE.equals(action)) { - policyDTO.setActive(false); - disable(policyDTO); - } else if (EntitlementConstants.PolicyPublish.ACTION_ORDER.equals(action)) { - policyDTO.setPolicyOrder(order); - order(policyDTO); - } else { - throw new EntitlementException("Unsupported publishing action. Action is : " + action); - } - } - - /** - * This would init module, each time policy is published - * - * @param propertyHolder publisher module data as PublisherDataHolder - * @throws EntitlementException throws if init fails - */ - public abstract void init(PublisherDataHolder propertyHolder) throws EntitlementException; - - /** - * Publish a new policy - * - * @param policyDTO PolicyDTO - * @throws EntitlementException throws, if fails - */ - public abstract void publishNew(PolicyDTO policyDTO) throws EntitlementException; - - /** - * Update a already published policy - * - * @param policyDTO PolicyDTO - * @throws EntitlementException throws, if fails - */ - public abstract void update(PolicyDTO policyDTO) throws EntitlementException; - - /** - * Deletes a published policy - * - * @param policyDTO PolicyDTO - * @throws EntitlementException throws, if fails - */ - public abstract void delete(PolicyDTO policyDTO) throws EntitlementException; - - /** - * Order policy - * - * @param policyDTO PolicyDTO - * @throws EntitlementException if fails - */ - public abstract void order(PolicyDTO policyDTO) throws EntitlementException; - - /** - * Disables policy in PDP - * - * @param policyDTO PolicyDTO - * @throws EntitlementException if fails - */ - public abstract void disable(PolicyDTO policyDTO) throws EntitlementException; - - /** - * Enables policy in PDP - * - * @param policyDTO PolicyDTO - * @throws EntitlementException if fails - */ - public abstract void enable(PolicyDTO policyDTO) throws EntitlementException; -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/publisher/CarbonBasicPolicyPublisherModule.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/publisher/CarbonBasicPolicyPublisherModule.java deleted file mode 100644 index 0e09299dca8c..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/publisher/CarbonBasicPolicyPublisherModule.java +++ /dev/null @@ -1,223 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.policy.publisher; - - -import org.apache.axiom.om.util.AXIOMUtil; -import org.apache.axis2.AxisFault; -import org.apache.axis2.Constants; -import org.apache.axis2.client.Options; -import org.apache.axis2.client.ServiceClient; -import org.apache.axis2.context.ConfigurationContext; -import org.apache.axis2.context.ConfigurationContextFactory; -import org.apache.axis2.transport.http.HTTPConstants; -import org.apache.axis2.transport.http.HttpTransportProperties; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.dto.PolicyDTO; -import org.wso2.carbon.identity.entitlement.dto.PublisherDataHolder; -import org.wso2.carbon.identity.entitlement.dto.PublisherPropertyDTO; - -import javax.xml.stream.XMLStreamException; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -/** - * Carbon implementation of PolicyPublisherModule - */ -public class CarbonBasicPolicyPublisherModule extends AbstractPolicyPublisherModule { - - private static final String MODULE_NAME = "Carbon Basic Auth Policy Publisher Module"; - private static Log log = LogFactory.getLog(CarbonBasicPolicyPublisherModule.class); - private ConfigurationContext configCtx; - private String serverUrl; - - private String serverUserName; - - private String serverPassword; - - @Override - public void init(PublisherDataHolder propertyHolder) throws EntitlementException { - - PublisherPropertyDTO[] propertyDTOs = propertyHolder.getPropertyDTOs(); - for (PublisherPropertyDTO dto : propertyDTOs) { - if ("subscriberURL".equals(dto.getId())) { - serverUrl = dto.getValue(); - } else if ("subscriberUserName".equals(dto.getId())) { - serverUserName = dto.getValue(); - } else if ("subscriberPassword".equals(dto.getId())) { - serverPassword = dto.getValue(); - } - } - - try { - configCtx = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null); - } catch (AxisFault axisFault) { - log.error("Error while initializing module", axisFault); - throw new EntitlementException("Error while initializing module", axisFault); - } - } - - public String getModuleName() { - return MODULE_NAME; - } - - @Override - public Properties loadProperties() { - - Properties properties = new Properties(); - - Map dataMap1 = new HashMap(); - dataMap1.put(AbstractPolicyPublisherModule.REQUIRED, "true"); - dataMap1.put(AbstractPolicyPublisherModule.DISPLAY_NAME, "Subscriber URL"); - dataMap1.put(AbstractPolicyPublisherModule.ORDER, "1"); - - Map dataMap2 = new HashMap(); - dataMap2.put(AbstractPolicyPublisherModule.REQUIRED, "true"); - dataMap2.put(AbstractPolicyPublisherModule.DISPLAY_NAME, "Subscriber User Name"); - dataMap2.put(AbstractPolicyPublisherModule.ORDER, "2"); - - Map dataMap3 = new HashMap(); - dataMap3.put(AbstractPolicyPublisherModule.REQUIRED, "true"); - dataMap3.put(AbstractPolicyPublisherModule.DISPLAY_NAME, "Subscriber Password"); - dataMap3.put(AbstractPolicyPublisherModule.ORDER, "3"); - dataMap3.put(AbstractPolicyPublisherModule.SECRET, "true"); - - properties.put("subscriberURL", dataMap1); - properties.put("subscriberUserName", dataMap2); - properties.put("subscriberPassword", dataMap3); - - return properties; - } - - public void publishNew(PolicyDTO policyDTO) throws EntitlementException { - - String body = "" + - " " + - " " + Boolean.toString(policyDTO.isActive()) + "" + - " " + - " " + policyDTO.getPolicyId() + "" + - " " + policyDTO.getPolicyOrder() + "" + - " true" + - " " + - " "; - doSend(body); - } - - @Override - public void order(PolicyDTO policyDTO) throws EntitlementException { - - String body = "" + - "" + policyDTO.getPolicyId() + "" + - "" + policyDTO.getPolicyOrder() + "" + - ""; - doSend(body); - } - - @Override - public void disable(PolicyDTO policyDTO) throws EntitlementException { - - String body = "" + - "" + policyDTO.getPolicyId() + "" + - "false" + - ""; - doSend(body); - } - - @Override - public void enable(PolicyDTO policyDTO) throws EntitlementException { - - String body = "" + - "" + policyDTO.getPolicyId() + "" + - "true" + - ""; - doSend(body); - } - - @Override - public void update(PolicyDTO policyDTO) throws EntitlementException { - - String body = "" + - " " + - " " + - " " + policyDTO.getPolicyId() + "" + - " true" + - " " + - " "; - doSend(body); - } - - @Override - public void delete(PolicyDTO policyDTO) throws EntitlementException { - - String body = "" + - "" + policyDTO.getPolicyId() + "" + - ""; - doSend(body); - } - - - private void doSend(String body) throws EntitlementException { - - if (serverUrl != null) { - serverUrl = serverUrl.trim(); - if (!serverUrl.endsWith("/")) { - serverUrl += "/"; - } - } - - String serverEndPoint = serverUrl + "EntitlementPolicyAdminService"; - ServiceClient client = null; - try { - MultiThreadedHttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager(); - HttpClient httpClient = new HttpClient(httpConnectionManager); - client = new ServiceClient(configCtx, null); - Options option = client.getOptions(); - option.setManageSession(true); - HttpTransportProperties.Authenticator authenticator = - new HttpTransportProperties.Authenticator(); - authenticator.setUsername(serverUserName); - authenticator.setPassword(serverPassword); - authenticator.setPreemptiveAuthentication(true); - option.setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, authenticator); - option.setProperty(Constants.Configuration.TRANSPORT_URL, serverEndPoint); - option.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, Constants.VALUE_TRUE); - option.setProperty(HTTPConstants.CACHED_HTTP_CLIENT, httpClient); - client.sendRobust(AXIOMUtil.stringToOM(body)); - } catch (AxisFault axisFault) { - log.error("Policy publish fails due : " + axisFault.getMessage(), axisFault); - throw new EntitlementException("Policy publish fails due : " + axisFault.getMessage()); - } catch (XMLStreamException e) { - log.error("Policy publish fails due : " + e.getMessage(), e); - throw new EntitlementException("Policy publish fails due : " + e.getMessage()); - } finally { - if (client != null) { - try { - client.cleanupTransport(); - client.cleanup(); - } catch (AxisFault axisFault) { - log.error("Error while cleaning HTTP client", axisFault); - } - } - } - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/publisher/CarbonPDPPublisher.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/publisher/CarbonPDPPublisher.java deleted file mode 100644 index f17f6b73b8f4..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/publisher/CarbonPDPPublisher.java +++ /dev/null @@ -1,72 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.policy.publisher; - -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.common.EntitlementConstants; -import org.wso2.carbon.identity.entitlement.dto.PolicyDTO; -import org.wso2.carbon.identity.entitlement.pap.EntitlementAdminEngine; -import org.wso2.carbon.identity.entitlement.policy.store.PolicyStoreManager; - -import java.util.Properties; - -/** - * - */ -public class CarbonPDPPublisher implements PolicyPublisherModule { - - @Override - public void init(Properties properties) { - - } - - @Override - public Properties loadProperties() { - return new Properties(); - } - - @Override - public String getModuleName() { - return "PDP Publisher"; - } - - @Override - public void publish(PolicyDTO policyDTO, String action, boolean enabled, int order) throws EntitlementException { - - PolicyStoreManager manager = EntitlementAdminEngine.getInstance().getPolicyStoreManager(); - - if (EntitlementConstants.PolicyPublish.ACTION_CREATE.equals(action)) { - policyDTO.setPolicyOrder(order); - policyDTO.setActive(enabled); - manager.addPolicy(policyDTO); - } else if (EntitlementConstants.PolicyPublish.ACTION_DELETE.equals(action)) { - manager.removePolicy(policyDTO); - } else if (EntitlementConstants.PolicyPublish.ACTION_UPDATE.equals(action)) { - manager.updatePolicy(policyDTO); - } else if (EntitlementConstants.PolicyPublish.ACTION_ENABLE.equals(action)) { - policyDTO.setActive(true); - manager.enableDisablePolicy(policyDTO); - } else if (EntitlementConstants.PolicyPublish.ACTION_DISABLE.equals(action)) { - policyDTO.setActive(false); - manager.enableDisablePolicy(policyDTO); - } else if (EntitlementConstants.PolicyPublish.ACTION_ORDER.equals(action)) { - policyDTO.setPolicyOrder(order); - manager.orderPolicy(policyDTO); - } - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/publisher/PolicyPublishExecutor.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/publisher/PolicyPublishExecutor.java deleted file mode 100644 index d50e1c31b534..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/publisher/PolicyPublishExecutor.java +++ /dev/null @@ -1,316 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.policy.publisher; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.PAPStatusDataHandler; -import org.wso2.carbon.identity.entitlement.PDPConstants; -import org.wso2.carbon.identity.entitlement.common.EntitlementConstants; -import org.wso2.carbon.identity.entitlement.persistence.PolicyPersistenceManager; -import org.wso2.carbon.identity.entitlement.persistence.SubscriberPersistenceManager; -import org.wso2.carbon.identity.entitlement.dto.PolicyDTO; -import org.wso2.carbon.identity.entitlement.dto.PublisherDataHolder; -import org.wso2.carbon.identity.entitlement.dto.StatusHolder; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; -import org.wso2.carbon.identity.entitlement.pap.EntitlementAdminEngine; -import org.wso2.carbon.registry.api.Registry; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Set; - -/** - * Policy publish executor - */ -public class PolicyPublishExecutor { - - private static Log log = LogFactory.getLog(PolicyPublishExecutor.class); - private String[] policyIds; - private String[] subscriberIds; - private PolicyPublisher publisher; - private String version; - private String action; - private String verificationCode; - private boolean toPDP; - private String tenantDomain; - private int tenantId; - private String userName; - private int order; - private boolean enabled; - - public PolicyPublishExecutor(String[] policyIds, String version, String action, boolean enabled, int order, - String[] subscriberIds, PolicyPublisher publisher, - boolean toPDP, String verificationCode) { - - this.policyIds = policyIds; - if (toPDP) { - this.subscriberIds = new String[]{"PDPSubscriber"}; - } - this.subscriberIds = subscriberIds; - this.action = action; - this.version = version; - this.publisher = publisher; - this.toPDP = toPDP; - this.order = order; - this.enabled = enabled; - this.verificationCode = verificationCode; - } - - public void run() { - - PrivilegedCarbonContext.startTenantFlow(); - PrivilegedCarbonContext context = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - context.setTenantDomain(tenantDomain); - context.setTenantId(tenantId); - context.setUsername(userName); - try { - publish(); - } finally { - PrivilegedCarbonContext.endTenantFlow(); - } - - } - - public void publish() { - - - if ((policyIds == null || policyIds.length > 0) && verificationCode != null) { - loadVerificationCode(verificationCode); - } - - String newVerificationCode = null; - ArrayList notPublishedSubscribers = new ArrayList(); - - - PolicyPublisherModule policyPublisherModule = null; - Set publisherModules = publisher.getPublisherModules(); - - if (publisherModules == null) { - return; - } - - PublisherDataHolder holder = null; - Set papStatusDataHandler = publisher.getPapStatusDataHandlers(); - for (String subscriberId : subscriberIds) { - - // there is only one known subscriber, if policies are publishing to PDP - List subscriberHolders = new ArrayList(); - List policyHolders = new ArrayList(); - if (toPDP) { - policyPublisherModule = new CarbonPDPPublisher(); - holder = new PublisherDataHolder(policyPublisherModule.getModuleName()); - } else { - try { - SubscriberPersistenceManager subscriberManager = EntitlementAdminEngine.getInstance() - .getSubscriberPersistenceManager(); - holder = subscriberManager.getSubscriber(subscriberId, true); - } catch (EntitlementException e) { - log.error("Subscriber details can not be retrieved. So skip publishing policies " + - "for subscriber : " + subscriberId); - } - - if (holder != null) { - for (PolicyPublisherModule publisherModule : publisherModules) { - if (publisherModule.getModuleName().equals(holder.getModuleName())) { - policyPublisherModule = publisherModule; - if (policyPublisherModule instanceof AbstractPolicyPublisherModule) { - try { - ((AbstractPolicyPublisherModule) policyPublisherModule).init(holder); - } catch (Exception e) { - subscriberHolders.add(new StatusHolder(EntitlementConstants.StatusTypes.PUBLISH_POLICY, - subscriberId, version, "More than one Policy", action, false, e.getMessage())); - continue; - } - } - break; - } - } - } - } - - if (policyPublisherModule == null) { - subscriberHolders.add(new StatusHolder(EntitlementConstants.StatusTypes.PUBLISH_POLICY, - subscriberId, version, "More than one Policy", action, false, - "No policy publish module is defined for subscriber : " + subscriberId)); - continue; - } - - // try with post verification module. - try { - PublisherVerificationModule verificationModule = publisher.getVerificationModule(); - if (verificationModule != null && !verificationModule.doVerify(verificationCode)) { - newVerificationCode = verificationModule.getVerificationCode(holder); - notPublishedSubscribers.add(subscriberId); - break; - } - - } catch (EntitlementException e) { - // ignore - log.error("Error while calling the post verification publisher module", e); - } - - for (String policyId : policyIds) { - - PolicyDTO policyDTO = null; - - if (EntitlementConstants.PolicyPublish.ACTION_CREATE.equalsIgnoreCase(action) || - EntitlementConstants.PolicyPublish.ACTION_UPDATE.equalsIgnoreCase(action)) { - PolicyPersistenceManager policyStore = EntitlementAdminEngine.getInstance().getPolicyPersistenceManager(); - try { - policyDTO = policyStore.getPolicy(policyId, version); - } catch (EntitlementException e) { - // ignore - } - } else { - policyDTO = new PolicyDTO(); - policyDTO.setPolicyId(policyId); - policyDTO.setVersion(version); - policyDTO.setPolicyOrder(order); - } - - if (policyDTO == null) { - subscriberHolders.add(new StatusHolder(EntitlementConstants.StatusTypes.PUBLISH_POLICY, - subscriberId, version, policyId, action, false, - "Can not found policy under policy id : " + policyId)); - policyHolders.add(new StatusHolder(EntitlementConstants.StatusTypes.PUBLISH_POLICY, - policyId, version, subscriberId, action, false, - "Can not found policy under policy id : " + policyId)); - continue; - } - - try { - policyPublisherModule.publish(policyDTO, action, enabled, order); - subscriberHolders.add(new StatusHolder(EntitlementConstants.StatusTypes.PUBLISH_POLICY, - subscriberId, version, policyId, action)); - policyHolders.add(new StatusHolder(EntitlementConstants.StatusTypes.PUBLISH_POLICY, - policyId, version, subscriberId, action)); - } catch (Exception e) { - subscriberHolders.add(new StatusHolder(EntitlementConstants.StatusTypes.PUBLISH_POLICY, - subscriberId, version, policyId, action, false, e.getMessage())); - policyHolders.add(new StatusHolder(EntitlementConstants.StatusTypes.PUBLISH_POLICY, - policyId, version, subscriberId, action, false, e.getMessage())); - } - - for (PAPStatusDataHandler module : papStatusDataHandler) { - try { - module.handle(EntitlementConstants.Status.ABOUT_POLICY, policyId, policyHolders); - policyHolders = new ArrayList(); - } catch (EntitlementException e) { - // ignore - log.error("Error while calling post publishers", e); - } - } - } - - for (PAPStatusDataHandler module : papStatusDataHandler) { - try { - module.handle(EntitlementConstants.Status.ABOUT_SUBSCRIBER, subscriberId, subscriberHolders); - subscriberHolders = new ArrayList(); - } catch (EntitlementException e) { - // ignore - log.error("Error while calling post publishers", e); - } - } - } - - if (newVerificationCode != null) { - persistVerificationCode(newVerificationCode, - notPublishedSubscribers.toArray(new String[notPublishedSubscribers.size()])); - } - } - - /** - * Helper method - * - * @param verificationCode verificationCode as String - * @param subscriberIds Array of subscriberIds - */ - private void persistVerificationCode(String verificationCode, String[] subscriberIds) { - - Registry registry = EntitlementServiceComponent. - getGovernanceRegistry(CarbonContext.getThreadLocalCarbonContext().getTenantId()); - try { - org.wso2.carbon.registry.api.Resource resource = registry.newResource(); - resource.setProperty("subscriberIds", Arrays.asList(subscriberIds)); - resource.setProperty("policyIds", Arrays.asList(policyIds)); - resource.setProperty("action", action); - resource.setProperty("version", version); - resource.setProperty("order", Integer.toString(order)); - registry.put(PDPConstants.ENTITLEMENT_POLICY_PUBLISHER_VERIFICATION + verificationCode, - resource); - } catch (org.wso2.carbon.registry.api.RegistryException e) { - log.error("Error while persisting verification code", e); - } - - } - - /** - * Helper method - * - * @param verificationCode verificationCode as String - */ - private void loadVerificationCode(String verificationCode) { - - Registry registry = EntitlementServiceComponent. - getGovernanceRegistry(CarbonContext.getThreadLocalCarbonContext().getTenantId()); - try { - org.wso2.carbon.registry.api.Resource resource = registry. - get(PDPConstants.ENTITLEMENT_POLICY_PUBLISHER_VERIFICATION + verificationCode); - List list = resource.getPropertyValues("subscriberIds"); - if (list != null) { - subscriberIds = list.toArray(new String[list.size()]); - } - list = resource.getPropertyValues("policyIds"); - if (list != null) { - policyIds = list.toArray(new String[list.size()]); - } - String version = resource.getProperty("version"); - if (version != null) { - this.version = version; - } - String action = resource.getProperty("action"); - if (action != null) { - this.action = action; - } - String order = resource.getProperty("order"); - if (order != null) { - this.order = Integer.parseInt(order); - } - } catch (org.wso2.carbon.registry.api.RegistryException e) { - log.error("Error while loading verification code", e); - } - } - - public void setTenantId(int tenantId) { - this.tenantId = tenantId; - } - - public void setTenantDomain(String tenantDomain) { - this.tenantDomain = tenantDomain; - } - - public void setUserName(String userName) { - this.userName = userName; - } -} \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/publisher/PolicyPublisher.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/publisher/PolicyPublisher.java deleted file mode 100644 index 92536edd385a..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/publisher/PolicyPublisher.java +++ /dev/null @@ -1,150 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.policy.publisher; - -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.PAPStatusDataHandler; -import org.wso2.carbon.identity.entitlement.common.EntitlementConstants; -import org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerFactory; -import org.wso2.carbon.identity.entitlement.persistence.SubscriberPersistenceManager; -import org.wso2.carbon.identity.entitlement.dto.PublisherDataHolder; -import org.wso2.carbon.identity.entitlement.dto.PublisherPropertyDTO; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; - -import java.util.HashSet; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -/** - * This is policy publisher. There can be different modules that have been plugged with this. - * - */ -public class PolicyPublisher { - - public static final String SUBSCRIBER_ID = "subscriberId"; - public static final String SUBSCRIBER_DISPLAY_NAME = "Subscriber Id"; - - - /** - * set of publisher modules - */ - Set publisherModules = new HashSet(); - - /** - * set of post publisher modules - */ - Set papStatusDataHandlers = new HashSet(); - - /** - * Verification publisher modules - */ - PublisherVerificationModule verificationModule = null; - - - /** - * Creates PolicyPublisher instance - */ - public PolicyPublisher() { - - Map publisherModules = EntitlementServiceComponent. - getEntitlementConfig().getPolicyPublisherModules(); - if (publisherModules != null && !publisherModules.isEmpty()) { - this.publisherModules.addAll(publisherModules.keySet()); - } - - Map prePublisherModules = EntitlementServiceComponent. - getEntitlementConfig().getPublisherVerificationModule(); - if (prePublisherModules != null && !prePublisherModules.isEmpty()) { - this.verificationModule = prePublisherModules.keySet().iterator().next(); - } - - // Creates a default subscriber to publish policies to PDP - CarbonPDPPublisher publisher = new CarbonPDPPublisher(); - this.publisherModules.add(publisher); - - PublisherDataHolder holder = new PublisherDataHolder(publisher.getModuleName()); - PublisherPropertyDTO dto = new PublisherPropertyDTO(); - dto.setId(SUBSCRIBER_ID); - dto.setDisplayName(SUBSCRIBER_DISPLAY_NAME); - dto.setValue(EntitlementConstants.PDP_SUBSCRIBER_ID); - holder.setPropertyDTOs(new PublisherPropertyDTO[] {dto}); - try { - PublisherDataHolder pdpDataHolder = null; - SubscriberPersistenceManager subscriberManager = PersistenceManagerFactory.getSubscriberPersistenceManager(); - try { - pdpDataHolder = subscriberManager.getSubscriber(EntitlementConstants.PDP_SUBSCRIBER_ID, false); - } catch (Exception e) { - // ignore - } - if (pdpDataHolder == null) { - subscriberManager.addSubscriber(holder); - } - } catch (EntitlementException e) { - // ignore - } - } - - /** - * publish policy - * - * @param policyIds policy ids to publish, - * @param version - * @param action - * @param enabled - * @param order - * @param subscriberIds subscriber ids to publish, - * @param verificationCode verificationCode as String - * @throws EntitlementException throws if can not be created PolicyPublishExecutor instant - */ - public void publishPolicy(String[] policyIds, String version, String action, boolean enabled, int order, - String[] subscriberIds, String verificationCode) throws EntitlementException { - - boolean toPDP = false; - - if (subscriberIds == null) { - toPDP = true; - } - - PolicyPublishExecutor executor = new PolicyPublishExecutor(policyIds, version, action, enabled, order, - subscriberIds, this, toPDP, verificationCode); - executor.setTenantDomain(CarbonContext.getThreadLocalCarbonContext().getTenantDomain()); - executor.setTenantId(CarbonContext.getThreadLocalCarbonContext().getTenantId()); - executor.setUserName(CarbonContext.getThreadLocalCarbonContext().getUsername()); - - executor.run(); - } - - public Set getPublisherModules() { - return publisherModules; - } - - public Set getPapStatusDataHandlers() { - return papStatusDataHandlers; - } - - public void setPapStatusDataHandlers(Set papStatusDataHandlers) { - this.papStatusDataHandlers = papStatusDataHandlers; - } - - public PublisherVerificationModule getVerificationModule() { - return verificationModule; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/publisher/PolicyPublisherModule.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/publisher/PolicyPublisherModule.java deleted file mode 100644 index 090c459ab321..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/publisher/PolicyPublisherModule.java +++ /dev/null @@ -1,69 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.policy.publisher; - -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.dto.PolicyDTO; - -import java.util.Properties; - -/** - * policy publisher module that is used to publish policies to external PDPs. External PDP can be - * identity server or else can be any thing. Therefore this interface provide an extension to publish - * policies to different modules. - */ -public interface PolicyPublisherModule { - - /** - * initializes policy publisher retriever module - * - * @param properties Properties, that are needed to initialize the module or - * that are needed to populate the management console ui of publisher configuration. - * These properties can be defined in entitlement-properties file. - */ - public void init(Properties properties); - - /** - * Load the properties are needed to initialize the module or that are needed to populate - * to populate the management console ui of publisher configuration. - * These properties can be loaded from external source - * - * @return Properties - */ - public Properties loadProperties(); - - /** - * gets name of this module - * - * @return name as String - */ - public String getModuleName(); - - /** - * publishes policy to given subscriber - * - * @param policyDTO policy as PolicyDTO - * @param action publishing action - * @param enable enable - * @param order - * @throws EntitlementException - */ - public void publish(PolicyDTO policyDTO, String action, boolean enable, int order) throws EntitlementException; - -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/publisher/PostPublisherModule.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/publisher/PostPublisherModule.java deleted file mode 100644 index 00accb313842..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/publisher/PostPublisherModule.java +++ /dev/null @@ -1,50 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.policy.publisher; - -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.dto.PublisherDataHolder; -import org.wso2.carbon.identity.entitlement.dto.StatusHolder; - -import java.util.List; -import java.util.Properties; - - -/** - * - */ -public interface PostPublisherModule { - - /** - * initializes policy publisher retriever module - * - * @param properties Properties, that are needed to initialize the module - * @throws Exception throws when initialization is failed - */ - public void init(Properties properties) throws Exception; - - /** - * @param holder - * @param statusHolders - * @return if true, this would skip calling to other modules - * @throws EntitlementException - */ - public boolean postPublish(PublisherDataHolder holder, - List statusHolders) throws EntitlementException; - -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/publisher/PublisherVerificationModule.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/publisher/PublisherVerificationModule.java deleted file mode 100644 index f1c78f2a964c..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/publisher/PublisherVerificationModule.java +++ /dev/null @@ -1,57 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.policy.publisher; - -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.dto.PublisherDataHolder; - -import java.util.Properties; - -/** - * This is extension point where you can verify the policy publish - */ -public abstract class PublisherVerificationModule { - - /** - * initializes policy publisher retriever module - * - * @param properties Properties, that are needed to initialize the module - * @throws Exception throws when initialization is failed - */ - public abstract void init(Properties properties) throws Exception; - - - /** - * Generates the verification code based on publisher - * - * @param holder PublisherDataHolder - * @return returns verification code as String - * @throws EntitlementException if there are errors in generating verification code - */ - public abstract String getVerificationCode(PublisherDataHolder holder) throws EntitlementException; - - /** - * Verifies whether given verification code is valid or not - * - * @param code verification code as String - * @return whether True or False - */ - public abstract boolean doVerify(String code); - -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/search/PolicySearch.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/search/PolicySearch.java deleted file mode 100644 index 1759479047b1..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/search/PolicySearch.java +++ /dev/null @@ -1,547 +0,0 @@ -/* - * Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.entitlement.policy.search; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.balana.ctx.AbstractRequestCtx; -import org.wso2.balana.ctx.AbstractResult; -import org.wso2.balana.ctx.ResponseCtx; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.EntitlementUtil; -import org.wso2.carbon.identity.entitlement.PDPConstants; -import org.wso2.carbon.identity.entitlement.cache.PolicySearchCache; -import org.wso2.carbon.identity.entitlement.dto.AttributeDTO; -import org.wso2.carbon.identity.entitlement.dto.EntitledAttributesDTO; -import org.wso2.carbon.identity.entitlement.dto.EntitledResultSetDTO; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; -import org.wso2.carbon.identity.entitlement.pdp.EntitlementEngine; -import org.wso2.carbon.identity.entitlement.policy.finder.PolicyFinderModule; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -/** - * This contains the searching methods for policies based on policy attribute values and how subjects - * are entitled to resources - */ -public class PolicySearch { - - private static Log log = LogFactory.getLog(PolicySearch.class); - - - private List finderModules = null; - - private boolean cachingEnable; - - private PolicySearchCache policySearchCache = null; - - public PolicySearch(boolean cachingEnable, int cachingInterval) { - // get registered finder modules - Map finderModules = EntitlementServiceComponent. - getEntitlementConfig().getPolicyFinderModules(); - - if (finderModules != null) { - this.finderModules = new ArrayList(finderModules.keySet()); - } - - this.cachingEnable = cachingEnable; - - // Note that PolicySearchCache also uses EntitlementEngine.getInstance().getPdpDecisionCacheEnable() - // to set cache timeout. - this.policySearchCache = new PolicySearchCache(cachingInterval); - } - - /** - * This returns resource name as the list of the entitled attributes for given - * user or role and action, after evaluating the all the active policies in the PDP - * - * @param subjectName subject name - * @param resourceName resource name - * @param subjectId subject attribute Id - * @param action Action Name - * @param enableChildSearch whether search is done for the child resources under the given resource name - * @return entitled resource id set - * @throws EntitlementException throws - */ - public EntitledResultSetDTO getEntitledAttributes(String subjectName, String resourceName, - String subjectId, String action, boolean enableChildSearch) - throws EntitlementException { - String cacheKey = ""; - - if (cachingEnable) { - - cacheKey = (subjectId != null ? subjectId : "") + (subjectName != null ? subjectName : "") + - (resourceName != null ? resourceName : "") + - (action != null ? action : "") + enableChildSearch; - SearchResult searchResult = policySearchCache.getFromCache(cacheKey); - - if (searchResult != null) { - return searchResult.getResultSetDTO(); - } - } - - AttributeDTO subjectAttributeDTO; - boolean hierarchicalResource = false; - EntitledResultSetDTO resultSetDTO = new EntitledResultSetDTO(); - Set resultSet = new HashSet(); - - if (subjectName != null && subjectName.trim().length() > 0) { - subjectAttributeDTO = new AttributeDTO(); - subjectAttributeDTO.setCategory(PDPConstants.SUBJECT_CATEGORY_URI); - subjectAttributeDTO.setAttributeValue(subjectName); - subjectAttributeDTO.setAttributeDataType(PDPConstants.STRING_DATA_TYPE); - if (subjectId != null && subjectId.trim().length() > 0) { - subjectAttributeDTO.setAttributeId(subjectId); - } else { - subjectAttributeDTO.setAttributeId(PDPConstants.SUBJECT_ID_DEFAULT); - } - } else { - throw new EntitlementException("Error : subject value can not be null"); - } - - if (getResponse(Arrays.asList(subjectAttributeDTO))) { - EntitledAttributesDTO dto = new EntitledAttributesDTO(); - dto.setAllActions(true); - dto.setAllResources(true); - EntitledResultSetDTO setDTO = new EntitledResultSetDTO(); - setDTO.setEntitledAttributesDTOs(new EntitledAttributesDTO[]{dto}); - return setDTO; - } - - for (PolicyFinderModule module : finderModules) { - if (module.isDefaultCategoriesSupported() && - PolicyFinderModule.COMBINATIONS_BY_CATEGORY_AND_PARAMETER == - module.getSupportedSearchAttributesScheme()) { - Map> requestMap = module. - getSearchAttributes(null, new HashSet(Arrays.asList(subjectAttributeDTO))); - - for (Map.Entry> entry : requestMap.entrySet()) { - Set attributeDTOs = entry.getValue(); - if (attributeDTOs != null) { - Set actions = new HashSet(); - Set resources = new HashSet(); - Set requestAttributes = new HashSet(); - if (resourceName != null && resourceName.trim().length() > 0) { - AttributeDTO resourceAttribute = new AttributeDTO(); - resourceAttribute.setAttributeValue(resourceName); - resourceAttribute.setAttributeDataType(PDPConstants.STRING_DATA_TYPE); - resourceAttribute.setAttributeId(PDPConstants.RESOURCE_ID_DEFAULT); - resourceAttribute.setCategory(PDPConstants.RESOURCE_CATEGORY_URI); - resources.add(resourceAttribute); - hierarchicalResource = true; - } - - AttributeDTO resourceScopeAttribute = new AttributeDTO(); - resourceScopeAttribute.setAttributeValue(PDPConstants.RESOURCE_DESCENDANTS); - resourceScopeAttribute.setAttributeDataType(PDPConstants.STRING_DATA_TYPE); - resourceScopeAttribute.setAttributeId(PDPConstants.RESOURCE_SCOPE_ID); - resourceScopeAttribute.setCategory(PDPConstants.RESOURCE_CATEGORY_URI); - - for (AttributeDTO attributeDTO : attributeDTOs) { - if (PDPConstants.ENVIRONMENT_CATEGORY_URI.equals(attributeDTO.getCategory()) || - PDPConstants.ENVIRONMENT_ELEMENT.equals(attributeDTO.getCategory())) { - requestAttributes.add(attributeDTO); - attributeDTO.setAttributeId(PDPConstants.ENVIRONMENT_ID_DEFAULT); - requestAttributes.add(attributeDTO); - } else if (PDPConstants.ACTION_CATEGORY_URI.equals(attributeDTO.getCategory()) || - PDPConstants.ACTION_ELEMENT.equals(attributeDTO.getCategory())) { - if (action != null && action.trim().length() > 0) { - attributeDTO.setAttributeValue(action); - } - actions.add(attributeDTO); - attributeDTO.setAttributeId(PDPConstants.ACTION_ID_DEFAULT); - actions.add(attributeDTO); - } else if ((PDPConstants.RESOURCE_CATEGORY_URI.equals(attributeDTO.getCategory()) || - PDPConstants.RESOURCE_ELEMENT.equals(attributeDTO - .getCategory())) && - !hierarchicalResource) { - attributeDTO.setAttributeId(PDPConstants.RESOURCE_ID_DEFAULT); - resources.add(attributeDTO); - } - } - - if (resultSetDTO.getMessage() == null) { - List entitledActions = new ArrayList(); - for (AttributeDTO actionDTO : actions) { - List currentRequestAttributes = - new ArrayList(); - currentRequestAttributes.add(subjectAttributeDTO); - currentRequestAttributes.add(actionDTO); - if (getResponse(currentRequestAttributes)) { - EntitledAttributesDTO dto = new EntitledAttributesDTO(); - dto.setAllResources(true); - dto.setAction(actionDTO.getAttributeValue()); - resultSet.add(dto); - entitledActions.add(actionDTO.getAttributeValue()); - } - } - - for (AttributeDTO resource : resources) { - if (PDPConstants.RESOURCE_CATEGORY_URI.equals(resource.getCategory()) - || PDPConstants.RESOURCE_ELEMENT.equals(resource.getCategory())) { - - boolean allActionsAllowed = false; - - int noOfRequests = 1; - if (enableChildSearch) { - noOfRequests = 0; - } - - while (noOfRequests < 2) { - List currentRequestAttributes = - new ArrayList(); - for (AttributeDTO dto : requestAttributes) { - currentRequestAttributes.add(dto); - } - if (noOfRequests < 1) { - currentRequestAttributes.add(resourceScopeAttribute); - } - currentRequestAttributes.add(subjectAttributeDTO); - currentRequestAttributes.add(resource); - - if (getResponse(currentRequestAttributes)) { - EntitledAttributesDTO dto = new EntitledAttributesDTO(); - dto.setResourceName(resource.getAttributeValue()); - dto.setAllActions(true); - resultSet.add(dto); - allActionsAllowed = true; - } - noOfRequests++; - } - - if (allActionsAllowed) { - continue; - } - - for (AttributeDTO actionAttributeDTO : actions) { - - if (entitledActions.contains(actionAttributeDTO.getAttributeValue())) { - continue; - } - - noOfRequests = 1; - if (enableChildSearch) { - noOfRequests = 0; - } - while (noOfRequests < 2) { - List currentRequestAttributes = - new ArrayList(); - for (AttributeDTO dto : requestAttributes) { - currentRequestAttributes.add(dto); - } - if (noOfRequests < 1) { - currentRequestAttributes.add(resourceScopeAttribute); - } - currentRequestAttributes.add(subjectAttributeDTO); - currentRequestAttributes.add(resource); - currentRequestAttributes.add(actionAttributeDTO); - - if (getResponse(currentRequestAttributes)) { - EntitledAttributesDTO dto = new EntitledAttributesDTO(); - dto.setResourceName(resource.getAttributeValue()); - dto.setAction(actionAttributeDTO.getAttributeValue()); - resultSet.add(dto); - } - noOfRequests++; - } - } - } - } - } - } - } - } - } - - resultSetDTO.setEntitledAttributesDTOs(resultSet. - toArray(new EntitledAttributesDTO[resultSet.size()])); - - if (cachingEnable) { - SearchResult result = new SearchResult(); - result.setResultSetDTO(resultSetDTO); - policySearchCache.addToCache(cacheKey, result); - if (log.isDebugEnabled()) { - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - log.debug("PDP Decision Cache Updated for tenantId " + tenantId); - } - } - return resultSetDTO; - } - - /** - * gets all entitled attributes for given set of attributes - * this an universal method to do policy search and find entitlement attributes - * - * @param identifier identifier to separate out the attributes that is used for search - * this is not required and can be null - * @param givenAttributes user provided attributes - * @return all the attributes that is entitled - */ - public EntitledResultSetDTO getEntitledAttributes(String identifier, AttributeDTO[] givenAttributes) { - - String cacheKey = ""; - - if (cachingEnable) { - - int hashCode = 0; - for (AttributeDTO dto : givenAttributes) { - hashCode = hashCode + (31 * dto.hashCode()); - } - - cacheKey = identifier + hashCode; - - SearchResult searchResult = policySearchCache.getFromCache(cacheKey); - - if (searchResult != null) { - if (log.isDebugEnabled()) { - log.debug("PDP Search Cache Hit"); - } - return searchResult.getResultSetDTO(); - } else { - if (log.isDebugEnabled()) { - log.debug("PDP Search Cache Miss"); - } - } - } - - EntitledResultSetDTO result = new EntitledResultSetDTO(); - Set resultAttributes = new HashSet(); - Set attributeDTOs = new HashSet(Arrays.asList(givenAttributes)); - - for (PolicyFinderModule finderModule : finderModules) { - Map> attributesMap = finderModule. - getSearchAttributes(identifier, attributeDTOs); - int supportedSearchScheme = finderModule.getSupportedSearchAttributesScheme(); - Set> requestSet = getPossibleRequests(attributesMap, supportedSearchScheme); - if (requestSet == null) { - log.error("Invalid Search scheme in policy finder : " + finderModule.getModuleName()); - } else { - for (List attributeDTOList : requestSet) { - if (getResponse(attributeDTOList)) { - EntitledAttributesDTO dto = new EntitledAttributesDTO(); - dto.setAttributeDTOs(attributeDTOList. - toArray(new AttributeDTO[attributeDTOList.size()])); - resultAttributes.add(dto); - } - } - } - } - result.setAdvanceResult(true); - result.setEntitledAttributesDTOs(resultAttributes. - toArray(new EntitledAttributesDTO[resultAttributes.size()])); - - - if (cachingEnable) { - SearchResult searchResult = new SearchResult(); - searchResult.setResultSetDTO(result); - policySearchCache.addToCache(cacheKey, searchResult); - if (log.isDebugEnabled()) { - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - log.debug("PDP Decision Cache Updated for tenantId " + tenantId); - } - } - - return result; - } - - public void clearCache() { - - policySearchCache.clearCache(); - } - - public PolicySearchCache getPolicySearchCache() { - - return this.policySearchCache; - } - - /** - * Helper method to get possible XACML requests with attributes - * - * @param attributesMap - * @param supportedSearchScheme - * @return - */ - private Set> getPossibleRequests(Map> attributesMap, - int supportedSearchScheme) { - - if (PolicyFinderModule.ALL_COMBINATIONS == supportedSearchScheme) { - - if (attributesMap.entrySet() != null) { - return getAllCombinations(attributesMap.entrySet().iterator().next().getValue()); - } - - } else if (PolicyFinderModule.COMBINATIONS_BY_CATEGORY == supportedSearchScheme) { - - return getAllCombinationsWithCategory(attributesMap); - - } else if (PolicyFinderModule.COMBINATIONS_BY_PARAMETER == supportedSearchScheme) { - - Set> requestSet = new HashSet>(); - for (Map.Entry> entry : attributesMap.entrySet()) { - requestSet.addAll(getAllCombinations(entry.getValue())); - } - return requestSet; - - } else if (PolicyFinderModule.COMBINATIONS_BY_CATEGORY_AND_PARAMETER == supportedSearchScheme) { - - Set> requestSet = new HashSet>(); - for (Map.Entry> entry : attributesMap.entrySet()) { - Map> map = new HashMap>(); - for (AttributeDTO dto : entry.getValue()) { - if (!map.containsKey(dto.getCategory())) { - Set attributeDTOSet = new HashSet(); - attributeDTOSet.add(dto); - map.put(dto.getCategory(), attributeDTOSet); - } - map.get(dto.getCategory()).add(dto); - } - requestSet.addAll(getAllCombinationsWithCategory(map)); - } - return requestSet; - } else if (PolicyFinderModule.NO_COMBINATIONS == supportedSearchScheme) { - Set> requestSet = new HashSet>(); - for (Map.Entry> entry : attributesMap.entrySet()) { - requestSet.add(new ArrayList(entry.getValue())); - } - return requestSet; - } - - return null; - } - - /** - * Helper method to get all possible combination for given set of attributes - * - * @param allAttributes - * @return - */ - private Set> getAllCombinations(Set allAttributes) { - - Set> requestSet = new HashSet>(); - - if (allAttributes.isEmpty()) { - requestSet.add(new ArrayList()); - return requestSet; - } - - List list = new ArrayList(allAttributes); - - AttributeDTO head = list.get(0); - Set rest = new HashSet(list.subList(1, list.size())); - - for (List set : getAllCombinations(rest)) { - List newSet = new ArrayList(); - newSet.add(head); - newSet.addAll(set); - requestSet.add(newSet); - requestSet.add(set); - } - - return requestSet; - } - - /** - * Helper method to get all possible combination for given set of attributes based on category - * - * @param attributesMap - * @return - */ - private Set> getAllCombinationsWithCategory(Map> attributesMap) { - - Set> requestSet = new HashSet>(); - List categories = new ArrayList(attributesMap.keySet()); - - if (!categories.isEmpty()) { - String category = categories.get(0); - Set attributeDTOs = attributesMap.get(category); - - List dtoList; - for (AttributeDTO dto : attributeDTOs) { - dtoList = new ArrayList(); - dtoList.add(dto); - if (categories.get(1) != null) { - processCombinations(1, categories, attributesMap, dtoList, requestSet); - } - } - } - - return requestSet; - } - - /** - * Helper method to get all possible combination for given set of attributes based on category - * - * @param i - * @param categories - * @param attributesMap - * @param dtoList - * @param requestSet - */ - private void processCombinations(int i, List categories, Map> attributesMap, List dtoList, - Set> requestSet) { - if (categories.size() > i) { - String category = categories.get(i); - i++; - if (category != null) { - List currentList = new ArrayList(dtoList); - Set attributeDTOs = attributesMap.get(category); - for (AttributeDTO dto : attributeDTOs) { - dtoList.add(dto); - processCombinations(i, categories, attributesMap, dtoList, requestSet); - requestSet.add(dtoList); - dtoList = new ArrayList(currentList); - } - } - } - } - - /** - * Helper method to get XACML decision - * - * @param requestAttributes XACML request attributes - * @return whether permit or deny - */ - private boolean getResponse(List requestAttributes) { - - ResponseCtx responseCtx; - AbstractRequestCtx requestCtx = EntitlementUtil.createRequestContext(requestAttributes); - - responseCtx = EntitlementEngine.getInstance().evaluateByContext(requestCtx); - - if (responseCtx != null) { - Set results = responseCtx.getResults(); - for (AbstractResult result : results) { - if (result.getDecision() == AbstractResult.DECISION_PERMIT) { - return true; - } - } - } - - return false; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/search/PolicySearchCacheInvalidationClusteringMessage.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/search/PolicySearchCacheInvalidationClusteringMessage.java deleted file mode 100644 index ad7dcc002263..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/search/PolicySearchCacheInvalidationClusteringMessage.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.entitlement.policy.search; - -import org.apache.axis2.clustering.ClusteringCommand; -import org.apache.axis2.clustering.ClusteringFault; -import org.apache.axis2.clustering.ClusteringMessage; -import org.apache.axis2.context.ConfigurationContext; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.identity.core.util.IdentityTenantUtil; -import org.wso2.carbon.identity.entitlement.pdp.EntitlementEngine; - -/** - * ClusterMessage to invalidate {@link org.wso2.carbon.identity.entitlement.cache.PolicySearchCache} in other nodes. - */ -public class PolicySearchCacheInvalidationClusteringMessage extends ClusteringMessage { - - private static Log log = LogFactory.getLog(PolicySearchCacheInvalidationClusteringMessage.class); - private static final long serialVersionUID = -5025603871368248102L; - - private int tenantId; - - public PolicySearchCacheInvalidationClusteringMessage(int tenantId) { - - this.tenantId = tenantId; - } - - @Override - public ClusteringCommand getResponse() { - - return null; - } - - @Override - public void execute(ConfigurationContext configurationContext) throws ClusteringFault { - - if (log.isDebugEnabled()) { - log.debug("Received PolicySearchCacheInvalidationClusteringMessage."); - } - // We need to clear our local policy search cache of the corresponding tenant based on the received cluster - // message from other node. - int tenantIdInThreadLocalContext = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - try{ - // Clear local cache for the tenant domain included with the cluster message. - PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true); - - EntitlementEngine.getInstance().getPolicySearch().getPolicySearchCache().clearCache(); - if (log.isDebugEnabled()) { - log.debug("Local policy search cache is cleared for the tenant: " - + IdentityTenantUtil.getTenantDomain(tenantId) + "."); - } - } finally { - // Switch back to the original tenant domain used in this thread local context. - PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantIdInThreadLocalContext, true); - } - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/search/SearchResult.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/search/SearchResult.java deleted file mode 100644 index a7e1ccf7d488..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/search/SearchResult.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.entitlement.policy.search; - - -import org.wso2.carbon.identity.entitlement.dto.EntitledResultSetDTO; - -import java.io.Serializable; - -/** - * Encapsulate result - */ -public class SearchResult implements Serializable { - - private static final long serialVersionUID = -6701359087661169326L; - - /** - * Result - */ - private EntitledResultSetDTO resultSetDTO; - - - public EntitledResultSetDTO getResultSetDTO() { - return resultSetDTO; - } - - public void setResultSetDTO(EntitledResultSetDTO resultSetDTO) { - this.resultSetDTO = resultSetDTO; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/store/DefaultPolicyDataStore.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/store/DefaultPolicyDataStore.java deleted file mode 100644 index 7885237d886f..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/store/DefaultPolicyDataStore.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.entitlement.policy.store; - -import org.apache.commons.lang.NotImplementedException; -import org.wso2.balana.combine.PolicyCombiningAlgorithm; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.persistence.ConfigPersistenceManager; -import org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerFactory; -import org.wso2.carbon.identity.entitlement.persistence.PolicyPersistenceManager; -import org.wso2.carbon.identity.entitlement.dto.PolicyDTO; -import org.wso2.carbon.identity.entitlement.dto.PolicyStoreDTO; - -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -/** - * This is the default implementation of PolicyDataStore - */ -public class DefaultPolicyDataStore implements PolicyDataStore { - - private final PolicyPersistenceManager policyPersistenceManager = - PersistenceManagerFactory.getPolicyPersistenceManager(); - - @Override - public void init(Properties properties) throws EntitlementException { - - policyPersistenceManager.init(properties); - } - - /** - * This method is not implemented since the data is already being - * retrieved with {@link ConfigPersistenceManager#getGlobalPolicyAlgorithm()} - */ - @Override - public PolicyCombiningAlgorithm getGlobalPolicyAlgorithm() { - - throw new NotImplementedException(); - } - - /** - * This method is not implemented since the data is already being - * set with {@link ConfigPersistenceManager#addOrUpdateGlobalPolicyAlgorithm(String)} - */ - @Override - public void setGlobalPolicyAlgorithm(String policyCombiningAlgorithm) throws EntitlementException { - - throw new NotImplementedException(); - } - - /** - * This method is not implemented since the data is already being - * retrieved with {@link ConfigPersistenceManager#getGlobalPolicyAlgorithmName()} - */ - @Override - public String getGlobalPolicyAlgorithmName() { - - throw new NotImplementedException(); - } - - /** - * This method is not implemented since the data is already being retrieved with - * {@link org.wso2.carbon.identity.entitlement.EntitlementUtil#getAllGlobalPolicyAlgorithmNames()} - */ - @Override - public String[] getAllGlobalPolicyAlgorithmNames() { - - throw new NotImplementedException(); - } - - /** - * Gets policy data for given policy id. - * - * @param policyId policy id as String. - * @return policy data such as order and so on PolicyStoreDTO. - */ - @Override - public PolicyStoreDTO getPolicyData(String policyId) { - - return policyPersistenceManager.getPublishedPolicy(policyId); - } - - /** - * Gets all policy data. - * - * @return Array of PolicyStoreDTO. - */ - @Override - public PolicyStoreDTO[] getPolicyData() { - - String[] publishedPolicyIds = policyPersistenceManager.getOrderedPolicyIdentifiers(); - List policyStoreDTOs = new ArrayList<>(); - if (publishedPolicyIds != null) { - for (String policyId : publishedPolicyIds) { - policyStoreDTOs.add(getPolicyData(policyId)); - } - } - return policyStoreDTOs.toArray(new PolicyStoreDTO[0]); - } - - /** - * This method is not implemented since the data is already being - * set with {@link PolicyStoreManageModule#updatePolicy(PolicyStoreDTO)} - * - * @param policyId policy id - * @param policyDataDTO policy data - * @throws EntitlementException if an error occurs - */ - @Override - public void setPolicyData(String policyId, PolicyStoreDTO policyDataDTO) throws EntitlementException { - - // No default implementation provided. - } - - /** - * This method is not implemented since the data is already being - * removed with {@link PolicyStoreManageModule#deletePolicy(String)} - * - * @param policyId policy id - * @throws EntitlementException if an error occurs - */ - @Override - public void removePolicyData(String policyId) throws EntitlementException { - - // No default implementation provided. - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/store/PolicyDataStore.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/store/PolicyDataStore.java deleted file mode 100644 index 3b1141c54f70..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/store/PolicyDataStore.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.entitlement.policy.store; - -import org.wso2.balana.combine.PolicyCombiningAlgorithm; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.dto.PolicyStoreDTO; - -import java.util.Properties; - -/** - * This is the entitlement policy data store that is used to persist meta data of the policies - * Such as global policy combining algorithm. - */ -public interface PolicyDataStore { - - /** - * initializes the PolicyDataStore. - * - * @param properties properties, that need to initialize the module. - * @throws EntitlementException throws when initialization is failed. - */ - void init(Properties properties) throws EntitlementException; - - /** - * Gets the policy combining algorithm of the PDP. - * - * @return policy combining algorithm as PolicyCombiningAlgorithm. - */ - PolicyCombiningAlgorithm getGlobalPolicyAlgorithm(); - - /** - * Persist the policy combining algorithm in to data store. - * - * @param policyCombiningAlgorithm policy combining algorithm name to persist. - * @throws EntitlementException throws if fails. - */ - void setGlobalPolicyAlgorithm(String policyCombiningAlgorithm) throws EntitlementException; - - /** - * Gets the policy combining algorithm name of the PDP. - * - * @return policy combining algorithm name as String. - */ - String getGlobalPolicyAlgorithmName(); - - /** - * Gets all supported policy combining algorithm name of the PDP. - * - * @return policy combining algorithm names as Array of String. - */ - String[] getAllGlobalPolicyAlgorithmNames(); - - /** - * Gets policy data for given policy id. - * - * @param policyId policy id as String. - * @return policy data such as order and so on PolicyStoreDTO. - */ - PolicyStoreDTO getPolicyData(String policyId); - - /** - * Gets all policy data. - * - * @return Array of PolicyStoreDTO. - */ - PolicyStoreDTO[] getPolicyData(); - - /** - * Set policy data for give policy id. - * - * @param policyId policy id as String. - * @param policyDataDTO policy data such as order and so on PolicyStoreDTO. - * @throws EntitlementException if it is failed. - */ - void setPolicyData(String policyId, PolicyStoreDTO policyDataDTO) throws EntitlementException; - - /** - * Remove policy data for give policy id. - * - * @param policyId policy id as String. - * @throws EntitlementException if it is failed. - */ - void removePolicyData(String policyId) throws EntitlementException; -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/store/PolicyStoreManageModule.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/store/PolicyStoreManageModule.java deleted file mode 100644 index e5ca04ffb75d..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/store/PolicyStoreManageModule.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) WSO2 LLC (http://www.wso2.com) All Rights Reserved. - * - * WSO2 LLC 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.wso2.carbon.identity.entitlement.policy.store; - -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.dto.PolicyStoreDTO; -import org.wso2.carbon.identity.entitlement.policy.finder.PolicyFinderModule; - -import java.util.Properties; - -/** - * Carbon policy manage module is an extension point where XACML policies can be stored and - * loaded in to the PDP from different sources. This is specially written for storing policies. - * There can be only one policy store manage module in PDP - */ -public interface PolicyStoreManageModule extends PolicyFinderModule { - - /** - * Init policy store module - * - * @param properties properties that are need to initialize the module. - */ - public void init(Properties properties); - - /** - * Add policy in to the store. - * - * @param policy policy as PolicyStoreDTO. - */ - public void addPolicy(PolicyStoreDTO policy) throws EntitlementException; - - /** - * Update policy in to the store. - * - * @param policy policy as PolicyStoreDTO. - */ - public void updatePolicy(PolicyStoreDTO policy) throws EntitlementException; - - /** - * Delete policy from the store. - * - * @param policyIdentifier policy identifier as String. - */ - public boolean deletePolicy(String policyIdentifier) throws EntitlementException; - - /** - * Check whether policy is published or not. - * - * @param policyId policy id as String. - * @return whether true or false. - */ - public boolean isPolicyExist(String policyId); -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/store/PolicyStoreManager.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/store/PolicyStoreManager.java deleted file mode 100644 index 06a48d996a6c..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/policy/store/PolicyStoreManager.java +++ /dev/null @@ -1,200 +0,0 @@ -/* -* Copyright (c) WSO2 LLC (http://www.wso2.com) All Rights Reserved. -* -* WSO2 LLC 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.wso2.carbon.identity.entitlement.policy.store; - -import org.apache.commons.collections.MapUtils; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.common.EntitlementConstants; -import org.wso2.carbon.identity.entitlement.persistence.PersistenceManagerFactory; -import org.wso2.carbon.identity.entitlement.dto.PolicyDTO; -import org.wso2.carbon.identity.entitlement.dto.PolicyStoreDTO; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; -import org.wso2.carbon.identity.entitlement.policy.finder.AbstractPolicyFinderModule; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -/** - * This manages the storing and reading of policies and policy meta data that is related - * with PDP component. This instance is not tenant aware. But you can make this tenant aware by - * returning data that is relevant to the given tenant. Tenant domain or id can be available via - * CarbonContext which can be call by extension module. - */ -public class PolicyStoreManager { - - private final PolicyStoreManageModule policyStore; - private final PolicyDataStore policyDataStore; - - public PolicyStoreManager(PolicyDataStore policyDataStore) { - - Map policyCollections = EntitlementServiceComponent. - getEntitlementConfig().getPolicyStore(); - if (MapUtils.isNotEmpty(policyCollections)) { - policyStore = policyCollections.entrySet().iterator().next().getKey(); - } else { - policyStore = PersistenceManagerFactory.getPolicyPersistenceManager(); - } - this.policyDataStore = policyDataStore; - } - - public void addPolicy(PolicyDTO policyDTO) throws EntitlementException { - - PolicyStoreDTO dto = new PolicyStoreDTO(); - dto.setPolicyId(policyDTO.getPolicyId()); - dto.setPolicy(policyDTO.getPolicy()); - dto.setActive(policyDTO.isActive()); - dto.setPolicyOrder(policyDTO.getPolicyOrder()); - dto.setAttributeDTOs(policyDTO.getAttributeDTOs()); - dto.setVersion(policyDTO.getVersion()); - - if (policyStore.isPolicyExist(policyDTO.getPolicyId())) { - dto.setSetActive(false); - dto.setSetOrder(false); - } else { - dto.setSetOrder(true); - dto.setSetActive(true); - } - policyStore.addPolicy(dto); - policyDataStore.setPolicyData(policyDTO.getPolicyId(), dto); - AbstractPolicyFinderModule - .invalidateCache(dto.getPolicyId(), EntitlementConstants.PolicyPublish.ACTION_UPDATE); - } - - public void updatePolicy(PolicyDTO policyDTO) throws EntitlementException { - - if (!policyStore.isPolicyExist(policyDTO.getPolicyId())) { - throw new EntitlementException("Policy does not exist in the Policy Store : PolicyId " + - policyDTO.getPolicyId()); - } - - PolicyStoreDTO dto = new PolicyStoreDTO(); - dto.setPolicyId(policyDTO.getPolicyId()); - dto.setPolicy(policyDTO.getPolicy()); - dto.setActive(policyDTO.isActive()); - dto.setPolicyOrder(policyDTO.getPolicyOrder()); - dto.setAttributeDTOs(policyDTO.getAttributeDTOs()); - dto.setVersion(policyDTO.getVersion()); - dto.setSetActive(false); - dto.setSetOrder(false); - - policyStore.updatePolicy(dto); - AbstractPolicyFinderModule - .invalidateCache(dto.getPolicyId(), EntitlementConstants.PolicyPublish.ACTION_UPDATE); - } - - public void enableDisablePolicy(PolicyDTO policyDTO) throws EntitlementException { - - if (!policyStore.isPolicyExist(policyDTO.getPolicyId())) { - throw new EntitlementException("Policy does not exist in the Policy Store : PolicyId " + - policyDTO.getPolicyId()); - } - - PolicyStoreDTO dto = new PolicyStoreDTO(); - dto.setPolicyId(policyDTO.getPolicyId()); - dto.setPolicy(policyDTO.getPolicy()); - dto.setActive(policyDTO.isActive()); - dto.setVersion(policyDTO.getVersion()); - dto.setSetActive(true); - - policyStore.updatePolicy(dto); - policyDataStore.setPolicyData(policyDTO.getPolicyId(), dto); - if (policyDTO.isActive()) { - AbstractPolicyFinderModule - .invalidateCache(dto.getPolicyId(), EntitlementConstants.PolicyPublish.ACTION_ENABLE); - } else { - AbstractPolicyFinderModule - .invalidateCache(dto.getPolicyId(), EntitlementConstants.PolicyPublish.ACTION_DISABLE); - } - } - - public void orderPolicy(PolicyDTO policyDTO) throws EntitlementException { - - if (!policyStore.isPolicyExist(policyDTO.getPolicyId())) { - throw new EntitlementException("Policy does not exist in the Policy Store : PolicyId " + - policyDTO.getPolicyId()); - } - - PolicyStoreDTO dto = new PolicyStoreDTO(); - dto.setPolicyId(policyDTO.getPolicyId()); - dto.setPolicy(policyDTO.getPolicy()); - dto.setPolicyOrder(policyDTO.getPolicyOrder()); - dto.setVersion(policyDTO.getVersion()); - dto.setSetOrder(true); - - policyStore.updatePolicy(dto); - policyDataStore.setPolicyData(policyDTO.getPolicyId(), dto); - AbstractPolicyFinderModule - .invalidateCache(dto.getPolicyId(), EntitlementConstants.PolicyPublish.ACTION_ORDER); - } - - public void removePolicy(PolicyDTO policyDTO) throws EntitlementException { - - if (!policyStore.isPolicyExist(policyDTO.getPolicyId())) { - throw new EntitlementException("Policy does not exist in the Policy Store : PolicyId " + - policyDTO.getPolicyId()); - } - policyStore.deletePolicy(policyDTO.getPolicyId()); - policyDataStore.removePolicyData(policyDTO.getPolicyId()); - AbstractPolicyFinderModule - .invalidateCache(policyDTO.getPolicyId(), EntitlementConstants.PolicyPublish.ACTION_DELETE); - } - - public PolicyDTO getPolicy(String policyId) { - - PolicyDTO policyDTO = new PolicyDTO(); - policyDTO.setPolicyId(policyId); - String policy = policyStore.getPolicy(policyId); - PolicyStoreDTO storeDTO = policyDataStore.getPolicyData(policyId); - if (policy != null) { - policyDTO.setPolicy(policy); - policyDTO.setActive(storeDTO.isActive()); - policyDTO.setPolicyOrder(storeDTO.getPolicyOrder()); - } - return policyDTO; - } - - public String[] getPolicyIds() { - - return policyStore.getOrderedPolicyIdentifiers(); - } - - public PolicyDTO[] getLightPolicies() { - - List policyDTOs = new ArrayList<>(); - String[] policies = policyStore.getOrderedPolicyIdentifiers(); - if (policies != null) { - for (String policy : policies) { - PolicyDTO policyDTO = new PolicyDTO(); - policyDTO.setPolicyId(policy); - PolicyStoreDTO dto = policyDataStore.getPolicyData(policy); - policyDTO.setActive(dto.isActive()); - policyDTO.setPolicyOrder(dto.getPolicyOrder()); - policyDTOs.add(policyDTO); - } - } - return policyDTOs.toArray(new PolicyDTO[0]); - } - - public PolicyStoreDTO[] getAllPolicyData() { - - return policyDataStore.getPolicyData(); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/thrift/EntitlementException.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/thrift/EntitlementException.java deleted file mode 100644 index 7b487b03b08b..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/thrift/EntitlementException.java +++ /dev/null @@ -1,387 +0,0 @@ -/** - * Copyright (c) 2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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. - * - * Autogenerated by Thrift Compiler (0.12.0) - * - * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING - * @generated - */ - -package org.wso2.carbon.identity.entitlement.thrift; - -@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"}) -@javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.12.0)", date = "2019-03-21") -public class EntitlementException extends org.apache.thrift.TException implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("EntitlementException"); - - private static final org.apache.thrift.protocol.TField MESSAGE_FIELD_DESC = new org.apache.thrift.protocol.TField("message", org.apache.thrift.protocol.TType.STRING, (short)1); - - private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new EntitlementExceptionStandardSchemeFactory(); - private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new EntitlementExceptionTupleSchemeFactory(); - - public @org.apache.thrift.annotation.Nullable String message; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - MESSAGE((short)1, "message"); - - private static final java.util.Map byName = new java.util.HashMap(); - - static { - for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - @org.apache.thrift.annotation.Nullable - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // MESSAGE - return MESSAGE; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - @org.apache.thrift.annotation.Nullable - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.MESSAGE, new org.apache.thrift.meta_data.FieldMetaData("message", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); - metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(EntitlementException.class, metaDataMap); - } - - public EntitlementException() { - } - - public EntitlementException( - String message) - { - this(); - this.message = message; - } - - /** - * Performs a deep copy on other. - */ - public EntitlementException(EntitlementException other) { - if (other.isSetMessage()) { - this.message = other.message; - } - } - - public EntitlementException deepCopy() { - return new EntitlementException(this); - } - - @Override - public void clear() { - this.message = null; - } - - @org.apache.thrift.annotation.Nullable - public String getMessage() { - return this.message; - } - - public EntitlementException setMessage(@org.apache.thrift.annotation.Nullable String message) { - this.message = message; - return this; - } - - public void unsetMessage() { - this.message = null; - } - - /** Returns true if field message is set (has been assigned a value) and false otherwise */ - public boolean isSetMessage() { - return this.message != null; - } - - public void setMessageIsSet(boolean value) { - if (!value) { - this.message = null; - } - } - - public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable Object value) { - switch (field) { - case MESSAGE: - if (value == null) { - unsetMessage(); - } else { - setMessage((String)value); - } - break; - - } - } - - @org.apache.thrift.annotation.Nullable - public Object getFieldValue(_Fields field) { - switch (field) { - case MESSAGE: - return getMessage(); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case MESSAGE: - return isSetMessage(); - } - throw new IllegalStateException(); - } - - @Override - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof EntitlementException) - return this.equals((EntitlementException)that); - return false; - } - - public boolean equals(EntitlementException that) { - if (that == null) - return false; - if (this == that) - return true; - - boolean this_present_message = true && this.isSetMessage(); - boolean that_present_message = true && that.isSetMessage(); - if (this_present_message || that_present_message) { - if (!(this_present_message && that_present_message)) - return false; - if (!this.message.equals(that.message)) - return false; - } - - return true; - } - - @Override - public int hashCode() { - int hashCode = 1; - - hashCode = hashCode * 8191 + ((isSetMessage()) ? 131071 : 524287); - if (isSetMessage()) - hashCode = hashCode * 8191 + message.hashCode(); - - return hashCode; - } - - @Override - public int compareTo(EntitlementException other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - - lastComparison = Boolean.valueOf(isSetMessage()).compareTo(other.isSetMessage()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetMessage()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.message, other.message); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - @org.apache.thrift.annotation.Nullable - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - scheme(iprot).read(iprot, this); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - scheme(oprot).write(oprot, this); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("EntitlementException("); - boolean first = true; - - sb.append("message:"); - if (this.message == null) { - sb.append("null"); - } else { - sb.append(this.message); - } - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - if (message == null) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'message' was not present! Struct: " + toString()); - } - // check for sub-struct validity - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private static class EntitlementExceptionStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public EntitlementExceptionStandardScheme getScheme() { - return new EntitlementExceptionStandardScheme(); - } - } - - private static class EntitlementExceptionStandardScheme extends org.apache.thrift.scheme.StandardScheme { - - public void read(org.apache.thrift.protocol.TProtocol iprot, EntitlementException struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField schemeField; - iprot.readStructBegin(); - while (true) - { - schemeField = iprot.readFieldBegin(); - if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (schemeField.id) { - case 1: // MESSAGE - if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { - struct.message = iprot.readString(); - struct.setMessageIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - struct.validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot, EntitlementException struct) throws org.apache.thrift.TException { - struct.validate(); - - oprot.writeStructBegin(STRUCT_DESC); - if (struct.message != null) { - oprot.writeFieldBegin(MESSAGE_FIELD_DESC); - oprot.writeString(struct.message); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - } - - private static class EntitlementExceptionTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public EntitlementExceptionTupleScheme getScheme() { - return new EntitlementExceptionTupleScheme(); - } - } - - private static class EntitlementExceptionTupleScheme extends org.apache.thrift.scheme.TupleScheme { - - @Override - public void write(org.apache.thrift.protocol.TProtocol prot, EntitlementException struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - oprot.writeString(struct.message); - } - - @Override - public void read(org.apache.thrift.protocol.TProtocol prot, EntitlementException struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - struct.message = iprot.readString(); - struct.setMessageIsSet(true); - } - } - - private static S scheme(org.apache.thrift.protocol.TProtocol proto) { - return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); - } -} - diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/thrift/EntitlementService.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/thrift/EntitlementService.java deleted file mode 100644 index c01322ff0c78..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/thrift/EntitlementService.java +++ /dev/null @@ -1,2669 +0,0 @@ -/** - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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. - * - * Autogenerated by Thrift Compiler (0.12.0) - * - * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING - * @generated - */ - -package org.wso2.carbon.identity.entitlement.thrift; - -@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"}) -@javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.12.0)", date = "2019-03-21") -public class EntitlementService { - - public interface Iface { - - public String getDecision(String request, String sessionId) throws EntitlementException, org.apache.thrift.TException; - - public String getDecisionByAttributes(String subject, String resource, String action, java.util.List environment, String sessionId) throws EntitlementException, org.apache.thrift.TException; - - } - - public interface AsyncIface { - - public void getDecision(String request, String sessionId, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; - - public void getDecisionByAttributes(String subject, String resource, String action, java.util.List environment, String sessionId, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; - - } - - public static class Client extends org.apache.thrift.TServiceClient implements Iface { - public static class Factory implements org.apache.thrift.TServiceClientFactory { - public Factory() {} - public Client getClient(org.apache.thrift.protocol.TProtocol prot) { - return new Client(prot); - } - public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) { - return new Client(iprot, oprot); - } - } - - public Client(org.apache.thrift.protocol.TProtocol prot) - { - super(prot, prot); - } - - public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) { - super(iprot, oprot); - } - - public String getDecision(String request, String sessionId) throws EntitlementException, org.apache.thrift.TException - { - send_getDecision(request, sessionId); - return recv_getDecision(); - } - - public void send_getDecision(String request, String sessionId) throws org.apache.thrift.TException - { - getDecision_args args = new getDecision_args(); - args.setRequest(request); - args.setSessionId(sessionId); - sendBase("getDecision", args); - } - - public String recv_getDecision() throws EntitlementException, org.apache.thrift.TException - { - getDecision_result result = new getDecision_result(); - receiveBase(result, "getDecision"); - if (result.isSetSuccess()) { - return result.success; - } - if (result.ee != null) { - throw result.ee; - } - throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "getDecision failed: unknown result"); - } - - public String getDecisionByAttributes(String subject, String resource, String action, java.util.List environment, String sessionId) throws EntitlementException, org.apache.thrift.TException - { - send_getDecisionByAttributes(subject, resource, action, environment, sessionId); - return recv_getDecisionByAttributes(); - } - - public void send_getDecisionByAttributes(String subject, String resource, String action, java.util.List environment, String sessionId) throws org.apache.thrift.TException - { - getDecisionByAttributes_args args = new getDecisionByAttributes_args(); - args.setSubject(subject); - args.setResource(resource); - args.setAction(action); - args.setEnvironment(environment); - args.setSessionId(sessionId); - sendBase("getDecisionByAttributes", args); - } - - public String recv_getDecisionByAttributes() throws EntitlementException, org.apache.thrift.TException - { - getDecisionByAttributes_result result = new getDecisionByAttributes_result(); - receiveBase(result, "getDecisionByAttributes"); - if (result.isSetSuccess()) { - return result.success; - } - if (result.ee != null) { - throw result.ee; - } - throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "getDecisionByAttributes failed: unknown result"); - } - - } - public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface { - public static class Factory implements org.apache.thrift.async.TAsyncClientFactory { - private org.apache.thrift.async.TAsyncClientManager clientManager; - private org.apache.thrift.protocol.TProtocolFactory protocolFactory; - public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) { - this.clientManager = clientManager; - this.protocolFactory = protocolFactory; - } - public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) { - return new AsyncClient(protocolFactory, clientManager, transport); - } - } - - public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) { - super(protocolFactory, clientManager, transport); - } - - public void getDecision(String request, String sessionId, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - checkReady(); - getDecision_call method_call = new getDecision_call(request, sessionId, resultHandler, this, ___protocolFactory, ___transport); - this.___currentMethod = method_call; - ___manager.call(method_call); - } - - public static class getDecision_call extends org.apache.thrift.async.TAsyncMethodCall { - private String request; - private String sessionId; - public getDecision_call(String request, String sessionId, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { - super(client, protocolFactory, transport, resultHandler, false); - this.request = request; - this.sessionId = sessionId; - } - - public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { - prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("getDecision", org.apache.thrift.protocol.TMessageType.CALL, 0)); - getDecision_args args = new getDecision_args(); - args.setRequest(request); - args.setSessionId(sessionId); - args.write(prot); - prot.writeMessageEnd(); - } - - public String getResult() throws EntitlementException, org.apache.thrift.TException { - if (getState() != State.RESPONSE_READ) { - throw new IllegalStateException("Method call not finished!"); - } - org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); - org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); - return (new Client(prot)).recv_getDecision(); - } - } - - public void getDecisionByAttributes(String subject, String resource, String action, java.util.List environment, String sessionId, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - checkReady(); - getDecisionByAttributes_call method_call = new getDecisionByAttributes_call(subject, resource, action, environment, sessionId, resultHandler, this, ___protocolFactory, ___transport); - this.___currentMethod = method_call; - ___manager.call(method_call); - } - - public static class getDecisionByAttributes_call extends org.apache.thrift.async.TAsyncMethodCall { - private String subject; - private String resource; - private String action; - private java.util.List environment; - private String sessionId; - public getDecisionByAttributes_call(String subject, String resource, String action, java.util.List environment, String sessionId, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { - super(client, protocolFactory, transport, resultHandler, false); - this.subject = subject; - this.resource = resource; - this.action = action; - this.environment = environment; - this.sessionId = sessionId; - } - - public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { - prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("getDecisionByAttributes", org.apache.thrift.protocol.TMessageType.CALL, 0)); - getDecisionByAttributes_args args = new getDecisionByAttributes_args(); - args.setSubject(subject); - args.setResource(resource); - args.setAction(action); - args.setEnvironment(environment); - args.setSessionId(sessionId); - args.write(prot); - prot.writeMessageEnd(); - } - - public String getResult() throws EntitlementException, org.apache.thrift.TException { - if (getState() != State.RESPONSE_READ) { - throw new IllegalStateException("Method call not finished!"); - } - org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); - org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); - return (new Client(prot)).recv_getDecisionByAttributes(); - } - } - - } - - public static class Processor extends org.apache.thrift.TBaseProcessor implements org.apache.thrift.TProcessor { - private static final org.slf4j.Logger _LOGGER = org.slf4j.LoggerFactory.getLogger(Processor.class.getName()); - public Processor(I iface) { - super(iface, getProcessMap(new java.util.HashMap>())); - } - - protected Processor(I iface, java.util.Map> processMap) { - super(iface, getProcessMap(processMap)); - } - - private static java.util.Map> getProcessMap(java.util.Map> processMap) { - processMap.put("getDecision", new getDecision()); - processMap.put("getDecisionByAttributes", new getDecisionByAttributes()); - return processMap; - } - - public static class getDecision extends org.apache.thrift.ProcessFunction { - public getDecision() { - super("getDecision"); - } - - public getDecision_args getEmptyArgsInstance() { - return new getDecision_args(); - } - - protected boolean isOneway() { - return false; - } - - @Override - protected boolean rethrowUnhandledExceptions() { - return false; - } - - public getDecision_result getResult(I iface, getDecision_args args) throws org.apache.thrift.TException { - getDecision_result result = new getDecision_result(); - try { - result.success = iface.getDecision(args.request, args.sessionId); - } catch (EntitlementException ee) { - result.ee = ee; - } - return result; - } - } - - public static class getDecisionByAttributes extends org.apache.thrift.ProcessFunction { - public getDecisionByAttributes() { - super("getDecisionByAttributes"); - } - - public getDecisionByAttributes_args getEmptyArgsInstance() { - return new getDecisionByAttributes_args(); - } - - protected boolean isOneway() { - return false; - } - - @Override - protected boolean rethrowUnhandledExceptions() { - return false; - } - - public getDecisionByAttributes_result getResult(I iface, getDecisionByAttributes_args args) throws org.apache.thrift.TException { - getDecisionByAttributes_result result = new getDecisionByAttributes_result(); - try { - result.success = iface.getDecisionByAttributes(args.subject, args.resource, args.action, args.environment, args.sessionId); - } catch (EntitlementException ee) { - result.ee = ee; - } - return result; - } - } - - } - - public static class AsyncProcessor extends org.apache.thrift.TBaseAsyncProcessor { - private static final org.slf4j.Logger _LOGGER = org.slf4j.LoggerFactory.getLogger(AsyncProcessor.class.getName()); - public AsyncProcessor(I iface) { - super(iface, getProcessMap(new java.util.HashMap>())); - } - - protected AsyncProcessor(I iface, java.util.Map> processMap) { - super(iface, getProcessMap(processMap)); - } - - private static java.util.Map> getProcessMap(java.util.Map> processMap) { - processMap.put("getDecision", new getDecision()); - processMap.put("getDecisionByAttributes", new getDecisionByAttributes()); - return processMap; - } - - public static class getDecision extends org.apache.thrift.AsyncProcessFunction { - public getDecision() { - super("getDecision"); - } - - public getDecision_args getEmptyArgsInstance() { - return new getDecision_args(); - } - - public org.apache.thrift.async.AsyncMethodCallback getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) { - final org.apache.thrift.AsyncProcessFunction fcall = this; - return new org.apache.thrift.async.AsyncMethodCallback() { - public void onComplete(String o) { - getDecision_result result = new getDecision_result(); - result.success = o; - try { - fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); - } catch (org.apache.thrift.transport.TTransportException e) { - _LOGGER.error("TTransportException writing to internal frame buffer", e); - fb.close(); - } catch (Exception e) { - _LOGGER.error("Exception writing to internal frame buffer", e); - onError(e); - } - } - public void onError(Exception e) { - byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; - org.apache.thrift.TSerializable msg; - getDecision_result result = new getDecision_result(); - if (e instanceof EntitlementException) { - result.ee = (EntitlementException) e; - result.setEeIsSet(true); - msg = result; - } else if (e instanceof org.apache.thrift.transport.TTransportException) { - _LOGGER.error("TTransportException inside handler", e); - fb.close(); - return; - } else if (e instanceof org.apache.thrift.TApplicationException) { - _LOGGER.error("TApplicationException inside handler", e); - msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; - msg = (org.apache.thrift.TApplicationException)e; - } else { - _LOGGER.error("Exception inside handler", e); - msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; - msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); - } - try { - fcall.sendResponse(fb,msg,msgType,seqid); - } catch (Exception ex) { - _LOGGER.error("Exception writing to internal frame buffer", ex); - fb.close(); - } - } - }; - } - - protected boolean isOneway() { - return false; - } - - public void start(I iface, getDecision_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - iface.getDecision(args.request, args.sessionId,resultHandler); - } - } - - public static class getDecisionByAttributes extends org.apache.thrift.AsyncProcessFunction { - public getDecisionByAttributes() { - super("getDecisionByAttributes"); - } - - public getDecisionByAttributes_args getEmptyArgsInstance() { - return new getDecisionByAttributes_args(); - } - - public org.apache.thrift.async.AsyncMethodCallback getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) { - final org.apache.thrift.AsyncProcessFunction fcall = this; - return new org.apache.thrift.async.AsyncMethodCallback() { - public void onComplete(String o) { - getDecisionByAttributes_result result = new getDecisionByAttributes_result(); - result.success = o; - try { - fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); - } catch (org.apache.thrift.transport.TTransportException e) { - _LOGGER.error("TTransportException writing to internal frame buffer", e); - fb.close(); - } catch (Exception e) { - _LOGGER.error("Exception writing to internal frame buffer", e); - onError(e); - } - } - public void onError(Exception e) { - byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; - org.apache.thrift.TSerializable msg; - getDecisionByAttributes_result result = new getDecisionByAttributes_result(); - if (e instanceof EntitlementException) { - result.ee = (EntitlementException) e; - result.setEeIsSet(true); - msg = result; - } else if (e instanceof org.apache.thrift.transport.TTransportException) { - _LOGGER.error("TTransportException inside handler", e); - fb.close(); - return; - } else if (e instanceof org.apache.thrift.TApplicationException) { - _LOGGER.error("TApplicationException inside handler", e); - msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; - msg = (org.apache.thrift.TApplicationException)e; - } else { - _LOGGER.error("Exception inside handler", e); - msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; - msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); - } - try { - fcall.sendResponse(fb,msg,msgType,seqid); - } catch (Exception ex) { - _LOGGER.error("Exception writing to internal frame buffer", ex); - fb.close(); - } - } - }; - } - - protected boolean isOneway() { - return false; - } - - public void start(I iface, getDecisionByAttributes_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - iface.getDecisionByAttributes(args.subject, args.resource, args.action, args.environment, args.sessionId,resultHandler); - } - } - - } - - public static class getDecision_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getDecision_args"); - - private static final org.apache.thrift.protocol.TField REQUEST_FIELD_DESC = new org.apache.thrift.protocol.TField("request", org.apache.thrift.protocol.TType.STRING, (short)1); - private static final org.apache.thrift.protocol.TField SESSION_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("sessionId", org.apache.thrift.protocol.TType.STRING, (short)2); - - private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new getDecision_argsStandardSchemeFactory(); - private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new getDecision_argsTupleSchemeFactory(); - - public @org.apache.thrift.annotation.Nullable String request; // required - public @org.apache.thrift.annotation.Nullable String sessionId; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - REQUEST((short)1, "request"), - SESSION_ID((short)2, "sessionId"); - - private static final java.util.Map byName = new java.util.HashMap(); - - static { - for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - @org.apache.thrift.annotation.Nullable - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // REQUEST - return REQUEST; - case 2: // SESSION_ID - return SESSION_ID; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - @org.apache.thrift.annotation.Nullable - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.REQUEST, new org.apache.thrift.meta_data.FieldMetaData("request", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); - tmpMap.put(_Fields.SESSION_ID, new org.apache.thrift.meta_data.FieldMetaData("sessionId", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); - metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getDecision_args.class, metaDataMap); - } - - public getDecision_args() { - } - - public getDecision_args( - String request, - String sessionId) - { - this(); - this.request = request; - this.sessionId = sessionId; - } - - /** - * Performs a deep copy on other. - */ - public getDecision_args(getDecision_args other) { - if (other.isSetRequest()) { - this.request = other.request; - } - if (other.isSetSessionId()) { - this.sessionId = other.sessionId; - } - } - - public getDecision_args deepCopy() { - return new getDecision_args(this); - } - - @Override - public void clear() { - this.request = null; - this.sessionId = null; - } - - @org.apache.thrift.annotation.Nullable - public String getRequest() { - return this.request; - } - - public getDecision_args setRequest(@org.apache.thrift.annotation.Nullable String request) { - this.request = request; - return this; - } - - public void unsetRequest() { - this.request = null; - } - - /** Returns true if field request is set (has been assigned a value) and false otherwise */ - public boolean isSetRequest() { - return this.request != null; - } - - public void setRequestIsSet(boolean value) { - if (!value) { - this.request = null; - } - } - - @org.apache.thrift.annotation.Nullable - public String getSessionId() { - return this.sessionId; - } - - public getDecision_args setSessionId(@org.apache.thrift.annotation.Nullable String sessionId) { - this.sessionId = sessionId; - return this; - } - - public void unsetSessionId() { - this.sessionId = null; - } - - /** Returns true if field sessionId is set (has been assigned a value) and false otherwise */ - public boolean isSetSessionId() { - return this.sessionId != null; - } - - public void setSessionIdIsSet(boolean value) { - if (!value) { - this.sessionId = null; - } - } - - public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable Object value) { - switch (field) { - case REQUEST: - if (value == null) { - unsetRequest(); - } else { - setRequest((String)value); - } - break; - - case SESSION_ID: - if (value == null) { - unsetSessionId(); - } else { - setSessionId((String)value); - } - break; - - } - } - - @org.apache.thrift.annotation.Nullable - public Object getFieldValue(_Fields field) { - switch (field) { - case REQUEST: - return getRequest(); - - case SESSION_ID: - return getSessionId(); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case REQUEST: - return isSetRequest(); - case SESSION_ID: - return isSetSessionId(); - } - throw new IllegalStateException(); - } - - @Override - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof getDecision_args) - return this.equals((getDecision_args)that); - return false; - } - - public boolean equals(getDecision_args that) { - if (that == null) - return false; - if (this == that) - return true; - - boolean this_present_request = true && this.isSetRequest(); - boolean that_present_request = true && that.isSetRequest(); - if (this_present_request || that_present_request) { - if (!(this_present_request && that_present_request)) - return false; - if (!this.request.equals(that.request)) - return false; - } - - boolean this_present_sessionId = true && this.isSetSessionId(); - boolean that_present_sessionId = true && that.isSetSessionId(); - if (this_present_sessionId || that_present_sessionId) { - if (!(this_present_sessionId && that_present_sessionId)) - return false; - if (!this.sessionId.equals(that.sessionId)) - return false; - } - - return true; - } - - @Override - public int hashCode() { - int hashCode = 1; - - hashCode = hashCode * 8191 + ((isSetRequest()) ? 131071 : 524287); - if (isSetRequest()) - hashCode = hashCode * 8191 + request.hashCode(); - - hashCode = hashCode * 8191 + ((isSetSessionId()) ? 131071 : 524287); - if (isSetSessionId()) - hashCode = hashCode * 8191 + sessionId.hashCode(); - - return hashCode; - } - - @Override - public int compareTo(getDecision_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - - lastComparison = Boolean.valueOf(isSetRequest()).compareTo(other.isSetRequest()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetRequest()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.request, other.request); - if (lastComparison != 0) { - return lastComparison; - } - } - lastComparison = Boolean.valueOf(isSetSessionId()).compareTo(other.isSetSessionId()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSessionId()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.sessionId, other.sessionId); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - @org.apache.thrift.annotation.Nullable - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - scheme(iprot).read(iprot, this); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - scheme(oprot).write(oprot, this); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("getDecision_args("); - boolean first = true; - - sb.append("request:"); - if (this.request == null) { - sb.append("null"); - } else { - sb.append(this.request); - } - first = false; - if (!first) sb.append(", "); - sb.append("sessionId:"); - if (this.sessionId == null) { - sb.append("null"); - } else { - sb.append(this.sessionId); - } - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - if (request == null) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'request' was not present! Struct: " + toString()); - } - if (sessionId == null) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'sessionId' was not present! Struct: " + toString()); - } - // check for sub-struct validity - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private static class getDecision_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public getDecision_argsStandardScheme getScheme() { - return new getDecision_argsStandardScheme(); - } - } - - private static class getDecision_argsStandardScheme extends org.apache.thrift.scheme.StandardScheme { - - public void read(org.apache.thrift.protocol.TProtocol iprot, getDecision_args struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField schemeField; - iprot.readStructBegin(); - while (true) - { - schemeField = iprot.readFieldBegin(); - if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (schemeField.id) { - case 1: // REQUEST - if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { - struct.request = iprot.readString(); - struct.setRequestIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - break; - case 2: // SESSION_ID - if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { - struct.sessionId = iprot.readString(); - struct.setSessionIdIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - struct.validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot, getDecision_args struct) throws org.apache.thrift.TException { - struct.validate(); - - oprot.writeStructBegin(STRUCT_DESC); - if (struct.request != null) { - oprot.writeFieldBegin(REQUEST_FIELD_DESC); - oprot.writeString(struct.request); - oprot.writeFieldEnd(); - } - if (struct.sessionId != null) { - oprot.writeFieldBegin(SESSION_ID_FIELD_DESC); - oprot.writeString(struct.sessionId); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - } - - private static class getDecision_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public getDecision_argsTupleScheme getScheme() { - return new getDecision_argsTupleScheme(); - } - } - - private static class getDecision_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme { - - @Override - public void write(org.apache.thrift.protocol.TProtocol prot, getDecision_args struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - oprot.writeString(struct.request); - oprot.writeString(struct.sessionId); - } - - @Override - public void read(org.apache.thrift.protocol.TProtocol prot, getDecision_args struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - struct.request = iprot.readString(); - struct.setRequestIsSet(true); - struct.sessionId = iprot.readString(); - struct.setSessionIdIsSet(true); - } - } - - private static S scheme(org.apache.thrift.protocol.TProtocol proto) { - return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); - } - } - - public static class getDecision_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getDecision_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRING, (short)0); - private static final org.apache.thrift.protocol.TField EE_FIELD_DESC = new org.apache.thrift.protocol.TField("ee", org.apache.thrift.protocol.TType.STRUCT, (short)1); - - private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new getDecision_resultStandardSchemeFactory(); - private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new getDecision_resultTupleSchemeFactory(); - - public @org.apache.thrift.annotation.Nullable String success; // required - public @org.apache.thrift.annotation.Nullable EntitlementException ee; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"), - EE((short)1, "ee"); - - private static final java.util.Map byName = new java.util.HashMap(); - - static { - for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - @org.apache.thrift.annotation.Nullable - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - case 1: // EE - return EE; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - @org.apache.thrift.annotation.Nullable - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); - tmpMap.put(_Fields.EE, new org.apache.thrift.meta_data.FieldMetaData("ee", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, EntitlementException.class))); - metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getDecision_result.class, metaDataMap); - } - - public getDecision_result() { - } - - public getDecision_result( - String success, - EntitlementException ee) - { - this(); - this.success = success; - this.ee = ee; - } - - /** - * Performs a deep copy on other. - */ - public getDecision_result(getDecision_result other) { - if (other.isSetSuccess()) { - this.success = other.success; - } - if (other.isSetEe()) { - this.ee = new EntitlementException(other.ee); - } - } - - public getDecision_result deepCopy() { - return new getDecision_result(this); - } - - @Override - public void clear() { - this.success = null; - this.ee = null; - } - - @org.apache.thrift.annotation.Nullable - public String getSuccess() { - return this.success; - } - - public getDecision_result setSuccess(@org.apache.thrift.annotation.Nullable String success) { - this.success = success; - return this; - } - - public void unsetSuccess() { - this.success = null; - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return this.success != null; - } - - public void setSuccessIsSet(boolean value) { - if (!value) { - this.success = null; - } - } - - @org.apache.thrift.annotation.Nullable - public EntitlementException getEe() { - return this.ee; - } - - public getDecision_result setEe(@org.apache.thrift.annotation.Nullable EntitlementException ee) { - this.ee = ee; - return this; - } - - public void unsetEe() { - this.ee = null; - } - - /** Returns true if field ee is set (has been assigned a value) and false otherwise */ - public boolean isSetEe() { - return this.ee != null; - } - - public void setEeIsSet(boolean value) { - if (!value) { - this.ee = null; - } - } - - public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((String)value); - } - break; - - case EE: - if (value == null) { - unsetEe(); - } else { - setEe((EntitlementException)value); - } - break; - - } - } - - @org.apache.thrift.annotation.Nullable - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return getSuccess(); - - case EE: - return getEe(); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - case EE: - return isSetEe(); - } - throw new IllegalStateException(); - } - - @Override - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof getDecision_result) - return this.equals((getDecision_result)that); - return false; - } - - public boolean equals(getDecision_result that) { - if (that == null) - return false; - if (this == that) - return true; - - boolean this_present_success = true && this.isSetSuccess(); - boolean that_present_success = true && that.isSetSuccess(); - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (!this.success.equals(that.success)) - return false; - } - - boolean this_present_ee = true && this.isSetEe(); - boolean that_present_ee = true && that.isSetEe(); - if (this_present_ee || that_present_ee) { - if (!(this_present_ee && that_present_ee)) - return false; - if (!this.ee.equals(that.ee)) - return false; - } - - return true; - } - - @Override - public int hashCode() { - int hashCode = 1; - - hashCode = hashCode * 8191 + ((isSetSuccess()) ? 131071 : 524287); - if (isSetSuccess()) - hashCode = hashCode * 8191 + success.hashCode(); - - hashCode = hashCode * 8191 + ((isSetEe()) ? 131071 : 524287); - if (isSetEe()) - hashCode = hashCode * 8191 + ee.hashCode(); - - return hashCode; - } - - @Override - public int compareTo(getDecision_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); - if (lastComparison != 0) { - return lastComparison; - } - } - lastComparison = Boolean.valueOf(isSetEe()).compareTo(other.isSetEe()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetEe()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ee, other.ee); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - @org.apache.thrift.annotation.Nullable - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - scheme(iprot).read(iprot, this); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - scheme(oprot).write(oprot, this); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("getDecision_result("); - boolean first = true; - - sb.append("success:"); - if (this.success == null) { - sb.append("null"); - } else { - sb.append(this.success); - } - first = false; - if (!first) sb.append(", "); - sb.append("ee:"); - if (this.ee == null) { - sb.append("null"); - } else { - sb.append(this.ee); - } - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - // check for sub-struct validity - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private static class getDecision_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public getDecision_resultStandardScheme getScheme() { - return new getDecision_resultStandardScheme(); - } - } - - private static class getDecision_resultStandardScheme extends org.apache.thrift.scheme.StandardScheme { - - public void read(org.apache.thrift.protocol.TProtocol iprot, getDecision_result struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField schemeField; - iprot.readStructBegin(); - while (true) - { - schemeField = iprot.readFieldBegin(); - if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (schemeField.id) { - case 0: // SUCCESS - if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { - struct.success = iprot.readString(); - struct.setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - break; - case 1: // EE - if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { - struct.ee = new EntitlementException(); - struct.ee.read(iprot); - struct.setEeIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - struct.validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot, getDecision_result struct) throws org.apache.thrift.TException { - struct.validate(); - - oprot.writeStructBegin(STRUCT_DESC); - if (struct.success != null) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeString(struct.success); - oprot.writeFieldEnd(); - } - if (struct.ee != null) { - oprot.writeFieldBegin(EE_FIELD_DESC); - struct.ee.write(oprot); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - } - - private static class getDecision_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public getDecision_resultTupleScheme getScheme() { - return new getDecision_resultTupleScheme(); - } - } - - private static class getDecision_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme { - - @Override - public void write(org.apache.thrift.protocol.TProtocol prot, getDecision_result struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - java.util.BitSet optionals = new java.util.BitSet(); - if (struct.isSetSuccess()) { - optionals.set(0); - } - if (struct.isSetEe()) { - optionals.set(1); - } - oprot.writeBitSet(optionals, 2); - if (struct.isSetSuccess()) { - oprot.writeString(struct.success); - } - if (struct.isSetEe()) { - struct.ee.write(oprot); - } - } - - @Override - public void read(org.apache.thrift.protocol.TProtocol prot, getDecision_result struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - java.util.BitSet incoming = iprot.readBitSet(2); - if (incoming.get(0)) { - struct.success = iprot.readString(); - struct.setSuccessIsSet(true); - } - if (incoming.get(1)) { - struct.ee = new EntitlementException(); - struct.ee.read(iprot); - struct.setEeIsSet(true); - } - } - } - - private static S scheme(org.apache.thrift.protocol.TProtocol proto) { - return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); - } - } - - public static class getDecisionByAttributes_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getDecisionByAttributes_args"); - - private static final org.apache.thrift.protocol.TField SUBJECT_FIELD_DESC = new org.apache.thrift.protocol.TField("subject", org.apache.thrift.protocol.TType.STRING, (short)1); - private static final org.apache.thrift.protocol.TField RESOURCE_FIELD_DESC = new org.apache.thrift.protocol.TField("resource", org.apache.thrift.protocol.TType.STRING, (short)2); - private static final org.apache.thrift.protocol.TField ACTION_FIELD_DESC = new org.apache.thrift.protocol.TField("action", org.apache.thrift.protocol.TType.STRING, (short)3); - private static final org.apache.thrift.protocol.TField ENVIRONMENT_FIELD_DESC = new org.apache.thrift.protocol.TField("environment", org.apache.thrift.protocol.TType.LIST, (short)4); - private static final org.apache.thrift.protocol.TField SESSION_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("sessionId", org.apache.thrift.protocol.TType.STRING, (short)5); - - private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new getDecisionByAttributes_argsStandardSchemeFactory(); - private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new getDecisionByAttributes_argsTupleSchemeFactory(); - - public @org.apache.thrift.annotation.Nullable String subject; // required - public @org.apache.thrift.annotation.Nullable String resource; // required - public @org.apache.thrift.annotation.Nullable String action; // required - public @org.apache.thrift.annotation.Nullable java.util.List environment; // required - public @org.apache.thrift.annotation.Nullable String sessionId; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUBJECT((short)1, "subject"), - RESOURCE((short)2, "resource"), - ACTION((short)3, "action"), - ENVIRONMENT((short)4, "environment"), - SESSION_ID((short)5, "sessionId"); - - private static final java.util.Map byName = new java.util.HashMap(); - - static { - for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - @org.apache.thrift.annotation.Nullable - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // SUBJECT - return SUBJECT; - case 2: // RESOURCE - return RESOURCE; - case 3: // ACTION - return ACTION; - case 4: // ENVIRONMENT - return ENVIRONMENT; - case 5: // SESSION_ID - return SESSION_ID; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - @org.apache.thrift.annotation.Nullable - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUBJECT, new org.apache.thrift.meta_data.FieldMetaData("subject", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); - tmpMap.put(_Fields.RESOURCE, new org.apache.thrift.meta_data.FieldMetaData("resource", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); - tmpMap.put(_Fields.ACTION, new org.apache.thrift.meta_data.FieldMetaData("action", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); - tmpMap.put(_Fields.ENVIRONMENT, new org.apache.thrift.meta_data.FieldMetaData("environment", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)))); - tmpMap.put(_Fields.SESSION_ID, new org.apache.thrift.meta_data.FieldMetaData("sessionId", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); - metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getDecisionByAttributes_args.class, metaDataMap); - } - - public getDecisionByAttributes_args() { - } - - public getDecisionByAttributes_args( - String subject, - String resource, - String action, - java.util.List environment, - String sessionId) - { - this(); - this.subject = subject; - this.resource = resource; - this.action = action; - this.environment = environment; - this.sessionId = sessionId; - } - - /** - * Performs a deep copy on other. - */ - public getDecisionByAttributes_args(getDecisionByAttributes_args other) { - if (other.isSetSubject()) { - this.subject = other.subject; - } - if (other.isSetResource()) { - this.resource = other.resource; - } - if (other.isSetAction()) { - this.action = other.action; - } - if (other.isSetEnvironment()) { - java.util.List __this__environment = new java.util.ArrayList(other.environment); - this.environment = __this__environment; - } - if (other.isSetSessionId()) { - this.sessionId = other.sessionId; - } - } - - public getDecisionByAttributes_args deepCopy() { - return new getDecisionByAttributes_args(this); - } - - @Override - public void clear() { - this.subject = null; - this.resource = null; - this.action = null; - this.environment = null; - this.sessionId = null; - } - - @org.apache.thrift.annotation.Nullable - public String getSubject() { - return this.subject; - } - - public getDecisionByAttributes_args setSubject(@org.apache.thrift.annotation.Nullable String subject) { - this.subject = subject; - return this; - } - - public void unsetSubject() { - this.subject = null; - } - - /** Returns true if field subject is set (has been assigned a value) and false otherwise */ - public boolean isSetSubject() { - return this.subject != null; - } - - public void setSubjectIsSet(boolean value) { - if (!value) { - this.subject = null; - } - } - - @org.apache.thrift.annotation.Nullable - public String getResource() { - return this.resource; - } - - public getDecisionByAttributes_args setResource(@org.apache.thrift.annotation.Nullable String resource) { - this.resource = resource; - return this; - } - - public void unsetResource() { - this.resource = null; - } - - /** Returns true if field resource is set (has been assigned a value) and false otherwise */ - public boolean isSetResource() { - return this.resource != null; - } - - public void setResourceIsSet(boolean value) { - if (!value) { - this.resource = null; - } - } - - @org.apache.thrift.annotation.Nullable - public String getAction() { - return this.action; - } - - public getDecisionByAttributes_args setAction(@org.apache.thrift.annotation.Nullable String action) { - this.action = action; - return this; - } - - public void unsetAction() { - this.action = null; - } - - /** Returns true if field action is set (has been assigned a value) and false otherwise */ - public boolean isSetAction() { - return this.action != null; - } - - public void setActionIsSet(boolean value) { - if (!value) { - this.action = null; - } - } - - public int getEnvironmentSize() { - return (this.environment == null) ? 0 : this.environment.size(); - } - - @org.apache.thrift.annotation.Nullable - public java.util.Iterator getEnvironmentIterator() { - return (this.environment == null) ? null : this.environment.iterator(); - } - - public void addToEnvironment(String elem) { - if (this.environment == null) { - this.environment = new java.util.ArrayList(); - } - this.environment.add(elem); - } - - @org.apache.thrift.annotation.Nullable - public java.util.List getEnvironment() { - return this.environment; - } - - public getDecisionByAttributes_args setEnvironment(@org.apache.thrift.annotation.Nullable java.util.List environment) { - this.environment = environment; - return this; - } - - public void unsetEnvironment() { - this.environment = null; - } - - /** Returns true if field environment is set (has been assigned a value) and false otherwise */ - public boolean isSetEnvironment() { - return this.environment != null; - } - - public void setEnvironmentIsSet(boolean value) { - if (!value) { - this.environment = null; - } - } - - @org.apache.thrift.annotation.Nullable - public String getSessionId() { - return this.sessionId; - } - - public getDecisionByAttributes_args setSessionId(@org.apache.thrift.annotation.Nullable String sessionId) { - this.sessionId = sessionId; - return this; - } - - public void unsetSessionId() { - this.sessionId = null; - } - - /** Returns true if field sessionId is set (has been assigned a value) and false otherwise */ - public boolean isSetSessionId() { - return this.sessionId != null; - } - - public void setSessionIdIsSet(boolean value) { - if (!value) { - this.sessionId = null; - } - } - - public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable Object value) { - switch (field) { - case SUBJECT: - if (value == null) { - unsetSubject(); - } else { - setSubject((String)value); - } - break; - - case RESOURCE: - if (value == null) { - unsetResource(); - } else { - setResource((String)value); - } - break; - - case ACTION: - if (value == null) { - unsetAction(); - } else { - setAction((String)value); - } - break; - - case ENVIRONMENT: - if (value == null) { - unsetEnvironment(); - } else { - setEnvironment((java.util.List)value); - } - break; - - case SESSION_ID: - if (value == null) { - unsetSessionId(); - } else { - setSessionId((String)value); - } - break; - - } - } - - @org.apache.thrift.annotation.Nullable - public Object getFieldValue(_Fields field) { - switch (field) { - case SUBJECT: - return getSubject(); - - case RESOURCE: - return getResource(); - - case ACTION: - return getAction(); - - case ENVIRONMENT: - return getEnvironment(); - - case SESSION_ID: - return getSessionId(); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUBJECT: - return isSetSubject(); - case RESOURCE: - return isSetResource(); - case ACTION: - return isSetAction(); - case ENVIRONMENT: - return isSetEnvironment(); - case SESSION_ID: - return isSetSessionId(); - } - throw new IllegalStateException(); - } - - @Override - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof getDecisionByAttributes_args) - return this.equals((getDecisionByAttributes_args)that); - return false; - } - - public boolean equals(getDecisionByAttributes_args that) { - if (that == null) - return false; - if (this == that) - return true; - - boolean this_present_subject = true && this.isSetSubject(); - boolean that_present_subject = true && that.isSetSubject(); - if (this_present_subject || that_present_subject) { - if (!(this_present_subject && that_present_subject)) - return false; - if (!this.subject.equals(that.subject)) - return false; - } - - boolean this_present_resource = true && this.isSetResource(); - boolean that_present_resource = true && that.isSetResource(); - if (this_present_resource || that_present_resource) { - if (!(this_present_resource && that_present_resource)) - return false; - if (!this.resource.equals(that.resource)) - return false; - } - - boolean this_present_action = true && this.isSetAction(); - boolean that_present_action = true && that.isSetAction(); - if (this_present_action || that_present_action) { - if (!(this_present_action && that_present_action)) - return false; - if (!this.action.equals(that.action)) - return false; - } - - boolean this_present_environment = true && this.isSetEnvironment(); - boolean that_present_environment = true && that.isSetEnvironment(); - if (this_present_environment || that_present_environment) { - if (!(this_present_environment && that_present_environment)) - return false; - if (!this.environment.equals(that.environment)) - return false; - } - - boolean this_present_sessionId = true && this.isSetSessionId(); - boolean that_present_sessionId = true && that.isSetSessionId(); - if (this_present_sessionId || that_present_sessionId) { - if (!(this_present_sessionId && that_present_sessionId)) - return false; - if (!this.sessionId.equals(that.sessionId)) - return false; - } - - return true; - } - - @Override - public int hashCode() { - int hashCode = 1; - - hashCode = hashCode * 8191 + ((isSetSubject()) ? 131071 : 524287); - if (isSetSubject()) - hashCode = hashCode * 8191 + subject.hashCode(); - - hashCode = hashCode * 8191 + ((isSetResource()) ? 131071 : 524287); - if (isSetResource()) - hashCode = hashCode * 8191 + resource.hashCode(); - - hashCode = hashCode * 8191 + ((isSetAction()) ? 131071 : 524287); - if (isSetAction()) - hashCode = hashCode * 8191 + action.hashCode(); - - hashCode = hashCode * 8191 + ((isSetEnvironment()) ? 131071 : 524287); - if (isSetEnvironment()) - hashCode = hashCode * 8191 + environment.hashCode(); - - hashCode = hashCode * 8191 + ((isSetSessionId()) ? 131071 : 524287); - if (isSetSessionId()) - hashCode = hashCode * 8191 + sessionId.hashCode(); - - return hashCode; - } - - @Override - public int compareTo(getDecisionByAttributes_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - - lastComparison = Boolean.valueOf(isSetSubject()).compareTo(other.isSetSubject()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSubject()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.subject, other.subject); - if (lastComparison != 0) { - return lastComparison; - } - } - lastComparison = Boolean.valueOf(isSetResource()).compareTo(other.isSetResource()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetResource()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.resource, other.resource); - if (lastComparison != 0) { - return lastComparison; - } - } - lastComparison = Boolean.valueOf(isSetAction()).compareTo(other.isSetAction()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetAction()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.action, other.action); - if (lastComparison != 0) { - return lastComparison; - } - } - lastComparison = Boolean.valueOf(isSetEnvironment()).compareTo(other.isSetEnvironment()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetEnvironment()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.environment, other.environment); - if (lastComparison != 0) { - return lastComparison; - } - } - lastComparison = Boolean.valueOf(isSetSessionId()).compareTo(other.isSetSessionId()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSessionId()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.sessionId, other.sessionId); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - @org.apache.thrift.annotation.Nullable - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - scheme(iprot).read(iprot, this); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - scheme(oprot).write(oprot, this); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("getDecisionByAttributes_args("); - boolean first = true; - - sb.append("subject:"); - if (this.subject == null) { - sb.append("null"); - } else { - sb.append(this.subject); - } - first = false; - if (!first) sb.append(", "); - sb.append("resource:"); - if (this.resource == null) { - sb.append("null"); - } else { - sb.append(this.resource); - } - first = false; - if (!first) sb.append(", "); - sb.append("action:"); - if (this.action == null) { - sb.append("null"); - } else { - sb.append(this.action); - } - first = false; - if (!first) sb.append(", "); - sb.append("environment:"); - if (this.environment == null) { - sb.append("null"); - } else { - sb.append(this.environment); - } - first = false; - if (!first) sb.append(", "); - sb.append("sessionId:"); - if (this.sessionId == null) { - sb.append("null"); - } else { - sb.append(this.sessionId); - } - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - if (subject == null) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'subject' was not present! Struct: " + toString()); - } - if (resource == null) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'resource' was not present! Struct: " + toString()); - } - if (action == null) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'action' was not present! Struct: " + toString()); - } - if (environment == null) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'environment' was not present! Struct: " + toString()); - } - if (sessionId == null) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'sessionId' was not present! Struct: " + toString()); - } - // check for sub-struct validity - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private static class getDecisionByAttributes_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public getDecisionByAttributes_argsStandardScheme getScheme() { - return new getDecisionByAttributes_argsStandardScheme(); - } - } - - private static class getDecisionByAttributes_argsStandardScheme extends org.apache.thrift.scheme.StandardScheme { - - public void read(org.apache.thrift.protocol.TProtocol iprot, getDecisionByAttributes_args struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField schemeField; - iprot.readStructBegin(); - while (true) - { - schemeField = iprot.readFieldBegin(); - if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (schemeField.id) { - case 1: // SUBJECT - if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { - struct.subject = iprot.readString(); - struct.setSubjectIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - break; - case 2: // RESOURCE - if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { - struct.resource = iprot.readString(); - struct.setResourceIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - break; - case 3: // ACTION - if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { - struct.action = iprot.readString(); - struct.setActionIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - break; - case 4: // ENVIRONMENT - if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { - { - org.apache.thrift.protocol.TList _list0 = iprot.readListBegin(); - struct.environment = new java.util.ArrayList(_list0.size); - @org.apache.thrift.annotation.Nullable String _elem1; - for (int _i2 = 0; _i2 < _list0.size; ++_i2) - { - _elem1 = iprot.readString(); - struct.environment.add(_elem1); - } - iprot.readListEnd(); - } - struct.setEnvironmentIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - break; - case 5: // SESSION_ID - if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { - struct.sessionId = iprot.readString(); - struct.setSessionIdIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - struct.validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot, getDecisionByAttributes_args struct) throws org.apache.thrift.TException { - struct.validate(); - - oprot.writeStructBegin(STRUCT_DESC); - if (struct.subject != null) { - oprot.writeFieldBegin(SUBJECT_FIELD_DESC); - oprot.writeString(struct.subject); - oprot.writeFieldEnd(); - } - if (struct.resource != null) { - oprot.writeFieldBegin(RESOURCE_FIELD_DESC); - oprot.writeString(struct.resource); - oprot.writeFieldEnd(); - } - if (struct.action != null) { - oprot.writeFieldBegin(ACTION_FIELD_DESC); - oprot.writeString(struct.action); - oprot.writeFieldEnd(); - } - if (struct.environment != null) { - oprot.writeFieldBegin(ENVIRONMENT_FIELD_DESC); - { - oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, struct.environment.size())); - for (String _iter3 : struct.environment) - { - oprot.writeString(_iter3); - } - oprot.writeListEnd(); - } - oprot.writeFieldEnd(); - } - if (struct.sessionId != null) { - oprot.writeFieldBegin(SESSION_ID_FIELD_DESC); - oprot.writeString(struct.sessionId); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - } - - private static class getDecisionByAttributes_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public getDecisionByAttributes_argsTupleScheme getScheme() { - return new getDecisionByAttributes_argsTupleScheme(); - } - } - - private static class getDecisionByAttributes_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme { - - @Override - public void write(org.apache.thrift.protocol.TProtocol prot, getDecisionByAttributes_args struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - oprot.writeString(struct.subject); - oprot.writeString(struct.resource); - oprot.writeString(struct.action); - { - oprot.writeI32(struct.environment.size()); - for (String _iter4 : struct.environment) - { - oprot.writeString(_iter4); - } - } - oprot.writeString(struct.sessionId); - } - - @Override - public void read(org.apache.thrift.protocol.TProtocol prot, getDecisionByAttributes_args struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - struct.subject = iprot.readString(); - struct.setSubjectIsSet(true); - struct.resource = iprot.readString(); - struct.setResourceIsSet(true); - struct.action = iprot.readString(); - struct.setActionIsSet(true); - { - org.apache.thrift.protocol.TList _list5 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, iprot.readI32()); - struct.environment = new java.util.ArrayList(_list5.size); - @org.apache.thrift.annotation.Nullable String _elem6; - for (int _i7 = 0; _i7 < _list5.size; ++_i7) - { - _elem6 = iprot.readString(); - struct.environment.add(_elem6); - } - } - struct.setEnvironmentIsSet(true); - struct.sessionId = iprot.readString(); - struct.setSessionIdIsSet(true); - } - } - - private static S scheme(org.apache.thrift.protocol.TProtocol proto) { - return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); - } - } - - public static class getDecisionByAttributes_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getDecisionByAttributes_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRING, (short)0); - private static final org.apache.thrift.protocol.TField EE_FIELD_DESC = new org.apache.thrift.protocol.TField("ee", org.apache.thrift.protocol.TType.STRUCT, (short)1); - - private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new getDecisionByAttributes_resultStandardSchemeFactory(); - private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new getDecisionByAttributes_resultTupleSchemeFactory(); - - public @org.apache.thrift.annotation.Nullable String success; // required - public @org.apache.thrift.annotation.Nullable EntitlementException ee; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"), - EE((short)1, "ee"); - - private static final java.util.Map byName = new java.util.HashMap(); - - static { - for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - @org.apache.thrift.annotation.Nullable - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - case 1: // EE - return EE; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - @org.apache.thrift.annotation.Nullable - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); - tmpMap.put(_Fields.EE, new org.apache.thrift.meta_data.FieldMetaData("ee", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, EntitlementException.class))); - metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getDecisionByAttributes_result.class, metaDataMap); - } - - public getDecisionByAttributes_result() { - } - - public getDecisionByAttributes_result( - String success, - EntitlementException ee) - { - this(); - this.success = success; - this.ee = ee; - } - - /** - * Performs a deep copy on other. - */ - public getDecisionByAttributes_result(getDecisionByAttributes_result other) { - if (other.isSetSuccess()) { - this.success = other.success; - } - if (other.isSetEe()) { - this.ee = new EntitlementException(other.ee); - } - } - - public getDecisionByAttributes_result deepCopy() { - return new getDecisionByAttributes_result(this); - } - - @Override - public void clear() { - this.success = null; - this.ee = null; - } - - @org.apache.thrift.annotation.Nullable - public String getSuccess() { - return this.success; - } - - public getDecisionByAttributes_result setSuccess(@org.apache.thrift.annotation.Nullable String success) { - this.success = success; - return this; - } - - public void unsetSuccess() { - this.success = null; - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return this.success != null; - } - - public void setSuccessIsSet(boolean value) { - if (!value) { - this.success = null; - } - } - - @org.apache.thrift.annotation.Nullable - public EntitlementException getEe() { - return this.ee; - } - - public getDecisionByAttributes_result setEe(@org.apache.thrift.annotation.Nullable EntitlementException ee) { - this.ee = ee; - return this; - } - - public void unsetEe() { - this.ee = null; - } - - /** Returns true if field ee is set (has been assigned a value) and false otherwise */ - public boolean isSetEe() { - return this.ee != null; - } - - public void setEeIsSet(boolean value) { - if (!value) { - this.ee = null; - } - } - - public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((String)value); - } - break; - - case EE: - if (value == null) { - unsetEe(); - } else { - setEe((EntitlementException)value); - } - break; - - } - } - - @org.apache.thrift.annotation.Nullable - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return getSuccess(); - - case EE: - return getEe(); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - case EE: - return isSetEe(); - } - throw new IllegalStateException(); - } - - @Override - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof getDecisionByAttributes_result) - return this.equals((getDecisionByAttributes_result)that); - return false; - } - - public boolean equals(getDecisionByAttributes_result that) { - if (that == null) - return false; - if (this == that) - return true; - - boolean this_present_success = true && this.isSetSuccess(); - boolean that_present_success = true && that.isSetSuccess(); - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (!this.success.equals(that.success)) - return false; - } - - boolean this_present_ee = true && this.isSetEe(); - boolean that_present_ee = true && that.isSetEe(); - if (this_present_ee || that_present_ee) { - if (!(this_present_ee && that_present_ee)) - return false; - if (!this.ee.equals(that.ee)) - return false; - } - - return true; - } - - @Override - public int hashCode() { - int hashCode = 1; - - hashCode = hashCode * 8191 + ((isSetSuccess()) ? 131071 : 524287); - if (isSetSuccess()) - hashCode = hashCode * 8191 + success.hashCode(); - - hashCode = hashCode * 8191 + ((isSetEe()) ? 131071 : 524287); - if (isSetEe()) - hashCode = hashCode * 8191 + ee.hashCode(); - - return hashCode; - } - - @Override - public int compareTo(getDecisionByAttributes_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); - if (lastComparison != 0) { - return lastComparison; - } - } - lastComparison = Boolean.valueOf(isSetEe()).compareTo(other.isSetEe()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetEe()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ee, other.ee); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - @org.apache.thrift.annotation.Nullable - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - scheme(iprot).read(iprot, this); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - scheme(oprot).write(oprot, this); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("getDecisionByAttributes_result("); - boolean first = true; - - sb.append("success:"); - if (this.success == null) { - sb.append("null"); - } else { - sb.append(this.success); - } - first = false; - if (!first) sb.append(", "); - sb.append("ee:"); - if (this.ee == null) { - sb.append("null"); - } else { - sb.append(this.ee); - } - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - // check for sub-struct validity - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private static class getDecisionByAttributes_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public getDecisionByAttributes_resultStandardScheme getScheme() { - return new getDecisionByAttributes_resultStandardScheme(); - } - } - - private static class getDecisionByAttributes_resultStandardScheme extends org.apache.thrift.scheme.StandardScheme { - - public void read(org.apache.thrift.protocol.TProtocol iprot, getDecisionByAttributes_result struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField schemeField; - iprot.readStructBegin(); - while (true) - { - schemeField = iprot.readFieldBegin(); - if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (schemeField.id) { - case 0: // SUCCESS - if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { - struct.success = iprot.readString(); - struct.setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - break; - case 1: // EE - if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { - struct.ee = new EntitlementException(); - struct.ee.read(iprot); - struct.setEeIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - struct.validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot, getDecisionByAttributes_result struct) throws org.apache.thrift.TException { - struct.validate(); - - oprot.writeStructBegin(STRUCT_DESC); - if (struct.success != null) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeString(struct.success); - oprot.writeFieldEnd(); - } - if (struct.ee != null) { - oprot.writeFieldBegin(EE_FIELD_DESC); - struct.ee.write(oprot); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - } - - private static class getDecisionByAttributes_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public getDecisionByAttributes_resultTupleScheme getScheme() { - return new getDecisionByAttributes_resultTupleScheme(); - } - } - - private static class getDecisionByAttributes_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme { - - @Override - public void write(org.apache.thrift.protocol.TProtocol prot, getDecisionByAttributes_result struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - java.util.BitSet optionals = new java.util.BitSet(); - if (struct.isSetSuccess()) { - optionals.set(0); - } - if (struct.isSetEe()) { - optionals.set(1); - } - oprot.writeBitSet(optionals, 2); - if (struct.isSetSuccess()) { - oprot.writeString(struct.success); - } - if (struct.isSetEe()) { - struct.ee.write(oprot); - } - } - - @Override - public void read(org.apache.thrift.protocol.TProtocol prot, getDecisionByAttributes_result struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - java.util.BitSet incoming = iprot.readBitSet(2); - if (incoming.get(0)) { - struct.success = iprot.readString(); - struct.setSuccessIsSet(true); - } - if (incoming.get(1)) { - struct.ee = new EntitlementException(); - struct.ee.read(iprot); - struct.setEeIsSet(true); - } - } - } - - private static S scheme(org.apache.thrift.protocol.TProtocol proto) { - return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); - } - } - -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/thrift/ThriftConfigConstants.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/thrift/ThriftConfigConstants.java deleted file mode 100644 index d6f6d39b9d55..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/thrift/ThriftConfigConstants.java +++ /dev/null @@ -1,33 +0,0 @@ -/* -* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.thrift; - -public class ThriftConfigConstants { - public static final String PARAM_ENABLE_THRIFT_SERVICE = - "EntitlementSettings.ThirftBasedEntitlementConfig.EnableThriftService"; - public static final String PARAM_RECEIVE_PORT = - "EntitlementSettings.ThirftBasedEntitlementConfig.ReceivePort"; - public static final String PARAM_CLIENT_TIMEOUT = - "EntitlementSettings.ThirftBasedEntitlementConfig.ClientTimeout"; - public static final String PARAM_KEYSTORE_LOCATION = - "EntitlementSettings.ThirftBasedEntitlementConfig.KeyStore.Location"; - public static final String PARAM_KEYSTORE_PASSWORD = - "EntitlementSettings.ThirftBasedEntitlementConfig.KeyStore.Password"; - public static final String PARAM_HOST_NAME = - "EntitlementSettings.ThirftBasedEntitlementConfig.ThriftHostName"; -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/thrift/ThriftEntitlementServiceImpl.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/thrift/ThriftEntitlementServiceImpl.java deleted file mode 100644 index 6965f16ef660..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/thrift/ThriftEntitlementServiceImpl.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.entitlement.thrift; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.thrift.TException; -import org.wso2.carbon.identity.entitlement.dto.AttributeDTO; -import org.wso2.carbon.identity.entitlement.dto.EntitledResultSetDTO; -import org.wso2.carbon.identity.thrift.authentication.ThriftAuthenticatorService; - -import java.util.List; - -/** - * Thrift based EntitlementService that is exposed by wrapping EntitlementService. - */ -public class ThriftEntitlementServiceImpl implements EntitlementService.Iface { - private static Log log = LogFactory.getLog(ThriftEntitlementServiceImpl.class); - /* Handler to ThriftAuthenticatorService which handles authentication to admin services. */ - private static ThriftAuthenticatorService thriftAuthenticatorService; - /* Handler to actual entitlement service which is going to be wrapped by thrift interface */ - private static org.wso2.carbon.identity.entitlement.EntitlementService entitlementService; - - /** - * Init the AuthenticationService handler to be used for authentication. - * - * @param authenticatorService ThriftAuthenticatorService - */ - public static void init(ThriftAuthenticatorService authenticatorService) { - thriftAuthenticatorService = authenticatorService; - entitlementService = new org.wso2.carbon.identity.entitlement.EntitlementService(); - - } - - /** - * Thrift based service method that wraps the same in EntitlementService - * - * @param request : XACML request - * @param sessionId : a sessionId obtained by authenticating to thrift based authentication - * service. - * @return - * @throws EntitlementException - * @throws TException - */ - public String getDecision(String request, String sessionId) throws EntitlementException, - TException { - try { - if (thriftAuthenticatorService != null && entitlementService != null) { - /* Authenticate session from thrift based authentication service. */ - if (thriftAuthenticatorService.isAuthenticated(sessionId)) { - try { - // perform the actual operation - return entitlementService.getDecision(request); - } catch (Exception e) { - String error = "Error while evaluating XACML decision from thrift service"; - log.error(error, e); - throw new EntitlementException(error); - } - } else { - String authErrorMsg = "User is not authenticated. Please login first."; - log.error(authErrorMsg); - throw new EntitlementException(authErrorMsg); - } - - } else { - String initErrorMsg = "Thrift Authenticator service or Entitlement " - + "service is not initialized."; - log.error(initErrorMsg); - throw new EntitlementException(initErrorMsg); - } - } catch (Exception e) { - String errorMsg = "Error occurred when invoking the Thrift based Entitlement Service."; - log.error(errorMsg, e); - throw new EntitlementException(errorMsg); - } - } - - public String getDecisionByAttributes(String subject, String resource, String action, - List environment, String sessionID) throws EntitlementException, TException { - try { - if (thriftAuthenticatorService != null && entitlementService != null) { - /* Authenticate session from thrift based authentication service. */ - if (thriftAuthenticatorService.isAuthenticated(sessionID)) { - try { - return entitlementService.getDecisionByAttributes(subject, resource, - action, environment.toArray(new String[environment.size()])); - } catch (Exception e) { - String error = "Error while evaluating XACML decision from thrift service"; - log.error(error, e); - throw new EntitlementException(error); - } - } else { - String authErrorMsg = "User is not authenticated. Please login first."; - log.error(authErrorMsg); - throw new EntitlementException(authErrorMsg); - } - - } else { - String initErrorMsg = "Thrift Authenticator service or Entitlement " - + "service is not initialized."; - log.error(initErrorMsg); - throw new EntitlementException(initErrorMsg); - } - } catch (Exception e) { - String errorMsg = "Error occurred when invoking the Thrift based Entitlement Service."; - log.error(errorMsg, e); - throw new EntitlementException(errorMsg); - } - } - - - public EntitledResultSetDTO getEntitledAttributes(String subjectName, String resourceName, - String subjectId, String action, boolean enableChildSearch, - String sessionID) throws EntitlementException, TException { - try { - if (thriftAuthenticatorService != null && entitlementService != null) { - /* Authenticate session from thrift based authentication service. */ - if (thriftAuthenticatorService.isAuthenticated(sessionID)) { - try { - return entitlementService.getEntitledAttributes(subjectName, resourceName, - subjectId, action, enableChildSearch); - } catch (Exception e) { - String error = "Error while evaluating XACML decision from thrift service"; - log.error(error, e); - throw new EntitlementException(error); - } - } else { - String authErrorMsg = "User is not authenticated. Please login first."; - log.error(authErrorMsg); - throw new EntitlementException(authErrorMsg); - } - - } else { - String initErrorMsg = "Thrift Authenticator service or Entitlement " - + "service is not initialized."; - log.error(initErrorMsg); - throw new EntitlementException(initErrorMsg); - } - } catch (Exception e) { - String errorMsg = "Error occurred when invoking the Thrift based Entitlement Service."; - log.error(errorMsg, e); - throw new EntitlementException(errorMsg); - } - } - - public EntitledResultSetDTO getAllEntitlements(String identifier, AttributeDTO[] givenAttributes, - String sessionID) throws EntitlementException, TException { - try { - if (thriftAuthenticatorService != null && entitlementService != null) { - /* Authenticate session from thrift based authentication service. */ - if (thriftAuthenticatorService.isAuthenticated(sessionID)) { - try { - return entitlementService.getAllEntitlements(identifier, givenAttributes); - } catch (Exception e) { - String error = "Error while evaluating XACML decision from thrift service"; - log.error(error, e); - throw new EntitlementException(error); - } - } else { - String authErrorMsg = "User is not authenticated. Please login first."; - log.error(authErrorMsg); - throw new EntitlementException(authErrorMsg); - } - - } else { - String initErrorMsg = "Thrift Authenticator service or Entitlement " - + "service is not initialized."; - log.error(initErrorMsg); - throw new EntitlementException(initErrorMsg); - } - } catch (Exception e) { - String errorMsg = "Error occurred when invoking the Thrift based Entitlement Service."; - log.error(errorMsg, e); - throw new EntitlementException(errorMsg); - } - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/wsxacml/WSXACMLMessageReceiver.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/wsxacml/WSXACMLMessageReceiver.java deleted file mode 100644 index c59d73588040..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/wsxacml/WSXACMLMessageReceiver.java +++ /dev/null @@ -1,523 +0,0 @@ -/* - * Copyright (c) 2012, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.wso2.carbon.identity.entitlement.wsxacml; - -import org.apache.axiom.om.OMAbstractFactory; -import org.apache.axiom.om.OMElement; -import org.apache.axiom.om.OMNamespace; -import org.apache.axiom.om.util.AXIOMUtil; -import org.apache.axiom.soap.SOAP11Constants; -import org.apache.axiom.soap.SOAP12Constants; -import org.apache.axiom.soap.SOAPEnvelope; -import org.apache.axiom.soap.SOAPFactory; -import org.apache.axis2.AxisFault; -import org.apache.axis2.context.MessageContext; -import org.apache.axis2.rpc.receivers.RPCMessageReceiver; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.xml.security.c14n.Canonicalizer; -import org.apache.xml.security.signature.XMLSignature; -import org.joda.time.DateTime; -import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; -import org.opensaml.saml.saml2.core.Assertion; -import org.opensaml.saml.saml2.core.Issuer; -import org.opensaml.saml.saml2.core.Response; -import org.opensaml.saml.saml2.core.Statement; -import org.opensaml.saml.saml2.core.impl.AssertionBuilder; -import org.opensaml.saml.saml2.core.impl.IssuerBuilder; -import org.opensaml.saml.saml2.core.impl.ResponseBuilder; -import org.opensaml.xacml.ctx.RequestType; -import org.opensaml.xacml.ctx.ResponseType; -import org.opensaml.xacml.profile.saml.XACMLAuthzDecisionQueryType; -import org.opensaml.xacml.profile.saml.XACMLAuthzDecisionStatementType; -import org.opensaml.xacml.profile.saml.impl.XACMLAuthzDecisionStatementTypeImplBuilder; -import org.opensaml.core.xml.XMLObject; -import org.opensaml.core.xml.XMLObjectBuilder; -import org.opensaml.core.xml.io.Marshaller; -import org.opensaml.core.xml.io.MarshallerFactory; -import org.opensaml.core.xml.io.Unmarshaller; -import org.opensaml.core.xml.io.UnmarshallerFactory; -import org.opensaml.security.x509.BasicX509Credential; -import org.opensaml.security.x509.X509Credential; -import org.opensaml.xmlsec.signature.KeyInfo; -import org.opensaml.xmlsec.signature.Signature; -import org.opensaml.xmlsec.signature.support.SignatureException; -import org.opensaml.xmlsec.signature.support.SignatureValidator; -import org.opensaml.xmlsec.signature.support.Signer; -import org.opensaml.xmlsec.signature.X509Certificate; -import org.opensaml.xmlsec.signature.X509Data; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.bootstrap.DOMImplementationRegistry; -import org.w3c.dom.ls.DOMImplementationLS; -import org.w3c.dom.ls.LSOutput; -import org.w3c.dom.ls.LSSerializer; -import org.wso2.carbon.core.util.KeyStoreManager; -import org.wso2.carbon.identity.core.util.IdentityUtil; -import org.wso2.carbon.identity.saml.common.util.SAMLInitializer; -import org.wso2.carbon.identity.entitlement.EntitlementException; - -import javax.xml.namespace.QName; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.security.PrivateKey; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.util.ArrayList; -import java.util.Base64; -import java.util.Iterator; -import java.util.List; - -public class WSXACMLMessageReceiver extends RPCMessageReceiver { - - private static Log log = LogFactory.getLog(WSXACMLMessageReceiver.class); - private static boolean isBootStrapped = false; - private static OMNamespace xacmlContextNS = OMAbstractFactory.getOMFactory() - .createOMNamespace("urn:oasis:names:tc:xacml:2.0:context:schema:os", "xacml-context"); - - /** - * Bootstrap the OpenSAML3 library only if it is not bootstrapped. - */ - public static void doBootstrap() { - - if (!isBootStrapped) { - try { - SAMLInitializer.doBootstrap(); - isBootStrapped = true; - } catch (org.opensaml.core.config.InitializationException e) { - log.error("Error in bootstrapping the OpenSAML3 library", e); - } - } - } - - /** - * Create the issuer object to be added - * - * @return : the issuer of the statements - */ - private static Issuer createIssuer() { - - IssuerBuilder issuer = (IssuerBuilder) XMLObjectProviderRegistrySupport.getBuilderFactory(). - getBuilder(Issuer.DEFAULT_ELEMENT_NAME); - Issuer issuerObject = issuer.buildObject(); - issuerObject.setValue("https://identity.carbon.wso2.org"); - issuerObject.setSPProvidedID("SPPProvierId"); - return issuerObject; - } - - /** - * Overloaded method to sign a SAML response - * - * @param response : SAML response to be signed - * @param signatureAlgorithm : algorithm to be used in signing - * @param cred : signing credentials - * @return signed SAML response - * @throws EntitlementException - */ - private static Response setSignature(Response response, String signatureAlgorithm, - X509Credential cred) throws EntitlementException { - doBootstrap(); - try { - Signature signature = (Signature) buildXMLObject(Signature.DEFAULT_ELEMENT_NAME); - signature.setSigningCredential(cred); - signature.setSignatureAlgorithm(signatureAlgorithm); - signature.setCanonicalizationAlgorithm(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); - - try { - KeyInfo keyInfo = (KeyInfo) buildXMLObject(KeyInfo.DEFAULT_ELEMENT_NAME); - X509Data data = (X509Data) buildXMLObject(X509Data.DEFAULT_ELEMENT_NAME); - X509Certificate cert = (X509Certificate) buildXMLObject(X509Certificate.DEFAULT_ELEMENT_NAME); - String value = Base64.getEncoder().encodeToString(cred.getEntityCertificate().getEncoded()); - cert.setValue(value); - data.getX509Certificates().add(cert); - keyInfo.getX509Datas().add(data); - signature.setKeyInfo(keyInfo); - } catch (CertificateEncodingException e) { - throw new EntitlementException("errorGettingCert"); - } - response.setSignature(signature); - List signatureList = new ArrayList(); - signatureList.add(signature); - //Marshall and Sign - MarshallerFactory marshallerFactory = XMLObjectProviderRegistrySupport.getMarshallerFactory(); - Marshaller marshaller = marshallerFactory.getMarshaller(response); - marshaller.marshall(response); - org.apache.xml.security.Init.init(); - Signer.signObjects(signatureList); - return response; - } catch (Exception e) { - throw new EntitlementException("Error When signing the assertion.", e); - } - } - - /** - * Create XMLObject from a given QName - * - * @param objectQName: QName of the object to be built into a XMLObject - * @return built xmlObject - * @throws EntitlementException - */ - private static XMLObject buildXMLObject(QName objectQName) throws EntitlementException { - - XMLObjectBuilder builder = XMLObjectProviderRegistrySupport.getBuilderFactory().getBuilder(objectQName); - if (builder == null) { - throw new EntitlementException("Unable to retrieve builder for object QName " - + objectQName); - } - return builder.buildObject(objectQName.getNamespaceURI(), objectQName.getLocalPart(), - objectQName.getPrefix()); - } - - /** - * Create basic credentials needed to generate signature using EntitlementServiceComponent - * - * @return basicX509Credential - */ - private static BasicX509Credential createBasicCredentials() { - - Certificate certificate = null; - PrivateKey issuerPK = null; - - KeyStoreManager keyMan = KeyStoreManager.getInstance(-1234); - - try { - certificate = keyMan.getDefaultPrimaryCertificate(); - issuerPK = keyMan.getDefaultPrivateKey(); - } catch (Exception e) { - log.error("Error occurred while getting the KeyStore from KeyManger.", e); - } - - BasicX509Credential basicCredential = new BasicX509Credential((java.security.cert.X509Certificate) certificate, issuerPK); - - return basicCredential; - } - - /** - * Set relevant xacml namespace to all the children in the given iterator. * - * - * @param iterator: Iterator for all children inside OMElement - */ - private static void setXACMLNamespace(Iterator iterator) { - - while (iterator.hasNext()) { - OMElement omElement2 = (OMElement) iterator.next(); - omElement2.setNamespace(xacmlContextNS); - if (omElement2.getChildElements().hasNext()) { - setXACMLNamespace(omElement2.getChildElements()); - } - } - } - - @Override - public void invokeBusinessLogic(MessageContext inMessageContext, MessageContext outMessageContext) - throws AxisFault { - - try { - OMElement xacmlAuthzDecisionQueryElement = inMessageContext.getEnvelope().getBody().getFirstElement(); - String xacmlAuthzDecisionQuery = xacmlAuthzDecisionQueryElement.toString(); - String xacmlRequest = extractXACMLRequest(xacmlAuthzDecisionQuery); - String serviceClass; - try { - serviceClass = inMessageContext.getAxisService().getParameterValue("XACMLHandlerImplClass"). - toString().trim(); - } catch (NullPointerException e) { - log.error("WS-XACML ServiceClass not specified in service context"); - throw new AxisFault("WS-XACML ServiceClass not specified in service context"); - } - if (serviceClass == null || serviceClass.length() == 0) { - log.error("WS-XACML ServiceClass not specified in service context"); - throw new AxisFault("WS-XACML ServiceClass not specified in service context"); - } - XACMLHandler xacmlHandler = (XACMLHandler) Class.forName(serviceClass).newInstance(); - xacmlRequest = xacmlRequest.replaceAll("xacml-context:", ""); - String xacmlResponse = xacmlHandler.XACMLAuthzDecisionQuery(xacmlRequest); - String samlResponse = secureXACMLResponse(xacmlResponse); - OMElement samlResponseElement = AXIOMUtil.stringToOM(samlResponse); - SOAPEnvelope outSOAPEnvelope = createDefaultSOAPEnvelope(inMessageContext); - if (outSOAPEnvelope != null) { - outSOAPEnvelope.getBody().addChild(samlResponseElement); - outMessageContext.setEnvelope(outSOAPEnvelope); - } else { - throw new Exception("SOAP envelope can not be null"); - } - } catch (Exception e) { - log.error("Error occurred while evaluating XACML request.", e); - throw new AxisFault("Error occurred while evaluating XACML request.", e); - } - } - - /* Creating a soap response according the the soap namespce uri */ - private SOAPEnvelope createDefaultSOAPEnvelope(MessageContext inMsgCtx) { - - String soapNamespace = inMsgCtx.getEnvelope().getNamespace() - .getNamespaceURI(); - SOAPFactory soapFactory = null; - if (soapNamespace.equals(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI)) { - soapFactory = OMAbstractFactory.getSOAP11Factory(); - } else if (soapNamespace - .equals(SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI)) { - soapFactory = OMAbstractFactory.getSOAP12Factory(); - } else { - log.error("Unknown SOAP Envelope"); - } - if (soapFactory != null) { - return soapFactory.getDefaultEnvelope(); - } - - return null; - } - - /** - * Extract XACML request from passed in SAML-XACMLAuthzDecisionQuery - * - * @param decisionQuery : XACMLAuthxDecisionQuery passed in from PEP as a String - * @return xacml Request - * @throws Exception - */ - private String extractXACMLRequest(String decisionQuery) throws Exception { - - RequestType xacmlRequest = null; - doBootstrap(); - String queryString = null; - XACMLAuthzDecisionQueryType xacmlAuthzDecisionQuery; - try { - xacmlAuthzDecisionQuery = (XACMLAuthzDecisionQueryType) unmarshall(decisionQuery); - //Access the XACML request only if Issuer and the Signature are valid. - if (validateIssuer(xacmlAuthzDecisionQuery.getIssuer())) { - if (validateSignature(xacmlAuthzDecisionQuery.getSignature())) { - xacmlRequest = xacmlAuthzDecisionQuery.getRequest(); - } else { - log.debug("The submitted signature is not valid!"); - } - } else { - log.debug("The submitted issuer is not valid!"); - } - - if (xacmlRequest != null) { - queryString = marshall(xacmlRequest); - queryString = queryString.replace("", "").replace("\n", ""); - } - return queryString; - } catch (Exception e) { - log.error("Error unmarshalling the XACMLAuthzDecisionQuery.", e); - throw new Exception("Error unmarshalling the XACMLAuthzDecisionQuery.", e); - } - - } - - /** - * Constructing the SAML or XACML Objects from a String - * - * @param xmlString Decoded SAML or XACML String - * @return SAML or XACML Object - * @throws org.wso2.carbon.identity.entitlement.EntitlementException - */ - public XMLObject unmarshall(String xmlString) throws EntitlementException { - - try { - doBootstrap(); - DocumentBuilderFactory documentBuilderFactory = IdentityUtil.getSecuredDocumentBuilderFactory(); - - DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder(); - Document document = docBuilder.parse(new ByteArrayInputStream(xmlString.trim().getBytes())); - Element element = document.getDocumentElement(); - UnmarshallerFactory unmarshallerFactory = XMLObjectProviderRegistrySupport.getUnmarshallerFactory(); - Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element); - return unmarshaller.unmarshall(element); - } catch (Exception e) { - log.error("Error in constructing XML(SAML or XACML) Object from the encoded String", e); - throw new EntitlementException("Error in constructing XML(SAML or XACML) from the encoded String ", e); - } - } - - /** - * Check for the validity of the issuer - * - * @param issuer :who makes the claims inside the Query - * @return whether the issuer is valid - */ - private boolean validateIssuer(Issuer issuer) { - - boolean isValidated = false; - - if (issuer.getValue().equals("https://identity.carbon.wso2.org") - && issuer.getSPProvidedID().equals("SPPProvierId")) { - isValidated = true; - } - return isValidated; - } - - /** - * ` - * Serialize XML objects - * - * @param xmlObject : XACML or SAML objects to be serialized - * @return serialized XACML or SAML objects - * @throws EntitlementException - */ - private String marshall(XMLObject xmlObject) throws EntitlementException { - - try { - doBootstrap(); - System.setProperty("javax.xml.parsers.DocumentBuilderFactory", - "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl"); - - MarshallerFactory marshallerFactory = XMLObjectProviderRegistrySupport.getMarshallerFactory(); - Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject); - Element element = marshaller.marshall(xmlObject); - - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); - DOMImplementationLS impl = - (DOMImplementationLS) registry.getDOMImplementation("LS"); - LSSerializer writer = impl.createLSSerializer(); - LSOutput output = impl.createLSOutput(); - output.setByteStream(byteArrayOutputStream); - writer.write(element, output); - return byteArrayOutputStream.toString(); - } catch (Exception e) { - log.error("Error Serializing the SAML Response"); - throw new EntitlementException("Error Serializing the SAML Response", e); - } - } - - /** - * Check the validity of the Signature - * - * @param signature : XML Signature that authenticates the assertion - * @return whether the signature is valid - * @throws Exception - */ - private boolean validateSignature(Signature signature) throws Exception { - - boolean isSignatureValid = false; - - try { - SignatureValidator.validate(signature, getPublicX509CredentialImpl()); - isSignatureValid = true; - } catch (SignatureException e) { - log.warn("Signature validation failed for the public X509 credential: " + getPublicX509CredentialImpl(), e); - } catch (Exception e) { - throw new Exception("Error in getting public X509Credentials to validate signature.", e); - } - return isSignatureValid; - } - - /** - * get a org.wso2.carbon.identity.entitlement.wsxacml.X509CredentialImpl using RegistryService - * - * @return created X509Credential - */ - private X509CredentialImpl getPublicX509CredentialImpl() throws Exception { - - X509CredentialImpl credentialImpl; - KeyStoreManager keyStoreManager; - try { - keyStoreManager = KeyStoreManager.getInstance(-1234); - // load the default pub. cert using the configuration in carbon.xml - java.security.cert.X509Certificate cert = keyStoreManager.getDefaultPrimaryCertificate(); - credentialImpl = new X509CredentialImpl(cert); - return credentialImpl; - } catch (Exception e) { - log.error("Error instantiating an org.wso2.carbon.identity.entitlement.wsxacml.X509CredentialImpl " + - "object for the public cert.", e); - throw new Exception("Error instantiating an org.wso2.carbon.identity.entitlement.wsxacml.X509CredentialImpl " + - "object for the public cert.", e); - } - } - - /** - * Encapsulates the passed in xacml response into a saml response - * - * @param xacmlResponse : xacml response returned from PDP - * @return saml response - * @throws Exception - */ - public String secureXACMLResponse(String xacmlResponse) throws Exception { - - ResponseType responseType; - String responseString; - doBootstrap(); - - try { - responseType = (ResponseType) unmarshall(formatResponse(xacmlResponse)); - } catch (Exception e) { - log.error("Error while unmarshalling the formatted XACML response.", e); - throw new EntitlementException("Error while unmarshalling the formatted XACML response.", e); - } - XACMLAuthzDecisionStatementTypeImplBuilder xacmlauthz = (XACMLAuthzDecisionStatementTypeImplBuilder) - XMLObjectProviderRegistrySupport.getBuilderFactory(). - getBuilder(XACMLAuthzDecisionStatementType.TYPE_NAME_XACML20); - XACMLAuthzDecisionStatementType xacmlAuthzDecisionStatement = xacmlauthz - .buildObject(Statement.DEFAULT_ELEMENT_NAME, XACMLAuthzDecisionStatementType.TYPE_NAME_XACML20); - xacmlAuthzDecisionStatement.setResponse(responseType); - AssertionBuilder assertionBuilder = (AssertionBuilder) XMLObjectProviderRegistrySupport.getBuilderFactory() - .getBuilder(Assertion.DEFAULT_ELEMENT_NAME); - DateTime currentTime = new DateTime(); - Assertion assertion = assertionBuilder.buildObject(); - assertion.setVersion(org.opensaml.saml.common.SAMLVersion.VERSION_20); - assertion.setIssuer(createIssuer()); - assertion.setIssueInstant(currentTime); - assertion.getStatements().add(xacmlAuthzDecisionStatement); - ResponseBuilder builder = (ResponseBuilder) XMLObjectProviderRegistrySupport.getBuilderFactory() - .getBuilder(Response.DEFAULT_ELEMENT_NAME); - Response response = builder.buildObject(); - response.getAssertions().add(assertion); - response.setIssuer(createIssuer()); - DateTime issueInstant = new DateTime(); - response.setIssueInstant(issueInstant); - response = setSignature(response, XMLSignature.ALGO_ID_SIGNATURE_RSA, createBasicCredentials()); - try { - responseString = marshall(response); - responseString = responseString.replace("\n", ""); - return responseString; - } catch (EntitlementException e) { - log.error("Error occurred while marshalling the SAML Response.", e); - throw new Exception("Error occurred while marshalling the SAML Response.", e); - } - } - - /** - * Format the sent in response as required by OpenSAML - * - * @param xacmlResponse : received XACML response - * @return formatted response - */ - private String formatResponse(String xacmlResponse) throws Exception { - - xacmlResponse = xacmlResponse.replace("\n", ""); - OMElement omElemnt; - - try { - omElemnt = org.apache.axiom.om.util.AXIOMUtil.stringToOM(xacmlResponse); - omElemnt.setNamespace(xacmlContextNS); - if (omElemnt.getChildren() != null) { - Iterator childIterator = omElemnt.getChildElements(); - setXACMLNamespace(childIterator); - } - } catch (Exception e) { - log.error("Error while generating the OMElement from the XACML request.", e); - throw new Exception("Error while generating the OMElement from the XACML request.", e); - } - - return omElemnt.toString(); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/wsxacml/X509CredentialImpl.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/wsxacml/X509CredentialImpl.java deleted file mode 100644 index a4ca7901464c..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/wsxacml/X509CredentialImpl.java +++ /dev/null @@ -1,131 +0,0 @@ -/* -* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.wsxacml; - -import org.opensaml.security.credential.Credential; -import org.opensaml.security.credential.CredentialContextSet; -import org.opensaml.security.credential.UsageType; -import org.opensaml.security.x509.X509Credential; - -import javax.crypto.SecretKey; -import java.math.BigInteger; -import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.cert.X509CRL; -import java.security.cert.X509Certificate; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.RSAPublicKeySpec; -import java.util.Collection; - -/** - * X509Credential implementation for signature verification of self issued tokens. The key is - * constructed from modulus and exponent - */ -public class X509CredentialImpl implements X509Credential { - - private PublicKey publicKey = null; - private X509Certificate signingCert = null; - - /** - * The key is constructed from modulus and exponent. - * - * @param modulus - * @param publicExponent - * @throws NoSuchAlgorithmException - * @throws InvalidKeySpecException - */ - public X509CredentialImpl(BigInteger modulus, BigInteger publicExponent) - throws NoSuchAlgorithmException, InvalidKeySpecException { - RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, publicExponent); - KeyFactory keyFactory = KeyFactory.getInstance("RSA"); - publicKey = keyFactory.generatePublic(spec); - } - - public X509CredentialImpl(X509Certificate cert) { - publicKey = cert.getPublicKey(); - signingCert = cert; - } - - /** - * Retrieves the publicKey - */ - public PublicKey getPublicKey() { - return publicKey; - } - - public X509Certificate getSigningCert() { - return signingCert; - } - - // ********** Not implemented ************************************************************** - - public X509Certificate getEntityCertificate() { - // TODO Auto-generated method stub - return null; - } - - public Collection getCRLs() { - // TODO Auto-generated method stub - return null; - } - - public Collection getEntityCertificateChain() { - // TODO Auto-generated method stub - return null; - } - - /*** - * Get the credential context set. - * @return This method is not supported so, the return is null. - */ - public CredentialContextSet getCredentialContextSet() { - return null; - } - - public Class getCredentialType() { - // TODO Auto-generated method stub - return null; - } - - public String getEntityId() { - // TODO Auto-generated method stub - return null; - } - - public Collection getKeyNames() { - // TODO Auto-generated method stub - return null; - } - - public PrivateKey getPrivateKey() { - // TODO Auto-generated method stub - return null; - } - - public SecretKey getSecretKey() { - // TODO Auto-generated method stub - return null; - } - - public UsageType getUsageType() { - // TODO Auto-generated method stub - return null; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/wsxacml/XACMLHandler.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/wsxacml/XACMLHandler.java deleted file mode 100644 index ff439d3990f9..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/wsxacml/XACMLHandler.java +++ /dev/null @@ -1,24 +0,0 @@ -/* -* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. 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.wso2.carbon.identity.entitlement.wsxacml; - -public interface XACMLHandler { - - String XACMLAuthzDecisionQuery(String xacmlRequest) throws Exception; - -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/resources/META-INF/component.xml b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/resources/META-INF/component.xml deleted file mode 100644 index fe8b787f3204..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/resources/META-INF/component.xml +++ /dev/null @@ -1,132 +0,0 @@ - - - - - Identity - /permission/admin/manage/identity - - - Entitlement Management - /permission/admin/manage/identity/entitlement - - - - - Entitlement PAP Management - /permission/admin/manage/identity/entitlement/pap - - - - - Entitlement Policy Management - /permission/admin/manage/identity/entitlement/pap/policy - - - Create - /permission/admin/manage/identity/entitlement/pap/policy/create - - - View - /permission/admin/manage/identity/entitlement/pap/policy/view - - - Update - /permission/admin/manage/identity/entitlement/pap/policy/update - - - Delete - /permission/admin/manage/identity/entitlement/pap/policy/delete - - - Publish - /permission/admin/manage/identity/entitlement/pap/policy/publish - - - Demote - /permission/admin/manage/identity/entitlement/pap/policy/demote - - - Enable - /permission/admin/manage/identity/entitlement/pap/policy/enable - - - Rollback - /permission/admin/manage/identity/entitlement/pap/policy/rollback - - - Order - /permission/admin/manage/identity/entitlement/pap/policy/order - - - List - /permission/admin/manage/identity/entitlement/pap/policy/list - - - - - - Entitlement Subscriber Management - /permission/admin/manage/identity/entitlement/pap/subscriber - - - Create - /permission/admin/manage/identity/entitlement/pap/subscriber/create - - - View - /permission/admin/manage/identity/entitlement/pap/subscriber/view - - - Update - /permission/admin/manage/identity/entitlement/pap/subscriber/update - - - Delete - /permission/admin/manage/identity/entitlement/pap/subscriber/delete - - - List - /permission/admin/manage/identity/entitlement/pap/subscriber/list - - - - - Entitlement PDP Management - /permission/admin/manage/identity/entitlement/pdp - - - Manage - /permission/admin/manage/identity/entitlement/pdp/manage - - - View - /permission/admin/manage/identity/entitlement/pdp/view - - - Test - /permission/admin/manage/identity/entitlement/pdp/test - - - - - Entitlement PEP Management - /permission/admin/manage/identity/entitlement/pep - - - \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/resources/META-INF/services.xml b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/resources/META-INF/services.xml deleted file mode 100644 index a0edccb3c940..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/resources/META-INF/services.xml +++ /dev/null @@ -1,214 +0,0 @@ - - - - - - https - - - To administer Identity Entitlement Policy related functionality. - - org.wso2.carbon.identity.entitlement.EntitlementPolicyAdminService - - - - /permission/admin/manage/identity/entitlement/pap/policy/create - - - /permission/admin/manage/identity/entitlement/pap/policy/create - - - /permission/admin/manage/identity/entitlement/pap/subscriber/create - - - /permission/admin/manage/identity/entitlement/pap/subscriber/delete - - - /permission/admin/manage/identity/entitlement/pap/policy/demote - - - /permission/admin/manage/identity/entitlement/pap/policy/enable - - - /permission/admin/manage/identity/entitlement/pap/policy/view - - - /permission/admin/manage/identity/entitlement/pap/policy/list - - - /permission/admin/manage/identity/entitlement/pap/policy/view - - - /permission/admin/manage/identity/entitlement/pap/policy/view - - - /permission/admin/manage/identity/entitlement/pap/policy/view - - - /permission/admin/manage/identity/entitlement/pap/policy/view - - - /permission/admin/manage/identity/entitlement/pap/policy/view - - - /permission/admin/manage/identity/entitlement/pap/policy/list - - - /permission/admin/manage/identity/entitlement/pap/subscriber/create - - - /permission/admin/manage/identity/entitlement/pap/policy/view - - - /permission/admin/manage/identity/entitlement/pap/subscriber/view - - - /permission/admin/manage/identity/entitlement/pap/subscriber/list - - - /permission/admin/manage/identity/entitlement/pap/policy/create, - /permission/admin/manage/identity/entitlement/pap/policy/update - - - /permission/admin/manage/identity/entitlement/pap/policy/order - - - /permission/admin/manage/identity/entitlement/pap/policy/publish - - - /permission/admin/manage/identity/entitlement/pap/policy/publish - - - /permission/admin/manage/identity/entitlement/pap/policy/publish - - - /permission/admin/manage/identity/entitlement/pap/policy/delete - - - /permission/admin/manage/identity/entitlement/pap/policy/delete - - - /permission/admin/manage/identity/entitlement/pap/policy/rollback - - - /permission/admin/manage/identity/entitlement/pap/policy/update - - - /permission/admin/manage/identity/entitlement/pap/subscriber/update - - - - - - https - - - To administer Identity Entitlement PDP related functionality. - - org.wso2.carbon.identity.entitlement.EntitlementAdminService - - - /permission/admin/manage/identity/entitlement/pdp/manage - - - /permission/admin/manage/identity/entitlement/pdp/manage - - - /permission/admin/manage/identity/entitlement/pdp/manage - - - /permission/admin/manage/identity/entitlement/pdp/manage - - - /permission/admin/manage/identity/entitlement/pdp/manage - - - /permission/admin/manage/identity/entitlement/pdp/manage - - - /permission/admin/manage/identity/entitlement/pdp/manage - - - /permission/admin/manage/identity/entitlement/pdp/manage - - - /permission/admin/manage/identity/entitlement/pdp/manage - - - /permission/admin/manage/identity/entitlement/pdp/test - - - /permission/admin/manage/identity/entitlement/pdp/test - - - /permission/admin/manage/identity/entitlement/pdp/view - - - /permission/admin/manage/identity/entitlement/pdp/view - - - /permission/admin/manage/identity/entitlement/pdp/view - - - /permission/admin/manage/identity/entitlement/pdp/view - - - /permission/admin/manage/identity/entitlement/pdp/view - - - /permission/admin/manage/identity/entitlement/pdp/manage - - - /permission/admin/manage/identity/entitlement/pdp/manage - - - /permission/admin/manage/identity/entitlement/pdp/manage - - - /permission/admin/manage/identity/entitlement/pdp/manage - - - - - - - https - - - User Entitlement related functionality. - - org.wso2.carbon.identity.entitlement.EntitlementService - - /permission/admin/manage/identity/pep - - - - - https - - - XACMLAuthzDecisionQuery - - - org.wso2.carbon.identity.entitlement.EntitlementService - /permission/admin/manage/identity/pep - - true - true - diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/resources/entitlement.thrift b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/resources/entitlement.thrift deleted file mode 100644 index 5119ba61f1f9..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/resources/entitlement.thrift +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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. - */ - -namespace java org.wso2.carbon.identity.entitlement.thrift - -exception EntitlementException { - 1: required string message -} - -service EntitlementService { - string getDecision ( - 1: required string request - 2: required string sessionId) throws (1:EntitlementException ee) - string getDecisionByAttributes ( - 1: required string subject - 2: required string resource - 3: required string action - 4: required list environment - 5: required string sessionId) throws (1:EntitlementException ee) -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/resources/pip-config.xml b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/resources/pip-config.xml deleted file mode 100644 index 2ce7618c04ee..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/resources/pip-config.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/resources/template.xml b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/resources/template.xml deleted file mode 100644 index 7b8972305fce..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/resources/template.xml +++ /dev/null @@ -1,96 +0,0 @@ - - - Sample XACML Authorization Policy - - - - - - - - - - - - http://localhost:8280/services/echo/ - - - - - - - - - - - - - - - - - read - - - - - - - - admin - - - - - - - - - - - - - - - - read - - - - - - - - admin - - - - - - \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/resources/xacml-request.xml b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/resources/xacml-request.xml deleted file mode 100644 index fd3de8cb56a9..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/resources/xacml-request.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - prabath - - - prabath@wso2.com - - - - - http://localhost:8280/services/echo/echoString - - - - - Read - - - - - - - - \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/resources/xacml1.xsd b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/resources/xacml1.xsd deleted file mode 100644 index 24776f33f216..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/resources/xacml1.xsd +++ /dev/null @@ -1,253 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/resources/xacml2.xsd b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/resources/xacml2.xsd deleted file mode 100644 index 255b22cf4fbb..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/resources/xacml2.xsd +++ /dev/null @@ -1,407 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/resources/xacml3.xsd b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/resources/xacml3.xsd deleted file mode 100644 index f975e3c0455c..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/resources/xacml3.xsd +++ /dev/null @@ -1,345 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/resources/xml.xsd b/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/resources/xml.xsd deleted file mode 100644 index aea7d0db0a42..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/main/resources/xml.xsd +++ /dev/null @@ -1,287 +0,0 @@ - - - - - - -

    -

    About the XML namespace

    - -
    -

    - This schema document describes the XML namespace, in a form - suitable for import by other schema documents. -

    -

    - See - http://www.w3.org/XML/1998/namespace.html and - - http://www.w3.org/TR/REC-xml for information - about this namespace. -

    -

    - Note that local names in this namespace are intended to be - defined only by the World Wide Web Consortium or its subgroups. - The names currently defined in this namespace are listed below. - They should not be used with conflicting semantics by any Working - Group, specification, or document instance. -

    -

    - See further below in this document for more information about how to refer to this schema document from your own - XSD schema documents and about the - namespace-versioning policy governing this schema document. -

    -
    -
    - - - - - - -
    - -

    lang (as an attribute name)

    -

    - denotes an attribute whose value - is a language code for the natural language of the content of - any element; its value is inherited. This name is reserved - by virtue of its definition in the XML specification.

    - -
    -
    -

    Notes

    -

    - Attempting to install the relevant ISO 2- and 3-letter - codes as the enumerated possible values is probably never - going to be a realistic possibility. -

    -

    - See BCP 47 at - http://www.rfc-editor.org/rfc/bcp/bcp47.txt - and the IANA language subtag registry at - - http://www.iana.org/assignments/language-subtag-registry - for further information. -

    -

    - The union allows for the 'un-declaration' of xml:lang with - the empty string. -

    -
    -
    -
    - - - - - - - - - -
    - - - - -
    - -

    space (as an attribute name)

    -

    - denotes an attribute whose - value is a keyword indicating what whitespace processing - discipline is intended for the content of the element; its - value is inherited. This name is reserved by virtue of its - definition in the XML specification.

    - -
    -
    -
    - - - - - - -
    - - - -
    - -

    base (as an attribute name)

    -

    - denotes an attribute whose value - provides a URI to be used as the base for interpreting any - relative URIs in the scope of the element on which it - appears; its value is inherited. This name is reserved - by virtue of its definition in the XML Base specification.

    - -

    - See http://www.w3.org/TR/xmlbase/ - for information about this attribute. -

    -
    -
    -
    -
    - - - - -
    - -

    id (as an attribute name)

    -

    - denotes an attribute whose value - should be interpreted as if declared to be of type ID. - This name is reserved by virtue of its definition in the - xml:id specification.

    - -

    - See http://www.w3.org/TR/xml-id/ - for information about this attribute. -

    -
    -
    -
    -
    - - - - - - - - - - -
    - -

    Father (in any context at all)

    - -
    -

    - denotes Jon Bosak, the chair of - the original XML Working Group. This name is reserved by - the following decision of the W3C XML Plenary and - XML Coordination groups: -

    -
    -

    - In appreciation for his vision, leadership and - dedication the W3C XML Plenary on this 10th day of - February, 2000, reserves for Jon Bosak in perpetuity - the XML name "xml:Father". -

    -
    -
    -
    -
    -
    - - - -
    -

    About this schema document

    - -
    -

    - This schema defines attributes and an attribute group suitable - for use by schemas wishing to allow xml:base, - xml:lang, xml:space or - xml:id attributes on elements they define. -

    -

    - To enable this, such a schema must import this schema for - the XML namespace, e.g. as follows: -

    -
    -          <schema . . .>
    -           . . .
    -           <import namespace="http://www.w3.org/XML/1998/namespace"
    -                      schemaLocation="http://www.w3.org/2001/xml.xsd"/>
    -     
    -

    - or -

    -
    -           <import namespace="http://www.w3.org/XML/1998/namespace"
    -                      schemaLocation="http://www.w3.org/2009/01/xml.xsd"/>
    -     
    -

    - Subsequently, qualified reference to any of the attributes or the - group defined below will have the desired effect, e.g. -

    -
    -          <type . . .>
    -           . . .
    -           <attributeGroup ref="xml:specialAttrs"/>
    -     
    -

    - will define a type which will schema-validate an instance element - with any of those attributes. -

    -
    -
    -
    -
    - - - -
    -

    Versioning policy for this schema document

    -
    -

    - In keeping with the XML Schema WG's standard versioning - policy, this schema document will persist at - - http://www.w3.org/2009/01/xml.xsd. -

    -

    - At the date of issue it can also be found at - - http://www.w3.org/2001/xml.xsd. -

    -

    - The schema document at that URI may however change in the future, - in order to remain compatible with the latest version of XML - Schema itself, or with the XML namespace itself. In other words, - if the XML Schema or XML namespaces change, the version of this - document at - http://www.w3.org/2001/xml.xsd - - will change accordingly; the version at - - http://www.w3.org/2009/01/xml.xsd - - will not change. -

    -

    - Previous dated (and unchanging) versions of this schema - document are at: -

    - -
    -
    -
    -
    - - - diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/ConfigPersistenceManagerFailureTest.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/ConfigPersistenceManagerFailureTest.java deleted file mode 100644 index 23104c54e152..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/ConfigPersistenceManagerFailureTest.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.mockito.Mock; -import org.mockito.MockedStatic; -import org.mockito.MockitoAnnotations; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.common.testng.WithCarbonHome; -import org.wso2.carbon.identity.common.testng.WithRealmService; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.internal.EntitlementConfigHolder; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; -import org.wso2.carbon.identity.entitlement.persistence.cache.CacheBackedConfigDAO; -import org.wso2.carbon.registry.core.Collection; -import org.wso2.carbon.registry.core.Registry; -import org.wso2.carbon.registry.core.exceptions.RegistryException; - -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; - -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mockStatic; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertThrows; -import static org.wso2.carbon.identity.entitlement.PDPConstants.Algorithms.DENY_OVERRIDES; -import static org.wso2.carbon.identity.entitlement.PDPConstants.Algorithms.PERMIT_OVERRIDES; -import static org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_ID; - -/** - * This class tests the failure scenarios of Database or Registry in ConfigPersistenceManager implementations. - */ -@WithCarbonHome -@WithRealmService(injectToSingletons = {EntitlementConfigHolder.class}, initUserStoreManager = true) -public class ConfigPersistenceManagerFailureTest { - - @Mock - private CacheBackedConfigDAO mockedConfigDAO; - - @Mock - private Registry mockedRegistry; - - @Mock - private Collection mockedCollection; - - MockedStatic entitlementServiceComponent; - - private JDBCConfigPersistenceManager jdbcConfigPersistenceManager; - private RegistryConfigPersistenceManager registryConfigPersistenceManager; - private HybridConfigPersistenceManager hybridConfigPersistenceManager; - - @BeforeMethod - public void setUp() throws Exception { - - MockitoAnnotations.openMocks(this); - jdbcConfigPersistenceManager = new JDBCConfigPersistenceManager(); - setPrivateStaticFinalField(JDBCConfigPersistenceManager.class, "configDAO", mockedConfigDAO); - - entitlementServiceComponent = mockStatic(EntitlementServiceComponent.class); - entitlementServiceComponent.when(() -> EntitlementServiceComponent.getGovernanceRegistry(anyInt())) - .thenReturn(mockedRegistry); - registryConfigPersistenceManager = new RegistryConfigPersistenceManager(); - - hybridConfigPersistenceManager = new HybridConfigPersistenceManager(); - setPrivateStaticFinalField(HybridConfigPersistenceManager.class, "configDAO", mockedConfigDAO); - } - - @AfterMethod - public void tearDown() throws Exception { - - entitlementServiceComponent.close(); - setPrivateStaticFinalField(JDBCConfigPersistenceManager.class, "configDAO", - CacheBackedConfigDAO.getInstance()); - setPrivateStaticFinalField(HybridConfigPersistenceManager.class, "configDAO", - CacheBackedConfigDAO.getInstance()); - } - - @Test - public void testGetAlgorithmWhenDatabaseErrorHappened() throws Exception { - - when(mockedConfigDAO.getPolicyCombiningAlgorithm(anyInt())).thenThrow(new EntitlementException("")); - String globalPolicyAlgorithmName = jdbcConfigPersistenceManager.getGlobalPolicyAlgorithmName(); - assertEquals(globalPolicyAlgorithmName, DENY_OVERRIDES); - } - - @Test - public void testAddAlgorithmWhenResourceCheckFailed() throws Exception { - - when(mockedConfigDAO.getPolicyCombiningAlgorithm(anyInt())).thenThrow(new EntitlementException("")); - jdbcConfigPersistenceManager.addOrUpdateGlobalPolicyAlgorithm(PERMIT_OVERRIDES); - verify(mockedConfigDAO, never()).updatePolicyCombiningAlgorithm(anyString(), anyInt()); - verify(mockedConfigDAO, times(1)).insertPolicyCombiningAlgorithm(PERMIT_OVERRIDES, SUPER_TENANT_ID); - } - - @Test - public void testAddAlgorithmWhenDatabaseErrorHappened() throws Exception { - - when(mockedConfigDAO.getPolicyCombiningAlgorithm(anyInt())).thenReturn(null); - doThrow(new EntitlementException("")).when(mockedConfigDAO) - .insertPolicyCombiningAlgorithm(anyString(), anyInt()); - assertThrows(EntitlementException.class, - () -> jdbcConfigPersistenceManager.addOrUpdateGlobalPolicyAlgorithm(PERMIT_OVERRIDES)); - } - - @Test - public void testGetAlgorithmWhenRegistryErrorHappened() throws Exception { - - when(mockedRegistry.resourceExists(anyString())).thenThrow(new RegistryException("")); - String actualAlgorithm = registryConfigPersistenceManager.getGlobalPolicyAlgorithmName(); - assertEquals(actualAlgorithm, DENY_OVERRIDES); - } - - @Test - public void testAddAlgorithmWhenRegistryErrorHappened() throws Exception { - - when(mockedRegistry.resourceExists(anyString())).thenThrow(new RegistryException("")); - assertThrows(EntitlementException.class, - () -> registryConfigPersistenceManager.addOrUpdateGlobalPolicyAlgorithm(PERMIT_OVERRIDES)); - } - - @Test - public void testDeleteAlgorithmWhenRegistryErrorHappened() throws Exception { - - when(mockedRegistry.resourceExists(anyString())).thenReturn(true); - doThrow(new RegistryException("")).when(mockedRegistry).delete(anyString()); - assertThrows(EntitlementException.class, () -> registryConfigPersistenceManager.deleteGlobalPolicyAlgorithm()); - } - - @Test - public void testGetAlgorithmViaHybridManagerWhenDatabaseErrorHappened() throws Exception { - - when(mockedConfigDAO.getPolicyCombiningAlgorithm(anyInt())).thenThrow(new EntitlementException("")); - when(mockedRegistry.resourceExists(anyString())).thenReturn(false); - String globalPolicyAlgorithmName = hybridConfigPersistenceManager.getGlobalPolicyAlgorithmName(); - assertEquals(globalPolicyAlgorithmName, DENY_OVERRIDES); - } - - @Test - public void testAddAlgorithmViaHybridManagerWhenRegistryResourceDeletionFailed() throws Exception { - - when(mockedRegistry.resourceExists(anyString())).thenReturn(true); - when(mockedRegistry.get(anyString())).thenReturn(mockedCollection); - when(mockedCollection.getProperty(anyString())).thenReturn(DENY_OVERRIDES); - doThrow(new RegistryException("")).when(mockedRegistry).delete(anyString()); - hybridConfigPersistenceManager.addOrUpdateGlobalPolicyAlgorithm(PERMIT_OVERRIDES); - } - - private static void setPrivateStaticFinalField(Class clazz, String fieldName, Object newValue) - throws ReflectiveOperationException { - - Field field = clazz.getDeclaredField(fieldName); - field.setAccessible(true); - - Field modifiers = Field.class.getDeclaredField("modifiers"); - modifiers.setAccessible(true); - modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL); - - field.set(null, newValue); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/ConfigPersistenceManagerTest.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/ConfigPersistenceManagerTest.java deleted file mode 100644 index 219f9e60d478..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/ConfigPersistenceManagerTest.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; -import org.wso2.balana.combine.PolicyCombiningAlgorithm; -import org.wso2.carbon.database.utils.jdbc.NamedPreparedStatement; -import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.EntitlementUtil; -import org.wso2.carbon.identity.entitlement.cache.ConfigCache; - -import java.sql.Connection; -import java.sql.SQLException; - -import static org.testng.Assert.assertEquals; -import static org.wso2.carbon.identity.entitlement.PDPConstants.Algorithms.DENY_OVERRIDES; -import static org.wso2.carbon.identity.entitlement.PDPConstants.Algorithms.FIRST_APPLICABLE; -import static org.wso2.carbon.identity.entitlement.PDPConstants.Algorithms.ONLY_ONE_APPLICABLE; -import static org.wso2.carbon.identity.entitlement.PDPConstants.Algorithms.ORDERED_DENY_OVERRIDES; -import static org.wso2.carbon.identity.entitlement.PDPConstants.Algorithms.ORDERED_PERMIT_OVERRIDES; -import static org.wso2.carbon.identity.entitlement.PDPConstants.Algorithms.PERMIT_OVERRIDES; - -/** - * This is the parent test class for the Config Persistence Manager test classes. - */ -public abstract class ConfigPersistenceManagerTest { - - ConfigPersistenceManager configPersistenceManager; - - @Test - public void testGetDefaultGlobalPolicyAlgorithmName() { - - String globalPolicyAlgorithmName = configPersistenceManager.getGlobalPolicyAlgorithmName(); - assertEquals(globalPolicyAlgorithmName, DENY_OVERRIDES); - - //Get policy object from the storage. - PolicyCombiningAlgorithm globalPolicyAlgorithm = configPersistenceManager.getGlobalPolicyAlgorithm(); - PolicyCombiningAlgorithm expectedPolicyCombiningAlgorithm = - EntitlementUtil.resolveGlobalPolicyAlgorithm(globalPolicyAlgorithmName); - assertEquals(globalPolicyAlgorithm.getIdentifier(), expectedPolicyCombiningAlgorithm.getIdentifier()); - } - - @DataProvider - public Object[][] globalPolicyAlgorithmData() { - - return new Object[][]{ - {DENY_OVERRIDES}, - {PERMIT_OVERRIDES}, - {FIRST_APPLICABLE}, - {ONLY_ONE_APPLICABLE}, - {ORDERED_DENY_OVERRIDES}, - {ORDERED_PERMIT_OVERRIDES} - }; - } - - @Test(dataProvider = "globalPolicyAlgorithmData") - public void testAddGlobalPolicyAlgorithm(String policyAlgorithmName) throws Exception { - - // Add the first global policy combining algorithm. - configPersistenceManager.addOrUpdateGlobalPolicyAlgorithm(policyAlgorithmName); - String policyAlgorithmNameFromStorage = configPersistenceManager.getGlobalPolicyAlgorithmName(); - assertEquals(policyAlgorithmNameFromStorage, policyAlgorithmName); - } - - @Test(dataProvider = "globalPolicyAlgorithmData") - public void testGetGlobalPolicyAlgorithmWhenCacheMisses(String policyAlgorithmName) throws Exception { - - // Add the first global policy combining algorithm. - configPersistenceManager.addOrUpdateGlobalPolicyAlgorithm(policyAlgorithmName); - // Clear the cache. - ConfigCache.getInstance().clear(-1234); - - String policyAlgorithmNameFromStorage = configPersistenceManager.getGlobalPolicyAlgorithmName(); - assertEquals(policyAlgorithmNameFromStorage, policyAlgorithmName); - } - - @Test(dataProvider = "globalPolicyAlgorithmData") - public void testUpdateGlobalPolicyAlgorithm(String policyAlgorithmName) throws Exception { - - configPersistenceManager.addOrUpdateGlobalPolicyAlgorithm(DENY_OVERRIDES); - // Update the global policy combining algorithm. - configPersistenceManager.addOrUpdateGlobalPolicyAlgorithm(policyAlgorithmName); - - String policyAlgorithmNameFromStorage = configPersistenceManager.getGlobalPolicyAlgorithmName(); - assertEquals(policyAlgorithmNameFromStorage, policyAlgorithmName); - } - - public void deletePolicyCombiningAlgorithmInDatabase() throws EntitlementException { - - ConfigCache configCache = ConfigCache.getInstance(); - configCache.clear(-1234); - - String DELETE_POLICY_COMBINING_ALGORITHMS_SQL = "DELETE FROM IDN_XACML_CONFIG"; - try (Connection connection = IdentityDatabaseUtil.getDBConnection(false)) { - try (NamedPreparedStatement removePolicyCombiningAlgoPrepStmt = new NamedPreparedStatement(connection, - DELETE_POLICY_COMBINING_ALGORITHMS_SQL)) { - removePolicyCombiningAlgoPrepStmt.execute(); - } - } catch (SQLException e) { - throw new EntitlementException("Error while removing global policy combining algorithm in policy store", e); - } - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/HybridConfigPersistenceManagerTest.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/HybridConfigPersistenceManagerTest.java deleted file mode 100644 index 622dc821738c..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/HybridConfigPersistenceManagerTest.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.common.testng.WithCarbonHome; -import org.wso2.carbon.identity.common.testng.WithH2Database; -import org.wso2.carbon.identity.common.testng.WithRealmService; -import org.wso2.carbon.identity.common.testng.WithRegistry; -import org.wso2.carbon.identity.entitlement.internal.EntitlementConfigHolder; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.wso2.carbon.identity.entitlement.PDPConstants.Algorithms.DENY_OVERRIDES; - -/** - * This class tests the behavior of the HybridConfigPersistenceManager class. - */ -@WithCarbonHome -@WithRegistry(injectToSingletons = {EntitlementServiceComponent.class}) -@WithRealmService(injectToSingletons = {EntitlementConfigHolder.class}, initUserStoreManager = true) -@WithH2Database(jndiName = "jdbc/WSO2IdentityDB", files = {"dbscripts/h2.sql"}) -public class HybridConfigPersistenceManagerTest extends ConfigPersistenceManagerTest { - - private JDBCConfigPersistenceManager jdbcConfigPersistenceManager; - private RegistryConfigPersistenceManager registryConfigPersistenceManager; - - @BeforeMethod - public void setUp() throws Exception { - - configPersistenceManager = new HybridConfigPersistenceManager(); - jdbcConfigPersistenceManager = new JDBCConfigPersistenceManager(); - registryConfigPersistenceManager = new RegistryConfigPersistenceManager(); - } - - @AfterMethod - public void tearDown() throws Exception { - - deletePolicyCombiningAlgorithmInDatabase(); - registryConfigPersistenceManager.deleteGlobalPolicyAlgorithm(); - } - - @Test(dataProvider = "globalPolicyAlgorithmData") - public void testGetGlobalPolicyAlgorithmNameFromRegistry(String policyAlgorithmName) throws Exception { - - // Add the global policy combining algorithm. - registryConfigPersistenceManager.addOrUpdateGlobalPolicyAlgorithm(policyAlgorithmName); - String policyAlgorithmFromRegistry = configPersistenceManager.getGlobalPolicyAlgorithmName(); - assertEquals(policyAlgorithmFromRegistry, policyAlgorithmName); - } - - @Test(dataProvider = "globalPolicyAlgorithmData") - public void testGetGlobalPolicyAlgorithmNameFromDatabase(String policyAlgorithmName) throws Exception { - - // Add the global policy combining algorithm. - jdbcConfigPersistenceManager.addOrUpdateGlobalPolicyAlgorithm(policyAlgorithmName); - String policyAlgorithmFromDatabase = configPersistenceManager.getGlobalPolicyAlgorithmName(); - assertEquals(policyAlgorithmFromDatabase, policyAlgorithmName); - } - - @Test(dataProvider = "globalPolicyAlgorithmData") - public void testUpdateGlobalPolicyAlgorithmInRegistry(String policyAlgorithmName) throws Exception { - - registryConfigPersistenceManager.addOrUpdateGlobalPolicyAlgorithm(DENY_OVERRIDES); - configPersistenceManager.addOrUpdateGlobalPolicyAlgorithm(policyAlgorithmName); - // Verify that the global policy combining algorithm value was deleted from the registry. - assertFalse(registryConfigPersistenceManager.isGlobalPolicyAlgorithmExist()); - - String policyAlgorithmFromDatabase = configPersistenceManager.getGlobalPolicyAlgorithmName(); - assertEquals(policyAlgorithmFromDatabase, policyAlgorithmName); - } - - @Test(dataProvider = "globalPolicyAlgorithmData") - public void testUpdateGlobalPolicyAlgorithmInDatabase(String policyAlgorithmName) throws Exception { - - // Add the global policy combining algorithm. - configPersistenceManager.addOrUpdateGlobalPolicyAlgorithm(DENY_OVERRIDES); - assertFalse(registryConfigPersistenceManager.isGlobalPolicyAlgorithmExist()); - configPersistenceManager.addOrUpdateGlobalPolicyAlgorithm(policyAlgorithmName); - assertFalse(registryConfigPersistenceManager.isGlobalPolicyAlgorithmExist()); - String policyAlgorithmFromDatabase = configPersistenceManager.getGlobalPolicyAlgorithmName(); - assertEquals(policyAlgorithmFromDatabase, policyAlgorithmName); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/HybridPAPStatusDataHandlerTest.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/HybridPAPStatusDataHandlerTest.java deleted file mode 100644 index 1638257717df..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/HybridPAPStatusDataHandlerTest.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.testng.annotations.Test; -import org.wso2.carbon.identity.common.testng.WithCarbonHome; -import org.wso2.carbon.identity.common.testng.WithH2Database; -import org.wso2.carbon.identity.common.testng.WithRealmService; -import org.wso2.carbon.identity.common.testng.WithRegistry; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.PAPStatusDataHandler; -import org.wso2.carbon.identity.entitlement.PDPConstants; -import org.wso2.carbon.identity.entitlement.SimplePAPStatusDataHandler; -import org.wso2.carbon.identity.entitlement.dto.StatusHolder; -import org.wso2.carbon.identity.entitlement.internal.EntitlementConfigHolder; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; - -import java.util.List; -import java.util.Properties; - -import static org.testng.Assert.assertEquals; - -/** - * This class tests the behavior of the Hybrid PAP Status Data Handler class. - */ -@WithCarbonHome -@WithRegistry(injectToSingletons = {EntitlementServiceComponent.class}) -@WithRealmService(injectToSingletons = {EntitlementConfigHolder.class}, initUserStoreManager = true) -@WithH2Database(files = {"dbscripts/h2.sql"}) -public class HybridPAPStatusDataHandlerTest extends PAPStatusDataHandlerTest { - - JDBCSimplePAPStatusDataHandler jdbcSimplePAPStatusDataHandler; - SimplePAPStatusDataHandler registrySimplePAPStatusDataHandler; - - public PAPStatusDataHandler createPAPStatusDataHandler() { - - Properties storeProps = new Properties(); - storeProps.put(PDPConstants.MAX_NO_OF_STATUS_RECORDS, "5"); - jdbcSimplePAPStatusDataHandler = new JDBCSimplePAPStatusDataHandler(); - jdbcSimplePAPStatusDataHandler.init(storeProps); - registrySimplePAPStatusDataHandler = new SimplePAPStatusDataHandler(); - registrySimplePAPStatusDataHandler.init(storeProps); - return new HybridPAPStatusDataHandler(); - } - - public SubscriberPersistenceManager createSubscriberPersistenceManager() { - - return new HybridSubscriberPersistenceManager(); - } - - @Test(priority = 5, dataProvider = "papStatusDataProvider") - public void testHandleStatusForNewPolicy(String about, String key, List statusHoldersForAdd, - List statusHoldersForModify) throws Exception { - - papStatusDataHandler.handle(about, key, statusHoldersForAdd); - - StatusHolder[] statusDataFromDb = jdbcSimplePAPStatusDataHandler.getStatusData(about, key, null, "*"); - assertEquals(statusDataFromDb.length, 1); - assertEquals(statusDataFromDb[0].getType(), statusHoldersForAdd.get(0).getType()); - assertEquals(statusDataFromDb[0].getKey(), statusHoldersForAdd.get(0).getKey()); - assertEquals(statusDataFromDb[0].getTarget(), statusHoldersForAdd.get(0).getTarget()); - assertEquals(statusDataFromDb[0].getTargetAction(), statusHoldersForAdd.get(0).getTargetAction()); - assertEquals(statusDataFromDb[0].getUser(), statusHoldersForAdd.get(0).getUser()); - - StatusHolder[] statusDataFromRegistry = registrySimplePAPStatusDataHandler.getStatusData(about, key, null, "*"); - assertEquals(statusDataFromRegistry.length, 0); - - papStatusDataHandler.handle(about, key, statusHoldersForModify); - StatusHolder[] allStatusDataFromDb = - jdbcSimplePAPStatusDataHandler.getStatusData(about, key, null, "*"); - assertEquals(allStatusDataFromDb.length, 2); - StatusHolder[] allStatusDataFromRegistry = - registrySimplePAPStatusDataHandler.getStatusData(about, key, null, "*"); - assertEquals(allStatusDataFromRegistry.length, 0); - } - - @Test(priority = 6, dataProvider = "papStatusDataProvider") - public void testHandleStatusWhenStatusExistsInDb(String about, String key, List statusHoldersForAdd, - List statusHoldersForModify) throws Exception { - - jdbcSimplePAPStatusDataHandler.handle(about, key, statusHoldersForAdd); - papStatusDataHandler.handle(about, key, statusHoldersForModify); - - StatusHolder[] allStatusDataFromDb = - jdbcSimplePAPStatusDataHandler.getStatusData(about, key, null, "*"); - assertEquals(allStatusDataFromDb.length, 2); - StatusHolder[] allStatusDataFromRegistry = - registrySimplePAPStatusDataHandler.getStatusData(about, key, null, "*"); - assertEquals(allStatusDataFromRegistry.length, 0); - } - - @Test(priority = 7, dataProvider = "papStatusDataProvider") - public void testHandleStatusWhenStatusExistsInRegistry(String about, String key, - List statusHoldersForAdd, - List statusHoldersForModify) throws Exception { - - registrySimplePAPStatusDataHandler.handle(about, key, statusHoldersForAdd); - papStatusDataHandler.handle(about, key, statusHoldersForModify); - - StatusHolder[] allStatusDataFromRegistry = - registrySimplePAPStatusDataHandler.getStatusData(about, key, null, "*"); - assertEquals(allStatusDataFromRegistry.length, 2); - StatusHolder[] allStatusDataFromDb = - jdbcSimplePAPStatusDataHandler.getStatusData(about, key, null, "*"); - assertEquals(allStatusDataFromDb.length, 0); - } - - @Test(priority = 8, dataProvider = "papStatusDataProvider") - public void testGetStatusWhenPolicyStatusExistsInDb(String about, String key, - List statusHoldersForAdd, - List statusHoldersForModify) throws Exception { - - jdbcSimplePAPStatusDataHandler.handle(about, key, statusHoldersForAdd); - verifyStatusDataFromStorage(about, key, statusHoldersForAdd); - } - - @Test(priority = 9, dataProvider = "papStatusDataProvider") - public void testGetStatusWhenPolicyStatusExistsInRegistry(String about, String key, - List statusHoldersForAdd, - List statusHoldersForModify) - throws Exception { - - registrySimplePAPStatusDataHandler.handle(about, key, statusHoldersForAdd); - verifyStatusDataFromStorage(about, key, statusHoldersForAdd); - } - - private void verifyStatusDataFromStorage(String about, String key, List statusHoldersForAdd) - throws EntitlementException { - - StatusHolder[] statusDataFromStorage = papStatusDataHandler.getStatusData(about, key, null, "*"); - assertEquals(statusDataFromStorage.length, 1); - assertEquals(statusDataFromStorage[0].getType(), statusHoldersForAdd.get(0).getType()); - assertEquals(statusDataFromStorage[0].getKey(), statusHoldersForAdd.get(0).getKey()); - assertEquals(statusDataFromStorage[0].getTarget(), statusHoldersForAdd.get(0).getTarget()); - assertEquals(statusDataFromStorage[0].getTargetAction(), statusHoldersForAdd.get(0).getTargetAction()); - assertEquals(statusDataFromStorage[0].getUser(), statusHoldersForAdd.get(0).getUser()); - } - - @Test(priority = 10, dataProvider = "dataProviderForRemoveStatus") - public void testHandleRemoveStatusWhenPolicyStatusExistsInDb(String about, String key, - List statusHoldersForAdd, - List statusHoldersForRemove) - throws Exception { - - jdbcSimplePAPStatusDataHandler.handle(about, key, statusHoldersForAdd); - papStatusDataHandler.handle(about, key, statusHoldersForRemove); - verifyRemoveStatusDataFromStorage(about, key); - } - - @Test(priority = 11, dataProvider = "dataProviderForRemoveStatus") - public void testHandleRemoveStatusWhenPolicyStatusExistsInRegistry(String about, String key, - List statusHoldersForAdd, - List statusHoldersForRemove) - throws Exception { - - registrySimplePAPStatusDataHandler.handle(about, key, statusHoldersForAdd); - papStatusDataHandler.handle(about, key, statusHoldersForRemove); - verifyRemoveStatusDataFromStorage(about, key); - } - - private void verifyRemoveStatusDataFromStorage(String about, String key) throws EntitlementException { - - StatusHolder[] statusDataFromDb = papStatusDataHandler.getStatusData(about, key, null, "*"); - assertEquals(statusDataFromDb.length, 0); - StatusHolder[] statusDataFromRegistry = papStatusDataHandler.getStatusData(about, key, null, "*"); - assertEquals(statusDataFromRegistry.length, 0); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/HybridPolicyPersistenceManagerTest.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/HybridPolicyPersistenceManagerTest.java deleted file mode 100644 index 1b0e81089775..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/HybridPolicyPersistenceManagerTest.java +++ /dev/null @@ -1,407 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.testng.annotations.Test; -import org.wso2.carbon.identity.common.testng.WithCarbonHome; -import org.wso2.carbon.identity.common.testng.WithH2Database; -import org.wso2.carbon.identity.common.testng.WithRealmService; -import org.wso2.carbon.identity.common.testng.WithRegistry; -import org.wso2.carbon.identity.entitlement.dto.PolicyDTO; -import org.wso2.carbon.identity.entitlement.dto.PolicyStoreDTO; -import org.wso2.carbon.identity.entitlement.internal.EntitlementConfigHolder; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; - -import java.util.List; -import java.util.Properties; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; - -/** - * This class tests the behavior of the Hybrid Policy Persistence Manager class. - */ -@WithCarbonHome -@WithRegistry(injectToSingletons = {EntitlementServiceComponent.class}) -@WithRealmService(injectToSingletons = {EntitlementConfigHolder.class}, initUserStoreManager = true) -@WithH2Database(jndiName = "jdbc/WSO2IdentityDB", files = {"dbscripts/h2.sql"}) -public class HybridPolicyPersistenceManagerTest extends PolicyPersistenceManagerTest { - - private JDBCPolicyPersistenceManager jdbcPolicyPersistenceManager; - private RegistryPolicyPersistenceManager registryPolicyPersistenceManager; - - public PolicyPersistenceManager createPolicyPersistenceManager() { - - Properties storeProps = new Properties(); - policyPersistenceManager = new HybridPolicyPersistenceManager(); - policyPersistenceManager.init(storeProps); - jdbcPolicyPersistenceManager = new JDBCPolicyPersistenceManager(); - registryPolicyPersistenceManager = new RegistryPolicyPersistenceManager(); - registryPolicyPersistenceManager.init(storeProps); - return policyPersistenceManager; - } - - @Test(priority = 13) - public void testAddPAPPolicyInDb() throws Exception { - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - - PolicyDTO policyFromStorage = jdbcPolicyPersistenceManager.getPAPPolicy(samplePAPPolicy1.getPolicyId()); - assertEquals(policyFromStorage.getPolicy(), samplePAPPolicy1.getPolicy()); - assertEquals(policyFromStorage.getPolicyId(), samplePAPPolicy1.getPolicyId()); - assertEquals(policyFromStorage.getVersion(), "1"); - assertTrue(jdbcPolicyPersistenceManager.isPolicyExistsInPap(samplePAPPolicy1.getPolicyId())); - assertFalse(registryPolicyPersistenceManager.isPolicyExistsInPap(samplePAPPolicy1.getPolicyId())); - } - - @Test(priority = 14) - public void testDeletePAPPolicyInDb() throws Exception { - - jdbcPolicyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.removePolicy(samplePAPPolicy1.getPolicyId()); - assertNull(policyPersistenceManager.getPolicy(samplePAPPolicy1.getPolicyId())); - assertNull(jdbcPolicyPersistenceManager.getPolicy(samplePAPPolicy1.getPolicyId())); - assertNull(registryPolicyPersistenceManager.getPolicy(samplePAPPolicy1.getPolicyId())); - } - - @Test(priority = 15) - public void testDeletePAPPolicyInRegistry() throws Exception { - - registryPolicyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.removePolicy(samplePAPPolicy1.getPolicyId()); - assertNull(policyPersistenceManager.getPolicy(samplePAPPolicy1.getPolicyId())); - assertNull(registryPolicyPersistenceManager.getPolicy(samplePAPPolicy1.getPolicyId())); - } - - @Test(priority = 16) - public void testUpdatePAPPolicyInDatabase() throws Exception { - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.addOrUpdatePolicy(sampleUpdatedPAPPolicy1, true); - - // Verify weather the get policy method returning the updated policy. - PolicyDTO updatedPolicy = policyPersistenceManager.getPAPPolicy(samplePAPPolicy1.getPolicyId()); - assertEquals(updatedPolicy.getPolicy(), sampleUpdatedPAPPolicy1.getPolicy()); - assertEquals(updatedPolicy.getPolicyId(), sampleUpdatedPAPPolicy1.getPolicyId()); - assertEquals(updatedPolicy.getVersion(), "2"); - - // Verify weather the policy was updated in the database. - PolicyDTO updatedPolicyFromDb = jdbcPolicyPersistenceManager.getPAPPolicy(samplePAPPolicy1.getPolicyId()); - assertEquals(updatedPolicyFromDb.getPolicy(), sampleUpdatedPAPPolicy1.getPolicy()); - assertEquals(updatedPolicyFromDb.getPolicyId(), sampleUpdatedPAPPolicy1.getPolicyId()); - assertEquals(updatedPolicyFromDb.getVersion(), "2"); - - // Verify weather get policy by version method returns the correct policy. - PolicyDTO oldPolicy = policyPersistenceManager.getPolicy(samplePAPPolicy1.getPolicyId(), "1"); - assertEquals(oldPolicy.getPolicy(), samplePAPPolicy1.getPolicy()); - PolicyDTO oldPolicyFromDb = jdbcPolicyPersistenceManager.getPolicy(samplePAPPolicy1.getPolicyId(), "1"); - assertEquals(oldPolicyFromDb.getPolicy(), samplePAPPolicy1.getPolicy()); - - PolicyDTO newPolicy = policyPersistenceManager.getPolicy(sampleUpdatedPAPPolicy1.getPolicyId(), "2"); - assertEquals(newPolicy.getPolicy(), sampleUpdatedPAPPolicy1.getPolicy()); - PolicyDTO newPolicyFromDb = jdbcPolicyPersistenceManager.getPolicy(sampleUpdatedPAPPolicy1.getPolicyId(), "2"); - assertEquals(newPolicyFromDb.getPolicy(), sampleUpdatedPAPPolicy1.getPolicy()); - - // Verify weather the total number of versions are correct. - String[] policyVersions = policyPersistenceManager.getVersions(samplePAPPolicy1.getPolicyId()); - assertEquals(policyVersions.length, 2); - String[] policyVersionsFromDb = jdbcPolicyPersistenceManager.getVersions(samplePAPPolicy1.getPolicyId()); - assertEquals(policyVersionsFromDb.length, 2); - } - - @Test(priority = 17) - public void testUpdatePAPPolicyInRegistry() throws Exception { - - registryPolicyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.addOrUpdatePolicy(sampleUpdatedPAPPolicy1, true); - - // Verify weather the get policy method returning the updated policy. - PolicyDTO updatedPolicy = policyPersistenceManager.getPAPPolicy(samplePAPPolicy1.getPolicyId()); - assertEquals(updatedPolicy.getPolicy(), sampleUpdatedPAPPolicy1.getPolicy()); - assertEquals(updatedPolicy.getPolicyId(), sampleUpdatedPAPPolicy1.getPolicyId()); - assertEquals(updatedPolicy.getVersion(), "2"); - - // Verify weather the policy was updated in the registry. - PolicyDTO updatedPolicyFromRegistry = - registryPolicyPersistenceManager.getPAPPolicy(samplePAPPolicy1.getPolicyId()); - assertEquals(updatedPolicyFromRegistry.getPolicy(), sampleUpdatedPAPPolicy1.getPolicy()); - assertEquals(updatedPolicyFromRegistry.getPolicyId(), sampleUpdatedPAPPolicy1.getPolicyId()); - assertEquals(updatedPolicyFromRegistry.getVersion(), "2"); - - // Verify weather get policy by version method returns the correct policy. - PolicyDTO policyVersion1 = policyPersistenceManager.getPolicy(samplePAPPolicy1.getPolicyId(), "1"); - assertEquals(policyVersion1.getPolicy(), samplePAPPolicy1.getPolicy()); - PolicyDTO policyVersion1FromRegistry = - registryPolicyPersistenceManager.getPolicy(samplePAPPolicy1.getPolicyId(), "1"); - assertEquals(policyVersion1FromRegistry.getPolicy(), samplePAPPolicy1.getPolicy()); - - PolicyDTO policyVersion2 = policyPersistenceManager.getPolicy(sampleUpdatedPAPPolicy1.getPolicyId(), "2"); - assertEquals(policyVersion2.getPolicy(), sampleUpdatedPAPPolicy1.getPolicy()); - PolicyDTO policyVersion2FromRegistry = - registryPolicyPersistenceManager.getPolicy(sampleUpdatedPAPPolicy1.getPolicyId(), "2"); - assertEquals(policyVersion2FromRegistry.getPolicy(), sampleUpdatedPAPPolicy1.getPolicy()); - - // Verify weather the total number of versions are correct. - String[] versions = policyPersistenceManager.getVersions(samplePAPPolicy1.getPolicyId()); - assertEquals(versions.length, 2); - String[] versionsFromRegistry = registryPolicyPersistenceManager.getVersions(samplePAPPolicy1.getPolicyId()); - assertEquals(versionsFromRegistry.length, 2); - } - - @Test(priority = 19) - public void testAddPDPPolicyInDatabase() throws Exception { - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.addPolicy(samplePDPPolicy1); - - assertTrue(jdbcPolicyPersistenceManager.isPolicyExist(samplePDPPolicy1.getPolicyId())); - PolicyStoreDTO policyFromDb = jdbcPolicyPersistenceManager.getPublishedPolicy(samplePDPPolicy1.getPolicyId()); - assertEquals(policyFromDb.getPolicy(), samplePDPPolicy1.getPolicy()); - assertEquals(policyFromDb.getPolicyId(), samplePDPPolicy1.getPolicyId()); - - policyPersistenceManager.deletePolicy(samplePDPPolicy1.getPolicyId()); - assertFalse(jdbcPolicyPersistenceManager.isPolicyExist(samplePDPPolicy1.getPolicyId())); - } - - @Test(priority = 20) - public void testAddPDPPolicyInRegistry() throws Exception { - - registryPolicyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - registryPolicyPersistenceManager.addPolicy(samplePDPPolicy1); - - assertTrue(policyPersistenceManager.isPolicyExist(samplePDPPolicy1.getPolicyId())); - // Verify weather the policy was added to the registry. - assertTrue(registryPolicyPersistenceManager.isPolicyExist(samplePDPPolicy1.getPolicyId())); - - PolicyStoreDTO policyFromStorage = policyPersistenceManager.getPublishedPolicy(samplePDPPolicy1.getPolicyId()); - assertEquals(policyFromStorage.getPolicy(), samplePDPPolicy1.getPolicy()); - assertEquals(policyFromStorage.getPolicyId(), samplePDPPolicy1.getPolicyId()); - PolicyStoreDTO policyFromRegistry = - registryPolicyPersistenceManager.getPublishedPolicy(samplePDPPolicy1.getPolicyId()); - assertEquals(policyFromRegistry.getPolicy(), samplePDPPolicy1.getPolicy()); - assertEquals(policyFromRegistry.getPolicyId(), samplePDPPolicy1.getPolicyId()); - - policyPersistenceManager.deletePolicy(samplePDPPolicy1.getPolicyId()); - assertFalse(policyPersistenceManager.isPolicyExist(samplePDPPolicy1.getPolicyId())); - assertFalse(registryPolicyPersistenceManager.isPolicyExist(samplePDPPolicy1.getPolicyId())); - } - - @Test(priority = 21) - public void testDeletePDPPolicyInDatabase() throws Exception { - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.addPolicy(samplePDPPolicy1); - policyPersistenceManager.deletePolicy(samplePDPPolicy1.getPolicyId()); - assertFalse(policyPersistenceManager.isPolicyExist(samplePDPPolicy1.getPolicyId())); - assertFalse(jdbcPolicyPersistenceManager.isPolicyExist(samplePDPPolicy1.getPolicyId())); - } - - @Test(priority = 22) - public void testDeletePDPPolicy() throws Exception { - - registryPolicyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - registryPolicyPersistenceManager.addPolicy(samplePDPPolicy1); - policyPersistenceManager.deletePolicy(samplePDPPolicy1.getPolicyId()); - assertFalse(policyPersistenceManager.isPolicyExist(samplePDPPolicy1.getPolicyId())); - assertFalse(registryPolicyPersistenceManager.isPolicyExist(samplePDPPolicy1.getPolicyId())); - } - - @Test(priority = 23) - public void testGetReferencedPolicyInDb() throws Exception { - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy2, true); - - policyPersistenceManager.addPolicy(samplePDPPolicy1); - policyPersistenceManager.addPolicy(samplePDPPolicy2); - - // Verify the policies that are not active. - assertNull(policyPersistenceManager.getReferencedPolicy(samplePDPPolicy1.getPolicyId())); - assertNull(jdbcPolicyPersistenceManager.getReferencedPolicy(samplePDPPolicy1.getPolicyId())); - - assertEquals(policyPersistenceManager.getReferencedPolicy(samplePDPPolicy2.getPolicyId()), - samplePDPPolicy2.getPolicy()); - assertEquals(jdbcPolicyPersistenceManager.getReferencedPolicy(samplePDPPolicy2.getPolicyId()), - samplePDPPolicy2.getPolicy()); - } - - @Test(priority = 24) - public void testGetReferencedPolicyInRegistry() throws Exception { - - registryPolicyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - registryPolicyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy2, true); - - registryPolicyPersistenceManager.addPolicy(samplePDPPolicy1); - registryPolicyPersistenceManager.addPolicy(samplePDPPolicy2); - - // Verify the policies that are not active. - assertNull(policyPersistenceManager.getReferencedPolicy(samplePDPPolicy1.getPolicyId())); - assertNull(registryPolicyPersistenceManager.getReferencedPolicy(samplePDPPolicy1.getPolicyId())); - - assertEquals(policyPersistenceManager.getReferencedPolicy(samplePDPPolicy2.getPolicyId()), - samplePDPPolicy2.getPolicy()); - assertEquals(registryPolicyPersistenceManager.getReferencedPolicy(samplePDPPolicy2.getPolicyId()), - samplePDPPolicy2.getPolicy()); - } - - @Test(priority = 25) - public void testGetPolicyOrderInDatabase() throws Exception { - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy3, true); - - policyPersistenceManager.addPolicy(samplePDPPolicy1); - policyPersistenceManager.addPolicy(samplePDPPolicy3); - - // Verify the policy order. - assertEquals(policyPersistenceManager.getPolicyOrder(samplePDPPolicy1.getPolicyId()), 0); - assertEquals(jdbcPolicyPersistenceManager.getPolicyOrder(samplePDPPolicy1.getPolicyId()), 0); - assertEquals(policyPersistenceManager.getPolicyOrder(samplePDPPolicy3.getPolicyId()), - samplePDPPolicy3.getPolicyOrder()); - assertEquals(jdbcPolicyPersistenceManager.getPolicyOrder(samplePDPPolicy3.getPolicyId()), - samplePDPPolicy3.getPolicyOrder()); - } - - @Test(priority = 26) - public void testGetPolicyOrderInRegistry() throws Exception { - - registryPolicyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - registryPolicyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy3, true); - - registryPolicyPersistenceManager.addPolicy(samplePDPPolicy1); - registryPolicyPersistenceManager.addPolicy(samplePDPPolicy3); - - // Verify the policy order. - assertEquals(policyPersistenceManager.getPolicyOrder(samplePDPPolicy1.getPolicyId()), 0); - assertEquals(registryPolicyPersistenceManager.getPolicyOrder(samplePDPPolicy1.getPolicyId()), 0); - - assertEquals(policyPersistenceManager.getPolicyOrder(samplePDPPolicy3.getPolicyId()), - samplePDPPolicy3.getPolicyOrder()); - assertEquals(registryPolicyPersistenceManager.getPolicyOrder(samplePDPPolicy3.getPolicyId()), - samplePDPPolicy3.getPolicyOrder()); - } - - @Test(priority = 27) - public void testListPDPPolicyInDatabase() throws Exception { - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy2, true); - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy3, true); - - policyPersistenceManager.addPolicy(samplePDPPolicy1); - policyPersistenceManager.addPolicy(samplePDPPolicy2); - policyPersistenceManager.addPolicy(samplePDPPolicy3); - - // Verify the number of published policies. - List policyIds = policyPersistenceManager.listPublishedPolicyIds(); - assertEquals(policyIds.size(), 3); - List dbPolicyIds = jdbcPolicyPersistenceManager.listPublishedPolicyIds(); - assertEquals(dbPolicyIds.size(), 3); - - // Verify the number of ordered policy identifiers. - String[] orderedPolicyIdentifiers = policyPersistenceManager.getOrderedPolicyIdentifiers(); - assertEquals(orderedPolicyIdentifiers.length, 3); - String[] orderedPolicyIdentifiersFromDb = jdbcPolicyPersistenceManager.getOrderedPolicyIdentifiers(); - assertEquals(orderedPolicyIdentifiersFromDb.length, 3); - - // Verify the number of active policies. - String[] activePolicies = policyPersistenceManager.getActivePolicies(); - assertEquals(activePolicies.length, 2); - String[] activePoliciesFromDb = jdbcPolicyPersistenceManager.getActivePolicies(); - assertEquals(activePoliciesFromDb.length, 2); - } - - @Test(priority = 28) - public void testListPDPPolicyInRegistry() throws Exception { - - registryPolicyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - registryPolicyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy2, true); - registryPolicyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy3, true); - - registryPolicyPersistenceManager.addPolicy(samplePDPPolicy1); - registryPolicyPersistenceManager.addPolicy(samplePDPPolicy2); - registryPolicyPersistenceManager.addPolicy(samplePDPPolicy3); - - // Verify the number of published policies. - List policyIds = policyPersistenceManager.listPublishedPolicyIds(); - assertEquals(policyIds.size(), 3); - List regPolicyIds = registryPolicyPersistenceManager.listPublishedPolicyIds(); - assertEquals(regPolicyIds.size(), 3); - - // Verify the number of ordered policy identifiers. - String[] orderedPolicyIdentifiers = policyPersistenceManager.getOrderedPolicyIdentifiers(); - assertEquals(orderedPolicyIdentifiers.length, 3); - String[] orderedPolicyIdentifiersFromRegistry = registryPolicyPersistenceManager.getOrderedPolicyIdentifiers(); - assertEquals(orderedPolicyIdentifiersFromRegistry.length, 3); - - // Verify the number of active policies. - String[] activePolicies = policyPersistenceManager.getActivePolicies(); - assertEquals(activePolicies.length, 2); - String[] activePoliciesFromRegistry = registryPolicyPersistenceManager.getActivePolicies(); - assertEquals(activePoliciesFromRegistry.length, 2); - } - - @Test(priority = 29) - public void testUpdatePDPPolicyInDatabase() throws Exception { - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.addPolicy(samplePDPPolicy1); - - // Update Policy order. - policyPersistenceManager.updatePolicy(orderedSamplePDPPolicy1); - policyPersistenceManager.getPublishedPolicy(samplePDPPolicy1.getPolicyId()); - assertEquals(policyPersistenceManager.getPolicyOrder(samplePDPPolicy1.getPolicyId()), - orderedSamplePDPPolicy1.getPolicyOrder()); - assertEquals(jdbcPolicyPersistenceManager.getPolicyOrder(samplePDPPolicy1.getPolicyId()), - orderedSamplePDPPolicy1.getPolicyOrder()); - - // Update Policy active status. - policyPersistenceManager.updatePolicy(inactiveSamplePDPPolicy1); - PolicyStoreDTO updatedPDPPolicy = policyPersistenceManager.getPublishedPolicy(samplePDPPolicy1.getPolicyId()); - assertFalse(updatedPDPPolicy.isActive()); - PolicyStoreDTO updatedPDPPolicyFromDb = - jdbcPolicyPersistenceManager.getPublishedPolicy(samplePDPPolicy1.getPolicyId()); - assertFalse(updatedPDPPolicyFromDb.isActive()); - } - - @Test(priority = 30) - public void testUpdatePDPPolicyInRegistry() throws Exception { - - registryPolicyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - registryPolicyPersistenceManager.addPolicy(samplePDPPolicy1); - - // Update Policy order. - policyPersistenceManager.updatePolicy(orderedSamplePDPPolicy1); - policyPersistenceManager.getPublishedPolicy(samplePDPPolicy1.getPolicyId()); - assertEquals(policyPersistenceManager.getPolicyOrder(samplePDPPolicy1.getPolicyId()), - orderedSamplePDPPolicy1.getPolicyOrder()); - assertEquals(registryPolicyPersistenceManager.getPolicyOrder(samplePDPPolicy1.getPolicyId()), - orderedSamplePDPPolicy1.getPolicyOrder()); - - // Update Policy active status. - policyPersistenceManager.updatePolicy(inactiveSamplePDPPolicy1); - PolicyStoreDTO updatedPDPPolicy = policyPersistenceManager.getPublishedPolicy(samplePDPPolicy1.getPolicyId()); - assertFalse(updatedPDPPolicy.isActive()); - PolicyStoreDTO updatedPDPPolicy1FromRegistry = - registryPolicyPersistenceManager.getPublishedPolicy(samplePDPPolicy1.getPolicyId()); - assertFalse(updatedPDPPolicy1FromRegistry.isActive()); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/HybridSubscriberPersistenceManagerTest.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/HybridSubscriberPersistenceManagerTest.java deleted file mode 100644 index 22ef729e7def..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/HybridSubscriberPersistenceManagerTest.java +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.testng.annotations.Test; -import org.wso2.carbon.identity.common.testng.WithCarbonHome; -import org.wso2.carbon.identity.common.testng.WithH2Database; -import org.wso2.carbon.identity.common.testng.WithRealmService; -import org.wso2.carbon.identity.common.testng.WithRegistry; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.dto.PublisherDataHolder; -import org.wso2.carbon.identity.entitlement.internal.EntitlementConfigHolder; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; - -import java.util.List; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertThrows; -import static org.testng.Assert.assertTrue; - -/** - * This class tests the behavior of the Hybrid Subscriber Persistence Manager class. - */ -@WithCarbonHome -@WithRegistry(injectToSingletons = {EntitlementServiceComponent.class}) -@WithRealmService(injectToSingletons = {EntitlementConfigHolder.class}, initUserStoreManager = true) -@WithH2Database(files = {"dbscripts/h2.sql"}) -public class HybridSubscriberPersistenceManagerTest extends SubscriberPersistenceManagerTest { - - JDBCSubscriberPersistenceManager jdbcSubscriberPersistenceManager; - RegistrySubscriberPersistenceManager registrySubscriberPersistenceManager; - - public SubscriberPersistenceManager createSubscriberPersistenceManager() { - - jdbcSubscriberPersistenceManager = new JDBCSubscriberPersistenceManager(); - registrySubscriberPersistenceManager = new RegistrySubscriberPersistenceManager(); - return new HybridSubscriberPersistenceManager(); - } - - @Test(priority = 5) - public void testAddSubscriberViaHybridImpl() throws Exception { - - subscriberPersistenceManager.addSubscriber(sampleHolder1); - assertTrue(jdbcSubscriberPersistenceManager.isSubscriberExists(SAMPLE_SUBSCRIBER_ID_1)); - assertFalse(registrySubscriberPersistenceManager.isSubscriberExists(SAMPLE_SUBSCRIBER_ID_1)); - } - - @Test(priority = 6) - public void testGetSubscriberInDatabase() throws Exception { - - jdbcSubscriberPersistenceManager.addSubscriber(sampleHolder1); - verifyGetSubscriberFromStorage(); - } - - @Test(priority = 7) - public void testGetSubscriberInRegistry() throws Exception { - - registrySubscriberPersistenceManager.addSubscriber(sampleHolder1); - verifyGetSubscriberFromStorage(); - } - - private void verifyGetSubscriberFromStorage() throws EntitlementException { - - PublisherDataHolder subscriberFromRegistry = - subscriberPersistenceManager.getSubscriber(SAMPLE_SUBSCRIBER_ID_1, false); - assertEquals(subscriberFromRegistry.getPropertyDTO(SUBSCRIBER_ID_KEY).getValue(), - sampleHolder1.getPropertyDTO(SUBSCRIBER_ID_KEY).getValue()); - assertEquals(subscriberFromRegistry.getPropertyDTO(SUBSCRIBER_URL_KEY).getValue(), - sampleHolder1.getPropertyDTO(SUBSCRIBER_URL_KEY).getValue()); - assertEquals(subscriberFromRegistry.getPropertyDTO(SUBSCRIBER_USERNAME_KEY).getValue(), - sampleHolder1.getPropertyDTO(SUBSCRIBER_USERNAME_KEY).getValue()); - assertEquals(subscriberFromRegistry.getPropertyDTO(SUBSCRIBER_PASSWORD_KEY).getValue(), - SAMPLE_ENCRYPTED_PASSWORD1); - - // Retrieve the subscriber with the decrypted secrets. - PublisherDataHolder decryptedSubscriberFromStorage = - subscriberPersistenceManager.getSubscriber(SAMPLE_SUBSCRIBER_ID_1, true); - assertEquals(decryptedSubscriberFromStorage.getPropertyDTO(SUBSCRIBER_PASSWORD_KEY).getValue(), - SAMPLE_SUBSCRIBER_PASSWORD_1); - } - - @Test(priority = 8) - public void listSubscriberIdsInDatabase() throws Exception { - - jdbcSubscriberPersistenceManager.addSubscriber(sampleHolder1); - jdbcSubscriberPersistenceManager.addSubscriber(sampleHolder2); - verifyListSubscriberIdsFromStorage(); - } - - @Test(priority = 9) - public void listSubscriberIdsInRegistry() throws Exception { - - registrySubscriberPersistenceManager.addSubscriber(sampleHolder1); - registrySubscriberPersistenceManager.addSubscriber(sampleHolder2); - verifyListSubscriberIdsFromStorage(); - } - - private void verifyListSubscriberIdsFromStorage() throws EntitlementException { - - List allSubscriberIds = subscriberPersistenceManager.listSubscriberIds("*"); - assertEquals(allSubscriberIds.size(), 2); - - List filteredSubscriberIds1 = subscriberPersistenceManager.listSubscriberIds(SAMPLE_SUBSCRIBER_ID_1); - assertEquals(filteredSubscriberIds1.size(), 1); - - List filteredSubscriberIds2 = subscriberPersistenceManager.listSubscriberIds("test"); - assertEquals(filteredSubscriberIds2.size(), 0); - } - - @Test(priority = 10) - public void testUpdateSubscriberInDatabase() throws Exception { - - jdbcSubscriberPersistenceManager.addSubscriber(sampleHolder1); - subscriberPersistenceManager.updateSubscriber(updatedSampleHolder1); - verifyUpdatedSubscriber(jdbcSubscriberPersistenceManager, registrySubscriberPersistenceManager); - } - - @Test(priority = 11) - public void testUpdateSubscriberInRegistry() throws Exception { - - registrySubscriberPersistenceManager.addSubscriber(sampleHolder1); - subscriberPersistenceManager.updateSubscriber(updatedSampleHolder1); - verifyUpdatedSubscriber(registrySubscriberPersistenceManager, jdbcSubscriberPersistenceManager); - } - - private void verifyUpdatedSubscriber(SubscriberPersistenceManager usedSubscriberManager, - SubscriberPersistenceManager unusedSubscriberManager) - throws EntitlementException { - - PublisherDataHolder subscriberFromStorage = - subscriberPersistenceManager.getSubscriber(SAMPLE_SUBSCRIBER_ID_1, false); - assertEquals(subscriberFromStorage.getPropertyDTO(SUBSCRIBER_ID_KEY).getValue(), - sampleHolder1.getPropertyDTO(SUBSCRIBER_ID_KEY).getValue()); - assertEquals(subscriberFromStorage.getPropertyDTO(SUBSCRIBER_URL_KEY).getValue(), - updatedSampleHolder1.getPropertyDTO(SUBSCRIBER_URL_KEY).getValue()); - assertEquals(subscriberFromStorage.getPropertyDTO(SUBSCRIBER_USERNAME_KEY).getValue(), - updatedSampleHolder1.getPropertyDTO(SUBSCRIBER_USERNAME_KEY).getValue()); - assertEquals(subscriberFromStorage.getPropertyDTO(SUBSCRIBER_PASSWORD_KEY).getValue(), - SAMPLE_ENCRYPTED_PASSWORD2); - - // Verify weather the subscriber was updated in the correct storage. - PublisherDataHolder subscriberFromUsedStorage = - usedSubscriberManager.getSubscriber(SAMPLE_SUBSCRIBER_ID_1, false); - assertEquals(subscriberFromUsedStorage.getPropertyDTO(SUBSCRIBER_ID_KEY).getValue(), - sampleHolder1.getPropertyDTO(SUBSCRIBER_ID_KEY).getValue()); - assertEquals(subscriberFromUsedStorage.getPropertyDTO(SUBSCRIBER_URL_KEY).getValue(), - updatedSampleHolder1.getPropertyDTO(SUBSCRIBER_URL_KEY).getValue()); - assertEquals(subscriberFromUsedStorage.getPropertyDTO(SUBSCRIBER_USERNAME_KEY).getValue(), - updatedSampleHolder1.getPropertyDTO(SUBSCRIBER_USERNAME_KEY).getValue()); - assertEquals(subscriberFromUsedStorage.getPropertyDTO(SUBSCRIBER_PASSWORD_KEY).getValue(), - SAMPLE_ENCRYPTED_PASSWORD2); - - // Verify weather the subscriber was not updated in the other storage. - assertThrows(EntitlementException.class, - () -> unusedSubscriberManager.getSubscriber(SAMPLE_SUBSCRIBER_ID_1, false)); - } - - @Test(priority = 12) - public void testRemoveSubscriberInDatabase() throws Exception { - - jdbcSubscriberPersistenceManager.addSubscriber(sampleHolder1); - subscriberPersistenceManager.removeSubscriber(SAMPLE_SUBSCRIBER_ID_1); - verifyRemoveSubscriberFromStorage(); - } - - @Test(priority = 13) - public void testRemoveSubscriberInRegistry() throws Exception { - - registrySubscriberPersistenceManager.addSubscriber(sampleHolder1); - subscriberPersistenceManager.removeSubscriber(SAMPLE_SUBSCRIBER_ID_1); - verifyRemoveSubscriberFromStorage(); - } - - private void verifyRemoveSubscriberFromStorage() throws EntitlementException { - - assertThrows(EntitlementException.class, - () -> subscriberPersistenceManager.getSubscriber(SAMPLE_SUBSCRIBER_ID_1, false)); - assertFalse(jdbcSubscriberPersistenceManager.isSubscriberExists(SAMPLE_SUBSCRIBER_ID_1)); - assertFalse(registrySubscriberPersistenceManager.isSubscriberExists(SAMPLE_SUBSCRIBER_ID_1)); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/JDBCConfigPersistenceManagerTest.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/JDBCConfigPersistenceManagerTest.java deleted file mode 100644 index c39fabb3bc46..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/JDBCConfigPersistenceManagerTest.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.wso2.carbon.identity.common.testng.WithCarbonHome; -import org.wso2.carbon.identity.common.testng.WithH2Database; -import org.wso2.carbon.identity.common.testng.WithRealmService; -import org.wso2.carbon.identity.common.testng.WithRegistry; -import org.wso2.carbon.identity.entitlement.internal.EntitlementConfigHolder; - -/** - * This class tests the behavior of the JDBCConfigPersistenceManager class. - */ -@WithCarbonHome -@WithRegistry -@WithRealmService(injectToSingletons = {EntitlementConfigHolder.class}, initUserStoreManager = true) -@WithH2Database(jndiName = "jdbc/WSO2IdentityDB", files = {"dbscripts/h2.sql"}) -public class JDBCConfigPersistenceManagerTest extends ConfigPersistenceManagerTest { - - @BeforeMethod - public void setUp() { - - configPersistenceManager = new JDBCConfigPersistenceManager(); - } - - @AfterMethod - public void tearDown() throws Exception { - - deletePolicyCombiningAlgorithmInDatabase(); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/JDBCPolicyPersistenceManagerTest.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/JDBCPolicyPersistenceManagerTest.java deleted file mode 100644 index 4853a7e5f451..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/JDBCPolicyPersistenceManagerTest.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.testng.annotations.Test; -import org.wso2.carbon.identity.common.testng.WithCarbonHome; -import org.wso2.carbon.identity.common.testng.WithH2Database; -import org.wso2.carbon.identity.common.testng.WithRealmService; -import org.wso2.carbon.identity.common.testng.WithRegistry; -import org.wso2.carbon.identity.entitlement.internal.EntitlementConfigHolder; - -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; - -/** - * This class tests the behavior of the JDBC Policy Persistence Manager class. - */ -@WithCarbonHome -@WithRegistry -@WithRealmService(injectToSingletons = {EntitlementConfigHolder.class}, initUserStoreManager = true) -@WithH2Database(files = {"dbscripts/h2.sql"}) -public class JDBCPolicyPersistenceManagerTest extends PolicyPersistenceManagerTest { - - public PolicyPersistenceManager createPolicyPersistenceManager() { - - return new JDBCPolicyPersistenceManager(); - } - - @Test - public void testIsPolicyExistsInPap() throws Exception { - - assertFalse(((JDBCPolicyPersistenceManager) policyPersistenceManager).isPolicyExistsInPap(null)); - assertFalse(((JDBCPolicyPersistenceManager) policyPersistenceManager).isPolicyExistsInPap(" ")); - assertFalse(((JDBCPolicyPersistenceManager) policyPersistenceManager).isPolicyExistsInPap( - samplePAPPolicy1.getPolicyId())); - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - assertTrue(((JDBCPolicyPersistenceManager) policyPersistenceManager). - isPolicyExistsInPap(samplePAPPolicy1.getPolicyId())); - } - - @Test(priority = 3) - public void testAddPAPPolicyNotFromPAP() throws Exception { - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, false); - assertNull(policyPersistenceManager.getPAPPolicy(samplePAPPolicy1.getPolicyId())); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/JDBCSimplePAPStatusDataHandlerTest.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/JDBCSimplePAPStatusDataHandlerTest.java deleted file mode 100644 index 738799cc3579..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/JDBCSimplePAPStatusDataHandlerTest.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.wso2.carbon.identity.common.testng.WithCarbonHome; -import org.wso2.carbon.identity.common.testng.WithH2Database; -import org.wso2.carbon.identity.common.testng.WithRealmService; -import org.wso2.carbon.identity.common.testng.WithRegistry; -import org.wso2.carbon.identity.entitlement.PAPStatusDataHandler; -import org.wso2.carbon.identity.entitlement.internal.EntitlementConfigHolder; - -/** - * This class tests the behavior of the JDBC Simple PAP Status Data Handler class. - */ -@WithCarbonHome -@WithRegistry -@WithRealmService(injectToSingletons = {EntitlementConfigHolder.class}, initUserStoreManager = true) -@WithH2Database(files = {"dbscripts/h2.sql"}) -public class JDBCSimplePAPStatusDataHandlerTest extends PAPStatusDataHandlerTest { - - public PAPStatusDataHandler createPAPStatusDataHandler() { - - return new JDBCSimplePAPStatusDataHandler(); - } - - public SubscriberPersistenceManager createSubscriberPersistenceManager() { - - return new JDBCSubscriberPersistenceManager(); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/JDBCSubscriberPersistenceManagerTest.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/JDBCSubscriberPersistenceManagerTest.java deleted file mode 100644 index d9b806d3ab40..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/JDBCSubscriberPersistenceManagerTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.testng.annotations.Test; -import org.wso2.carbon.identity.common.testng.WithCarbonHome; -import org.wso2.carbon.identity.common.testng.WithH2Database; -import org.wso2.carbon.identity.common.testng.WithRealmService; -import org.wso2.carbon.identity.common.testng.WithRegistry; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.internal.EntitlementConfigHolder; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; - -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; - -/** - * This class tests the behavior of the JDBC Subscriber Persistence Manager class. - */ -@WithCarbonHome -@WithRegistry(injectToSingletons = {EntitlementServiceComponent.class}) -@WithRealmService(injectToSingletons = {EntitlementConfigHolder.class}, initUserStoreManager = true) -@WithH2Database(files = {"dbscripts/h2.sql"}) -public class JDBCSubscriberPersistenceManagerTest extends SubscriberPersistenceManagerTest { - - public SubscriberPersistenceManager createSubscriberPersistenceManager() { - - return new JDBCSubscriberPersistenceManager(); - } - - @Test(priority = 5) - public void testIsSubscriberExists() throws EntitlementException { - - assertFalse(((JDBCSubscriberPersistenceManager) subscriberPersistenceManager). - isSubscriberExists(SAMPLE_SUBSCRIBER_ID_1)); - subscriberPersistenceManager.addSubscriber(sampleHolder1); - assertTrue(((JDBCSubscriberPersistenceManager) subscriberPersistenceManager). - isSubscriberExists(SAMPLE_SUBSCRIBER_ID_1)); - } - -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/PAPStatusDataHandlerTest.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/PAPStatusDataHandlerTest.java deleted file mode 100644 index ec6b82b85c03..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/PAPStatusDataHandlerTest.java +++ /dev/null @@ -1,289 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.mockito.MockedStatic; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.core.util.IdentityUtil; -import org.wso2.carbon.identity.entitlement.PAPStatusDataHandler; -import org.wso2.carbon.identity.entitlement.PDPConstants; -import org.wso2.carbon.identity.entitlement.dto.PublisherDataHolder; -import org.wso2.carbon.identity.entitlement.dto.PublisherPropertyDTO; -import org.wso2.carbon.identity.entitlement.dto.StatusHolder; -import org.wso2.carbon.identity.entitlement.internal.EntitlementConfigHolder; - -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import static org.mockito.Mockito.mockStatic; -import static org.testng.Assert.assertEquals; -import static org.wso2.carbon.identity.entitlement.common.EntitlementConstants.PROP_USE_LAST_STATUS_ONLY; -import static org.wso2.carbon.identity.entitlement.common.EntitlementConstants.PolicyPublish.ACTION_CREATE; -import static org.wso2.carbon.identity.entitlement.common.EntitlementConstants.PolicyPublish.ACTION_DELETE; -import static org.wso2.carbon.identity.entitlement.common.EntitlementConstants.PolicyPublish.ACTION_UPDATE; -import static org.wso2.carbon.identity.entitlement.common.EntitlementConstants.StatusTypes.ADD_POLICY; -import static org.wso2.carbon.identity.entitlement.common.EntitlementConstants.StatusTypes.DELETE_POLICY; -import static org.wso2.carbon.identity.entitlement.common.EntitlementConstants.StatusTypes.GET_POLICY; -import static org.wso2.carbon.identity.entitlement.common.EntitlementConstants.StatusTypes.PUBLISH_POLICY; -import static org.wso2.carbon.identity.entitlement.persistence.SubscriberPersistenceManagerTest.SUBSCRIBER_MODULE_NAME; - -/** - * This is the parent test class for the PAP Status Data Handler test classes. - */ -public abstract class PAPStatusDataHandlerTest { - - static final String SUBSCRIBER_ID_KEY = "subscriberId"; - static final String SUBSCRIBER_ID_DISPLAY_NAME = "Subscriber Id"; - - protected static final String ABOUT_POLICY = "POLICY"; - protected static final String ABOUT_SUBSCRIBER = "SUBSCRIBER"; - protected static final String POLICY_KEY = "simple_policy"; - protected static final String SUBSCRIBER_KEY = "PDP_Subscriber_test"; - protected static final String PAP_POLICY_STORE_TARGET = "PAP POLICY STORE"; - protected static final String TARGET_ACTION_PERSIST = "PERSIST"; - protected static final String TARGET_ACTION_REMOVE = "REMOVE"; - protected static final String TARGET_ACTION_LOAD = "LOAD"; - protected static final String POLICY_VERSION_1 = "1"; - protected static final String SAMPLE_USER = "admin"; - - StatusHolder statusHolderForAddPolicy; - StatusHolder statusHolderForGetPolicy; - StatusHolder statusHolderForRemovePolicy; - - StatusHolder statusHolderForAddPolicyInPDP; - StatusHolder statusHolderForUpdatePolicyInPDP; - StatusHolder statusHolderForRemovePolicyInPDP; - - List statusHolderListForAddPolicy; - List statusHolderListForGetPolicy; - List statusHolderListForRemovePolicy; - - List statusHolderListForAddPolicyInPDP; - List statusHolderListForUpdatePolicyInPDP; - List statusHolderListForRemovePolicyInPDP; - PublisherDataHolder publisherDataHolder; - - PAPStatusDataHandler papStatusDataHandler; - SubscriberPersistenceManager subscriberPersistenceManager; - - @BeforeClass - public void init() { - - setupPolicyStatusData(); - setupSubscriberStatusData(); - } - - @BeforeMethod - public void setUp() throws Exception { - - Properties engineProperties = new Properties(); - engineProperties.put(PDPConstants.MAX_NO_OF_STATUS_RECORDS, "5"); - EntitlementConfigHolder.getInstance().setEngineProperties(engineProperties); - - Properties storeProps = new Properties(); - storeProps.put(PDPConstants.MAX_NO_OF_STATUS_RECORDS, "5"); - papStatusDataHandler = createPAPStatusDataHandler(); - papStatusDataHandler.init(storeProps); - - subscriberPersistenceManager = createSubscriberPersistenceManager(); - setSampleSubscriber(); - } - - @AfterMethod - public void tearDown() throws Exception { - - papStatusDataHandler.handle(ABOUT_POLICY, POLICY_KEY, statusHolderListForRemovePolicy); - papStatusDataHandler.handle(ABOUT_SUBSCRIBER, SUBSCRIBER_KEY, statusHolderListForRemovePolicyInPDP); - subscriberPersistenceManager.removeSubscriber(SUBSCRIBER_KEY); - } - - @DataProvider - public Object[][] papStatusDataProvider() { - - return new Object[][]{ - {ABOUT_POLICY, POLICY_KEY, statusHolderListForAddPolicy, statusHolderListForGetPolicy}, - {ABOUT_SUBSCRIBER, SUBSCRIBER_KEY, statusHolderListForAddPolicyInPDP, - statusHolderListForUpdatePolicyInPDP} - }; - } - - @DataProvider - public Object[][] dataProviderForRemoveStatus() { - - return new Object[][]{ - {ABOUT_POLICY, POLICY_KEY, statusHolderListForAddPolicy, statusHolderListForRemovePolicy}, - {ABOUT_SUBSCRIBER, SUBSCRIBER_KEY, statusHolderListForAddPolicyInPDP, - statusHolderListForRemovePolicyInPDP} - }; - } - - @Test(priority = 1, dataProvider = "papStatusDataProvider") - public void testHandlePolicyStatus(String about, String key, List statusHoldersForAdd, - List statusHoldersForModify) throws Exception { - - papStatusDataHandler.handle(about, key, statusHoldersForAdd); - - StatusHolder[] statusDataFromStorage = - papStatusDataHandler.getStatusData(about, key, null, "*"); - assertEquals(statusDataFromStorage.length, 1); - assertEquals(statusDataFromStorage[0].getType(), statusHoldersForAdd.get(0).getType()); - assertEquals(statusDataFromStorage[0].getKey(), statusHoldersForAdd.get(0).getKey()); - assertEquals(statusDataFromStorage[0].getTarget(), statusHoldersForAdd.get(0).getTarget()); - assertEquals(statusDataFromStorage[0].getTargetAction(), statusHoldersForAdd.get(0).getTargetAction()); - assertEquals(statusDataFromStorage[0].getUser(), statusHoldersForAdd.get(0).getUser()); - - papStatusDataHandler.handle(about, key, statusHoldersForModify); - - StatusHolder[] allStatusDataFromStorage = - papStatusDataHandler.getStatusData(about, key, null, "*"); - assertEquals(allStatusDataFromStorage.length, 2); - } - - @Test(priority = 2, dataProvider = "papStatusDataProvider") - public void testHandlePolicyWhenOnlyLastStatusUsed(String about, String key, List statusHoldersForAdd, - List statusHoldersForModify) throws Exception { - - try (MockedStatic identityUtil = mockStatic(IdentityUtil.class)) { - identityUtil.when(() -> IdentityUtil.getProperty(PROP_USE_LAST_STATUS_ONLY)).thenReturn("true"); - - papStatusDataHandler.handle(about, key, statusHoldersForAdd); - StatusHolder[] statusDataFromStorage = - papStatusDataHandler.getStatusData(about, key, null, "*"); - assertEquals(statusDataFromStorage.length, 1); - - papStatusDataHandler.handle(about, key, statusHoldersForModify); - statusDataFromStorage = papStatusDataHandler.getStatusData(about, key, null, "*"); - assertEquals(statusDataFromStorage.length, 1); - - assertEquals(statusDataFromStorage[0].getType(), statusHoldersForModify.get(0).getType()); - assertEquals(statusDataFromStorage[0].getKey(), statusHoldersForModify.get(0).getKey()); - assertEquals(statusDataFromStorage[0].getTarget(), statusHoldersForModify.get(0).getTarget()); - assertEquals(statusDataFromStorage[0].getTargetAction(), statusHoldersForModify.get(0).getTargetAction()); - assertEquals(statusDataFromStorage[0].getUser(), statusHoldersForModify.get(0).getUser()); - } - } - - @Test(priority = 3, dataProvider = "dataProviderForRemoveStatus") - public void testHandleRemovePolicyStatus(String about, String key, List statusHoldersForAdd, - List statusHoldersForRemove) throws Exception { - - papStatusDataHandler.handle(about, key, statusHoldersForAdd); - papStatusDataHandler.handle(about, key, statusHoldersForRemove); - - StatusHolder[] statusDataFromStorage = papStatusDataHandler.getStatusData(about, key, null, "*"); - assertEquals(statusDataFromStorage.length, 0); - } - - @Test(priority = 4, dataProvider = "papStatusDataProvider") - public void testHandlePolicyWhenMaxNoOfRecordsExceeds(String about, String key, - List statusHoldersForAdd, - List statusHoldersForModify) throws Exception { - - papStatusDataHandler.handle(about, key, statusHoldersForAdd); - papStatusDataHandler.handle(about, key, statusHoldersForModify); - papStatusDataHandler.handle(about, key, statusHoldersForModify); - papStatusDataHandler.handle(about, key, statusHoldersForModify); - papStatusDataHandler.handle(about, key, statusHoldersForModify); - - StatusHolder[] statusDataFromStorage = papStatusDataHandler.getStatusData(about, key, null, "*"); - assertEquals(statusDataFromStorage.length, 5); - - papStatusDataHandler.handle(about, key, statusHoldersForModify); - StatusHolder[] statusDataAfterMaxNoOfRecords = - papStatusDataHandler.getStatusData(about, key, null, "*"); - assertEquals(statusDataAfterMaxNoOfRecords.length, 5); - } - - private void setupPolicyStatusData() { - - statusHolderForAddPolicy = new StatusHolder(ADD_POLICY, POLICY_KEY, POLICY_VERSION_1, PAP_POLICY_STORE_TARGET, - TARGET_ACTION_PERSIST, true, null); - statusHolderForAddPolicy.setUser(SAMPLE_USER); - statusHolderListForAddPolicy = new ArrayList<>(); - statusHolderListForAddPolicy.add(statusHolderForAddPolicy); - - statusHolderForGetPolicy = new StatusHolder(GET_POLICY, POLICY_KEY, POLICY_VERSION_1, PAP_POLICY_STORE_TARGET, - TARGET_ACTION_LOAD, true, null); - statusHolderForGetPolicy.setUser(SAMPLE_USER); - statusHolderListForGetPolicy = new ArrayList<>(); - statusHolderListForGetPolicy.add(statusHolderForGetPolicy); - - statusHolderForRemovePolicy = - new StatusHolder(DELETE_POLICY, POLICY_KEY, POLICY_VERSION_1, PAP_POLICY_STORE_TARGET, - TARGET_ACTION_REMOVE, true, null); - statusHolderForRemovePolicy.setUser(SAMPLE_USER); - statusHolderListForRemovePolicy = new ArrayList<>(); - statusHolderListForRemovePolicy.add(statusHolderForRemovePolicy); - } - - private void setupSubscriberStatusData() { - - statusHolderForAddPolicyInPDP = new StatusHolder(PUBLISH_POLICY, SUBSCRIBER_KEY, POLICY_VERSION_1, POLICY_KEY, - ACTION_CREATE, true, null); - statusHolderForAddPolicyInPDP.setUser(SAMPLE_USER); - statusHolderListForAddPolicyInPDP = new ArrayList<>(); - statusHolderListForAddPolicyInPDP.add(statusHolderForAddPolicyInPDP); - - statusHolderForUpdatePolicyInPDP = - new StatusHolder(PUBLISH_POLICY, SUBSCRIBER_KEY, POLICY_VERSION_1, POLICY_KEY, - ACTION_UPDATE, true, null); - statusHolderForUpdatePolicyInPDP.setUser(SAMPLE_USER); - statusHolderListForUpdatePolicyInPDP = new ArrayList<>(); - statusHolderListForUpdatePolicyInPDP.add(statusHolderForUpdatePolicyInPDP); - - statusHolderForRemovePolicyInPDP = new StatusHolder(DELETE_POLICY, SUBSCRIBER_KEY, POLICY_VERSION_1, POLICY_KEY, - ACTION_DELETE, true, null); - statusHolderForRemovePolicyInPDP.setUser(SAMPLE_USER); - statusHolderListForRemovePolicyInPDP = new ArrayList<>(); - statusHolderListForRemovePolicyInPDP.add(statusHolderForRemovePolicyInPDP); - } - - private void setSampleSubscriber() throws Exception { - - // Create a sample subscriber. - PublisherPropertyDTO idProperty = new PublisherPropertyDTO(); - idProperty.setId(SUBSCRIBER_ID_KEY); - idProperty.setValue(SUBSCRIBER_KEY); - idProperty.setDisplayName(SUBSCRIBER_ID_DISPLAY_NAME); - idProperty.setSecret(false); - publisherDataHolder = new PublisherDataHolder(); - publisherDataHolder.setModuleName(SUBSCRIBER_MODULE_NAME); - publisherDataHolder.setPropertyDTOs(new PublisherPropertyDTO[]{idProperty}); - subscriberPersistenceManager.addSubscriber(publisherDataHolder); - } - - /** - * Abstract method to create the PAP Status Data Handler. - * - * @return The PAP Status Data Handler. - */ - protected abstract PAPStatusDataHandler createPAPStatusDataHandler(); - - /** - * Abstract method to create the subscriber persistence manager - * - * @return The subscriber persistence manager. - */ - protected abstract SubscriberPersistenceManager createSubscriberPersistenceManager(); -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/PersistenceManagerFactoryTest.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/PersistenceManagerFactoryTest.java deleted file mode 100644 index f0bfb5f3a2fa..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/PersistenceManagerFactoryTest.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.mockito.MockedStatic; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; -import org.wso2.carbon.base.CarbonBaseConstants; -import org.wso2.carbon.identity.entitlement.PAPStatusDataHandler; -import org.wso2.carbon.identity.entitlement.PDPConstants; -import org.wso2.carbon.identity.entitlement.SimplePAPStatusDataHandler; -import org.wso2.carbon.identity.entitlement.internal.EntitlementConfigHolder; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; - -import java.lang.reflect.Field; -import java.nio.file.Paths; -import java.util.Properties; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.mockStatic; -import static org.mockito.Mockito.when; -import static org.mockito.MockitoAnnotations.initMocks; -import static org.testng.Assert.assertTrue; - -/** - * This class tests the behavior of the PersistenceManagerFactory class. - */ -public class PersistenceManagerFactoryTest { - - MockedStatic entitlementServiceComponent; - - @BeforeMethod - public void setUp() { - - initMocks(this); - setUpCarbonHome(); - - Properties engineProperties = new Properties(); - engineProperties.put(PDPConstants.MAX_NO_OF_POLICY_VERSIONS, "0"); - - EntitlementConfigHolder mockEntitlementConfigHolder = mock(EntitlementConfigHolder.class); - when(mockEntitlementConfigHolder.getEngineProperties()).thenReturn(engineProperties); - - entitlementServiceComponent = mockStatic(EntitlementServiceComponent.class); - entitlementServiceComponent.when(EntitlementServiceComponent::getEntitlementConfig). - thenReturn(mockEntitlementConfigHolder); - } - - @AfterMethod - public void tearDown() throws Exception { - - entitlementServiceComponent.close(); - setPrivateStaticField(PersistenceManagerFactory.class, "POLICY_STORAGE_TYPE", ""); - } - - @Test - public void shouldReturnDBBasedPersistenceManagerWhenConfigIsDatabase() throws Exception { - - setPrivateStaticField(PersistenceManagerFactory.class, "POLICY_STORAGE_TYPE", "database"); - - // Validate Policy Persistence Manager. - PolicyPersistenceManager policyPersistenceManager = PersistenceManagerFactory.getPolicyPersistenceManager(); - assertTrue(policyPersistenceManager instanceof JDBCPolicyPersistenceManager); - - // Validate Config Persistence Manager. - ConfigPersistenceManager configPersistenceManager = PersistenceManagerFactory.getConfigPersistenceManager(); - assertTrue(configPersistenceManager instanceof JDBCConfigPersistenceManager); - - // Validate Subscriber Persistence Manager. - SubscriberPersistenceManager subscriberPersistenceManager = - PersistenceManagerFactory.getSubscriberPersistenceManager(); - assertTrue(subscriberPersistenceManager instanceof JDBCSubscriberPersistenceManager); - - // Validate the PAP Status Data Handler. - PAPStatusDataHandler papStatusDataHandler = PersistenceManagerFactory.getPAPStatusDataHandler(); - assertTrue(papStatusDataHandler instanceof JDBCSimplePAPStatusDataHandler); - } - - @Test - public void shouldReturnHybridPersistenceManagerWhenConfigIsOnMigration() throws Exception { - - setPrivateStaticField(PersistenceManagerFactory.class, "POLICY_STORAGE_TYPE", "hybrid"); - - // Validate Policy Persistence Manager. - PolicyPersistenceManager policyPersistenceManager = PersistenceManagerFactory.getPolicyPersistenceManager(); - assertTrue(policyPersistenceManager instanceof HybridPolicyPersistenceManager); - - // Validate Config Persistence Manager. - ConfigPersistenceManager configPersistenceManager = PersistenceManagerFactory.getConfigPersistenceManager(); - assertTrue(configPersistenceManager instanceof HybridConfigPersistenceManager); - - // Validate Subscriber Persistence Manager. - SubscriberPersistenceManager subscriberPersistenceManager = - PersistenceManagerFactory.getSubscriberPersistenceManager(); - assertTrue(subscriberPersistenceManager instanceof HybridSubscriberPersistenceManager); - - // Validate the PAP Status Data Handler. - PAPStatusDataHandler papStatusDataHandler = PersistenceManagerFactory.getPAPStatusDataHandler(); - assertTrue(papStatusDataHandler instanceof HybridPAPStatusDataHandler); - } - - @Test - public void shouldReturnRegistryBasedPersistenceManagerWhenConfigIsRegistry() throws Exception { - - - setPrivateStaticField(PersistenceManagerFactory.class, "POLICY_STORAGE_TYPE", "registry"); - - // Validate Policy Persistence Manager. - PolicyPersistenceManager policyPersistenceManager = PersistenceManagerFactory.getPolicyPersistenceManager(); - assertTrue(policyPersistenceManager instanceof RegistryPolicyPersistenceManager); - - // Validate Config Persistence Manager. - ConfigPersistenceManager configPersistenceManager = PersistenceManagerFactory.getConfigPersistenceManager(); - assertTrue(configPersistenceManager instanceof RegistryConfigPersistenceManager); - - // Validate Subscriber Persistence Manager. - SubscriberPersistenceManager subscriberPersistenceManager = - PersistenceManagerFactory.getSubscriberPersistenceManager(); - assertTrue(subscriberPersistenceManager instanceof RegistrySubscriberPersistenceManager); - - // Validate the PAP Status Data Handler. - PAPStatusDataHandler papStatusDataHandler = PersistenceManagerFactory.getPAPStatusDataHandler(); - assertTrue(papStatusDataHandler instanceof SimplePAPStatusDataHandler); - } - - @Test - public void shouldReturnDBBasedPersistenceManagerWhenConfigIsInvalid() throws Exception { - - setPrivateStaticField(PersistenceManagerFactory.class, "POLICY_STORAGE_TYPE", "invalid"); - - // Validate Policy Persistence Manager. - PolicyPersistenceManager policyPersistenceManager = PersistenceManagerFactory.getPolicyPersistenceManager(); - assertTrue(policyPersistenceManager instanceof JDBCPolicyPersistenceManager); - - // Validate Config Persistence Manager. - ConfigPersistenceManager configPersistenceManager = PersistenceManagerFactory.getConfigPersistenceManager(); - assertTrue(configPersistenceManager instanceof JDBCConfigPersistenceManager); - - // Validate Subscriber Persistence Manager. - SubscriberPersistenceManager subscriberPersistenceManager = - PersistenceManagerFactory.getSubscriberPersistenceManager(); - assertTrue(subscriberPersistenceManager instanceof JDBCSubscriberPersistenceManager); - - // Validate the PAP Status Data Handler. - PAPStatusDataHandler papStatusDataHandler = PersistenceManagerFactory.getPAPStatusDataHandler(); - assertTrue(papStatusDataHandler instanceof JDBCSimplePAPStatusDataHandler); - } - - @Test - public void shouldReturnDBBasedPersistenceManagerWhenConfigIsEmpty() throws Exception { - - setPrivateStaticField(PersistenceManagerFactory.class, "POLICY_STORAGE_TYPE", ""); - - // Validate Policy Persistence Manager. - PolicyPersistenceManager policyPersistenceManager = PersistenceManagerFactory.getPolicyPersistenceManager(); - assertTrue(policyPersistenceManager instanceof JDBCPolicyPersistenceManager); - - // Validate Config Persistence Manager. - ConfigPersistenceManager configPersistenceManager = PersistenceManagerFactory.getConfigPersistenceManager(); - assertTrue(configPersistenceManager instanceof JDBCConfigPersistenceManager); - - // Validate Subscriber Persistence Manager. - SubscriberPersistenceManager subscriberPersistenceManager = - PersistenceManagerFactory.getSubscriberPersistenceManager(); - assertTrue(subscriberPersistenceManager instanceof JDBCSubscriberPersistenceManager); - - // Validate the PAP Status Data Handler. - PAPStatusDataHandler papStatusDataHandler = PersistenceManagerFactory.getPAPStatusDataHandler(); - assertTrue(papStatusDataHandler instanceof JDBCSimplePAPStatusDataHandler); - } - - @Test - public void shouldReturnDBBasedPersistenceManagerWhenConfigIsNull() throws Exception { - - setPrivateStaticField(PersistenceManagerFactory.class, "POLICY_STORAGE_TYPE", null); - - // Validate Policy Persistence Manager. - PolicyPersistenceManager policyPersistenceManager = PersistenceManagerFactory.getPolicyPersistenceManager(); - assertTrue(policyPersistenceManager instanceof JDBCPolicyPersistenceManager); - - // Validate Config Persistence Manager. - ConfigPersistenceManager configPersistenceManager = PersistenceManagerFactory.getConfigPersistenceManager(); - assertTrue(configPersistenceManager instanceof JDBCConfigPersistenceManager); - - // Validate Subscriber Persistence Manager. - SubscriberPersistenceManager subscriberPersistenceManager = - PersistenceManagerFactory.getSubscriberPersistenceManager(); - assertTrue(subscriberPersistenceManager instanceof JDBCSubscriberPersistenceManager); - - // Validate the PAP Status Data Handler. - PAPStatusDataHandler papStatusDataHandler = PersistenceManagerFactory.getPAPStatusDataHandler(); - assertTrue(papStatusDataHandler instanceof JDBCSimplePAPStatusDataHandler); - } - - - private static void setUpCarbonHome() { - - String carbonHome = Paths.get(System.getProperty("user.dir"), "target", "test-classes").toString(); - System.setProperty(CarbonBaseConstants.CARBON_HOME, carbonHome); - System.setProperty(CarbonBaseConstants.CARBON_CONFIG_DIR_PATH, Paths.get(carbonHome, - "repository/conf").toString()); - } - - private void setPrivateStaticField(Class clazz, String fieldName, Object newValue) - throws NoSuchFieldException, IllegalAccessException { - - Field field = clazz.getDeclaredField(fieldName); - field.setAccessible(true); - field.set(null, newValue); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/PolicyPersistenceManagerFailureTest.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/PolicyPersistenceManagerFailureTest.java deleted file mode 100644 index b20a96b8a951..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/PolicyPersistenceManagerFailureTest.java +++ /dev/null @@ -1,350 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.mockito.Mock; -import org.mockito.MockedStatic; -import org.mockito.MockitoAnnotations; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.common.testng.WithCarbonHome; -import org.wso2.carbon.identity.common.testng.WithRealmService; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.PDPConstants; -import org.wso2.carbon.identity.entitlement.dto.AttributeDTO; -import org.wso2.carbon.identity.entitlement.dto.PolicyDTO; -import org.wso2.carbon.identity.entitlement.dto.PolicyStoreDTO; -import org.wso2.carbon.identity.entitlement.internal.EntitlementConfigHolder; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; -import org.wso2.carbon.identity.entitlement.persistence.cache.CacheBackedPolicyDAO; -import org.wso2.carbon.registry.core.CollectionImpl; -import org.wso2.carbon.registry.core.Registry; -import org.wso2.carbon.registry.core.exceptions.RegistryException; -import org.wso2.carbon.registry.core.exceptions.ResourceNotFoundException; - -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.mockStatic; -import static org.mockito.Mockito.when; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertThrows; - -/** - * This class tests the failure scenarios of Database or Registry in Registry Policy Persistence Manager implementation. - */ -@WithCarbonHome -@WithRealmService(injectToSingletons = {EntitlementConfigHolder.class}, initUserStoreManager = true) -public class PolicyPersistenceManagerFailureTest { - - static final String SAMPLE_POLICY_STRING_1 = - "GETresourceASri LankaEngineer"; - static final String SAMPLE_POLICY_ID_1 = "sample_policy1"; - - PolicyDTO samplePAPPolicy1; - PolicyStoreDTO samplePDPPolicy1; - - @Mock - private CacheBackedPolicyDAO mockedPolicyDAO; - - @Mock - private Registry mockedRegistry; - - MockedStatic entitlementServiceComponent; - private RegistryPolicyPersistenceManager registryPolicyPersistenceManager; - private JDBCPolicyPersistenceManager jdbcPolicyPersistenceManager; - - @BeforeMethod - public void setUp() throws Exception { - - MockitoAnnotations.openMocks(this); - - Properties engineProperties = new Properties(); - engineProperties.put(PDPConstants.MAX_NO_OF_POLICY_VERSIONS, "4"); - - EntitlementConfigHolder mockEntitlementConfigHolder = mock(EntitlementConfigHolder.class); - when(mockEntitlementConfigHolder.getEngineProperties()).thenReturn(engineProperties); - - entitlementServiceComponent = mockStatic(EntitlementServiceComponent.class); - entitlementServiceComponent.when(EntitlementServiceComponent::getEntitlementConfig). - thenReturn(mockEntitlementConfigHolder); - entitlementServiceComponent.when(() -> EntitlementServiceComponent.getGovernanceRegistry(anyInt())) - .thenReturn(mockedRegistry); - - Properties storeProps = new Properties(); - registryPolicyPersistenceManager = new RegistryPolicyPersistenceManager(); - storeProps.setProperty("policyStorePath", "/repository/identity/entitlement/policy/pdp/"); - registryPolicyPersistenceManager.init(storeProps); - jdbcPolicyPersistenceManager = new JDBCPolicyPersistenceManager(); - setPrivateStaticFinalField(JDBCPolicyPersistenceManager.class, "policyDAO", mockedPolicyDAO); - - samplePAPPolicy1 = new PolicyDTO(SAMPLE_POLICY_ID_1); - samplePAPPolicy1.setPolicy(SAMPLE_POLICY_STRING_1); - samplePDPPolicy1 = getPDPPolicy(SAMPLE_POLICY_ID_1, SAMPLE_POLICY_STRING_1, "1", true, true, 0, false); - } - - @AfterMethod - public void tearDown() throws Exception { - - entitlementServiceComponent.close(); - registryPolicyPersistenceManager = null; - setPrivateStaticFinalField(JDBCPolicyPersistenceManager.class, "policyDAO", - CacheBackedPolicyDAO.getInstance()); - } - - @Test - public void testAddOrUpdatePolicyWhenDatabaseErrorHappened() throws Exception { - - doThrow(new EntitlementException("")).when(mockedPolicyDAO).insertPolicy(any(), anyInt()); - assertThrows(EntitlementException.class, - () -> jdbcPolicyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true)); - } - - @Test - public void testGetPAPPolicyWhenDatabaseErrorHappened() throws Exception { - - when(mockedPolicyDAO.getPAPPolicy(anyString(), anyInt())).thenThrow(new EntitlementException("")); - when(mockedRegistry.resourceExists(anyString())).thenReturn(true); - assertThrows(EntitlementException.class, - () -> jdbcPolicyPersistenceManager.getPAPPolicy(samplePAPPolicy1.getPolicyId())); - } - - @Test - public void testGetActivePoliciesWhenDatabaseErrorHappened() throws Exception { - - when(mockedPolicyDAO.getAllPDPPolicies(anyInt())).thenThrow(new EntitlementException("")); - String[] activePolicies = jdbcPolicyPersistenceManager.getActivePolicies(); - assertEquals(activePolicies.length, 0); - } - - @Test - public void testGetOrderedPolicyIdentifiersWhenDatabaseErrorHappened() throws Exception { - - when(mockedPolicyDAO.getAllPDPPolicies(anyInt())).thenThrow(new EntitlementException("")); - String[] orderedPolicies = jdbcPolicyPersistenceManager.getOrderedPolicyIdentifiers(); - assertEquals(orderedPolicies.length, 0); - } - - @Test - public void testGetPolicyIdentifiersWhenDatabaseErrorHappened() throws Exception { - - when(mockedPolicyDAO.getPublishedPolicyIds(anyInt())).thenThrow(new EntitlementException("")); - assertNull(jdbcPolicyPersistenceManager.getPolicyIdentifiers()); - } - - @Test - public void testGetSearchAttributesWhenDatabaseErrorHappened() throws Exception { - - when(mockedPolicyDAO.getAllPDPPolicies(anyInt())).thenThrow(new EntitlementException("")); - Map> attributes = jdbcPolicyPersistenceManager.getSearchAttributes(null, null); - assertEquals(attributes.size(), 0); - } - - @Test - public void testRemovePolicyWhenDatabaseErrorHappened() throws Exception { - - doThrow(new EntitlementException("")).when(mockedPolicyDAO).deletePAPPolicy(anyString(), anyInt()); - assertThrows(EntitlementException.class, - () -> jdbcPolicyPersistenceManager.removePolicy(samplePAPPolicy1.getPolicyId())); - } - - @Test - public void testAddPdPPolicyWhenDatabaseErrorHappened() throws Exception { - - doThrow(new EntitlementException("")).when(mockedPolicyDAO).insertOrUpdatePolicy(any(), anyInt()); - assertThrows(EntitlementException.class, - () -> jdbcPolicyPersistenceManager.addPolicy(samplePDPPolicy1)); - } - - @Test - public void testAddOrUpdatePolicyWhenRegistryErrorHappened() throws Exception { - - when(mockedRegistry.get(anyString())).thenThrow(new ResourceNotFoundException("")); - when(mockedRegistry.newCollection()).thenReturn(new CollectionImpl()); - when(mockedRegistry.put(anyString(), any())).thenThrow(new RegistryException("")); - when(mockedRegistry.resourceExists(anyString())).thenThrow(new RegistryException("")); - assertThrows(EntitlementException.class, - () -> registryPolicyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true)); - assertThrows(EntitlementException.class, - () -> registryPolicyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, false)); - } - - @Test - public void testGetPAPPolicyWhenRegistryErrorHappened() throws Exception { - - when(mockedRegistry.get(anyString())).thenThrow(new RegistryException("")); - when(mockedRegistry.resourceExists(anyString())).thenReturn(true); - assertThrows(EntitlementException.class, - () -> registryPolicyPersistenceManager.getPAPPolicy(samplePAPPolicy1.getPolicyId())); - } - - @Test - public void testGetVersionsWhenRegistryErrorHappened() throws Exception { - - when(mockedRegistry.get(anyString())).thenThrow(new RegistryException("")); - String[] versions = registryPolicyPersistenceManager.getVersions(samplePAPPolicy1.getPolicyId()); - assertEquals(versions.length, 0); - } - - @Test - public void testGetVersionsWhenRegistryErrorHappenedDueToResourceNotFound() throws Exception { - - when(mockedRegistry.get(anyString())).thenThrow(new ResourceNotFoundException("")); - String[] versions = registryPolicyPersistenceManager.getVersions(samplePAPPolicy1.getPolicyId()); - assertEquals(versions.length, 0); - } - - @Test - public void testGetActivePoliciesWhenRegistryErrorHappened() throws Exception { - - when(mockedRegistry.resourceExists(anyString())).thenThrow(new RegistryException("")); - String[] activePolicies = registryPolicyPersistenceManager.getActivePolicies(); - assertEquals(activePolicies.length, 0); - } - - @Test - public void testGetActivePoliciesWhenResourceNotExists() throws Exception { - - when(mockedRegistry.resourceExists(anyString())).thenReturn(false); - String[] activePolicies = registryPolicyPersistenceManager.getActivePolicies(); - assertEquals(activePolicies.length, 0); - } - - @Test - public void testGetOrderedPolicyIdentifiersWhenRegistryErrorHappened() throws Exception { - - when(mockedRegistry.resourceExists(anyString())).thenThrow(new RegistryException("")); - String[] orderedPolicies = registryPolicyPersistenceManager.getOrderedPolicyIdentifiers(); - assertEquals(orderedPolicies.length, 0); - } - - @Test - public void testGetPolicyIdentifiersWhenRegistryErrorHappened() throws Exception { - - when(mockedRegistry.resourceExists(anyString())).thenThrow(new RegistryException("")); - assertNull(registryPolicyPersistenceManager.getPolicyIdentifiers()); - } - - @Test - public void testGetPolicyIdentifiersWhenResourceNotExists() throws Exception { - - when(mockedRegistry.resourceExists(anyString())).thenReturn(false); - String[] policyIds = registryPolicyPersistenceManager.getPolicyIdentifiers(); - assertEquals(policyIds.length, 0); - } - - @Test - public void testGetSearchAttributesWhenRegistryErrorHappened() throws Exception { - - when(mockedRegistry.resourceExists(anyString())).thenThrow(new RegistryException("")); - Map> attributes = registryPolicyPersistenceManager.getSearchAttributes(null, null); - assertEquals(attributes.size(), 0); - } - - @Test - public void testIsPolicyExistsInPAPPWhenRegistryErrorHappened() throws Exception { - - when(mockedRegistry.resourceExists(anyString())).thenThrow(new RegistryException("")); - assertFalse(registryPolicyPersistenceManager.isPolicyExistsInPap(samplePAPPolicy1.getPolicyId())); - } - - @Test - public void testRemovePolicyWhenRegistryErrorHappened() throws Exception { - - when(mockedRegistry.resourceExists(anyString())).thenThrow(new RegistryException("")); - assertThrows(EntitlementException.class, - () -> registryPolicyPersistenceManager.removePolicy(samplePAPPolicy1.getPolicyId())); - } - - @Test - public void testAddPdPPolicyWhenRegistryErrorHappened() throws Exception { - - when(mockedRegistry.resourceExists(anyString())).thenThrow(new RegistryException("")); - assertThrows(EntitlementException.class, - () -> registryPolicyPersistenceManager.addPolicy(samplePDPPolicy1)); - } - - @Test - public void testIsPolicyExistsInPDPWhenRegistryErrorHappened() throws Exception { - - when(mockedRegistry.resourceExists(anyString())).thenThrow(new RegistryException("")); - assertFalse(registryPolicyPersistenceManager.isPolicyExist(samplePAPPolicy1.getPolicyId())); - } - - @Test - public void testDeletePolicyFromPDPWhenRegistryErrorHappened() throws Exception { - - doThrow(new RegistryException("")).when(mockedRegistry).delete(anyString()); - assertFalse(registryPolicyPersistenceManager.deletePolicy(samplePAPPolicy1.getPolicyId())); - } - - @Test - public void testGetPublishedPolicyWhenRegistryErrorHappened() throws Exception { - - when(mockedRegistry.get(anyString())).thenThrow(new RegistryException("")); - when(mockedRegistry.resourceExists(anyString())).thenReturn(true); - assertNull(registryPolicyPersistenceManager.getPolicy(samplePAPPolicy1.getPolicyId())); - } - - private PolicyStoreDTO getPDPPolicy(String id, String policy, String version, boolean active, boolean setActive, - int order, boolean setOrder) { - - PolicyStoreDTO policyStoreDTO = new PolicyStoreDTO(); - if (id != null) { - policyStoreDTO.setPolicyId(id); - } - if (policy != null) { - policyStoreDTO.setPolicy(policy); - } - if (version != null) { - policyStoreDTO.setVersion(version); - } - policyStoreDTO.setActive(active); - policyStoreDTO.setSetActive(setActive); - if (order != 0) { - policyStoreDTO.setPolicyOrder(order); - } - policyStoreDTO.setSetOrder(setOrder); - return policyStoreDTO; - } - - private static void setPrivateStaticFinalField(Class clazz, String fieldName, Object newValue) - throws ReflectiveOperationException { - - Field field = clazz.getDeclaredField(fieldName); - field.setAccessible(true); - - Field modifiers = Field.class.getDeclaredField("modifiers"); - modifiers.setAccessible(true); - modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL); - - field.set(null, newValue); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/PolicyPersistenceManagerTest.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/PolicyPersistenceManagerTest.java deleted file mode 100644 index e2de0baee50e..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/PolicyPersistenceManagerTest.java +++ /dev/null @@ -1,506 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.PDPConstants; -import org.wso2.carbon.identity.entitlement.dto.AttributeDTO; -import org.wso2.carbon.identity.entitlement.dto.PolicyDTO; -import org.wso2.carbon.identity.entitlement.dto.PolicyStoreDTO; -import org.wso2.carbon.identity.entitlement.internal.EntitlementConfigHolder; -import org.wso2.carbon.identity.entitlement.policy.finder.PolicyFinderModule; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertThrows; -import static org.testng.Assert.assertTrue; - -/** - * This is the parent test class for the Policy Persistence Manager test classes. - */ -public abstract class PolicyPersistenceManagerTest { - - PolicyPersistenceManager policyPersistenceManager; - - static final String SAMPLE_POLICY_STRING_1 = - "GETresourceASri LankaEngineer"; - static final String SAMPLE_POLICY_STRING_2 = - "GETresourceAIndiaEngineer"; - static final String SAMPLE_POLICY_STRING_3 = - "GETresourceAIndiaDoctor"; - - static final String SAMPLE_POLICY_ID_1 = "sample_policy1"; - static final String SAMPLE_POLICY_ID_2 = "sample_policy2"; - static final String SAMPLE_POLICY_ID_3 = "sample_policy3"; - - PolicyDTO samplePAPPolicy1; - PolicyDTO samplePAPPolicy2; - PolicyDTO samplePAPPolicy3; - PolicyDTO sampleUpdatedPAPPolicy1; - PolicyDTO papPolicyWithEmptyPolicyId; - - PolicyStoreDTO samplePDPPolicy1; - PolicyStoreDTO samplePDPPolicy2; - PolicyStoreDTO samplePDPPolicy3; - PolicyStoreDTO orderedSamplePDPPolicy1; - PolicyStoreDTO inactiveSamplePDPPolicy1; - PolicyStoreDTO updatedSamplePDPPolicy1; - PolicyStoreDTO pdpPolicyWithEmptyId; - PolicyStoreDTO pdpPolicyWithEmptyVersion; - - @BeforeMethod - public void setUp() { - - Properties engineProperties = new Properties(); - engineProperties.put(PDPConstants.MAX_NO_OF_POLICY_VERSIONS, "4"); - EntitlementConfigHolder.getInstance().setEngineProperties(engineProperties); - policyPersistenceManager = createPolicyPersistenceManager(); - - samplePAPPolicy1 = new PolicyDTO(SAMPLE_POLICY_ID_1); - samplePAPPolicy1.setPolicy(SAMPLE_POLICY_STRING_1); - samplePAPPolicy1.setPolicyEditorData(new String[]{"category|Resource", "policyDescription|"}); - samplePAPPolicy1.setPolicyEditor("XML"); - samplePAPPolicy1.setPolicyOrder(3); - - samplePAPPolicy2 = new PolicyDTO(SAMPLE_POLICY_ID_2); - samplePAPPolicy2.setPolicy(SAMPLE_POLICY_STRING_2); - - samplePAPPolicy3 = new PolicyDTO(SAMPLE_POLICY_ID_3); - samplePAPPolicy3.setPolicy(SAMPLE_POLICY_STRING_3); - - sampleUpdatedPAPPolicy1 = new PolicyDTO(SAMPLE_POLICY_ID_1); - sampleUpdatedPAPPolicy1.setPolicy(SAMPLE_POLICY_STRING_2); - - papPolicyWithEmptyPolicyId = new PolicyDTO(); - papPolicyWithEmptyPolicyId.setPolicy(null); - papPolicyWithEmptyPolicyId.setPolicy(SAMPLE_POLICY_STRING_1); - - samplePDPPolicy1 = getPDPPolicy(SAMPLE_POLICY_ID_1, SAMPLE_POLICY_STRING_1, "1", true, true, 0, false); - samplePDPPolicy2 = getPDPPolicy(SAMPLE_POLICY_ID_2, SAMPLE_POLICY_STRING_2, "1", false, true, 0, false); - samplePDPPolicy3 = getPDPPolicy(SAMPLE_POLICY_ID_3, SAMPLE_POLICY_STRING_3, "1", true, true, 2, true); - - orderedSamplePDPPolicy1 = getPDPPolicy(SAMPLE_POLICY_ID_1, SAMPLE_POLICY_STRING_1, null, true, false, 2, true); - inactiveSamplePDPPolicy1 = getPDPPolicy(SAMPLE_POLICY_ID_1, null, null, false, true, 0, false); - updatedSamplePDPPolicy1 = getPDPPolicy(SAMPLE_POLICY_ID_1, SAMPLE_POLICY_STRING_2, "2", true, false, 0, false); - pdpPolicyWithEmptyId = getPDPPolicy(null, null, null, false, false, 0, false); - pdpPolicyWithEmptyVersion = getPDPPolicy(SAMPLE_POLICY_ID_1, null, "", true, false, 0, false); - } - - @AfterMethod - public void tearDown() throws Exception { - - // Unpublish PDP policies used in test cases. - policyPersistenceManager.deletePolicy(SAMPLE_POLICY_ID_1); - policyPersistenceManager.deletePolicy(SAMPLE_POLICY_ID_2); - policyPersistenceManager.deletePolicy(SAMPLE_POLICY_ID_3); - - // Remove PAP policies used in test cases. - policyPersistenceManager.removePolicy(SAMPLE_POLICY_ID_1); - policyPersistenceManager.removePolicy(SAMPLE_POLICY_ID_2); - policyPersistenceManager.removePolicy(SAMPLE_POLICY_ID_3); - } - - @Test(priority = 1) - public void testGetModuleName() { - - assertEquals(policyPersistenceManager.getModuleName(), PDPConstants.MODULE_NAME); - } - - @Test(priority = 2) - public void testGetSupportedSearchAttributesScheme() { - - assertEquals(policyPersistenceManager.getSupportedSearchAttributesScheme(), - PolicyFinderModule.COMBINATIONS_BY_CATEGORY_AND_PARAMETER); - } - - @Test(priority = 3) - public void testAddPAPPolicy() throws Exception { - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - - PolicyDTO policyFromStorage = policyPersistenceManager.getPAPPolicy(samplePAPPolicy1.getPolicyId()); - assertEquals(policyFromStorage.getPolicy(), samplePAPPolicy1.getPolicy()); - assertEquals(policyFromStorage.getPolicyId(), samplePAPPolicy1.getPolicyId()); - assertEquals(policyFromStorage.getVersion(), "1"); - assertEquals(policyFromStorage.getPolicyEditorData(), samplePAPPolicy1.getPolicyEditorData()); - assertEquals(policyFromStorage.getPolicyOrder(), samplePAPPolicy1.getPolicyOrder()); - assertEquals(policyFromStorage.getAttributeDTOs().length, 4); - } - - @Test(priority = 3, dependsOnMethods = {"testAddPAPPolicy"}) - public void testAddPAPPolicyWhenPolicyMetaDataStoringDisabled() throws Exception { - - Properties properties = EntitlementConfigHolder.getInstance().getEngineProperties(); - properties.setProperty(PDPConstants.STORE_POLICY_META_DATA, "false"); - EntitlementConfigHolder.getInstance().setEngineProperties(properties); - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - // Verify weather the policy meta-data was not stored for PAP policy. - PolicyDTO papPolicyFromStorage = policyPersistenceManager.getPAPPolicy(samplePDPPolicy1.getPolicyId()); - assertEquals(papPolicyFromStorage.getAttributeDTOs().length, 0); - - properties.setProperty(PDPConstants.STORE_POLICY_META_DATA, "true"); - EntitlementConfigHolder.getInstance().setEngineProperties(properties); - } - - @Test(priority = 3) - public void testAddInvalidPolicy() { - - assertThrows(EntitlementException.class, () -> policyPersistenceManager. - addOrUpdatePolicy(papPolicyWithEmptyPolicyId, true)); - } - - @Test(priority = 3) - public void testAddPolicyMoreThanMaxVersions() throws Exception { - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - - String[] policyVersions = policyPersistenceManager.getVersions(samplePAPPolicy1.getPolicyId()); - assertEquals(policyVersions.length, 5); - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - String[] policyVersionsAfterMax = policyPersistenceManager.getVersions(samplePAPPolicy1.getPolicyId()); - assertEquals(policyVersionsAfterMax.length, 5); - assertFalse(Arrays.asList(policyVersionsAfterMax).contains("1")); - } - - @Test(priority = 3) - public void testAddPolicyMoreThanMaxVersionsWhenPolicyWasPublished() throws Exception { - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.addPolicy(samplePDPPolicy1); - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - - String[] policyVersions = policyPersistenceManager.getVersions(samplePAPPolicy1.getPolicyId()); - assertEquals(policyVersions.length, 5); - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - String[] policyVersionsAfterMax = policyPersistenceManager.getVersions(samplePAPPolicy1.getPolicyId()); - assertEquals(policyVersionsAfterMax.length, 5); - assertFalse(Arrays.asList(policyVersionsAfterMax).contains("1")); - - // Verify weather the policy was not deleted from PDP. - assertTrue(policyPersistenceManager.isPolicyExist(samplePAPPolicy1.getPolicyId())); - } - - @Test(priority = 3) - public void testGetPolicyForInvalidScenarios() throws EntitlementException { - - assertThrows(EntitlementException.class, () -> policyPersistenceManager. - getPolicy(SAMPLE_POLICY_ID_1, "")); - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - assertThrows(EntitlementException.class, () -> policyPersistenceManager. - getPolicy(SAMPLE_POLICY_ID_1, "2")); - } - - @Test(priority = 4) - public void testDeletePAPPolicy() throws Exception { - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.removePolicy(samplePAPPolicy1.getPolicyId()); - assertNull(policyPersistenceManager.getPAPPolicy(samplePAPPolicy1.getPolicyId())); - } - - @Test(priority = 4) - public void testDeletePublishedPAPPolicyFromPAP() throws Exception { - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.addPolicy(samplePDPPolicy1); - policyPersistenceManager.removePolicy(samplePAPPolicy1.getPolicyId()); - - assertNull(policyPersistenceManager.getPAPPolicy(samplePAPPolicy1.getPolicyId())); - assertTrue(policyPersistenceManager.isPolicyExist(samplePAPPolicy1.getPolicyId())); - - policyPersistenceManager.deletePolicy(samplePAPPolicy1.getPolicyId()); - policyPersistenceManager.removePolicy(samplePAPPolicy1.getPolicyId()); - assertFalse(policyPersistenceManager.isPolicyExist(samplePAPPolicy1.getPolicyId())); - } - - @Test(priority = 5) - public void testListPAPPolicy() throws Exception { - - List policyIds = new ArrayList<>(); - List papPolicies = policyPersistenceManager.getPAPPolicies(policyIds); - assertEquals(papPolicies.size(), 0); - papPolicies = policyPersistenceManager.getPAPPolicies(null); - assertEquals(papPolicies.size(), 0); - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy2, true); - - policyIds.add(samplePAPPolicy1.getPolicyId()); - policyIds.add(samplePAPPolicy2.getPolicyId()); - List papPoliciesFromStorage = policyPersistenceManager.getPAPPolicies(policyIds); - assertEquals(papPoliciesFromStorage.size(), 2); - - List policyIdListFromStorage = policyPersistenceManager.listPolicyIds(); - assertEquals(policyIdListFromStorage.size(), 2); - assertTrue(policyIdListFromStorage.containsAll(policyIds)); - } - - @Test(priority = 6) - public void testUpdatePAPPolicy() throws Exception { - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.addOrUpdatePolicy(sampleUpdatedPAPPolicy1, true); - - PolicyDTO updatedPolicyFromStorage = policyPersistenceManager.getPAPPolicy(samplePAPPolicy1.getPolicyId()); - assertEquals(updatedPolicyFromStorage.getPolicy(), sampleUpdatedPAPPolicy1.getPolicy()); - assertEquals(updatedPolicyFromStorage.getPolicyId(), sampleUpdatedPAPPolicy1.getPolicyId()); - assertEquals(updatedPolicyFromStorage.getVersion(), "2"); - - // Verify the policy version 1. - PolicyDTO policyVersion1 = policyPersistenceManager.getPolicy(samplePAPPolicy1.getPolicyId(), "1"); - assertEquals(policyVersion1.getPolicy(), samplePAPPolicy1.getPolicy()); - // Verify the policy version 2. - PolicyDTO policyVersion2 = policyPersistenceManager.getPolicy(samplePAPPolicy1.getPolicyId(), "2"); - assertEquals(policyVersion2.getPolicy(), sampleUpdatedPAPPolicy1.getPolicy()); - - // Verify the total number of versions. - String[] policyVersions = policyPersistenceManager.getVersions(samplePAPPolicy1.getPolicyId()); - assertEquals(policyVersions.length, 2); - } - - @Test(priority = 6) - public void testGetPolicyWithoutVersion() throws Exception { - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.addOrUpdatePolicy(sampleUpdatedPAPPolicy1, true); - - // Verify the policy version without defining the version. - PolicyDTO latestPolicy = policyPersistenceManager.getPolicy(samplePAPPolicy1.getPolicyId(), " "); - assertEquals(latestPolicy.getPolicy(), sampleUpdatedPAPPolicy1.getPolicy()); - - latestPolicy = policyPersistenceManager.getPolicy(samplePAPPolicy1.getPolicyId(), null); - assertEquals(latestPolicy.getPolicy(), sampleUpdatedPAPPolicy1.getPolicy()); - } - - @Test(priority = 7) - public void testAddPDPPolicy() throws Exception { - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.addPolicy(samplePDPPolicy1); - - assertTrue(policyPersistenceManager.isPolicyExist(samplePDPPolicy1.getPolicyId())); - PolicyStoreDTO publishedPolicyFromStorage = - policyPersistenceManager.getPublishedPolicy(samplePDPPolicy1.getPolicyId()); - assertEquals(publishedPolicyFromStorage.getPolicy(), samplePDPPolicy1.getPolicy()); - assertEquals(publishedPolicyFromStorage.getPolicyId(), samplePDPPolicy1.getPolicyId()); - } - - @Test(priority = 7) - public void testIsPolicyExists() throws Exception { - - assertFalse(policyPersistenceManager.isPolicyExist(null)); - assertFalse(policyPersistenceManager.isPolicyExist("")); - assertFalse(policyPersistenceManager.isPolicyExist("sample_policy1")); - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.addPolicy(samplePDPPolicy1); - assertTrue(policyPersistenceManager.isPolicyExist(samplePDPPolicy1.getPolicyId())); - } - - @Test(priority = 7) - public void testAddInvalidPDPPolicy() throws Exception { - - assertThrows(EntitlementException.class, () -> policyPersistenceManager.addPolicy(pdpPolicyWithEmptyId)); - assertThrows(EntitlementException.class, () -> policyPersistenceManager.addPolicy(pdpPolicyWithEmptyVersion)); - assertThrows(EntitlementException.class, () -> policyPersistenceManager.addPolicy(null)); - } - - @Test(priority = 8) - public void testDeletePDPPolicy() throws Exception { - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.addPolicy(samplePDPPolicy1); - - policyPersistenceManager.deletePolicy(samplePDPPolicy1.getPolicyId()); - assertFalse(policyPersistenceManager.isPolicyExist(samplePDPPolicy1.getPolicyId())); - } - - @Test(priority = 8) - public void testDeletePDPPolicyUsingBlankID() throws Exception { - - assertFalse(policyPersistenceManager.deletePolicy(null)); - assertFalse(policyPersistenceManager.deletePolicy("")); - } - - @Test(priority = 9) - public void testGetReferencedPolicy() throws Exception { - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy2, true); - - policyPersistenceManager.addPolicy(samplePDPPolicy1); - policyPersistenceManager.addPolicy(samplePDPPolicy2); - - // Verify the policies that are not active. - assertNull(policyPersistenceManager.getReferencedPolicy(samplePDPPolicy1.getPolicyId())); - assertEquals(policyPersistenceManager.getReferencedPolicy(samplePDPPolicy2.getPolicyId()), - samplePDPPolicy2.getPolicy()); - } - - @Test(priority = 10) - public void testGetPolicyOrder() throws Exception { - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy3, true); - - policyPersistenceManager.addPolicy(samplePDPPolicy1); - policyPersistenceManager.addPolicy(samplePDPPolicy3); - - // Verify the policy order. - assertEquals(policyPersistenceManager.getPolicyOrder(samplePDPPolicy1.getPolicyId()), 0); - assertEquals(policyPersistenceManager.getPolicyOrder(samplePDPPolicy3.getPolicyId()), - samplePDPPolicy3.getPolicyOrder()); - } - - @Test(priority = 11) - public void testListPDPPolicy() throws Exception { - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy2, true); - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy3, true); - - policyPersistenceManager.addPolicy(samplePDPPolicy1); - policyPersistenceManager.addPolicy(samplePDPPolicy2); - policyPersistenceManager.addPolicy(samplePDPPolicy3); - - // Verify the number of published policies. - List policyIds = policyPersistenceManager.listPublishedPolicyIds(); - assertEquals(policyIds.size(), 3); - - // Verify the number of ordered policy identifiers. - String[] orderedPolicyIdentifiers = policyPersistenceManager.getOrderedPolicyIdentifiers(); - assertEquals(orderedPolicyIdentifiers.length, 3); - - // Verify the number of active policies. - String[] activePolicies = policyPersistenceManager.getActivePolicies(); - assertEquals(activePolicies.length, 2); - } - - @Test(priority = 12) - public void testUpdatePDPPolicy() throws Exception { - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.addPolicy(samplePDPPolicy1); - - // Update Policy order. - policyPersistenceManager.updatePolicy(orderedSamplePDPPolicy1); - assertEquals(policyPersistenceManager.getPolicyOrder(samplePDPPolicy1.getPolicyId()), - orderedSamplePDPPolicy1.getPolicyOrder()); - PolicyStoreDTO orderUpdatedPDPPolicy = - policyPersistenceManager.getPublishedPolicy(samplePDPPolicy1.getPolicyId()); - assertTrue(orderUpdatedPDPPolicy.isActive()); - - // Update Policy active status. - policyPersistenceManager.updatePolicy(inactiveSamplePDPPolicy1); - PolicyStoreDTO statusUpdatedPDPPolicy = - policyPersistenceManager.getPublishedPolicy(samplePDPPolicy1.getPolicyId()); - assertEquals(policyPersistenceManager.getPolicyOrder(samplePDPPolicy1.getPolicyId()), - orderedSamplePDPPolicy1.getPolicyOrder()); - assertFalse(statusUpdatedPDPPolicy.isActive()); - - // Update only the policy String. - policyPersistenceManager.addOrUpdatePolicy(sampleUpdatedPAPPolicy1, true); - policyPersistenceManager.updatePolicy(updatedSamplePDPPolicy1); - PolicyStoreDTO policyUpdatedPDPPolicy = - policyPersistenceManager.getPublishedPolicy(samplePDPPolicy1.getPolicyId()); - assertEquals(policyUpdatedPDPPolicy.getPolicy(), updatedSamplePDPPolicy1.getPolicy()); - } - - @Test(priority = 12) - public void testUpdateInvalidPDPPolicy() throws Exception { - - assertThrows(EntitlementException.class, () -> policyPersistenceManager.updatePolicy(null)); - assertThrows(EntitlementException.class, () -> policyPersistenceManager.updatePolicy(pdpPolicyWithEmptyId)); - assertThrows(EntitlementException.class, () -> policyPersistenceManager. - updatePolicy(pdpPolicyWithEmptyVersion)); - assertThrows(EntitlementException.class, () -> policyPersistenceManager. - updatePolicy(inactiveSamplePDPPolicy1)); - } - - @Test(priority = 13) - public void testGetSearchAttributes() throws Exception { - - Map> attributes = policyPersistenceManager.getSearchAttributes("identifier", null); - assertEquals(attributes.size(), 0); - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.addPolicy(samplePDPPolicy1); - attributes = policyPersistenceManager.getSearchAttributes(null, null); - assertEquals(attributes.size(), 1); - assertEquals(attributes.get(samplePDPPolicy1.getPolicyId()).size(), 4); - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy3, true); - policyPersistenceManager.addPolicy(samplePDPPolicy3); - attributes = policyPersistenceManager.getSearchAttributes(null, null); - assertEquals(attributes.size(), 2); - assertEquals(attributes.get(samplePDPPolicy1.getPolicyId()).size(), 4); - assertEquals(attributes.get(samplePDPPolicy3.getPolicyId()).size(), 4); - } - - private PolicyStoreDTO getPDPPolicy(String id, String policy, String version, boolean active, boolean setActive, - int order, boolean setOrder) { - - PolicyStoreDTO policyStoreDTO = new PolicyStoreDTO(); - if (id != null) { - policyStoreDTO.setPolicyId(id); - } - if (policy != null) { - policyStoreDTO.setPolicy(policy); - } - if (version != null) { - policyStoreDTO.setVersion(version); - } - policyStoreDTO.setActive(active); - policyStoreDTO.setSetActive(setActive); - if (order != 0) { - policyStoreDTO.setPolicyOrder(order); - } - policyStoreDTO.setSetOrder(setOrder); - return policyStoreDTO; - } - - /** - * Abstract method to create the policy persistence manager. - * - * @return The policy persistence manager. - */ - public abstract PolicyPersistenceManager createPolicyPersistenceManager(); -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/RegistryConfigPersistenceManagerTest.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/RegistryConfigPersistenceManagerTest.java deleted file mode 100644 index 0f73bc2117c8..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/RegistryConfigPersistenceManagerTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.wso2.carbon.identity.common.testng.WithCarbonHome; -import org.wso2.carbon.identity.common.testng.WithH2Database; -import org.wso2.carbon.identity.common.testng.WithRealmService; -import org.wso2.carbon.identity.common.testng.WithRegistry; -import org.wso2.carbon.identity.entitlement.internal.EntitlementConfigHolder; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; - -/** - * This class tests the behavior of the RegistryConfigPersistenceManager class. - */ -@WithCarbonHome -@WithRegistry(injectToSingletons = {EntitlementServiceComponent.class}) -@WithRealmService(injectToSingletons = {EntitlementConfigHolder.class}, initUserStoreManager = true) -@WithH2Database(jndiName = "jdbc/WSO2IdentityDB", files = {"dbscripts/h2.sql"}) -public class RegistryConfigPersistenceManagerTest extends ConfigPersistenceManagerTest { - - @BeforeMethod - public void setUp() throws Exception { - - configPersistenceManager = new RegistryConfigPersistenceManager(); - } - - @AfterMethod - public void tearDown() throws Exception { - - ((RegistryConfigPersistenceManager) configPersistenceManager).deleteGlobalPolicyAlgorithm(); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/RegistryPolicyPersistenceManagerTest.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/RegistryPolicyPersistenceManagerTest.java deleted file mode 100644 index 63b4352fd90f..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/RegistryPolicyPersistenceManagerTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.testng.annotations.Test; -import org.wso2.carbon.identity.common.testng.WithCarbonHome; -import org.wso2.carbon.identity.common.testng.WithH2Database; -import org.wso2.carbon.identity.common.testng.WithRealmService; -import org.wso2.carbon.identity.common.testng.WithRegistry; -import org.wso2.carbon.identity.entitlement.internal.EntitlementConfigHolder; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; - -import java.util.Properties; - -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; - -/** - * This class tests the behavior of the Registry Policy Persistence Manager class. - */ -@WithCarbonHome -@WithRegistry(injectToSingletons = {EntitlementServiceComponent.class}) -@WithRealmService(injectToSingletons = {EntitlementConfigHolder.class}, initUserStoreManager = true) -@WithH2Database(files = {"dbscripts/h2.sql"}) -public class RegistryPolicyPersistenceManagerTest extends PolicyPersistenceManagerTest { - - public PolicyPersistenceManager createPolicyPersistenceManager() { - - Properties storeProps = new Properties(); - policyPersistenceManager = new RegistryPolicyPersistenceManager(); - policyPersistenceManager.init(storeProps); - return policyPersistenceManager; - } - - @Test - public void testIsPolicyExistsInPap() throws Exception { - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - assertTrue(((RegistryPolicyPersistenceManager) policyPersistenceManager). - isPolicyExistsInPap(samplePAPPolicy1.getPolicyId())); - policyPersistenceManager.removePolicy(samplePAPPolicy1.getPolicyId()); - - assertFalse(((RegistryPolicyPersistenceManager) policyPersistenceManager).isPolicyExistsInPap(null)); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/RegistrySimplePAPStatusDataHandlerTest.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/RegistrySimplePAPStatusDataHandlerTest.java deleted file mode 100644 index 8ea8c320490c..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/RegistrySimplePAPStatusDataHandlerTest.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.wso2.carbon.identity.common.testng.WithCarbonHome; -import org.wso2.carbon.identity.common.testng.WithH2Database; -import org.wso2.carbon.identity.common.testng.WithRealmService; -import org.wso2.carbon.identity.common.testng.WithRegistry; -import org.wso2.carbon.identity.entitlement.PAPStatusDataHandler; -import org.wso2.carbon.identity.entitlement.SimplePAPStatusDataHandler; -import org.wso2.carbon.identity.entitlement.internal.EntitlementConfigHolder; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; - -/** - * This class tests the behavior of the Registry Simple PAP Status Data Handler class. - */ -@WithCarbonHome -@WithRegistry(injectToSingletons = {EntitlementServiceComponent.class}) -@WithRealmService(injectToSingletons = {EntitlementConfigHolder.class}, initUserStoreManager = true) -@WithH2Database(files = {"dbscripts/h2.sql"}) -public class RegistrySimplePAPStatusDataHandlerTest extends PAPStatusDataHandlerTest { - - public PAPStatusDataHandler createPAPStatusDataHandler() { - - return new SimplePAPStatusDataHandler(); - } - - public SubscriberPersistenceManager createSubscriberPersistenceManager() { - - return new RegistrySubscriberPersistenceManager(); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/RegistrySubscriberPersistenceManagerTest.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/RegistrySubscriberPersistenceManagerTest.java deleted file mode 100644 index 2898ddb4d085..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/RegistrySubscriberPersistenceManagerTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.testng.annotations.Test; -import org.wso2.carbon.identity.common.testng.WithCarbonHome; -import org.wso2.carbon.identity.common.testng.WithH2Database; -import org.wso2.carbon.identity.common.testng.WithRealmService; -import org.wso2.carbon.identity.common.testng.WithRegistry; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.internal.EntitlementConfigHolder; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; - -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; - -/** - * This class tests the behavior of the Registry Subscriber Persistence Manager class. - */ -@WithCarbonHome -@WithRegistry(injectToSingletons = {EntitlementServiceComponent.class}) -@WithRealmService(injectToSingletons = {EntitlementConfigHolder.class}, initUserStoreManager = true) -@WithH2Database(files = {"dbscripts/h2.sql"}) -public class RegistrySubscriberPersistenceManagerTest extends SubscriberPersistenceManagerTest { - - public SubscriberPersistenceManager createSubscriberPersistenceManager() { - - return new RegistrySubscriberPersistenceManager(); - } - - @Test(priority = 5) - public void testIsSubscriberExists() throws EntitlementException { - - assertFalse(((RegistrySubscriberPersistenceManager) subscriberPersistenceManager). - isSubscriberExists(SAMPLE_SUBSCRIBER_ID_1)); - subscriberPersistenceManager.addSubscriber(sampleHolder1); - assertTrue(((RegistrySubscriberPersistenceManager) subscriberPersistenceManager). - isSubscriberExists(SAMPLE_SUBSCRIBER_ID_1)); - } - -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/SubscriberPersistenceManagerFailureTest.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/SubscriberPersistenceManagerFailureTest.java deleted file mode 100644 index c5a3f1ccaf44..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/SubscriberPersistenceManagerFailureTest.java +++ /dev/null @@ -1,262 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.apache.commons.codec.Charsets; -import org.mockito.Mock; -import org.mockito.MockedStatic; -import org.mockito.MockitoAnnotations; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; -import org.wso2.carbon.core.util.CryptoUtil; -import org.wso2.carbon.identity.common.testng.WithCarbonHome; -import org.wso2.carbon.identity.common.testng.WithRealmService; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.dto.PublisherDataHolder; -import org.wso2.carbon.identity.entitlement.dto.PublisherPropertyDTO; -import org.wso2.carbon.identity.entitlement.internal.EntitlementConfigHolder; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; -import org.wso2.carbon.identity.entitlement.persistence.cache.CacheBackedSubscriberDAO; -import org.wso2.carbon.registry.core.Registry; -import org.wso2.carbon.registry.core.exceptions.RegistryException; - -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.mockStatic; -import static org.mockito.Mockito.when; -import static org.testng.Assert.assertThrows; - -/** - * This class tests the failure scenarios of Database or Registry in Subscriber Persistence Manager implementations. - */ -@WithCarbonHome -@WithRealmService(injectToSingletons = {EntitlementConfigHolder.class}, initUserStoreManager = true) -public class SubscriberPersistenceManagerFailureTest { - - static final String SUBSCRIBER_MODULE_NAME = "Carbon Basic Auth Policy Publisher Module"; - static final String SUBSCRIBER_ID_KEY = "subscriberId"; - static final String SUBSCRIBER_ID_DISPLAY_NAME = "Subscriber Id"; - static final String SAMPLE_SUBSCRIBER_ID_1 = "Subscriber1"; - static final String SUBSCRIBER_URL_KEY = "subscriberURL"; - static final String SUBSCRIBER_URL_DISPLAY_NAME = "Subscriber URL"; - static final String SAMPLE_SUBSCRIBER_URL_1 = "https://localhost:9443/subscriber1"; - static final String SUBSCRIBER_USERNAME_KEY = "subscriberUserName"; - static final String SUBSCRIBER_USERNAME_DISPLAY_NAME = "Subscriber User Name"; - static final String SAMPLE_SUBSCRIBER_USERNAME_1 = "admin_user1"; - static final String SUBSCRIBER_PASSWORD_DISPLAY_NAME = "Subscriber Password"; - static final String SUBSCRIBER_PASSWORD_KEY = "subscriberPassword"; - static final String SAMPLE_SUBSCRIBER_PASSWORD_1 = "admin_password1"; - static final String SAMPLE_ENCRYPTED_PASSWORD1 = "encrypted_admin_password1"; - - public PublisherDataHolder sampleHolder1; - - @Mock - private CacheBackedSubscriberDAO mockedSubscriberDAO; - - @Mock - private Registry mockedRegistry; - - private JDBCSubscriberPersistenceManager jdbcSubscriberPersistenceManager; - private RegistrySubscriberPersistenceManager registrySubscriberPersistenceManager; - - MockedStatic entitlementServiceComponent; - private CryptoUtil mockCryptoUtil; - private MockedStatic cryptoUtil; - - @BeforeClass - public void setUpClass() throws Exception { - - cryptoUtil = mockStatic(CryptoUtil.class); - mockCryptoUtil = mock(CryptoUtil.class); - cryptoUtil.when(CryptoUtil::getDefaultCryptoUtil).thenReturn(mockCryptoUtil); - when(mockCryptoUtil.encryptAndBase64Encode(SAMPLE_ENCRYPTED_PASSWORD1.getBytes(Charsets.UTF_8))).thenReturn( - SAMPLE_ENCRYPTED_PASSWORD1); - } - - @BeforeMethod - public void setUp() throws Exception { - - MockitoAnnotations.openMocks(this); - - entitlementServiceComponent = mockStatic(EntitlementServiceComponent.class); - entitlementServiceComponent.when(() -> EntitlementServiceComponent.getGovernanceRegistry(anyInt())) - .thenReturn(mockedRegistry); - - registrySubscriberPersistenceManager = new RegistrySubscriberPersistenceManager(); - jdbcSubscriberPersistenceManager = new JDBCSubscriberPersistenceManager(); - setPrivateStaticFinalField(JDBCSubscriberPersistenceManager.class, "subscriberDAO", mockedSubscriberDAO); - - sampleHolder1 = - createSampleHolder(SAMPLE_SUBSCRIBER_ID_1, SAMPLE_SUBSCRIBER_URL_1, SAMPLE_SUBSCRIBER_USERNAME_1, - SAMPLE_SUBSCRIBER_PASSWORD_1); - } - - @AfterMethod - public void tearDown() throws Exception { - - entitlementServiceComponent.close(); - setPrivateStaticFinalField(JDBCSubscriberPersistenceManager.class, "subscriberDAO", - CacheBackedSubscriberDAO.getInstance()); - } - - @Test - public void testAddSubscriberWhenDatabaseErrorHappened() throws Exception { - - doThrow(new EntitlementException("")).when(mockedSubscriberDAO).insertSubscriber(anyString(), any(), anyInt()); - assertThrows(EntitlementException.class, () -> jdbcSubscriberPersistenceManager.addSubscriber(sampleHolder1)); - } - - @Test - public void testUpdateSubscriberWhenDatabaseErrorHappened() throws Exception { - - when(mockedSubscriberDAO.isSubscriberExists(anyString(), anyInt())).thenReturn(false); - assertThrows(EntitlementException.class, - () -> jdbcSubscriberPersistenceManager.updateSubscriber(sampleHolder1)); - } - - @Test - public void testGetSubscriberIdsWhenDatabaseErrorHappened() throws Exception { - - when(mockedSubscriberDAO.getSubscriber(anyString(), anyInt())).thenThrow(new EntitlementException("")); - assertThrows(EntitlementException.class, - () -> jdbcSubscriberPersistenceManager.getSubscriber(SUBSCRIBER_ID_KEY, false)); - } - - @Test - public void testListSubscriberWhenDatabaseErrorHappened() throws Exception { - - when(mockedSubscriberDAO.getSubscriberIds(anyInt())).thenThrow(new EntitlementException("")); - assertThrows(EntitlementException.class, - () -> jdbcSubscriberPersistenceManager.listSubscriberIds(SUBSCRIBER_ID_KEY)); - } - - @Test - public void testIsSubscriberExistsWhenDatabaseErrorHappened() throws Exception { - - when(mockedSubscriberDAO.isSubscriberExists(anyString(), anyInt())).thenThrow(new EntitlementException("")); - assertThrows(EntitlementException.class, - () -> jdbcSubscriberPersistenceManager.isSubscriberExists(SUBSCRIBER_ID_KEY)); - } - - @Test - public void testRemoveSubscriberWhenDatabaseErrorHappened() throws Exception { - - doThrow(new EntitlementException("")).when(mockedSubscriberDAO).deleteSubscriber(anyString(), anyInt()); - assertThrows(EntitlementException.class, - () -> jdbcSubscriberPersistenceManager.removeSubscriber(SUBSCRIBER_ID_KEY)); - } - - @Test - public void testAddSubscriberWhenRegistryErrorHappened() throws Exception { - - when(mockedRegistry.resourceExists(anyString())).thenThrow(new RegistryException("")); - assertThrows(EntitlementException.class, - () -> registrySubscriberPersistenceManager.addSubscriber(sampleHolder1)); - } - - @Test - public void testUpdateSubscriberWhenRegistryErrorHappened() throws Exception { - - when(mockedRegistry.resourceExists(anyString())).thenThrow(new RegistryException("")); - assertThrows(EntitlementException.class, - () -> registrySubscriberPersistenceManager.updateSubscriber(sampleHolder1)); - } - - @Test - public void testGetSubscriberWhenRegistryErrorHappened() throws Exception { - - when(mockedRegistry.resourceExists(anyString())).thenReturn(true); - when(mockedRegistry.get(anyString())).thenThrow(new RegistryException("")); - assertThrows(EntitlementException.class, - () -> registrySubscriberPersistenceManager.getSubscriber(SUBSCRIBER_ID_KEY, false)); - } - - @Test - public void testListSubscriberIdsWhenRegistryErrorHappened() throws Exception { - - when(mockedRegistry.resourceExists(anyString())).thenReturn(true); - when(mockedRegistry.get(anyString())).thenThrow(new RegistryException("")); - assertThrows(EntitlementException.class, () -> registrySubscriberPersistenceManager.listSubscriberIds("*")); - } - - @Test - public void testIsSubscriberExistsWhenRegistryErrorHappened() throws Exception { - - when(mockedRegistry.resourceExists(anyString())).thenThrow(new RegistryException("")); - assertThrows(EntitlementException.class, - () -> registrySubscriberPersistenceManager.isSubscriberExists(SUBSCRIBER_ID_KEY)); - } - - @Test - public void testRemoveSubscriberWhenRegistryErrorHappened() throws Exception { - - when(mockedRegistry.resourceExists(anyString())).thenReturn(true); - doThrow(new RegistryException("")).when(mockedRegistry).delete(anyString()); - assertThrows(EntitlementException.class, - () -> registrySubscriberPersistenceManager.removeSubscriber(SUBSCRIBER_ID_KEY)); - } - - private PublisherDataHolder createSampleHolder(String id, String url, String username, String password) { - - PublisherPropertyDTO idProperty = - getPublisherPropertyDTO(SUBSCRIBER_ID_KEY, id, SUBSCRIBER_ID_DISPLAY_NAME, false); - PublisherPropertyDTO urlProperty = - getPublisherPropertyDTO(SUBSCRIBER_URL_KEY, url, SUBSCRIBER_URL_DISPLAY_NAME, false); - PublisherPropertyDTO usernameProperty = - getPublisherPropertyDTO(SUBSCRIBER_USERNAME_KEY, username, SUBSCRIBER_USERNAME_DISPLAY_NAME, false); - PublisherPropertyDTO passwordProperty = - getPublisherPropertyDTO(SUBSCRIBER_PASSWORD_KEY, password, SUBSCRIBER_PASSWORD_DISPLAY_NAME, true); - - PublisherDataHolder holder = new PublisherDataHolder(); - holder.setModuleName(SUBSCRIBER_MODULE_NAME); - holder.setPropertyDTOs(new PublisherPropertyDTO[]{idProperty, urlProperty, usernameProperty, passwordProperty}); - return holder; - } - - private PublisherPropertyDTO getPublisherPropertyDTO(String id, String value, String displayName, boolean secret) { - - PublisherPropertyDTO dto = new PublisherPropertyDTO(); - dto.setId(id); - dto.setValue(value); - dto.setDisplayName(displayName); - dto.setSecret(secret); - return dto; - } - - private static void setPrivateStaticFinalField(Class clazz, String fieldName, Object newValue) - throws ReflectiveOperationException { - - Field field = clazz.getDeclaredField(fieldName); - field.setAccessible(true); - - Field modifiers = Field.class.getDeclaredField("modifiers"); - modifiers.setAccessible(true); - modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL); - - field.set(null, newValue); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/SubscriberPersistenceManagerTest.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/SubscriberPersistenceManagerTest.java deleted file mode 100644 index 7aa3d01a42ad..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/persistence/SubscriberPersistenceManagerTest.java +++ /dev/null @@ -1,294 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.persistence; - -import org.apache.commons.codec.Charsets; -import org.mockito.MockedStatic; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; -import org.wso2.carbon.core.util.CryptoUtil; -import org.wso2.carbon.identity.entitlement.EntitlementException; -import org.wso2.carbon.identity.entitlement.dto.PublisherDataHolder; -import org.wso2.carbon.identity.entitlement.dto.PublisherPropertyDTO; - -import java.util.List; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.mockStatic; -import static org.mockito.Mockito.when; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertThrows; -import static org.wso2.carbon.identity.entitlement.common.EntitlementConstants.PDP_SUBSCRIBER_ID; - -/** - * This class tests the behavior of the Subscriber Persistence Manager class. - */ -public abstract class SubscriberPersistenceManagerTest { - - public SubscriberPersistenceManager subscriberPersistenceManager; - private CryptoUtil mockCryptoUtil; - private MockedStatic cryptoUtil; - - static final String SUBSCRIBER_MODULE_NAME = "Carbon Basic Auth Policy Publisher Module"; - static final String SUBSCRIBER_ID_KEY = "subscriberId"; - static final String SUBSCRIBER_ID_DISPLAY_NAME = "Subscriber Id"; - static final String SAMPLE_SUBSCRIBER_ID_1 = "Subscriber1"; - static final String SAMPLE_SUBSCRIBER_ID_2 = "Subscriber2"; - static final String SUBSCRIBER_URL_KEY = "subscriberURL"; - static final String SUBSCRIBER_URL_DISPLAY_NAME = "Subscriber URL"; - static final String SAMPLE_SUBSCRIBER_URL_1 = "https://localhost:9443/subscriber1"; - static final String SAMPLE_SUBSCRIBER_URL_2 = "https://localhost:9443/subscriber2"; - static final String SUBSCRIBER_USERNAME_KEY = "subscriberUserName"; - static final String SUBSCRIBER_USERNAME_DISPLAY_NAME = "Subscriber User Name"; - static final String SAMPLE_SUBSCRIBER_USERNAME_1 = "admin_user1"; - static final String SAMPLE_SUBSCRIBER_USERNAME_2 = "admin_user2"; - static final String SUBSCRIBER_PASSWORD_DISPLAY_NAME = "Subscriber Password"; - static final String SUBSCRIBER_PASSWORD_KEY = "subscriberPassword"; - static final String SAMPLE_SUBSCRIBER_PASSWORD_1 = "admin_password1"; - static final String SAMPLE_SUBSCRIBER_PASSWORD_2 = "admin_password2"; - static final String SAMPLE_ENCRYPTED_PASSWORD1 = "encrypted_admin_password1"; - static final String SAMPLE_ENCRYPTED_PASSWORD2 = "encrypted_admin_password2"; - static final String NEW_MODULE_NAME = "New Updated Module"; - - public PublisherDataHolder sampleHolder1; - public PublisherDataHolder sampleHolder2; - public PublisherDataHolder updatedSampleHolder1; - private PublisherDataHolder moduleNameUpdatedSampleHolder1; - public PublisherDataHolder invalidSampleHolder; - - @BeforeClass - public void setUpClass() throws Exception { - - cryptoUtil = mockStatic(CryptoUtil.class); - mockCryptoUtil = mock(CryptoUtil.class); - cryptoUtil.when(CryptoUtil::getDefaultCryptoUtil).thenReturn(mockCryptoUtil); - mockSecretEncryption(SAMPLE_SUBSCRIBER_PASSWORD_1); - mockSecretEncryption(SAMPLE_SUBSCRIBER_PASSWORD_2); - mockSecretDecryption(SAMPLE_ENCRYPTED_PASSWORD1); - mockSecretDecryption(SAMPLE_ENCRYPTED_PASSWORD2); - } - - @BeforeMethod - public void setUp() { - - // Reinitialize the subscriber manager and sample holders before each test. - subscriberPersistenceManager = createSubscriberPersistenceManager(); - sampleHolder1 = - createSampleHolder(SAMPLE_SUBSCRIBER_ID_1, SAMPLE_SUBSCRIBER_URL_1, SAMPLE_SUBSCRIBER_USERNAME_1, - SAMPLE_SUBSCRIBER_PASSWORD_1); - sampleHolder2 = - createSampleHolder(SAMPLE_SUBSCRIBER_ID_2, SAMPLE_SUBSCRIBER_URL_2, SAMPLE_SUBSCRIBER_USERNAME_2, - SAMPLE_SUBSCRIBER_PASSWORD_2); - updatedSampleHolder1 = - createSampleHolder(SAMPLE_SUBSCRIBER_ID_1, SAMPLE_SUBSCRIBER_URL_2, SAMPLE_SUBSCRIBER_USERNAME_2, - SAMPLE_SUBSCRIBER_PASSWORD_2); - moduleNameUpdatedSampleHolder1 = createSampleHolder(SAMPLE_SUBSCRIBER_ID_1, SAMPLE_SUBSCRIBER_URL_1, - SAMPLE_SUBSCRIBER_USERNAME_1, SAMPLE_SUBSCRIBER_PASSWORD_1); - moduleNameUpdatedSampleHolder1.setModuleName(NEW_MODULE_NAME); - invalidSampleHolder = createSampleHolder(null, null, null, null); - } - - @AfterMethod - public void tearDown() throws Exception { - - subscriberPersistenceManager.removeSubscriber(SAMPLE_SUBSCRIBER_ID_1); - subscriberPersistenceManager.removeSubscriber(SAMPLE_SUBSCRIBER_ID_2); - } - - @AfterClass - public void wrapUp() { - - cryptoUtil.close(); - } - - @Test(priority = 1) - public void testAddSubscriber() throws Exception { - - subscriberPersistenceManager.addSubscriber(sampleHolder1); - - PublisherDataHolder subscriberFromStorage = - subscriberPersistenceManager.getSubscriber(SAMPLE_SUBSCRIBER_ID_1, false); - assertEquals(subscriberFromStorage.getPropertyDTO(SUBSCRIBER_ID_KEY).getValue(), - sampleHolder1.getPropertyDTO(SUBSCRIBER_ID_KEY).getValue()); - assertEquals(subscriberFromStorage.getPropertyDTO(SUBSCRIBER_URL_KEY).getValue(), - sampleHolder1.getPropertyDTO(SUBSCRIBER_URL_KEY).getValue()); - assertEquals(subscriberFromStorage.getPropertyDTO(SUBSCRIBER_USERNAME_KEY).getValue(), - sampleHolder1.getPropertyDTO(SUBSCRIBER_USERNAME_KEY).getValue()); - assertEquals(subscriberFromStorage.getPropertyDTO(SUBSCRIBER_PASSWORD_KEY).getValue(), - SAMPLE_ENCRYPTED_PASSWORD1); - - // Retrieve the subscriber with the decrypted secrets. - PublisherDataHolder decryptedSubscriberFromStorage = - subscriberPersistenceManager.getSubscriber(SAMPLE_SUBSCRIBER_ID_1, true); - assertEquals(decryptedSubscriberFromStorage.getPropertyDTO(SUBSCRIBER_PASSWORD_KEY).getValue(), - SAMPLE_SUBSCRIBER_PASSWORD_1); - } - - @Test(priority = 1) - public void testAddInvalidSubscriber() throws Exception { - - assertThrows(EntitlementException.class, () -> subscriberPersistenceManager.addSubscriber(invalidSampleHolder)); - } - - @Test(priority = 1) - public void testAddSubscriberWithDuplicateId() throws Exception { - - subscriberPersistenceManager.addSubscriber(sampleHolder1); - assertThrows(EntitlementException.class, () -> subscriberPersistenceManager.addSubscriber(sampleHolder1)); - } - - @Test(priority = 2) - public void testListSubscriberIds() throws Exception { - - List subscriberIds = subscriberPersistenceManager.listSubscriberIds("*"); - assertEquals(subscriberIds.size(), 0); - - subscriberPersistenceManager.addSubscriber(sampleHolder1); - subscriberPersistenceManager.addSubscriber(sampleHolder2); - - List allSubscriberIds = subscriberPersistenceManager.listSubscriberIds("*"); - assertEquals(allSubscriberIds.size(), 2); - - List filteredSubscriberIds1 = subscriberPersistenceManager.listSubscriberIds(SAMPLE_SUBSCRIBER_ID_1); - assertEquals(filteredSubscriberIds1.size(), 1); - - List filteredSubscriberIds2 = subscriberPersistenceManager.listSubscriberIds("test"); - assertEquals(filteredSubscriberIds2.size(), 0); - } - - @Test(priority = 3) - public void testUpdateSubscriber() throws Exception { - - subscriberPersistenceManager.addSubscriber(sampleHolder1); - subscriberPersistenceManager.updateSubscriber(updatedSampleHolder1); - - PublisherDataHolder subscriberFromStorage = - subscriberPersistenceManager.getSubscriber(SAMPLE_SUBSCRIBER_ID_1, false); - assertEquals(subscriberFromStorage.getPropertyDTO(SUBSCRIBER_ID_KEY).getValue(), - sampleHolder1.getPropertyDTO(SUBSCRIBER_ID_KEY).getValue()); - assertEquals(subscriberFromStorage.getPropertyDTO(SUBSCRIBER_URL_KEY).getValue(), - updatedSampleHolder1.getPropertyDTO(SUBSCRIBER_URL_KEY).getValue()); - assertEquals(subscriberFromStorage.getPropertyDTO(SUBSCRIBER_USERNAME_KEY).getValue(), - updatedSampleHolder1.getPropertyDTO(SUBSCRIBER_USERNAME_KEY).getValue()); - assertEquals(subscriberFromStorage.getPropertyDTO(SUBSCRIBER_PASSWORD_KEY).getValue(), - SAMPLE_ENCRYPTED_PASSWORD2); - - PublisherDataHolder decryptedSubscriberFromStorage = - subscriberPersistenceManager.getSubscriber(SAMPLE_SUBSCRIBER_ID_1, true); - assertEquals(decryptedSubscriberFromStorage.getPropertyDTO(SUBSCRIBER_PASSWORD_KEY).getValue(), - SAMPLE_SUBSCRIBER_PASSWORD_2); - } - - @Test(priority = 3) - public void testUpdateSubscriberModuleName() throws Exception { - - subscriberPersistenceManager.addSubscriber(sampleHolder1); - subscriberPersistenceManager.updateSubscriber(moduleNameUpdatedSampleHolder1); - - PublisherDataHolder subscriberFromStorage = - subscriberPersistenceManager.getSubscriber(SAMPLE_SUBSCRIBER_ID_1, false); - assertEquals(subscriberFromStorage.getModuleName(), moduleNameUpdatedSampleHolder1.getModuleName()); - } - - @Test(priority = 3) - public void testUpdateInvalidSubscriber() throws Exception { - - assertThrows(EntitlementException.class, - () -> subscriberPersistenceManager.updateSubscriber(invalidSampleHolder)); - } - - @Test(priority = 4) - public void testRemoveSubscriber() throws Exception { - - subscriberPersistenceManager.addSubscriber(sampleHolder1); - subscriberPersistenceManager.removeSubscriber(SAMPLE_SUBSCRIBER_ID_1); - assertThrows(EntitlementException.class, - () -> subscriberPersistenceManager.getSubscriber(SAMPLE_SUBSCRIBER_ID_1, false)); - } - - @Test(priority = 4) - public void testRemoveInvalidSubscriber() { - - assertThrows(EntitlementException.class, () -> subscriberPersistenceManager.removeSubscriber(null)); - assertThrows(EntitlementException.class, - () -> subscriberPersistenceManager.removeSubscriber(PDP_SUBSCRIBER_ID)); - } - - private void mockSecretEncryption(String secret) throws org.wso2.carbon.core.util.CryptoException { - - if (SAMPLE_SUBSCRIBER_PASSWORD_1.equals(secret)) { - when(mockCryptoUtil.encryptAndBase64Encode(secret.getBytes(Charsets.UTF_8))).thenReturn( - SAMPLE_ENCRYPTED_PASSWORD1); - } else { - when(mockCryptoUtil.encryptAndBase64Encode(secret.getBytes(Charsets.UTF_8))).thenReturn( - SAMPLE_ENCRYPTED_PASSWORD2); - } - } - - private void mockSecretDecryption(String cipherText) throws org.wso2.carbon.core.util.CryptoException { - - if (SAMPLE_ENCRYPTED_PASSWORD1.equals(cipherText)) { - when(mockCryptoUtil.base64DecodeAndDecrypt(cipherText)).thenReturn(SAMPLE_SUBSCRIBER_PASSWORD_1.getBytes()); - } else { - when(mockCryptoUtil.base64DecodeAndDecrypt(cipherText)).thenReturn(SAMPLE_SUBSCRIBER_PASSWORD_2.getBytes()); - } - } - - private PublisherDataHolder createSampleHolder(String id, String url, String username, String password) { - - PublisherPropertyDTO idProperty = - getPublisherPropertyDTO(SUBSCRIBER_ID_KEY, id, SUBSCRIBER_ID_DISPLAY_NAME, false); - PublisherPropertyDTO urlProperty = - getPublisherPropertyDTO(SUBSCRIBER_URL_KEY, url, SUBSCRIBER_URL_DISPLAY_NAME, false); - PublisherPropertyDTO usernameProperty = - getPublisherPropertyDTO(SUBSCRIBER_USERNAME_KEY, username, SUBSCRIBER_USERNAME_DISPLAY_NAME, false); - PublisherPropertyDTO passwordProperty = - getPublisherPropertyDTO(SUBSCRIBER_PASSWORD_KEY, password, SUBSCRIBER_PASSWORD_DISPLAY_NAME, true); - return getPublisherHolder( - new PublisherPropertyDTO[]{idProperty, urlProperty, usernameProperty, passwordProperty}); - } - - private PublisherPropertyDTO getPublisherPropertyDTO(String id, String value, String displayName, boolean secret) { - - PublisherPropertyDTO dto = new PublisherPropertyDTO(); - dto.setId(id); - dto.setValue(value); - dto.setDisplayName(displayName); - dto.setSecret(secret); - return dto; - } - - private PublisherDataHolder getPublisherHolder(PublisherPropertyDTO[] propertyDTOs) { - - PublisherDataHolder holder = new PublisherDataHolder(); - holder.setModuleName(SUBSCRIBER_MODULE_NAME); - holder.setPropertyDTOs(propertyDTOs); - return holder; - } - - /** - * Abstract method to create the subscriber persistence manager - * - * @return The subscriber persistence manager. - */ - protected abstract SubscriberPersistenceManager createSubscriberPersistenceManager(); -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/policy/finder/HybridPolicyPersistenceManagerTest.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/policy/finder/HybridPolicyPersistenceManagerTest.java deleted file mode 100644 index 83f6e57adff7..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/policy/finder/HybridPolicyPersistenceManagerTest.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.policy.finder; - -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.common.testng.WithCarbonHome; -import org.wso2.carbon.identity.common.testng.WithH2Database; -import org.wso2.carbon.identity.common.testng.WithRealmService; -import org.wso2.carbon.identity.common.testng.WithRegistry; -import org.wso2.carbon.identity.entitlement.internal.EntitlementConfigHolder; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; -import org.wso2.carbon.identity.entitlement.persistence.HybridPolicyPersistenceManager; -import org.wso2.carbon.identity.entitlement.persistence.JDBCPolicyPersistenceManager; -import org.wso2.carbon.identity.entitlement.persistence.RegistryPolicyPersistenceManager; - -import java.util.Properties; - -import static org.testng.Assert.assertEquals; - -/** - * This class tests the behavior of the JDBC Policy Persistence Manager class. - */ -@WithCarbonHome -@WithRegistry(injectToSingletons = {EntitlementServiceComponent.class}) -@WithRealmService(injectToSingletons = {EntitlementConfigHolder.class}, initUserStoreManager = true) -@WithH2Database(files = {"dbscripts/h2.sql"}) -public class HybridPolicyPersistenceManagerTest extends PolicyPersistenceManagerTest { - - private JDBCPolicyPersistenceManager jdbcPolicyPersistenceManager; - private RegistryPolicyPersistenceManager registryPolicyPersistenceManager; - - @BeforeMethod - public void setUp() throws Exception { - - Properties storeProps = new Properties(); - policyPersistenceManager = new HybridPolicyPersistenceManager(); - policyPersistenceManager.init(storeProps); - jdbcPolicyPersistenceManager = new JDBCPolicyPersistenceManager(); - registryPolicyPersistenceManager = new RegistryPolicyPersistenceManager(); - registryPolicyPersistenceManager.init(storeProps); - } - - @Test - public void testGetPolicyIdentifiersInDb() throws Exception { - - jdbcPolicyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - jdbcPolicyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy2, true); - jdbcPolicyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy3, true); - - String[] policyIdentifiersBeforePublishing = ((AbstractPolicyFinderModule) policyPersistenceManager) - .getPolicyIdentifiers(); - assertEquals(policyIdentifiersBeforePublishing.length, 0); - String[] policyIdentifiersBeforePublishingInDb = ((AbstractPolicyFinderModule) jdbcPolicyPersistenceManager) - .getPolicyIdentifiers(); - assertEquals(policyIdentifiersBeforePublishingInDb.length, 0); - - jdbcPolicyPersistenceManager.addPolicy(samplePDPPolicy1); - jdbcPolicyPersistenceManager.addPolicy(samplePDPPolicy2); - jdbcPolicyPersistenceManager.addPolicy(samplePDPPolicy3); - - String[] policyIdentifiersAfterPublishing = ((AbstractPolicyFinderModule) policyPersistenceManager). - getPolicyIdentifiers(); - assertEquals(policyIdentifiersAfterPublishing.length, 3); - String[] policyIdentifiersAfterPublishingInDb = ((AbstractPolicyFinderModule) jdbcPolicyPersistenceManager). - getPolicyIdentifiers(); - assertEquals(policyIdentifiersAfterPublishingInDb.length, 3); - } - - @Test - public void testGetPolicyIdentifiersInRegistry() throws Exception { - - registryPolicyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - registryPolicyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy2, true); - registryPolicyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy3, true); - - String[] policyIdentifiersBeforePublishing = ((AbstractPolicyFinderModule) policyPersistenceManager) - .getPolicyIdentifiers(); - assertEquals(policyIdentifiersBeforePublishing.length, 0); - String[] policyIdentifiersBeforePublishingInRegistry = ((AbstractPolicyFinderModule) policyPersistenceManager) - .getPolicyIdentifiers(); - assertEquals(policyIdentifiersBeforePublishingInRegistry.length, 0); - - registryPolicyPersistenceManager.addPolicy(samplePDPPolicy1); - registryPolicyPersistenceManager.addPolicy(samplePDPPolicy2); - registryPolicyPersistenceManager.addPolicy(samplePDPPolicy3); - - String[] policyIdentifiersAfterPublishing = ((AbstractPolicyFinderModule) registryPolicyPersistenceManager). - getPolicyIdentifiers(); - assertEquals(policyIdentifiersAfterPublishing.length, 3); - String[] policyIdentifiersAfterPublishingInRegistry = - ((AbstractPolicyFinderModule) registryPolicyPersistenceManager). - getPolicyIdentifiers(); - assertEquals(policyIdentifiersAfterPublishingInRegistry.length, 3); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/policy/finder/JDBCPolicyPersistenceManagerTest.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/policy/finder/JDBCPolicyPersistenceManagerTest.java deleted file mode 100644 index 1519ea5fbec0..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/policy/finder/JDBCPolicyPersistenceManagerTest.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.policy.finder; - -import org.testng.annotations.BeforeMethod; -import org.wso2.carbon.identity.common.testng.WithCarbonHome; -import org.wso2.carbon.identity.common.testng.WithH2Database; -import org.wso2.carbon.identity.common.testng.WithRealmService; -import org.wso2.carbon.identity.common.testng.WithRegistry; -import org.wso2.carbon.identity.entitlement.internal.EntitlementConfigHolder; -import org.wso2.carbon.identity.entitlement.persistence.JDBCPolicyPersistenceManager; - -/** - * This class tests the behavior of the JDBC Policy Persistence Manager class. - */ -@WithCarbonHome -@WithRegistry -@WithRealmService(injectToSingletons = {EntitlementConfigHolder.class}, initUserStoreManager = true) -@WithH2Database(files = {"dbscripts/h2.sql"}) -public class JDBCPolicyPersistenceManagerTest extends PolicyPersistenceManagerTest { - - @BeforeMethod - public void setUp() throws Exception { - - policyPersistenceManager = new JDBCPolicyPersistenceManager(); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/policy/finder/PolicyPersistenceManagerTest.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/policy/finder/PolicyPersistenceManagerTest.java deleted file mode 100644 index 10b2119396a7..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/policy/finder/PolicyPersistenceManagerTest.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.policy.finder; - -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.entitlement.PDPConstants; -import org.wso2.carbon.identity.entitlement.dto.PolicyDTO; -import org.wso2.carbon.identity.entitlement.dto.PolicyStoreDTO; -import org.wso2.carbon.identity.entitlement.internal.EntitlementConfigHolder; -import org.wso2.carbon.identity.entitlement.persistence.PolicyPersistenceManager; - -import java.util.Properties; - -import static org.testng.Assert.assertEquals; - -/** - * This is the parent test class for the Policy Persistence Manager test classes. - */ -public class PolicyPersistenceManagerTest { - - PolicyPersistenceManager policyPersistenceManager; - - static final String SAMPLE_POLICY_STRING_1 = - "GETresourceASri LankaEngineer"; - static final String SAMPLE_POLICY_STRING_2 = - "GETresourceAIndiaEngineer"; - static final String SAMPLE_POLICY_STRING_3 = - "GETresourceAIndiaDoctor"; - - static final String SAMPLE_POLICY_ID_1 = "sample_policy1"; - static final String SAMPLE_POLICY_ID_2 = "sample_policy2"; - static final String SAMPLE_POLICY_ID_3 = "sample_policy3"; - - PolicyDTO samplePAPPolicy1; - PolicyDTO samplePAPPolicy2; - PolicyDTO samplePAPPolicy3; - - PolicyStoreDTO samplePDPPolicy1; - PolicyStoreDTO samplePDPPolicy2; - PolicyStoreDTO samplePDPPolicy3; - - @BeforeClass - public void setUpClass() { - - Properties engineProperties = new Properties(); - engineProperties.put(PDPConstants.MAX_NO_OF_POLICY_VERSIONS, "0"); - EntitlementConfigHolder.getInstance().setEngineProperties(engineProperties); - - samplePAPPolicy1 = new PolicyDTO(SAMPLE_POLICY_ID_1); - samplePAPPolicy1.setPolicy(SAMPLE_POLICY_STRING_1); - - samplePAPPolicy2 = new PolicyDTO(SAMPLE_POLICY_ID_2); - samplePAPPolicy2.setPolicy(SAMPLE_POLICY_STRING_2); - - samplePAPPolicy3 = new PolicyDTO(SAMPLE_POLICY_ID_3); - samplePAPPolicy3.setPolicy(SAMPLE_POLICY_STRING_3); - - samplePDPPolicy1 = getPDPPolicy(SAMPLE_POLICY_ID_1, SAMPLE_POLICY_STRING_1, "1", true, true, 0, false); - samplePDPPolicy2 = getPDPPolicy(SAMPLE_POLICY_ID_2, SAMPLE_POLICY_STRING_2, "1", false, true, 0, false); - samplePDPPolicy3 = getPDPPolicy(SAMPLE_POLICY_ID_3, SAMPLE_POLICY_STRING_3, "1", true, true, 2, true); - } - - @AfterMethod - public void tearDown() throws Exception { - - // Unpublish PDP policies used in test cases. - policyPersistenceManager.deletePolicy(SAMPLE_POLICY_ID_1); - policyPersistenceManager.deletePolicy(SAMPLE_POLICY_ID_2); - policyPersistenceManager.deletePolicy(SAMPLE_POLICY_ID_3); - - // Remove PAP policies used in test cases. - policyPersistenceManager.removePolicy(SAMPLE_POLICY_ID_1); - policyPersistenceManager.removePolicy(SAMPLE_POLICY_ID_2); - policyPersistenceManager.removePolicy(SAMPLE_POLICY_ID_3); - } - - @Test - public void testGetPolicyIdentifiers() throws Exception { - - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy1, true); - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy2, true); - policyPersistenceManager.addOrUpdatePolicy(samplePAPPolicy3, true); - - String[] policyIdentifiersBeforePublishing = ((AbstractPolicyFinderModule) policyPersistenceManager) - .getPolicyIdentifiers(); - assertEquals(policyIdentifiersBeforePublishing.length, 0); - - policyPersistenceManager.addPolicy(samplePDPPolicy1); - policyPersistenceManager.addPolicy(samplePDPPolicy2); - policyPersistenceManager.addPolicy(samplePDPPolicy3); - - String[] policyIdentifiersAfterPublishing = ((AbstractPolicyFinderModule) policyPersistenceManager). - getPolicyIdentifiers(); - assertEquals(policyIdentifiersAfterPublishing.length, 3); - } - - private PolicyStoreDTO getPDPPolicy(String id, String policy, String version, boolean active, boolean setActive, - int order, boolean setOrder) { - - PolicyStoreDTO policyStoreDTO = new PolicyStoreDTO(); - if (id != null) { - policyStoreDTO.setPolicyId(id); - } - if (policy != null) { - policyStoreDTO.setPolicy(policy); - } - if (version != null) { - policyStoreDTO.setVersion(version); - } - policyStoreDTO.setActive(active); - policyStoreDTO.setSetActive(setActive); - if (order != 0) { - policyStoreDTO.setPolicyOrder(order); - } - policyStoreDTO.setSetOrder(setOrder); - return policyStoreDTO; - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/policy/finder/RegistryPolicyPersistenceManagerTest.java b/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/policy/finder/RegistryPolicyPersistenceManagerTest.java deleted file mode 100644 index 311bda159c12..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/java/org/wso2/carbon/identity/entitlement/policy/finder/RegistryPolicyPersistenceManagerTest.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). - * - * WSO2 LLC. 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.wso2.carbon.identity.entitlement.policy.finder; - -import org.testng.annotations.BeforeMethod; -import org.wso2.carbon.identity.common.testng.WithCarbonHome; -import org.wso2.carbon.identity.common.testng.WithH2Database; -import org.wso2.carbon.identity.common.testng.WithRealmService; -import org.wso2.carbon.identity.common.testng.WithRegistry; -import org.wso2.carbon.identity.entitlement.internal.EntitlementConfigHolder; -import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent; -import org.wso2.carbon.identity.entitlement.persistence.RegistryPolicyPersistenceManager; - -import java.util.Properties; - -/** - * This class tests the behavior of the Registry Policy Persistence Manager class. - */ -@WithCarbonHome -@WithRegistry(injectToSingletons = {EntitlementServiceComponent.class}) -@WithRealmService(injectToSingletons = {EntitlementConfigHolder.class}, initUserStoreManager = true) -@WithH2Database(files = {"dbscripts/h2.sql"}) -public class RegistryPolicyPersistenceManagerTest extends PolicyPersistenceManagerTest { - - @BeforeMethod - public void setUp() throws Exception { - - Properties storeProps = new Properties(); - policyPersistenceManager = new RegistryPolicyPersistenceManager(); - policyPersistenceManager.init(storeProps); - } -} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/resources/dbscripts/h2.sql b/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/resources/dbscripts/h2.sql deleted file mode 100644 index d533c642133a..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/resources/dbscripts/h2.sql +++ /dev/null @@ -1,1572 +0,0 @@ -CREATE TABLE IF NOT EXISTS IDN_BASE_TABLE ( - PRODUCT_NAME VARCHAR (20), - PRIMARY KEY (PRODUCT_NAME) -); - -INSERT INTO IDN_BASE_TABLE values ('WSO2 Identity Server'); - -CREATE TABLE IF NOT EXISTS IDN_OAUTH_CONSUMER_APPS ( - ID INTEGER NOT NULL AUTO_INCREMENT, - CONSUMER_KEY VARCHAR (255), - CONSUMER_SECRET VARCHAR (2048), - USERNAME VARCHAR (255), - TENANT_ID INTEGER DEFAULT 0, - USER_DOMAIN VARCHAR(50), - APP_NAME VARCHAR (255), - OAUTH_VERSION VARCHAR (128), - CALLBACK_URL VARCHAR (2048), - GRANT_TYPES VARCHAR (1024), - PKCE_MANDATORY CHAR(1) DEFAULT '0', - PKCE_SUPPORT_PLAIN CHAR(1) DEFAULT '0', - APP_STATE VARCHAR (25) DEFAULT 'ACTIVE', - USER_ACCESS_TOKEN_EXPIRE_TIME BIGINT DEFAULT 3600, - APP_ACCESS_TOKEN_EXPIRE_TIME BIGINT DEFAULT 3600, - REFRESH_TOKEN_EXPIRE_TIME BIGINT DEFAULT 84600, - ID_TOKEN_EXPIRE_TIME BIGINT DEFAULT 3600, - CONSTRAINT CONSUMER_KEY_CONSTRAINT UNIQUE (TENANT_ID, CONSUMER_KEY), - PRIMARY KEY (ID) -); - -CREATE TABLE IF NOT EXISTS IDN_OAUTH2_SCOPE_VALIDATORS ( - APP_ID INTEGER NOT NULL, - SCOPE_VALIDATOR VARCHAR (128) NOT NULL, - PRIMARY KEY (APP_ID,SCOPE_VALIDATOR), - FOREIGN KEY (APP_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS IDN_OAUTH1A_REQUEST_TOKEN ( - REQUEST_TOKEN VARCHAR (512), - REQUEST_TOKEN_SECRET VARCHAR (512), - CONSUMER_KEY_ID INTEGER, - CALLBACK_URL VARCHAR (2048), - SCOPE VARCHAR(2048), - AUTHORIZED VARCHAR (128), - OAUTH_VERIFIER VARCHAR (512), - AUTHZ_USER VARCHAR (512), - TENANT_ID INTEGER DEFAULT -1, - PRIMARY KEY (REQUEST_TOKEN), - FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS IDN_OAUTH1A_ACCESS_TOKEN ( - ACCESS_TOKEN VARCHAR (512), - ACCESS_TOKEN_SECRET VARCHAR (512), - CONSUMER_KEY_ID INTEGER, - SCOPE VARCHAR(2048), - AUTHZ_USER VARCHAR (512), - TENANT_ID INTEGER DEFAULT -1, - PRIMARY KEY (ACCESS_TOKEN), - FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS IDN_OAUTH2_ACCESS_TOKEN ( - TOKEN_ID VARCHAR (255), - ACCESS_TOKEN VARCHAR (2048), - REFRESH_TOKEN VARCHAR (2048), - CONSUMER_KEY_ID INTEGER, - AUTHZ_USER VARCHAR (100), - TENANT_ID INTEGER, - USER_DOMAIN VARCHAR(50), - USER_TYPE VARCHAR (25), - GRANT_TYPE VARCHAR (50), - TIME_CREATED TIMESTAMP DEFAULT 0, - REFRESH_TOKEN_TIME_CREATED TIMESTAMP DEFAULT 0, - VALIDITY_PERIOD BIGINT, - REFRESH_TOKEN_VALIDITY_PERIOD BIGINT, - TOKEN_SCOPE_HASH VARCHAR (32), - TOKEN_STATE VARCHAR (25) DEFAULT 'ACTIVE', - TOKEN_STATE_ID VARCHAR (128) DEFAULT 'NONE', - SUBJECT_IDENTIFIER VARCHAR(255), - ACCESS_TOKEN_HASH VARCHAR (512), - REFRESH_TOKEN_HASH VARCHAR (512), - IDP_ID INTEGER DEFAULT -1 NOT NULL, - TOKEN_BINDING_REF VARCHAR (32) DEFAULT 'NONE', - CONSENTED_TOKEN VARCHAR(6), - AUTHORIZED_ORGANIZATION VARCHAR(36) DEFAULT 'NONE' NOT NULL, - PRIMARY KEY (TOKEN_ID), - FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE, - CONSTRAINT CON_APP_KEY UNIQUE (CONSUMER_KEY_ID,AUTHZ_USER,TENANT_ID,USER_DOMAIN,USER_TYPE,TOKEN_SCOPE_HASH, - TOKEN_STATE,TOKEN_STATE_ID,IDP_ID,TOKEN_BINDING_REF,AUTHORIZED_ORGANIZATION) -); - -CREATE TABLE IF NOT EXISTS IDN_OAUTH2_TOKEN_BINDING ( - TOKEN_ID VARCHAR (255), - TOKEN_BINDING_TYPE VARCHAR (32), - TOKEN_BINDING_REF VARCHAR (32), - TOKEN_BINDING_VALUE VARCHAR (1024), - TENANT_ID INTEGER DEFAULT -1, - UNIQUE (TOKEN_ID,TOKEN_BINDING_TYPE,TOKEN_BINDING_VALUE), - FOREIGN KEY (TOKEN_ID) REFERENCES IDN_OAUTH2_ACCESS_TOKEN(TOKEN_ID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS IDN_OAUTH2_ACCESS_TOKEN_AUDIT ( - ID INTEGER NOT NULL AUTO_INCREMENT, - TOKEN_ID VARCHAR (255), - ACCESS_TOKEN VARCHAR(2048), - REFRESH_TOKEN VARCHAR(2048), - CONSUMER_KEY_ID INTEGER, - AUTHZ_USER VARCHAR (100), - TENANT_ID INTEGER, - USER_DOMAIN VARCHAR(50), - USER_TYPE VARCHAR (25), - GRANT_TYPE VARCHAR (50), - TIME_CREATED TIMESTAMP NULL, - REFRESH_TOKEN_TIME_CREATED TIMESTAMP NULL, - VALIDITY_PERIOD BIGINT, - REFRESH_TOKEN_VALIDITY_PERIOD BIGINT, - TOKEN_SCOPE_HASH VARCHAR(32), - TOKEN_STATE VARCHAR(25), - TOKEN_STATE_ID VARCHAR (128) , - SUBJECT_IDENTIFIER VARCHAR(255), - ACCESS_TOKEN_HASH VARCHAR(512), - REFRESH_TOKEN_HASH VARCHAR(512), - INVALIDATED_TIME TIMESTAMP NULL, - IDP_ID INTEGER DEFAULT -1 NOT NULL, - PRIMARY KEY(ID) -); - - -CREATE TABLE IF NOT EXISTS IDN_OAUTH2_AUTHORIZATION_CODE ( - CODE_ID VARCHAR (255), - AUTHORIZATION_CODE VARCHAR (2048), - CONSUMER_KEY_ID INTEGER, - CALLBACK_URL VARCHAR (2048), - SCOPE VARCHAR(2048), - AUTHZ_USER VARCHAR (100), - TENANT_ID INTEGER, - USER_DOMAIN VARCHAR(50), - TIME_CREATED TIMESTAMP, - VALIDITY_PERIOD BIGINT, - STATE VARCHAR (25) DEFAULT 'ACTIVE', - TOKEN_ID VARCHAR(255), - SUBJECT_IDENTIFIER VARCHAR(255), - PKCE_CODE_CHALLENGE VARCHAR (255), - PKCE_CODE_CHALLENGE_METHOD VARCHAR(128), - AUTHORIZATION_CODE_HASH VARCHAR (512), - IDP_ID INTEGER DEFAULT -1 NOT NULL, - PRIMARY KEY (CODE_ID), - FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS IDN_OAUTH2_AUTHZ_CODE_SCOPE( - CODE_ID VARCHAR(255), - SCOPE VARCHAR(255), - TENANT_ID INTEGER DEFAULT -1, - PRIMARY KEY (CODE_ID, SCOPE), - FOREIGN KEY (CODE_ID) REFERENCES IDN_OAUTH2_AUTHORIZATION_CODE (CODE_ID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS IDN_OAUTH2_DEVICE_FLOW ( - CODE_ID VARCHAR(255), - DEVICE_CODE VARCHAR(255), - USER_CODE VARCHAR(25), - QUANTIFIER INTEGER NOT NULL DEFAULT 0, - CONSUMER_KEY_ID INTEGER, - LAST_POLL_TIME TIMESTAMP NOT NULL, - EXPIRY_TIME TIMESTAMP NOT NULL, - TIME_CREATED TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - POLL_TIME BIGINT, - STATUS VARCHAR (25) DEFAULT 'PENDING', - AUTHZ_USER VARCHAR (100), - TENANT_ID INTEGER, - USER_DOMAIN VARCHAR(50), - IDP_ID INTEGER, - SUBJECT_IDENTIFIER VARCHAR(255), - PRIMARY KEY (DEVICE_CODE), - UNIQUE (CODE_ID), - CONSTRAINT USRCDE_QNTFR_CONSTRAINT UNIQUE (USER_CODE, QUANTIFIER), - FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS IDN_OAUTH2_DEVICE_FLOW_SCOPES ( - ID INTEGER NOT NULL AUTO_INCREMENT, - SCOPE_ID VARCHAR(255), - SCOPE VARCHAR(255), - PRIMARY KEY (ID), - FOREIGN KEY (SCOPE_ID) REFERENCES IDN_OAUTH2_DEVICE_FLOW(CODE_ID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS IDN_OAUTH2_ACCESS_TOKEN_SCOPE ( - TOKEN_ID VARCHAR (255), - TOKEN_SCOPE VARCHAR (255), - TENANT_ID INTEGER DEFAULT -1, - PRIMARY KEY (TOKEN_ID, TOKEN_SCOPE), - FOREIGN KEY (TOKEN_ID) REFERENCES IDN_OAUTH2_ACCESS_TOKEN(TOKEN_ID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS IDN_OAUTH2_SCOPE ( - SCOPE_ID INTEGER NOT NULL AUTO_INCREMENT, - NAME VARCHAR(255) NOT NULL, - DISPLAY_NAME VARCHAR(255) NOT NULL, - DESCRIPTION VARCHAR(512), - TENANT_ID INTEGER NOT NULL DEFAULT -1, - SCOPE_TYPE VARCHAR(255) NOT NULL, - PRIMARY KEY (SCOPE_ID), - UNIQUE (NAME, TENANT_ID) -); - -CREATE TABLE IF NOT EXISTS IDN_OAUTH2_SCOPE_BINDING ( - ID INTEGER NOT NULL AUTO_INCREMENT, - SCOPE_ID INTEGER NOT NULL, - SCOPE_BINDING VARCHAR(255) NOT NULL, - BINDING_TYPE VARCHAR(255) NOT NULL, - FOREIGN KEY (SCOPE_ID) REFERENCES IDN_OAUTH2_SCOPE(SCOPE_ID) ON DELETE CASCADE, - UNIQUE (SCOPE_ID, SCOPE_BINDING, BINDING_TYPE), - PRIMARY KEY (ID) -); - -CREATE TABLE IF NOT EXISTS IDN_OAUTH2_RESOURCE_SCOPE ( - RESOURCE_PATH VARCHAR(255) NOT NULL, - SCOPE_ID INTEGER NOT NULL, - TENANT_ID INTEGER DEFAULT -1, - PRIMARY KEY (RESOURCE_PATH), - FOREIGN KEY (SCOPE_ID) REFERENCES IDN_OAUTH2_SCOPE (SCOPE_ID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS IDN_SCIM_GROUP ( - ID INTEGER NOT NULL AUTO_INCREMENT, - TENANT_ID INTEGER NOT NULL, - ROLE_NAME VARCHAR(255) NOT NULL, - ATTR_NAME VARCHAR(1024) NOT NULL, - ATTR_VALUE VARCHAR(1024), - AUDIENCE_REF_ID INTEGER DEFAULT -1 NOT NULL, - UNIQUE(TENANT_ID, ROLE_NAME, ATTR_NAME, AUDIENCE_REF_ID), - PRIMARY KEY (ID) -); - - - -CREATE TABLE IF NOT EXISTS IDN_OPENID_REMEMBER_ME ( - USER_NAME VARCHAR(255) NOT NULL, - TENANT_ID INTEGER DEFAULT 0, - COOKIE_VALUE VARCHAR(1024), - CREATED_TIME TIMESTAMP, - PRIMARY KEY (USER_NAME, TENANT_ID) -); - -CREATE TABLE IF NOT EXISTS IDN_OPENID_USER_RPS ( - USER_NAME VARCHAR(255) NOT NULL, - TENANT_ID INTEGER DEFAULT 0, - RP_URL VARCHAR(255) NOT NULL, - TRUSTED_ALWAYS VARCHAR(128) DEFAULT 'FALSE', - LAST_VISIT DATE NOT NULL, - VISIT_COUNT INTEGER DEFAULT 0, - DEFAULT_PROFILE_NAME VARCHAR(255) DEFAULT 'DEFAULT', - PRIMARY KEY (USER_NAME, TENANT_ID, RP_URL) -); - -CREATE TABLE IF NOT EXISTS IDN_OPENID_ASSOCIATIONS ( - HANDLE VARCHAR(255) NOT NULL, - ASSOC_TYPE VARCHAR(255) NOT NULL, - EXPIRE_IN TIMESTAMP NOT NULL, - MAC_KEY VARCHAR(255) NOT NULL, - ASSOC_STORE VARCHAR(128) DEFAULT 'SHARED', - TENANT_ID INTEGER DEFAULT -1, - PRIMARY KEY (HANDLE) -); - -CREATE TABLE IDN_STS_STORE ( - ID INTEGER AUTO_INCREMENT, - TOKEN_ID VARCHAR(255) NOT NULL, - TOKEN_CONTENT BLOB(1024) NOT NULL, - CREATE_DATE TIMESTAMP NOT NULL, - EXPIRE_DATE TIMESTAMP NOT NULL, - STATE INTEGER DEFAULT 0, - PRIMARY KEY (ID) -); - -CREATE TABLE IDN_IDENTITY_USER_DATA ( - TENANT_ID INTEGER DEFAULT -1234, - USER_NAME VARCHAR(255) NOT NULL, - DATA_KEY VARCHAR(255) NOT NULL, - DATA_VALUE VARCHAR(2048), - PRIMARY KEY (TENANT_ID, USER_NAME, DATA_KEY) -); - -CREATE TABLE IDN_IDENTITY_META_DATA ( - USER_NAME VARCHAR(255) NOT NULL, - TENANT_ID INTEGER DEFAULT -1234, - METADATA_TYPE VARCHAR(255) NOT NULL, - METADATA VARCHAR(255) NOT NULL, - VALID VARCHAR(255) NOT NULL, - PRIMARY KEY (TENANT_ID, USER_NAME, METADATA_TYPE,METADATA) -); - -CREATE TABLE IF NOT EXISTS IDN_THRIFT_SESSION ( - SESSION_ID VARCHAR(255) NOT NULL, - USER_NAME VARCHAR(255) NOT NULL, - CREATED_TIME VARCHAR(255) NOT NULL, - LAST_MODIFIED_TIME VARCHAR(255) NOT NULL, - TENANT_ID INTEGER DEFAULT -1, - PRIMARY KEY (SESSION_ID) -); - -CREATE TABLE IDN_AUTH_SESSION_STORE ( - SESSION_ID VARCHAR (100) NOT NULL, - SESSION_TYPE VARCHAR(100) NOT NULL, - OPERATION VARCHAR(10) NOT NULL, - SESSION_OBJECT BLOB, - TIME_CREATED BIGINT, - TENANT_ID INTEGER DEFAULT -1, - EXPIRY_TIME BIGINT, - PRIMARY KEY (SESSION_ID, SESSION_TYPE, TIME_CREATED, OPERATION) -); - - -CREATE TABLE IDN_AUTH_TEMP_SESSION_STORE ( - SESSION_ID VARCHAR (100) NOT NULL, - SESSION_TYPE VARCHAR(100) NOT NULL, - OPERATION VARCHAR(10) NOT NULL, - SESSION_OBJECT BLOB, - TIME_CREATED BIGINT, - TENANT_ID INTEGER DEFAULT -1, - EXPIRY_TIME BIGINT, - PRIMARY KEY (SESSION_ID, SESSION_TYPE, TIME_CREATED, OPERATION) -); - -CREATE TABLE IF NOT EXISTS IDN_AUTH_USER ( - USER_ID VARCHAR(255) NOT NULL, - USER_NAME VARCHAR(255) NOT NULL, - TENANT_ID INTEGER NOT NULL, - DOMAIN_NAME VARCHAR(255) NOT NULL, - IDP_ID INTEGER NOT NULL, - PRIMARY KEY (USER_ID), - CONSTRAINT USER_STORE_CONSTRAINT UNIQUE (USER_NAME, TENANT_ID, DOMAIN_NAME, IDP_ID)); - -CREATE TABLE IF NOT EXISTS IDN_AUTH_USER_SESSION_MAPPING ( - ID INTEGER NOT NULL AUTO_INCREMENT, - USER_ID VARCHAR(255) NOT NULL, - SESSION_ID VARCHAR(255) NOT NULL, - CONSTRAINT USER_SESSION_STORE_CONSTRAINT UNIQUE (USER_ID, SESSION_ID), - PRIMARY KEY (ID)); - -CREATE TABLE IF NOT EXISTS IDN_AUTH_SESSION_APP_INFO ( - SESSION_ID VARCHAR (100) NOT NULL, - SUBJECT VARCHAR (100) NOT NULL, - APP_ID INTEGER NOT NULL, - INBOUND_AUTH_TYPE VARCHAR (255) NOT NULL, - PRIMARY KEY (SESSION_ID, SUBJECT, APP_ID, INBOUND_AUTH_TYPE)); - -CREATE TABLE IF NOT EXISTS IDN_AUTH_SESSION_META_DATA ( - SESSION_ID VARCHAR (100) NOT NULL, - PROPERTY_TYPE VARCHAR (100) NOT NULL, - `VALUE` VARCHAR (255) NOT NULL, - PRIMARY KEY (SESSION_ID, PROPERTY_TYPE, `VALUE`) - ); - -CREATE TABLE IF NOT EXISTS SP_APP ( - ID INTEGER NOT NULL AUTO_INCREMENT, - TENANT_ID INTEGER NOT NULL, - APP_NAME VARCHAR (255) NOT NULL , - USER_STORE VARCHAR (255) NOT NULL, - USERNAME VARCHAR (255) NOT NULL , - DESCRIPTION VARCHAR (1024), - ROLE_CLAIM VARCHAR (512), - AUTH_TYPE VARCHAR (255) NOT NULL, - PROVISIONING_USERSTORE_DOMAIN VARCHAR (512), - IS_LOCAL_CLAIM_DIALECT CHAR(1) DEFAULT '1', - IS_SEND_LOCAL_SUBJECT_ID CHAR(1) DEFAULT '0', - IS_SEND_AUTH_LIST_OF_IDPS CHAR(1) DEFAULT '0', - IS_USE_TENANT_DOMAIN_SUBJECT CHAR(1) DEFAULT '1', - IS_USE_USER_DOMAIN_SUBJECT CHAR(1) DEFAULT '1', - ENABLE_AUTHORIZATION CHAR(1) DEFAULT '0', - SUBJECT_CLAIM_URI VARCHAR (512), - IS_SAAS_APP CHAR(1) DEFAULT '0', - IS_DUMB_MODE CHAR(1) DEFAULT '0', - UUID CHAR(36), - IMAGE_URL VARCHAR(1024), - ACCESS_URL VARCHAR(1024), - IS_DISCOVERABLE CHAR(1) DEFAULT '0', - - PRIMARY KEY (ID)); - -ALTER TABLE SP_APP ADD CONSTRAINT APPLICATION_NAME_CONSTRAINT UNIQUE(APP_NAME, TENANT_ID); -ALTER TABLE SP_APP ADD CONSTRAINT APPLICATION_UUID_CONSTRAINT UNIQUE(UUID); - -CREATE TABLE IF NOT EXISTS SP_METADATA ( - ID INTEGER AUTO_INCREMENT, - SP_ID INTEGER, - NAME VARCHAR(255) NOT NULL, - `VALUE` VARCHAR(255) NOT NULL, - DISPLAY_NAME VARCHAR(255), - TENANT_ID INTEGER DEFAULT -1, - PRIMARY KEY (ID), - CONSTRAINT SP_METADATA_CONSTRAINT UNIQUE (SP_ID, NAME), - FOREIGN KEY (SP_ID) REFERENCES SP_APP(ID) ON DELETE CASCADE); - -CREATE TABLE IF NOT EXISTS SP_INBOUND_AUTH ( - ID INTEGER NOT NULL AUTO_INCREMENT, - TENANT_ID INTEGER NOT NULL, - INBOUND_AUTH_KEY VARCHAR (255), - INBOUND_AUTH_TYPE VARCHAR (255) NOT NULL, - INBOUND_CONFIG_TYPE VARCHAR (255) NOT NULL, - PROP_NAME VARCHAR (255), - PROP_VALUE VARCHAR (1024) , - APP_ID INTEGER NOT NULL, - PRIMARY KEY (ID)); - -ALTER TABLE SP_INBOUND_AUTH ADD CONSTRAINT APPLICATION_ID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; - -CREATE TABLE IF NOT EXISTS SP_AUTH_STEP ( - ID INTEGER NOT NULL AUTO_INCREMENT, - TENANT_ID INTEGER NOT NULL, - STEP_ORDER INTEGER DEFAULT 1, - APP_ID INTEGER NOT NULL , - IS_SUBJECT_STEP CHAR(1) DEFAULT '0', - IS_ATTRIBUTE_STEP CHAR(1) DEFAULT '0', - PRIMARY KEY (ID)); - -ALTER TABLE SP_AUTH_STEP ADD CONSTRAINT APPLICATION_ID_CONSTRAINT_STEP FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; - -CREATE TABLE IF NOT EXISTS SP_FEDERATED_IDP ( - ID INTEGER NOT NULL, - TENANT_ID INTEGER NOT NULL, - AUTHENTICATOR_ID INTEGER NOT NULL, - PRIMARY KEY (ID, AUTHENTICATOR_ID)); - -ALTER TABLE SP_FEDERATED_IDP ADD CONSTRAINT STEP_ID_CONSTRAINT FOREIGN KEY (ID) REFERENCES SP_AUTH_STEP (ID) ON DELETE CASCADE; - -CREATE TABLE IF NOT EXISTS SP_CLAIM_DIALECT ( - ID INTEGER NOT NULL AUTO_INCREMENT, - TENANT_ID INTEGER NOT NULL, - SP_DIALECT VARCHAR (512) NOT NULL, - APP_ID INTEGER NOT NULL, - PRIMARY KEY (ID)); - -ALTER TABLE SP_CLAIM_DIALECT ADD CONSTRAINT DIALECTID_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; - -CREATE TABLE IF NOT EXISTS SP_CLAIM_MAPPING ( - ID INTEGER NOT NULL AUTO_INCREMENT, - TENANT_ID INTEGER NOT NULL, - IDP_CLAIM VARCHAR (512) NOT NULL , - SP_CLAIM VARCHAR (512) NOT NULL , - APP_ID INTEGER NOT NULL, - IS_REQUESTED VARCHAR(128) DEFAULT '0', - IS_MANDATORY VARCHAR(128) DEFAULT '0', - DEFAULT_VALUE VARCHAR(255), - PRIMARY KEY (ID)); - -ALTER TABLE SP_CLAIM_MAPPING ADD CONSTRAINT CLAIMID_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; - -CREATE TABLE IF NOT EXISTS SP_ROLE_MAPPING ( - ID INTEGER NOT NULL AUTO_INCREMENT, - TENANT_ID INTEGER NOT NULL, - IDP_ROLE VARCHAR (255) NOT NULL , - SP_ROLE VARCHAR (255) NOT NULL , - APP_ID INTEGER NOT NULL, - PRIMARY KEY (ID)); - -ALTER TABLE SP_ROLE_MAPPING ADD CONSTRAINT ROLEID_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; - -CREATE TABLE IF NOT EXISTS SP_REQ_PATH_AUTHENTICATOR ( - ID INTEGER NOT NULL AUTO_INCREMENT, - TENANT_ID INTEGER NOT NULL, - AUTHENTICATOR_NAME VARCHAR (255) NOT NULL , - APP_ID INTEGER NOT NULL, - PRIMARY KEY (ID)); - -ALTER TABLE SP_REQ_PATH_AUTHENTICATOR ADD CONSTRAINT REQ_AUTH_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; - -CREATE TABLE IF NOT EXISTS SP_PROVISIONING_CONNECTOR ( - ID INTEGER NOT NULL AUTO_INCREMENT, - TENANT_ID INTEGER NOT NULL, - IDP_NAME VARCHAR (255) NOT NULL , - CONNECTOR_NAME VARCHAR (255) NOT NULL , - APP_ID INTEGER NOT NULL, - IS_JIT_ENABLED CHAR(1) NOT NULL DEFAULT '0', - BLOCKING CHAR(1) NOT NULL DEFAULT '0', - RULE_ENABLED CHAR(1) NOT NULL DEFAULT '0', - PRIMARY KEY (ID)); - -ALTER TABLE SP_PROVISIONING_CONNECTOR ADD CONSTRAINT PRO_CONNECTOR_APPID_CONSTRAINT FOREIGN KEY (APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE; - -CREATE TABLE IF NOT EXISTS SP_AUTH_SCRIPT ( - ID INTEGER AUTO_INCREMENT NOT NULL, - TENANT_ID INTEGER NOT NULL, - APP_ID INTEGER NOT NULL, - TYPE VARCHAR(255) NOT NULL, - CONTENT BLOB DEFAULT NULL, - IS_ENABLED CHAR(1) NOT NULL DEFAULT '0', - PRIMARY KEY (ID)); - -CREATE TABLE SP_TEMPLATE ( - ID INTEGER AUTO_INCREMENT NOT NULL, - TENANT_ID INTEGER NOT NULL, - NAME VARCHAR(255) NOT NULL, - DESCRIPTION VARCHAR(1023), - CONTENT BLOB DEFAULT NULL, - PRIMARY KEY (ID), - CONSTRAINT SP_TEMPLATE_CONSTRAINT UNIQUE (TENANT_ID, NAME)); - -CREATE TABLE IF NOT EXISTS IDN_AUTH_WAIT_STATUS ( - ID INTEGER AUTO_INCREMENT NOT NULL, - TENANT_ID INTEGER NOT NULL, - LONG_WAIT_KEY VARCHAR(255) NOT NULL, - WAIT_STATUS CHAR(1) NOT NULL DEFAULT '1', - TIME_CREATED TIMESTAMP DEFAULT 0, - EXPIRE_TIME TIMESTAMP DEFAULT 0, - PRIMARY KEY (ID), - CONSTRAINT IDN_AUTH_WAIT_STATUS_KEY UNIQUE (LONG_WAIT_KEY)); - -CREATE TABLE IF NOT EXISTS IDP ( - ID INTEGER AUTO_INCREMENT, - TENANT_ID INTEGER, - NAME VARCHAR(254) NOT NULL, - IS_ENABLED CHAR(1) NOT NULL DEFAULT '1', - IS_PRIMARY CHAR(1) NOT NULL DEFAULT '0', - HOME_REALM_ID VARCHAR(254), - IMAGE MEDIUMBLOB, - CERTIFICATE BLOB, - ALIAS VARCHAR(254), - INBOUND_PROV_ENABLED CHAR(1) NOT NULL DEFAULT '0', - INBOUND_PROV_USER_STORE_ID VARCHAR(254), - USER_CLAIM_URI VARCHAR(254), - ROLE_CLAIM_URI VARCHAR(254), - DESCRIPTION VARCHAR(1024), - DEFAULT_AUTHENTICATOR_NAME VARCHAR(254), - DEFAULT_PRO_CONNECTOR_NAME VARCHAR(254), - PROVISIONING_ROLE VARCHAR(128), - IS_FEDERATION_HUB CHAR(1) NOT NULL DEFAULT '0', - IS_LOCAL_CLAIM_DIALECT CHAR(1) NOT NULL DEFAULT '0', - DISPLAY_NAME VARCHAR(255), - IMAGE_URL VARCHAR(1024), - UUID CHAR(36) NOT NULL, - PRIMARY KEY (ID), - UNIQUE (TENANT_ID, NAME), - UNIQUE (UUID) -); - -CREATE TABLE IF NOT EXISTS IDP_ROLE ( - ID INTEGER AUTO_INCREMENT, - IDP_ID INTEGER, - TENANT_ID INTEGER, - ROLE VARCHAR(254), - PRIMARY KEY (ID), - UNIQUE (IDP_ID, ROLE), - FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE); - -CREATE TABLE IF NOT EXISTS IDP_GROUP ( - ID INTEGER AUTO_INCREMENT NOT NULL, - IDP_ID INTEGER NOT NULL, - TENANT_ID INTEGER NOT NULL, - GROUP_NAME VARCHAR(255) NOT NULL, - UUID CHAR(36) NOT NULL, - PRIMARY KEY (ID), - UNIQUE (IDP_ID, GROUP_NAME), - UNIQUE (UUID), - FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE); - -CREATE TABLE IF NOT EXISTS IDP_ROLE_MAPPING ( - ID INTEGER AUTO_INCREMENT, - IDP_ROLE_ID INTEGER, - TENANT_ID INTEGER, - USER_STORE_ID VARCHAR (253), - LOCAL_ROLE VARCHAR(253), - PRIMARY KEY (ID), - UNIQUE (IDP_ROLE_ID, TENANT_ID, USER_STORE_ID, LOCAL_ROLE), - FOREIGN KEY (IDP_ROLE_ID) REFERENCES IDP_ROLE(ID) ON DELETE CASCADE); - -CREATE TABLE IF NOT EXISTS IDP_CLAIM ( - ID INTEGER AUTO_INCREMENT, - IDP_ID INTEGER, - TENANT_ID INTEGER, - CLAIM VARCHAR(254), - PRIMARY KEY (ID), - UNIQUE (IDP_ID, CLAIM), - FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE); - -CREATE TABLE IF NOT EXISTS IDP_CLAIM_MAPPING ( - ID INTEGER AUTO_INCREMENT, - IDP_CLAIM_ID INTEGER, - TENANT_ID INTEGER, - LOCAL_CLAIM VARCHAR(253), - DEFAULT_VALUE VARCHAR(255), - IS_REQUESTED VARCHAR(128) DEFAULT '0', - PRIMARY KEY (ID), - UNIQUE (IDP_CLAIM_ID, TENANT_ID, LOCAL_CLAIM), - FOREIGN KEY (IDP_CLAIM_ID) REFERENCES IDP_CLAIM(ID) ON DELETE CASCADE); - -CREATE TABLE IF NOT EXISTS IDP_AUTHENTICATOR ( - ID INTEGER AUTO_INCREMENT, - TENANT_ID INTEGER, - IDP_ID INTEGER, - NAME VARCHAR(255) NOT NULL, - IS_ENABLED CHAR (1) DEFAULT '1', - DISPLAY_NAME VARCHAR(255), - DEFINED_BY VARCHAR(25) NOT NULL, - AUTHENTICATION_TYPE VARCHAR(25) NOT NULL, - PRIMARY KEY (ID), - UNIQUE (TENANT_ID, IDP_ID, NAME), - FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE); - -CREATE TABLE IF NOT EXISTS IDP_METADATA ( - ID INTEGER AUTO_INCREMENT, - IDP_ID INTEGER, - NAME VARCHAR(255) NOT NULL, - `VALUE` VARCHAR(255) NOT NULL, - DISPLAY_NAME VARCHAR(255), - TENANT_ID INTEGER DEFAULT -1, - PRIMARY KEY (ID), - CONSTRAINT IDP_METADATA_CONSTRAINT UNIQUE (IDP_ID, NAME), - FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE); - -CREATE TABLE IF NOT EXISTS IDP_AUTHENTICATOR_PROPERTY ( - ID INTEGER AUTO_INCREMENT, - TENANT_ID INTEGER, - AUTHENTICATOR_ID INTEGER, - PROPERTY_KEY VARCHAR(255) NOT NULL, - PROPERTY_VALUE VARCHAR(2047), - IS_SECRET CHAR (1) DEFAULT '0', - PRIMARY KEY (ID), - UNIQUE (TENANT_ID, AUTHENTICATOR_ID, PROPERTY_KEY), - FOREIGN KEY (AUTHENTICATOR_ID) REFERENCES IDP_AUTHENTICATOR(ID) ON DELETE CASCADE); - -CREATE TABLE IF NOT EXISTS IDP_PROVISIONING_CONFIG ( - ID INTEGER AUTO_INCREMENT, - TENANT_ID INTEGER, - IDP_ID INTEGER, - PROVISIONING_CONNECTOR_TYPE VARCHAR(255) NOT NULL, - IS_ENABLED CHAR (1) DEFAULT '0', - IS_BLOCKING CHAR (1) DEFAULT '0', - IS_RULES_ENABLED CHAR (1) DEFAULT '0', - PRIMARY KEY (ID), - UNIQUE (TENANT_ID, IDP_ID, PROVISIONING_CONNECTOR_TYPE), - FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE); - -CREATE TABLE IF NOT EXISTS IDP_PROV_CONFIG_PROPERTY ( - ID INTEGER AUTO_INCREMENT, - TENANT_ID INTEGER, - PROVISIONING_CONFIG_ID INTEGER, - PROPERTY_KEY VARCHAR(255) NOT NULL, - PROPERTY_VALUE VARCHAR(2048), - PROPERTY_BLOB_VALUE BLOB, - PROPERTY_TYPE VARCHAR(32) NOT NULL, - IS_SECRET CHAR (1) DEFAULT '0', - PRIMARY KEY (ID), - UNIQUE (TENANT_ID, PROVISIONING_CONFIG_ID, PROPERTY_KEY), - FOREIGN KEY (PROVISIONING_CONFIG_ID) REFERENCES IDP_PROVISIONING_CONFIG(ID) ON DELETE CASCADE); - -CREATE TABLE IF NOT EXISTS IDP_PROVISIONING_ENTITY ( - ID INTEGER AUTO_INCREMENT, - PROVISIONING_CONFIG_ID INTEGER, - ENTITY_TYPE VARCHAR(255) NOT NULL, - ENTITY_LOCAL_USERSTORE VARCHAR(255) NOT NULL, - ENTITY_NAME VARCHAR(255) NOT NULL, - ENTITY_VALUE VARCHAR(255), - TENANT_ID INTEGER, - ENTITY_LOCAL_ID VARCHAR(255), - PRIMARY KEY (ID), - UNIQUE (ENTITY_TYPE, TENANT_ID, ENTITY_LOCAL_USERSTORE, ENTITY_NAME, PROVISIONING_CONFIG_ID), - UNIQUE (PROVISIONING_CONFIG_ID, ENTITY_TYPE, ENTITY_VALUE), - FOREIGN KEY (PROVISIONING_CONFIG_ID) REFERENCES IDP_PROVISIONING_CONFIG(ID) ON DELETE CASCADE); - -CREATE TABLE IF NOT EXISTS IDP_LOCAL_CLAIM ( - ID INTEGER AUTO_INCREMENT, - TENANT_ID INTEGER, - IDP_ID INTEGER, - CLAIM_URI VARCHAR(255) NOT NULL, - DEFAULT_VALUE VARCHAR(255), - IS_REQUESTED VARCHAR(128) DEFAULT '0', - PRIMARY KEY (ID), - UNIQUE (TENANT_ID, IDP_ID, CLAIM_URI), - FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE); - -CREATE TABLE IF NOT EXISTS IDN_ASSOCIATED_ID ( - ID INTEGER AUTO_INCREMENT, - IDP_USER_ID VARCHAR(255) NOT NULL, - TENANT_ID INTEGER DEFAULT -1234, - IDP_ID INTEGER NOT NULL, - DOMAIN_NAME VARCHAR(255) NOT NULL, - USER_NAME VARCHAR(255) NOT NULL, - ASSOCIATION_ID CHAR(36) NOT NULL, - PRIMARY KEY (ID), - UNIQUE(IDP_USER_ID, TENANT_ID, IDP_ID), - FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS IDN_USER_ACCOUNT_ASSOCIATION ( - ASSOCIATION_KEY VARCHAR(255) NOT NULL, - TENANT_ID INTEGER, - DOMAIN_NAME VARCHAR(255) NOT NULL, - USER_NAME VARCHAR(255) NOT NULL, - PRIMARY KEY (TENANT_ID, DOMAIN_NAME, USER_NAME)); - -CREATE TABLE IF NOT EXISTS FIDO_DEVICE_STORE ( - TENANT_ID INTEGER, - DOMAIN_NAME VARCHAR(255) NOT NULL, - USER_NAME VARCHAR(45) NOT NULL, - TIME_REGISTERED TIMESTAMP, - KEY_HANDLE VARCHAR(200) NOT NULL, - DEVICE_DATA VARCHAR(2048) NOT NULL, - PRIMARY KEY (TENANT_ID, DOMAIN_NAME, USER_NAME, KEY_HANDLE)); - -CREATE TABLE IF NOT EXISTS FIDO2_DEVICE_STORE ( - TENANT_ID INTEGER, - DOMAIN_NAME VARCHAR(255) NOT NULL, - USER_NAME VARCHAR(45) NOT NULL, - TIME_REGISTERED TIMESTAMP, - USER_HANDLE VARCHAR(200) NOT NULL, - CREDENTIAL_ID VARCHAR(200) NOT NULL, - PUBLIC_KEY_COSE VARCHAR(2048) NOT NULL, - SIGNATURE_COUNT BIGINT, - USER_IDENTITY VARCHAR(200) NOT NULL, - DISPLAY_NAME VARCHAR(255), - IS_USERNAMELESS_SUPPORTED CHAR(1) DEFAULT '0', - PRIMARY KEY (CREDENTIAL_ID, USER_HANDLE)); - -CREATE TABLE IF NOT EXISTS IDN_RECOVERY_FLOW_DATA ( - RECOVERY_FLOW_ID VARCHAR(255) NOT NULL, - CODE VARCHAR(255), - FAILED_ATTEMPTS INTEGER DEFAULT 0 NOT NULL, - RESEND_COUNT INTEGER DEFAULT 0 NOT NULL, - TIME_CREATED TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY(RECOVERY_FLOW_ID) -); - -CREATE TABLE IF NOT EXISTS IDN_RECOVERY_DATA ( - USER_NAME VARCHAR(255) NOT NULL, - USER_DOMAIN VARCHAR(127) NOT NULL, - TENANT_ID INTEGER DEFAULT -1, - CODE VARCHAR(255) NOT NULL, - SCENARIO VARCHAR(255) NOT NULL, - STEP VARCHAR(127) NOT NULL, - TIME_CREATED TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - REMAINING_SETS VARCHAR(2500) DEFAULT NULL, - RECOVERY_FLOW_ID VARCHAR(255), - PRIMARY KEY(USER_NAME, USER_DOMAIN, TENANT_ID, SCENARIO,STEP), - FOREIGN KEY (RECOVERY_FLOW_ID) REFERENCES IDN_RECOVERY_FLOW_DATA(RECOVERY_FLOW_ID) ON DELETE CASCADE, - UNIQUE(CODE) -); - -CREATE TABLE IF NOT EXISTS IDN_PASSWORD_HISTORY_DATA ( - ID INTEGER NOT NULL AUTO_INCREMENT, - USER_NAME VARCHAR(255) NOT NULL, - USER_DOMAIN VARCHAR(127) NOT NULL, - TENANT_ID INTEGER DEFAULT -1, - SALT_VALUE VARCHAR(255), - HASH VARCHAR(255) NOT NULL, - TIME_CREATED TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (ID), - UNIQUE (USER_NAME,USER_DOMAIN,TENANT_ID,SALT_VALUE,HASH) -); - -CREATE TABLE IF NOT EXISTS IDN_CLAIM_DIALECT ( - ID INTEGER NOT NULL AUTO_INCREMENT, - DIALECT_URI VARCHAR (255) NOT NULL, - TENANT_ID INTEGER NOT NULL, - PRIMARY KEY (ID), - CONSTRAINT DIALECT_URI_CONSTRAINT UNIQUE (DIALECT_URI, TENANT_ID) -); - -CREATE TABLE IF NOT EXISTS IDN_CLAIM ( - ID INTEGER NOT NULL AUTO_INCREMENT, - DIALECT_ID INTEGER NOT NULL, - CLAIM_URI VARCHAR (255) NOT NULL, - TENANT_ID INTEGER NOT NULL, - PRIMARY KEY (ID), - FOREIGN KEY (DIALECT_ID) REFERENCES IDN_CLAIM_DIALECT(ID) ON DELETE CASCADE, - CONSTRAINT CLAIM_URI_CONSTRAINT UNIQUE (DIALECT_ID, CLAIM_URI, TENANT_ID) -); - -CREATE TABLE IF NOT EXISTS IDN_CLAIM_MAPPED_ATTRIBUTE ( - ID INTEGER NOT NULL AUTO_INCREMENT, - LOCAL_CLAIM_ID INTEGER, - USER_STORE_DOMAIN_NAME VARCHAR (255) NOT NULL, - ATTRIBUTE_NAME VARCHAR (255) NOT NULL, - TENANT_ID INTEGER NOT NULL, - PRIMARY KEY (ID), - FOREIGN KEY (LOCAL_CLAIM_ID) REFERENCES IDN_CLAIM(ID) ON DELETE CASCADE, - CONSTRAINT USER_STORE_DOMAIN_CONSTRAINT UNIQUE (LOCAL_CLAIM_ID, USER_STORE_DOMAIN_NAME, TENANT_ID) -); - -CREATE TABLE IF NOT EXISTS IDN_CLAIM_PROPERTY ( - ID INTEGER NOT NULL AUTO_INCREMENT, - LOCAL_CLAIM_ID INTEGER, - PROPERTY_NAME VARCHAR (255) NOT NULL, - PROPERTY_VALUE VARCHAR (255) NOT NULL, - TENANT_ID INTEGER NOT NULL, - PRIMARY KEY (ID), - FOREIGN KEY (LOCAL_CLAIM_ID) REFERENCES IDN_CLAIM(ID) ON DELETE CASCADE, - CONSTRAINT PROPERTY_NAME_CONSTRAINT UNIQUE (LOCAL_CLAIM_ID, PROPERTY_NAME, TENANT_ID) -); - -CREATE TABLE IF NOT EXISTS IDN_CLAIM_MAPPING ( - ID INTEGER NOT NULL AUTO_INCREMENT, - EXT_CLAIM_ID INTEGER NOT NULL, - MAPPED_LOCAL_CLAIM_ID INTEGER NOT NULL, - TENANT_ID INTEGER NOT NULL, - PRIMARY KEY (ID), - FOREIGN KEY (EXT_CLAIM_ID) REFERENCES IDN_CLAIM(ID) ON DELETE CASCADE, - FOREIGN KEY (MAPPED_LOCAL_CLAIM_ID) REFERENCES IDN_CLAIM(ID) ON DELETE CASCADE, - CONSTRAINT EXT_TO_LOC_MAPPING_CONSTRN UNIQUE (EXT_CLAIM_ID, TENANT_ID) -); - -CREATE TABLE IF NOT EXISTS IDN_SAML2_ASSERTION_STORE ( - ID INTEGER NOT NULL AUTO_INCREMENT, - SAML2_ID VARCHAR(255) , - SAML2_ISSUER VARCHAR(255) , - SAML2_SUBJECT VARCHAR(255) , - SAML2_SESSION_INDEX VARCHAR(255) , - SAML2_AUTHN_CONTEXT_CLASS_REF VARCHAR(255) , - SAML2_ASSERTION VARCHAR(4096) , - ASSERTION BLOB , - PRIMARY KEY (ID) -); - -CREATE TABLE IDN_SAML2_ARTIFACT_STORE ( - ID INT NOT NULL AUTO_INCREMENT, - SOURCE_ID VARCHAR(255) NOT NULL, - MESSAGE_HANDLER VARCHAR(255) NOT NULL, - AUTHN_REQ_DTO BLOB NOT NULL, - SESSION_ID VARCHAR(255) NOT NULL, - INIT_TIMESTAMP TIMESTAMP NOT NULL, - EXP_TIMESTAMP TIMESTAMP NOT NULL, - ASSERTION_ID VARCHAR(255), - PRIMARY KEY (`ID`) -); - -CREATE TABLE IF NOT EXISTS IDN_OIDC_JTI ( - JWT_ID VARCHAR(255), - TENANT_ID INTEGER NOT NULL, - EXP_TIME TIMESTAMP NOT NULL , - TIME_CREATED TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP , - PRIMARY KEY (JWT_ID, TENANT_ID) -); - - -CREATE TABLE IF NOT EXISTS IDN_OIDC_PROPERTY ( - ID INTEGER NOT NULL AUTO_INCREMENT, - TENANT_ID INTEGER, - CONSUMER_KEY VARCHAR(255) , - PROPERTY_KEY VARCHAR(255) NOT NULL, - PROPERTY_VALUE VARCHAR(2047) , - PRIMARY KEY (ID), - FOREIGN KEY (TENANT_ID, CONSUMER_KEY) REFERENCES IDN_OAUTH_CONSUMER_APPS(TENANT_ID, CONSUMER_KEY) ON DELETE CASCADE -); -CREATE TABLE IF NOT EXISTS IDN_OIDC_REQ_OBJECT_REFERENCE ( - ID INTEGER NOT NULL AUTO_INCREMENT, - CONSUMER_KEY_ID INTEGER , - CODE_ID VARCHAR(255) , - TOKEN_ID VARCHAR(255) , - SESSION_DATA_KEY VARCHAR(255), - PRIMARY KEY (ID), - FOREIGN KEY (CONSUMER_KEY_ID) REFERENCES IDN_OAUTH_CONSUMER_APPS(ID) ON DELETE CASCADE, - FOREIGN KEY (TOKEN_ID) REFERENCES IDN_OAUTH2_ACCESS_TOKEN(TOKEN_ID) ON DELETE CASCADE, - FOREIGN KEY (CODE_ID) REFERENCES IDN_OAUTH2_AUTHORIZATION_CODE(CODE_ID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS IDN_OIDC_REQ_OBJECT_CLAIMS ( - ID INTEGER NOT NULL AUTO_INCREMENT, - REQ_OBJECT_ID INTEGER, - CLAIM_ATTRIBUTE VARCHAR(255) , - ESSENTIAL CHAR(1) NOT NULL DEFAULT '0', - `VALUE` VARCHAR(255) , - IS_USERINFO CHAR(1) NOT NULL DEFAULT '0', - PRIMARY KEY (ID), - FOREIGN KEY (REQ_OBJECT_ID) REFERENCES IDN_OIDC_REQ_OBJECT_REFERENCE (ID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS IDN_OIDC_REQ_OBJ_CLAIM_VALUES ( - ID INTEGER NOT NULL AUTO_INCREMENT, - REQ_OBJECT_CLAIMS_ID INTEGER , - CLAIM_VALUES VARCHAR(255) , - PRIMARY KEY (ID), - FOREIGN KEY (REQ_OBJECT_CLAIMS_ID) REFERENCES IDN_OIDC_REQ_OBJECT_CLAIMS(ID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS IDN_CERTIFICATE ( - ID INTEGER NOT NULL AUTO_INCREMENT, - NAME VARCHAR(100), - CERTIFICATE_IN_PEM BLOB, - TENANT_ID INTEGER DEFAULT 0, - PRIMARY KEY(ID), - CONSTRAINT CERTIFICATE_UNIQUE_KEY UNIQUE (NAME, TENANT_ID) -); - -CREATE TABLE IF NOT EXISTS IDN_OIDC_SCOPE_CLAIM_MAPPING ( - ID INTEGER NOT NULL AUTO_INCREMENT, - SCOPE_ID INTEGER NOT NULL, - EXTERNAL_CLAIM_ID INTEGER NOT NULL, - PRIMARY KEY (ID), - FOREIGN KEY (SCOPE_ID) REFERENCES IDN_OAUTH2_SCOPE(SCOPE_ID) ON DELETE CASCADE, - FOREIGN KEY (EXTERNAL_CLAIM_ID) REFERENCES IDN_CLAIM(ID) ON DELETE CASCADE, - UNIQUE (SCOPE_ID, EXTERNAL_CLAIM_ID) -); - -CREATE TABLE IF NOT EXISTS IDN_FUNCTION_LIBRARY ( - NAME VARCHAR(255) NOT NULL, - DESCRIPTION VARCHAR(1023), - TYPE VARCHAR(255) NOT NULL, - TENANT_ID INTEGER NOT NULL, - DATA BLOB NOT NULL, - PRIMARY KEY (TENANT_ID,NAME) -); - -CREATE TABLE IF NOT EXISTS IDN_OAUTH2_CIBA_AUTH_CODE ( - AUTH_CODE_KEY CHAR (36), - AUTH_REQ_ID CHAR (36), - ISSUED_TIME TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - CONSUMER_KEY VARCHAR(255), - LAST_POLLED_TIME TIMESTAMP NOT NULL, - POLLING_INTERVAL INTEGER, - EXPIRES_IN INTEGER, - AUTHENTICATED_USER_NAME VARCHAR(255), - USER_STORE_DOMAIN VARCHAR(100), - TENANT_ID INTEGER, - AUTH_REQ_STATUS VARCHAR (100) DEFAULT 'REQUESTED', - IDP_ID INTEGER, - UNIQUE(AUTH_REQ_ID), - PRIMARY KEY (AUTH_CODE_KEY), - FOREIGN KEY (TENANT_ID, CONSUMER_KEY) REFERENCES IDN_OAUTH_CONSUMER_APPS(TENANT_ID, CONSUMER_KEY) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS IDN_OAUTH2_CIBA_REQUEST_SCOPES ( - ID INTEGER NOT NULL AUTO_INCREMENT, - AUTH_CODE_KEY CHAR (36), - SCOPE VARCHAR (255), - FOREIGN KEY (AUTH_CODE_KEY) REFERENCES IDN_OAUTH2_CIBA_AUTH_CODE(AUTH_CODE_KEY) ON DELETE CASCADE, - PRIMARY KEY (ID) -); - -CREATE TABLE IF NOT EXISTS IDN_FED_AUTH_SESSION_MAPPING ( - ID INTEGER NOT NULL AUTO_INCREMENT, - IDP_SESSION_ID VARCHAR(255) NOT NULL, - SESSION_ID VARCHAR(255) NOT NULL, - IDP_NAME VARCHAR(255) NOT NULL, - AUTHENTICATOR_ID VARCHAR(255), - PROTOCOL_TYPE VARCHAR(255), - TIME_CREATED TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - TENANT_ID INTEGER NOT NULL DEFAULT 0, - IDP_ID INTEGER NOT NULL DEFAULT 0, - FOREIGN KEY (IDP_ID) REFERENCES IDP(ID) ON DELETE CASCADE, - PRIMARY KEY (ID), - UNIQUE (IDP_SESSION_ID, TENANT_ID, IDP_ID) -); - -CREATE TABLE IF NOT EXISTS IDN_CONFIG_TYPE ( - ID VARCHAR(255) NOT NULL, - NAME VARCHAR(255) NOT NULL, - DESCRIPTION VARCHAR(1023) NULL, - PRIMARY KEY (ID), - CONSTRAINT TYPE_NAME_CONSTRAINT UNIQUE (NAME) -); - -INSERT INTO IDN_CONFIG_TYPE (ID, NAME, DESCRIPTION) VALUES -('9ab0ef95-13e9-4ed5-afaf-d29bed62f7bd', 'IDP_TEMPLATE', 'Template type to uniquely identify IDP templates'), -('3c4ac3d0-5903-4e3d-aaca-38df65b33bfd', 'APPLICATION_TEMPLATE', 'Template type to uniquely identify Application templates'), -('8ec6dbf1-218a-49bf-bc34-0d2db52d151c', 'CORS_CONFIGURATION', 'A resource type to keep the tenant CORS configurations'), -('669b99ca-cdb0-44a6-8cae-babed3b585df', 'Publisher', 'A resource type to keep the event publisher configurations'), -('73f6d9ca-62f4-4566-bab9-2a930ae51ba8', 'BRANDING_PREFERENCES', 'A resource type to keep the tenant branding preferences'), -('8469a176-3e6c-438a-ba01-71e9077072fa', 'APPLICATION_BRANDING_PREFERENCES', 'A resource type to keep the application branding preferences'), -('899c69b2-8bf7-46b5-9666-f7f99f90d6cc', 'fido-config', 'A resource type to store FIDO authenticator related preferences'), -('7f24050f-3e3d-4a00-b10f-fd5450d6523e', 'input-validation-configurations', 'A resource type to store input validation related configurations'), -('f4e83b8a-d1c4-a0d6-03a7-d48e268c60c5', 'PK_JWT_CONFIGURATION', 'A resource type to keep the tenant private key jwt configuration.'), -('9ec61e9d-f0e6-4952-9a09-ab842aeb2db2', 'ATTRIBUTE_CONFIGURATION', 'A resource type to store attribute related configurations.'), -('132b0ee6-43e0-462d-8b4b-15b68109d71d', 'ORGANIZATION_CONFIGURATION', 'A resource type to keep the organization configurations.'), -('1fc809a0-dc0d-4cb2-82f3-58934d389236', 'CUSTOM_TEXT', 'A resource type to keep the tenant custom text preferences.'), -('c385a42a-5697-4604-b49a-62456621e926', 'DCR_CONFIGURATION', 'A resource type to keep the DCR configurations.'); - -CREATE TABLE IF NOT EXISTS IDN_CONFIG_RESOURCE ( - ID VARCHAR(255) NOT NULL, - TENANT_ID INT NOT NULL, - NAME VARCHAR(255) NOT NULL, - CREATED_TIME TIMESTAMP NOT NULL, - LAST_MODIFIED TIMESTAMP NOT NULL, - HAS_FILE BOOLEAN NOT NULL, - HAS_ATTRIBUTE BOOLEAN NOT NULL, - TYPE_ID VARCHAR(255) NOT NULL, - UNIQUE (NAME, TENANT_ID, TYPE_ID), - PRIMARY KEY (ID) -); -ALTER TABLE IDN_CONFIG_RESOURCE -ADD CONSTRAINT TYPE_ID_FOREIGN_CONSTRAINT FOREIGN KEY (TYPE_ID) REFERENCES IDN_CONFIG_TYPE (ID) -ON DELETE CASCADE ON UPDATE CASCADE; - -CREATE TABLE IF NOT EXISTS IDN_CONFIG_ATTRIBUTE ( - ID VARCHAR(255) NOT NULL, - RESOURCE_ID VARCHAR(255) NOT NULL, - ATTR_KEY VARCHAR(255) NOT NULL, - ATTR_VALUE VARCHAR(1023) NULL, - PRIMARY KEY (ID), - UNIQUE (RESOURCE_ID, ATTR_KEY) -); -ALTER TABLE IDN_CONFIG_ATTRIBUTE -ADD CONSTRAINT RESOURCE_ID_ATTRIBUTE_FOREIGN_CONSTRAINT FOREIGN KEY (RESOURCE_ID) REFERENCES -IDN_CONFIG_RESOURCE (ID) ON DELETE CASCADE ON UPDATE CASCADE; - -CREATE TABLE IF NOT EXISTS IDN_CONFIG_FILE ( - ID VARCHAR(255) NOT NULL, - `VALUE` BLOB NULL, - RESOURCE_ID VARCHAR(255) NOT NULL, - NAME VARCHAR(255) NULL, - PRIMARY KEY (ID) -); -ALTER TABLE IDN_CONFIG_FILE -ADD CONSTRAINT RESOURCE_ID_FILE_FOREIGN_CONSTRAINT FOREIGN KEY (RESOURCE_ID) REFERENCES -IDN_CONFIG_RESOURCE (ID) ON DELETE CASCADE ON UPDATE CASCADE; - -CREATE TABLE IF NOT EXISTS IDN_REMOTE_FETCH_CONFIG ( - ID VARCHAR(255) NOT NULL, - TENANT_ID INTEGER NOT NULL, - IS_ENABLED CHAR(1) NOT NULL, - REPO_MANAGER_TYPE VARCHAR(255) NOT NULL, - ACTION_LISTENER_TYPE VARCHAR(255) NOT NULL, - CONFIG_DEPLOYER_TYPE VARCHAR(255) NOT NULL, - REMOTE_FETCH_NAME VARCHAR(255), - REMOTE_RESOURCE_URI VARCHAR(255) NOT NULL, - ATTRIBUTES_JSON MEDIUMTEXT NOT NULL, - PRIMARY KEY (ID), - CONSTRAINT UC_REMOTE_RESOURCE_TYPE UNIQUE (TENANT_ID, CONFIG_DEPLOYER_TYPE) -); - -CREATE TABLE IF NOT EXISTS IDN_REMOTE_FETCH_REVISIONS ( - ID VARCHAR(255) NOT NULL, - CONFIG_ID VARCHAR(255) NOT NULL, - FILE_PATH VARCHAR(255) NOT NULL, - FILE_HASH VARCHAR(255), - DEPLOYED_DATE TIMESTAMP, - LAST_SYNC_TIME TIMESTAMP, - DEPLOYMENT_STATUS VARCHAR(255), - ITEM_NAME VARCHAR(255), - DEPLOY_ERR_LOG MEDIUMTEXT, - PRIMARY KEY (ID), - FOREIGN KEY (CONFIG_ID) REFERENCES IDN_REMOTE_FETCH_CONFIG(ID) ON DELETE CASCADE, - CONSTRAINT UC_REVISIONS UNIQUE (CONFIG_ID, ITEM_NAME) -); - - -CREATE TABLE IF NOT EXISTS IDN_USER_FUNCTIONALITY_MAPPING ( - ID VARCHAR(255) NOT NULL, - USER_ID VARCHAR(255) NOT NULL, - TENANT_ID INTEGER NOT NULL, - FUNCTIONALITY_ID VARCHAR(255) NOT NULL, - IS_FUNCTIONALITY_LOCKED BOOLEAN NOT NULL, - FUNCTIONALITY_UNLOCK_TIME BIGINT NOT NULL, - FUNCTIONALITY_LOCK_REASON VARCHAR(1023), - FUNCTIONALITY_LOCK_REASON_CODE VARCHAR(255), - PRIMARY KEY (ID), - CONSTRAINT IDN_USER_FUNCTIONALITY_MAPPING_CONSTRAINT UNIQUE (USER_ID, TENANT_ID, FUNCTIONALITY_ID) -); - -CREATE TABLE IF NOT EXISTS IDN_USER_FUNCTIONALITY_PROPERTY ( - ID VARCHAR(255) NOT NULL, - USER_ID VARCHAR(255) NOT NULL, - TENANT_ID INTEGER NOT NULL, - FUNCTIONALITY_ID VARCHAR(255) NOT NULL, - PROPERTY_NAME VARCHAR(255), - PROPERTY_VALUE VARCHAR(255), - PRIMARY KEY (ID), - CONSTRAINT IDN_USER_FUNCTIONALITY_PROPERTY_CONSTRAINT UNIQUE (USER_ID, TENANT_ID, FUNCTIONALITY_ID, PROPERTY_NAME) -); - -CREATE TABLE IF NOT EXISTS IDN_CORS_ORIGIN ( - ID INT NOT NULL AUTO_INCREMENT, - TENANT_ID INT NOT NULL, - ORIGIN VARCHAR(2048) NOT NULL, - UUID CHAR(36) NOT NULL, - - PRIMARY KEY (ID), - UNIQUE (TENANT_ID, ORIGIN), - UNIQUE (UUID) -); - -CREATE TABLE IF NOT EXISTS IDN_CORS_ASSOCIATION ( - IDN_CORS_ORIGIN_ID INT NOT NULL, - SP_APP_ID INT NOT NULL, - - PRIMARY KEY (IDN_CORS_ORIGIN_ID, SP_APP_ID), - FOREIGN KEY (IDN_CORS_ORIGIN_ID) REFERENCES IDN_CORS_ORIGIN (ID) ON DELETE CASCADE, - FOREIGN KEY (SP_APP_ID) REFERENCES SP_APP (ID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS IDN_OAUTH2_USER_CONSENT ( - ID INTEGER NOT NULL AUTO_INCREMENT, - USER_ID VARCHAR(255) NOT NULL, - APP_ID CHAR(36) NOT NULL, - TENANT_ID INTEGER NOT NULL DEFAULT -1, - CONSENT_ID VARCHAR(255) NOT NULL, - PRIMARY KEY (ID), - FOREIGN KEY (APP_ID) REFERENCES SP_APP(UUID) ON DELETE CASCADE, - UNIQUE (USER_ID, APP_ID, TENANT_ID), - UNIQUE (CONSENT_ID) -); - -CREATE TABLE IF NOT EXISTS IDN_OAUTH2_USER_CONSENTED_SCOPES ( - ID INTEGER NOT NULL AUTO_INCREMENT, - CONSENT_ID VARCHAR(255) NOT NULL, - TENANT_ID INTEGER NOT NULL DEFAULT -1, - SCOPE VARCHAR(255) NOT NULL, - CONSENT BOOLEAN NOT NULL, - PRIMARY KEY (ID), - FOREIGN KEY (CONSENT_ID) REFERENCES IDN_OAUTH2_USER_CONSENT(CONSENT_ID) ON DELETE CASCADE, - UNIQUE (CONSENT_ID, SCOPE) -); - -CREATE TABLE IF NOT EXISTS IDN_SECRET_TYPE ( - ID VARCHAR(255) NOT NULL, - NAME VARCHAR(255) NOT NULL, - DESCRIPTION VARCHAR(1023) NULL, - PRIMARY KEY (ID), - CONSTRAINT SECRET_TYPE_NAME_CONSTRAINT UNIQUE (NAME) -); - -INSERT INTO IDN_SECRET_TYPE (ID, NAME, DESCRIPTION) VALUES -('1358bdbf-e0cc-4268-a42c-c3e0960e13f0', 'ADAPTIVE_AUTH_CALL_CHOREO', 'Secret type to uniquely identify secrets relevant to callChoreo adaptive auth function'), -('c508ca28-60c0-4493-a758-77e4173ffdb9', 'IDP_SECRET_PROPERTIES', 'Secret type to uniquely identify secrets relevant to identity providers'), -('433df096-62b7-4a36-b3eb-1bed9150ed35', 'IDVP_SECRET_PROPERTIES', 'Secret type to uniquely identify secrets relevant to identity verification providers'), -('29d0c37d-139a-4b1e-a343-7b8d26f0a2a9', 'ANDROID_ATTESTATION_CREDENTIALS', 'Secret type to uniquely identify secrets relevant to android client attestation credentials'); - -CREATE TABLE IF NOT EXISTS IDN_SECRET ( - ID VARCHAR(255) NOT NULL, - TENANT_ID INT NOT NULL, - SECRET_NAME VARCHAR(1023) NOT NULL, - SECRET_VALUE VARCHAR(8000) NOT NULL, - CREATED_TIME TIMESTAMP NOT NULL, - LAST_MODIFIED TIMESTAMP NOT NULL, - TYPE_ID VARCHAR(255) NOT NULL, - DESCRIPTION VARCHAR(1023) NULL, - KEY_ID VARCHAR(255) NULL, - PRIMARY KEY (ID), - FOREIGN KEY (TYPE_ID) REFERENCES IDN_SECRET_TYPE(ID) ON DELETE CASCADE, - UNIQUE (SECRET_NAME, TENANT_ID, TYPE_ID) -); - -CREATE TABLE IF NOT EXISTS SP_SHARED_APP ( - ID INTEGER NOT NULL AUTO_INCREMENT, - MAIN_APP_ID CHAR(36) NOT NULL, - OWNER_ORG_ID CHAR(36) NOT NULL, - SHARED_APP_ID CHAR(36) NOT NULL, - SHARED_ORG_ID CHAR(36) NOT NULL, - SHARE_WITH_ALL_CHILDREN BOOLEAN DEFAULT FALSE, - PRIMARY KEY (ID), - FOREIGN KEY (MAIN_APP_ID) REFERENCES SP_APP(UUID) ON DELETE CASCADE, - FOREIGN KEY (SHARED_APP_ID) REFERENCES SP_APP(UUID) ON DELETE CASCADE, - UNIQUE (MAIN_APP_ID, OWNER_ORG_ID, SHARED_ORG_ID), - UNIQUE (SHARED_APP_ID) -); - -CREATE TABLE IF NOT EXISTS IDVP ( - ID INTEGER NOT NULL AUTO_INCREMENT, - UUID CHAR(36) NOT NULL, - TENANT_ID INTEGER NOT NULL, - IDVP_TYPE VARCHAR(254), - NAME VARCHAR(254), - DESCRIPTION VARCHAR(1024), - IS_ENABLED CHAR(1) NOT NULL DEFAULT '0', - PRIMARY KEY (ID), - UNIQUE (TENANT_ID, NAME), - UNIQUE (UUID) -); - -CREATE TABLE IF NOT EXISTS IDVP_CLAIM_MAPPING ( - ID INTEGER NOT NULL AUTO_INCREMENT, - IDVP_ID INTEGER NOT NULL, - TENANT_ID INTEGER NOT NULL, - CLAIM VARCHAR(254), - LOCAL_CLAIM VARCHAR(254), - PRIMARY KEY (ID), - UNIQUE (IDVP_ID, CLAIM, TENANT_ID), - FOREIGN KEY (IDVP_ID) REFERENCES IDVP(ID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS IDVP_CONFIG ( - ID INTEGER NOT NULL AUTO_INCREMENT, - IDVP_ID INTEGER NOT NULL, - TENANT_ID INTEGER NOT NULL, - PROPERTY_KEY VARCHAR(254) NOT NULL, - PROPERTY_VALUE VARCHAR(1024), - IS_SECRET CHAR (1) DEFAULT '0', - PRIMARY KEY (ID), - UNIQUE (IDVP_ID, PROPERTY_KEY, TENANT_ID), - FOREIGN KEY (IDVP_ID) REFERENCES IDVP(ID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS IDV_CLAIM ( - ID INTEGER NOT NULL AUTO_INCREMENT, - UUID CHAR(36) NOT NULL, - USER_ID VARCHAR(254) NOT NULL, - CLAIM_URI VARCHAR(254), - IDVP_ID CHAR(36) NOT NULL, - TENANT_ID INTEGER NOT NULL, - IS_VERIFIED CHAR(1) NOT NULL DEFAULT '0', - METADATA BLOB, - PRIMARY KEY (ID), - UNIQUE (CLAIM_URI, TENANT_ID, USER_ID, IDVP_ID), - UNIQUE (UUID), - FOREIGN KEY (IDVP_ID) REFERENCES IDVP(UUID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS IDN_OAUTH_PAR ( - REQ_URI_REF VARCHAR(255) PRIMARY KEY, - CLIENT_ID VARCHAR(255) NOT NULL, - SCHEDULED_EXPIRY BIGINT NOT NULL, - PARAMETERS MEDIUMTEXT -); - -CREATE TABLE IF NOT EXISTS IDN_ORG_USER_INVITATION ( - ID INTEGER NOT NULL AUTO_INCREMENT, - INVITATION_ID VARCHAR(40) NOT NULL, - CONFIRMATION_CODE VARCHAR(40) NOT NULL, - USER_NAME VARCHAR(254) NOT NULL, - DOMAIN_NAME VARCHAR(254) NOT NULL, - EMAIL VARCHAR(254) NOT NULL, - USER_ORG_ID VARCHAR(254) NOT NULL, - INVITED_ORG_ID VARCHAR(254) NOT NULL, - USER_REDIRECT_URL VARCHAR(1024) NOT NULL, - STATUS VARCHAR(10) NOT NULL, - CREATED_AT TIMESTAMP NOT NULL, - EXPIRED_AT TIMESTAMP NOT NULL, - PRIMARY KEY (INVITATION_ID) -); - -CREATE TABLE IF NOT EXISTS IDN_ORG_USER_INVITE_ASSIGNMENT( - ID INTEGER NOT NULL AUTO_INCREMENT, - INVITATION_ID VARCHAR(40) NOT NULL, - ASSIGNMENT_ID VARCHAR(255) NOT NULL, - ASSIGNMENT_TYPE VARCHAR(255) NOT NULL, - PRIMARY KEY (INVITATION_ID, ASSIGNMENT_ID, ASSIGNMENT_TYPE), - FOREIGN KEY (INVITATION_ID) REFERENCES IDN_ORG_USER_INVITATION(INVITATION_ID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS API_RESOURCE ( - ID CHAR(36) NOT NULL PRIMARY KEY, - CURSOR_KEY INTEGER NOT NULL AUTO_INCREMENT, - NAME VARCHAR(255) NOT NULL, - IDENTIFIER VARCHAR(255) NOT NULL, - TENANT_ID INT, - DESCRIPTION VARCHAR(255), - TYPE VARCHAR(255) NOT NULL, - REQUIRES_AUTHORIZATION BOOLEAN NOT NULL -); - -CREATE TABLE IF NOT EXISTS API_RESOURCE_PROPERTY ( - ID INTEGER AUTO_INCREMENT, - API_ID CHAR(36) NOT NULL, - NAME VARCHAR(255) NOT NULL, - `VALUE` VARCHAR(255) NOT NULL, - PRIMARY KEY (ID), - CONSTRAINT API_RESOURCE_PROPERTY_CONSTRAINT UNIQUE (API_ID, NAME), - FOREIGN KEY (API_ID) REFERENCES API_RESOURCE(ID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS SCOPE ( - ID CHAR(36) NOT NULL PRIMARY KEY, - CURSOR_KEY INTEGER NOT NULL AUTO_INCREMENT, - API_ID CHAR(36) NOT NULL, - NAME VARCHAR(255) NOT NULL, - DISPLAY_NAME VARCHAR(255) NOT NULL, - TENANT_ID INT, - DESCRIPTION VARCHAR(300), - FOREIGN KEY (API_ID) REFERENCES API_RESOURCE(ID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS APP_ROLE_ASSOCIATION ( - APP_ID CHAR(36) NOT NULL, - ROLE_ID VARCHAR(255) NOT NULL, - PRIMARY KEY (APP_ID, ROLE_ID), - FOREIGN KEY (APP_ID) REFERENCES SP_APP(UUID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS ROLE_SCOPE ( - ROLE_ID VARCHAR(255) NOT NULL, - SCOPE_ID CHAR(36) NOT NULL, - PRIMARY KEY (ROLE_ID, SCOPE_ID), - FOREIGN KEY (SCOPE_ID) REFERENCES SCOPE(ID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS AUTHORIZED_API( - APP_ID CHAR(36) NOT NULL, - API_ID CHAR(36) NOT NULL, - POLICY_ID VARCHAR(255) NOT NULL, - CONSTRAINT PK_APP_API PRIMARY KEY (APP_ID, API_ID), - FOREIGN KEY (API_ID) REFERENCES API_RESOURCE(ID) ON DELETE CASCADE, - FOREIGN KEY (APP_ID) REFERENCES SP_APP(UUID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS AUTHORIZED_SCOPE( - APP_ID CHAR(36) NOT NULL, - API_ID CHAR(36) NOT NULL, - SCOPE_ID CHAR(36) NOT NULL, - CONSTRAINT PK_APP_API_SCOPE PRIMARY KEY (APP_ID, API_ID, SCOPE_ID), - FOREIGN KEY (API_ID) REFERENCES API_RESOURCE(ID), - FOREIGN KEY (SCOPE_ID) REFERENCES SCOPE(ID) ON DELETE CASCADE, - FOREIGN KEY (APP_ID) REFERENCES SP_APP(UUID), - FOREIGN KEY (APP_ID, API_ID) REFERENCES AUTHORIZED_API(APP_ID, API_ID) ON DELETE CASCADE, - CONSTRAINT AUTHORIZED_SCOPE_UNIQUE UNIQUE (APP_ID, SCOPE_ID) -); - -CREATE TABLE IF NOT EXISTS IDN_NOTIFICATION_TYPE ( - ID INTEGER NOT NULL AUTO_INCREMENT, - TYPE_KEY VARCHAR(255) NOT NULL, - NAME VARCHAR(255) NOT NULL, - CHANNEL VARCHAR(255) NOT NULL, - TENANT_ID INTEGER NOT NULL, - PRIMARY KEY (ID), - CONSTRAINT NOTIFICATION_TYPE_KEY_CONSTRAINT UNIQUE (TYPE_KEY, CHANNEL, TENANT_ID), - CONSTRAINT NOTIFICATION_TYPE_NAME_CONSTRAINT UNIQUE (NAME, CHANNEL, TENANT_ID) -); - -CREATE TABLE IF NOT EXISTS IDN_NOTIFICATION_ORG_TEMPLATE ( - ID INTEGER NOT NULL AUTO_INCREMENT, - TEMPLATE_KEY VARCHAR(50) NOT NULL, - LOCALE VARCHAR(50) NOT NULL, - SUBJECT VARCHAR(4000), - BODY MEDIUMTEXT, - FOOTER MEDIUMTEXT, - CONTENT_TYPE VARCHAR(50), - TYPE_ID INTEGER NOT NULL, - TENANT_ID INTEGER NOT NULL, - PRIMARY KEY (ID), - FOREIGN KEY (TYPE_ID) REFERENCES IDN_NOTIFICATION_TYPE(ID) ON DELETE CASCADE, - CONSTRAINT ORG_NOTIFICATION_TEMPLATE_KEY_CONSTRAINT UNIQUE (TEMPLATE_KEY, TYPE_ID, TENANT_ID), - CONSTRAINT ORG_NOTIFICATION_TEMPLATE_LOCALE_CONSTRAINT UNIQUE (LOCALE, TYPE_ID, TENANT_ID) -); - -CREATE TABLE IF NOT EXISTS IDN_NOTIFICATION_APP_TEMPLATE ( - ID INTEGER NOT NULL AUTO_INCREMENT, - TEMPLATE_KEY VARCHAR(50) NOT NULL, - LOCALE VARCHAR(50) NOT NULL, - SUBJECT VARCHAR(4000), - BODY MEDIUMTEXT, - FOOTER MEDIUMTEXT, - CONTENT_TYPE VARCHAR(50), - TYPE_ID INTEGER NOT NULL, - APP_ID VARCHAR(255) NOT NULL, - TENANT_ID INTEGER NOT NULL, - PRIMARY KEY (ID), - FOREIGN KEY (TYPE_ID) REFERENCES IDN_NOTIFICATION_TYPE(ID) ON DELETE CASCADE, - CONSTRAINT APP_NOTIFICATION_TEMPLATE_KEY_CONSTRAINT UNIQUE (TEMPLATE_KEY, TYPE_ID, APP_ID, TENANT_ID), - CONSTRAINT APP_NOTIFICATION_TEMPLATE_LOCALE_CONSTRAINT UNIQUE (LOCALE, TYPE_ID, APP_ID, TENANT_ID) -); - -CREATE TABLE IF NOT EXISTS IDN_XACML_CONFIG ( - CONFIG_KEY VARCHAR(255) NOT NULL, - CONFIG_VALUE VARCHAR(255) NOT NULL, - TENANT_ID INTEGER NOT NULL, - PRIMARY KEY (TENANT_ID, CONFIG_KEY) -); - -CREATE TABLE IF NOT EXISTS IDN_XACML_POLICY ( - POLICY_ID VARCHAR(255) NOT NULL, - VERSION INTEGER NOT NULL, - IS_IN_PAP BOOLEAN NOT NULL DEFAULT TRUE, - IS_IN_PDP BOOLEAN NOT NULL DEFAULT FALSE, - POLICY CLOB NOT NULL, - IS_ACTIVE BOOLEAN NOT NULL DEFAULT FALSE, - POLICY_TYPE VARCHAR(255) NOT NULL, - POLICY_EDITOR VARCHAR(255), - POLICY_ORDER INTEGER NOT NULL, - LAST_MODIFIED_TIME TIMESTAMP NOT NULL, - LAST_MODIFIED_USER VARCHAR(255), - TENANT_ID INTEGER NOT NULL, - PRIMARY KEY (POLICY_ID, VERSION, TENANT_ID), - CONSTRAINT IDN_XACML_POLICY_KEY_CONSTRAINT UNIQUE (POLICY_ID, VERSION, TENANT_ID) -); - -CREATE TABLE IF NOT EXISTS IDN_XACML_POLICY_ATTRIBUTE ( - ID INTEGER AUTO_INCREMENT NOT NULL, - ATTRIBUTE_ID VARCHAR(255) NOT NULL, - ATTRIBUTE_VALUE VARCHAR(255) NOT NULL, - DATA_TYPE VARCHAR(255) NOT NULL, - CATEGORY VARCHAR(255) NOT NULL, - POLICY_ID VARCHAR(255) NOT NULL, - VERSION INTEGER NOT NULL, - TENANT_ID INTEGER NOT NULL, - PRIMARY KEY (ID), - FOREIGN KEY (POLICY_ID, VERSION, TENANT_ID) REFERENCES IDN_XACML_POLICY (POLICY_ID, VERSION, TENANT_ID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS IDN_XACML_POLICY_EDITOR_DATA ( - ID INTEGER AUTO_INCREMENT NOT NULL, - DATA VARCHAR(500), - DATA_ORDER INTEGER NOT NULL, - POLICY_ID VARCHAR(255) NOT NULL, - VERSION INTEGER NOT NULL, - TENANT_ID INTEGER NOT NULL, - PRIMARY KEY (ID), - FOREIGN KEY (POLICY_ID, VERSION, TENANT_ID) REFERENCES IDN_XACML_POLICY (POLICY_ID, VERSION, TENANT_ID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS IDN_XACML_POLICY_REFERENCE ( - REFERENCE VARCHAR(255) NOT NULL, - POLICY_ID VARCHAR(255) NOT NULL, - VERSION INTEGER NOT NULL, - TENANT_ID INTEGER NOT NULL, - PRIMARY KEY (REFERENCE, POLICY_ID, VERSION, TENANT_ID), - FOREIGN KEY (POLICY_ID, VERSION, TENANT_ID) REFERENCES IDN_XACML_POLICY (POLICY_ID, VERSION, TENANT_ID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS IDN_XACML_POLICY_SET_REFERENCE ( - SET_REFERENCE VARCHAR(255) NOT NULL, - POLICY_ID VARCHAR(255) NOT NULL, - VERSION INTEGER NOT NULL, - TENANT_ID INTEGER NOT NULL, - PRIMARY KEY (SET_REFERENCE, POLICY_ID, VERSION, TENANT_ID), - FOREIGN KEY (POLICY_ID, VERSION, TENANT_ID) REFERENCES IDN_XACML_POLICY (POLICY_ID, VERSION, TENANT_ID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS IDN_XACML_SUBSCRIBER ( - SUBSCRIBER_ID VARCHAR(255) NOT NULL, - ENTITLEMENT_MODULE_NAME VARCHAR(255) NOT NULL, - TENANT_ID INTEGER NOT NULL, - PRIMARY KEY (SUBSCRIBER_ID, TENANT_ID), - CONSTRAINT IDN_XACML_SUBSCRIBER_KEY_CONSTRAINT UNIQUE (SUBSCRIBER_ID, TENANT_ID) -); - -CREATE TABLE IF NOT EXISTS IDN_XACML_SUBSCRIBER_PROPERTY ( - PROPERTY_ID VARCHAR(255) NOT NULL, - DISPLAY_NAME VARCHAR(255) NOT NULL, - PROPERTY_VALUE VARCHAR(2000) NOT NULL, - IS_REQUIRED BOOLEAN NOT NULL DEFAULT FALSE, - DISPLAY_ORDER INTEGER NOT NULL, - IS_SECRET BOOLEAN NOT NULL DEFAULT FALSE, - PROPERTY_MODULE VARCHAR(255), - SUBSCRIBER_ID VARCHAR(255) NOT NULL, - TENANT_ID INTEGER NOT NULL, - PRIMARY KEY (PROPERTY_ID, SUBSCRIBER_ID, TENANT_ID), - FOREIGN KEY (SUBSCRIBER_ID, TENANT_ID) REFERENCES IDN_XACML_SUBSCRIBER (SUBSCRIBER_ID, TENANT_ID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS IDN_XACML_SUBSCRIBER_STATUS ( - ID INTEGER AUTO_INCREMENT NOT NULL, - TYPE VARCHAR(255) NOT NULL, - IS_SUCCESS BOOLEAN NOT NULL DEFAULT FALSE, - USERNAME VARCHAR(255) NOT NULL, - TARGET VARCHAR(255) NOT NULL, - TARGET_ACTION VARCHAR(255) NOT NULL, - LOGGED_AT TIMESTAMP NOT NULL, - MESSAGE VARCHAR(255) NULL, - SUBSCRIBER_ID VARCHAR(255) NOT NULL, - TENANT_ID INTEGER NOT NULL, - PRIMARY KEY (ID), - FOREIGN KEY (SUBSCRIBER_ID, TENANT_ID) REFERENCES IDN_XACML_SUBSCRIBER (SUBSCRIBER_ID, TENANT_ID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS IDN_XACML_POLICY_STATUS ( - ID INTEGER AUTO_INCREMENT NOT NULL, - TYPE VARCHAR(255) NOT NULL, - IS_SUCCESS BOOLEAN NOT NULL DEFAULT FALSE, - USERNAME VARCHAR(255) NOT NULL, - TARGET VARCHAR(255) NOT NULL, - TARGET_ACTION VARCHAR(255) NOT NULL, - LOGGED_AT TIMESTAMP NOT NULL, - MESSAGE VARCHAR(255) NULL, - POLICY_ID VARCHAR(255) NOT NULL, - POLICY_VERSION INTEGER DEFAULT -1, - TENANT_ID INTEGER NOT NULL, - PRIMARY KEY (ID) -); - --- --------------------------- INDEX CREATION ----------------------------- --- IDN_OAUTH2_ACCESS_TOKEN -- -CREATE INDEX IDX_TC ON IDN_OAUTH2_ACCESS_TOKEN(TIME_CREATED); -CREATE INDEX IDX_ATH ON IDN_OAUTH2_ACCESS_TOKEN(ACCESS_TOKEN_HASH); -CREATE INDEX IDX_AT_TI_UD ON IDN_OAUTH2_ACCESS_TOKEN(AUTHZ_USER, TENANT_ID, TOKEN_STATE, USER_DOMAIN); -CREATE INDEX IDX_AT_AT ON IDN_OAUTH2_ACCESS_TOKEN(ACCESS_TOKEN); -CREATE INDEX IDX_AT_RTH ON IDN_OAUTH2_ACCESS_TOKEN(REFRESH_TOKEN_HASH); -CREATE INDEX IDX_AT_RT ON IDN_OAUTH2_ACCESS_TOKEN(REFRESH_TOKEN); -CREATE INDEX IDX_TBR_TS ON IDN_OAUTH2_ACCESS_TOKEN(TOKEN_BINDING_REF, TOKEN_STATE); - --- IDN_OAUTH2_AUTHORIZATION_CODE -- -CREATE INDEX IDX_AUTHORIZATION_CODE_HASH ON IDN_OAUTH2_AUTHORIZATION_CODE (AUTHORIZATION_CODE_HASH, CONSUMER_KEY_ID); -CREATE INDEX IDX_AUTHORIZATION_CODE_AU_TI ON IDN_OAUTH2_AUTHORIZATION_CODE (AUTHZ_USER, TENANT_ID, USER_DOMAIN, STATE); -CREATE INDEX IDX_AC_CKID ON IDN_OAUTH2_AUTHORIZATION_CODE(CONSUMER_KEY_ID); -CREATE INDEX IDX_AC_TID ON IDN_OAUTH2_AUTHORIZATION_CODE(TOKEN_ID); -CREATE INDEX IDX_AC_AC_CKID ON IDN_OAUTH2_AUTHORIZATION_CODE(AUTHORIZATION_CODE, CONSUMER_KEY_ID); -CREATE INDEX IDX_AT_CKID_AU_TID_UD_TSH_TS ON IDN_OAUTH2_ACCESS_TOKEN(CONSUMER_KEY_ID, AUTHZ_USER, TENANT_ID, USER_DOMAIN, TOKEN_SCOPE_HASH, TOKEN_STATE); - --- IDN_SCIM_GROUP -- -CREATE INDEX IDX_IDN_SCIM_GROUP_TI_RN ON IDN_SCIM_GROUP (TENANT_ID, ROLE_NAME); -CREATE INDEX IDX_IDN_SCIM_GROUP_TI_RN_AN ON IDN_SCIM_GROUP (TENANT_ID, ROLE_NAME, ATTR_NAME); - --- IDN_AUTH_SESSION_STORE -- -CREATE INDEX IDX_IDN_AUTH_SESSION_TIME ON IDN_AUTH_SESSION_STORE (TIME_CREATED); -CREATE INDEX IDX_IDN_AUTH_SSTR_ST_OP_ID_TM ON IDN_AUTH_SESSION_STORE (OPERATION, SESSION_TYPE, SESSION_ID, TIME_CREATED); -CREATE INDEX IDX_IDN_AUTH_SSTR_ET_ID ON IDN_AUTH_SESSION_STORE (EXPIRY_TIME, SESSION_ID); - --- IDN_AUTH_TEMP_SESSION_STORE -- -CREATE INDEX IDX_IDN_AUTH_TMP_SESSION_TIME ON IDN_AUTH_TEMP_SESSION_STORE (TIME_CREATED); - --- IDN_OIDC_SCOPE_CLAIM_MAPPING -- -CREATE INDEX IDX_AT_SI_ECI ON IDN_OIDC_SCOPE_CLAIM_MAPPING(SCOPE_ID, EXTERNAL_CLAIM_ID); - --- IDN_OAUTH2_SCOPE -- -CREATE INDEX IDX_SC_TID ON IDN_OAUTH2_SCOPE(TENANT_ID); - --- IDN_OAUTH2_SCOPE_BINDING -- -CREATE INDEX IDX_SB_SCPID ON IDN_OAUTH2_SCOPE_BINDING(SCOPE_ID); - --- IDN_OIDC_REQ_OBJECT_REFERENCE -- -CREATE INDEX IDX_OROR_TID ON IDN_OIDC_REQ_OBJECT_REFERENCE(TOKEN_ID); - --- IDN_OAUTH2_ACCESS_TOKEN_SCOPE -- -CREATE INDEX IDX_ATS_TID ON IDN_OAUTH2_ACCESS_TOKEN_SCOPE(TOKEN_ID); - --- SP_TEMPLATE -- -CREATE INDEX IDX_SP_TEMPLATE ON SP_TEMPLATE (TENANT_ID, NAME); - --- IDN_AUTH_USER -- -CREATE INDEX IDX_AUTH_USER_UN_TID_DN ON IDN_AUTH_USER (USER_NAME, TENANT_ID, DOMAIN_NAME); -CREATE INDEX IDX_AUTH_USER_DN_TOD ON IDN_AUTH_USER (DOMAIN_NAME, TENANT_ID); - --- IDN_AUTH_USER_SESSION_MAPPING -- -CREATE INDEX IDX_USER_ID ON IDN_AUTH_USER_SESSION_MAPPING (USER_ID); -CREATE INDEX IDX_SESSION_ID ON IDN_AUTH_USER_SESSION_MAPPING (SESSION_ID); - --- IDN_AUTH_SESSION_APP_INFO -- -CREATE INDEX IDX_AUTH_SAI_UN_AID_SID ON IDN_AUTH_SESSION_APP_INFO (APP_ID, SUBJECT, SESSION_ID); - --- IDN_OAUTH_CONSUMER_APPS -- -CREATE INDEX IDX_OCA_UM_TID_UD_APN ON IDN_OAUTH_CONSUMER_APPS(USERNAME,TENANT_ID,USER_DOMAIN, APP_NAME); - --- IDX_SPI_APP -- -CREATE INDEX IDX_SPI_APP ON SP_INBOUND_AUTH(APP_ID); - --- IDN_OIDC_PROPERTY -- -CREATE INDEX IDX_IOP_CK ON IDN_OIDC_PROPERTY(TENANT_ID, CONSUMER_KEY); - --- IDN_FIDO2_PROPERTY -- -CREATE INDEX IDX_FIDO2_STR ON FIDO2_DEVICE_STORE(USER_NAME, TENANT_ID, DOMAIN_NAME, CREDENTIAL_ID, USER_HANDLE); - --- IDN_ASSOCIATED_ID -- -CREATE INDEX IDX_AI_DN_UN_AI ON IDN_ASSOCIATED_ID(DOMAIN_NAME, USER_NAME, ASSOCIATION_ID); - --- IDN_OAUTH2_TOKEN_BINDING -- -CREATE INDEX IDX_IDN_AUTH_BIND ON IDN_OAUTH2_TOKEN_BINDING (TOKEN_BINDING_REF); -CREATE INDEX IDX_TK_VALUE_TYPE ON IDN_OAUTH2_TOKEN_BINDING (TOKEN_BINDING_VALUE, TOKEN_BINDING_TYPE); - --- IDN_FED_AUTH_SESSION_MAPPING -- -CREATE INDEX IDX_FEDERATED_AUTH_SESSION_ID ON IDN_FED_AUTH_SESSION_MAPPING (SESSION_ID); - --- IDN_REMOTE_FETCH_REVISIONS -- -CREATE INDEX IDX_REMOTE_FETCH_REVISION_CONFIG_ID ON IDN_REMOTE_FETCH_REVISIONS (CONFIG_ID); - --- IDN_CORS_ASSOCIATION -- -CREATE INDEX IDX_CORS_SP_APP_ID ON IDN_CORS_ASSOCIATION (SP_APP_ID); - --- IDN_CORS_ASSOCIATION -- -CREATE INDEX IDX_CORS_ORIGIN_ID ON IDN_CORS_ASSOCIATION (IDN_CORS_ORIGIN_ID); - --- IDN_SECRET -- -CREATE INDEX IDN_SECRET_TYPE_ID ON IDN_SECRET (TYPE_ID); - --- IDN_CLAIM -- -CREATE INDEX IDX_CLAIM_TI_CU ON IDN_CLAIM (TENANT_ID, CLAIM_URI); - --- IDP_AUTHENTICATOR_PROPERTY -- -CREATE INDEX IDX_AUTH_PROP_AUTH_ID ON IDP_AUTHENTICATOR_PROPERTY (AUTHENTICATOR_ID); - --- IDN_CONFIG_FILE -- -CREATE INDEX IDX_CON_FILE_RES_ID ON IDN_CONFIG_FILE (RESOURCE_ID); - --- SCOPE -- -CREATE INDEX API_ID_NAME_INDEX ON SCOPE (API_ID, NAME); - --- XACML -- -CREATE INDEX IDX_POLICY_ATTRIBUTE ON IDN_XACML_POLICY_ATTRIBUTE (POLICY_ID, VERSION, TENANT_ID); -CREATE INDEX IDX_POLICY_EDITOR_DATA_FK ON IDN_XACML_POLICY_EDITOR_DATA (POLICY_ID, VERSION, TENANT_ID); -CREATE INDEX IDX_POLICY_REF ON IDN_XACML_POLICY_REFERENCE (POLICY_ID, VERSION, TENANT_ID); -CREATE INDEX IDX_POLICY_SET_REF ON IDN_XACML_POLICY_SET_REFERENCE (POLICY_ID, VERSION, TENANT_ID); -CREATE INDEX IDX_SUBSCRIBER_PROPERTY ON IDN_XACML_SUBSCRIBER_PROPERTY (SUBSCRIBER_ID, TENANT_ID); -CREATE INDEX IDX_XACML_SUBSCRIBER_STATUS ON IDN_XACML_SUBSCRIBER_STATUS (SUBSCRIBER_ID, TENANT_ID); -CREATE INDEX IDX_XACML_POLICY_STATUS ON IDN_XACML_POLICY_STATUS (POLICY_ID, POLICY_VERSION, TENANT_ID); diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/resources/repository/conf/carbon.xml b/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/resources/repository/conf/carbon.xml deleted file mode 100644 index a5a1a6470cbc..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/resources/repository/conf/carbon.xml +++ /dev/null @@ -1,686 +0,0 @@ - - - - - - - - WSO2 Identity Server - - - IS - - - 5.3.0 - - - localhost - - - localhost - - - local:/${carbon.context}/services/ - - - - - - - IdentityServer - - - - - - - org.wso2.carbon - - - / - - - - - - - - - 15 - - - - - - - - - 0 - - - - - 9999 - - 11111 - - - - - - 10389 - - 8000 - - - - - - 10500 - - - - - - - - - org.wso2.carbon.tomcat.jndi.CarbonJavaURLContextFactory - - - - - - - - - java - - - - - - - - - - false - - - false - - - 600 - - - - false - - - - - - - - 30 - - - - - - - - - 15 - - - - - - ${carbon.home}/repository/deployment/server/ - - - 15 - - - ${carbon.home}/repository/conf/axis2/axis2.xml - - - 30000 - - - ${carbon.home}/repository/deployment/client/ - - ${carbon.home}/repository/conf/axis2/axis2_client.xml - - true - - - - - - - - - - admin - Default Administrator Role - - - user - Default User Role - - - - - - - - - - - - ${carbon.home}/repository/resources/security/wso2carbon.jks - - JKS - - wso2carbon - - wso2carbon - - wso2carbon - - - - - - ${carbon.home}/repository/resources/security/client-truststore.jks - - JKS - - wso2carbon - - - - - - - - - - - - - - - - - - - UserManager - - - false - - org.wso2.carbon.identity.provider.AttributeCallbackHandler - - - org.wso2.carbon.identity.sts.store.DBTokenStore - - - true - allow - - - - - - - claim_mgt_menu - identity_mgt_emailtemplate_menu - identity_security_questions_menu - - - - ${carbon.home}/tmp/work - - - - - - true - - - 10 - - - 30 - - - - - - 100 - - - - keystore - certificate - * - - org.wso2.carbon.ui.transports.fileupload.AnyFileUploadExecutor - - - - - jarZip - - org.wso2.carbon.ui.transports.fileupload.JarZipUploadExecutor - - - - dbs - - org.wso2.carbon.ui.transports.fileupload.DBSFileUploadExecutor - - - - tools - - org.wso2.carbon.ui.transports.fileupload.ToolsFileUploadExecutor - - - - toolsAny - - org.wso2.carbon.ui.transports.fileupload.ToolsAnyFileUploadExecutor - - - - - - - - - - info - org.wso2.carbon.core.transports.util.InfoProcessor - - - wsdl - org.wso2.carbon.core.transports.util.Wsdl11Processor - - - wsdl2 - org.wso2.carbon.core.transports.util.Wsdl20Processor - - - xsd - org.wso2.carbon.core.transports.util.XsdProcessor - - - - - - false - false - true - svn - http://svnrepo.example.com/repos/ - username - password - true - - - - - - - - - - - - - - - ${require.carbon.servlet} - - - - - true - - - - - - - default repository - http://product-dist.wso2.com/p2/carbon/releases/wilkes/ - - - - - - - - true - - - - - - true - - diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/resources/repository/conf/identity/identity.xml b/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/resources/repository/conf/identity/identity.xml deleted file mode 100644 index 07de6831dbf4..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/resources/repository/conf/identity/identity.xml +++ /dev/null @@ -1,743 +0,0 @@ - - - - - - - - - jdbc/WSO2IdentityDB - - - - - true - true - 0 - - true - 20160 - 1140 - - - true - 720 - - - - - - - 15 - 20160 - - - - - - ${carbon.home}/conf/keystores - SunX509 - SunX509 - - - - SelfAndManaged - CertValidate - - - - - - - - - - - ${carbon.protocol}://${carbon.host}:${carbon.management.port}/openidserver - ${carbon.protocol}://${carbon.host}:${carbon.management.port}/openid - ${carbon.protocol}://${carbon.host}:${carbon.management.port}/authenticationendpoint/openid_login.do - - - false - - 7200 - - false - - - - - - - - - - - - - - - - - - - - - - -1 - -1 - -1 - -1 - - - ${carbon.protocol}://${carbon.host}:${carbon.management.port}/oauth/request-token - ${carbon.protocol}://${carbon.host}:${carbon.management.port}/oauth/authorize-url - ${carbon.protocol}://${carbon.host}:${carbon.management.port}/oauth/access-token - ${carbon.protocol}://${carbon.host}:${carbon.management.port}/oauth2/authorize - ${carbon.protocol}://${carbon.host}:${carbon.management.port}/oauth2/token - ${carbon.protocol}://${carbon.host}:${carbon.management.port}/oauth2/revoke - ${carbon.protocol}://${carbon.host}:${carbon.management.port}/oauth2/introspect - ${carbon.protocol}://${carbon.host}:${carbon.management.port}/oauth2/userinfo - ${carbon.protocol}://${carbon.host}:${carbon.management.port}/oidc/checksession - ${carbon.protocol}://${carbon.host}:${carbon.management.port}/oidc/logout - ${carbon.protocol}://${carbon.host}:${carbon.management.port}/authenticationendpoint/oauth2_authz.do - ${carbon.protocol}://${carbon.host}:${carbon.management.port}/authenticationendpoint/oauth2_error.do - ${carbon.protocol}://${carbon.host}:${carbon.management.port}/authenticationendpoint/oauth2_consent.do - ${carbon.protocol}://${carbon.host}:${carbon.management.port}/authenticationendpoint/oauth2_logout_consent.do - ${carbon.protocol}://${carbon.host}:${carbon.management.port}/authenticationendpoint/oauth2_logout.do - - ${carbon.protocol}://${carbon.host}:${carbon.management.port}/.well-known/webfinger - - - ${carbon.protocol}://${carbon.host}:${carbon.management.port}/identity/connect/register - ${carbon.protocol}://${carbon.host}:${carbon.management.port}/oauth2/jwks - ${carbon.protocol}://${carbon.host}:${carbon.management.port}/oauth2/oidcdiscovery - - - 300 - - 3600 - - 3600 - - 84600 - - 300 - - false - - true - - org.wso2.carbon.identity.oauth.tokenprocessor.PlainTextPersistenceProcessor - - - - false - - - - - - token - org.wso2.carbon.identity.oauth2.authz.handlers.AccessTokenResponseTypeHandler - - - code - org.wso2.carbon.identity.oauth2.authz.handlers.CodeResponseTypeHandler - - - id_token - org.wso2.carbon.identity.oauth2.authz.handlers.IDTokenResponseTypeHandler - - - id_token token - org.wso2.carbon.identity.oauth2.authz.handlers.IDTokenTokenResponseTypeHandler - - - - - - authorization_code - org.wso2.carbon.identity.oauth2.token.handlers.grant.AuthorizationCodeGrantHandler - - - password - org.wso2.carbon.identity.oauth2.token.handlers.grant.PasswordGrantHandler - - - refresh_token - org.wso2.carbon.identity.oauth2.token.handlers.grant.RefreshGrantHandler - - - client_credentials - org.wso2.carbon.identity.oauth2.token.handlers.grant.ClientCredentialsGrantHandler - - - urn:ietf:params:oauth:grant-type:saml2-bearer - org.wso2.carbon.identity.oauth2.token.handlers.grant.saml.SAML2BearerGrantHandler - - - iwa:ntlm - org.wso2.carbon.identity.oauth2.token.handlers.grant.iwa.ntlm.NTLMAuthenticationGrantHandler - - - idTokenNotAllowedGrantType - org.wso2.carbon.identity.oauth2.token.handlers.grant.idTokenNotAllowedGrantHandler - false - - - - - - - - - false - - - - false - - - - false - org.wso2.carbon.identity.oauth2.authcontext.JWTTokenGenerator - org.wso2.carbon.identity.oauth2.authcontext.DefaultClaimsRetriever - http://wso2.org/claims - SHA256withRSA - 10 - - - - - - org.wso2.carbon.identity.openidconnect.DefaultIDTokenBuilder - SHA256withRSA - - - - - - ${carbon.protocol}://${carbon.host}:${carbon.management.port}/oauth2/token - org.wso2.carbon.identity.openidconnect.DefaultOIDCClaimsCallbackHandler - 3600 - org.wso2.carbon.identity.oauth.endpoint.user.impl.UserInfoUserStoreClaimRetriever - org.wso2.carbon.identity.oauth.endpoint.user.impl.UserInforRequestDefaultValidator - org.wso2.carbon.identity.oauth.endpoint.user.impl.UserInfoISAccessTokenValidator - org.wso2.carbon.identity.oauth.endpoint.user.impl.UserInfoJSONResponseBuilder - false - - - - - - - - gtalk - talk.google.com - 5222 - gmail.com - multifactor1@gmail.com - wso2carbon - - - - - - 157680000 - 157680000 - ${carbon.host} - - ${carbon.protocol}://${carbon.host}:${carbon.management.port}/samlsso - ${carbon.protocol}://${carbon.host}:${carbon.management.port}/authenticationendpoint/samlsso_logout.do - ${carbon.protocol}://${carbon.host}:${carbon.management.port}/authenticationendpoint/samlsso_notification.do - 5 - 60000 - - false - http://wso2.org/claims - org.wso2.carbon.identity.sso.saml.builders.assertion.ExtendedDefaultAssertionBuilder - - org.wso2.carbon.identity.sso.saml.builders.encryption.DefaultSSOEncrypter - org.wso2.carbon.identity.sso.saml.builders.signature.DefaultSSOSigner - org.wso2.carbon.identity.sso.saml.validators.SAML2HTTPRedirectDeflateSignatureValidator - - - - 5 - false - http://www.w3.org/2000/09/xmldsig#rsa-sha1 - http://www.w3.org/2000/09/xmldsig#sha1 - true - - - - - ${carbon.protocol}://${carbon.host}:${carbon.management.port}/services/wso2carbon-sts - - - - - ${carbon.protocol}://${carbon.host}:${carbon.management.port}/passivests - ${carbon.protocol}://${carbon.host}:${carbon.management.port}/authenticationendpoint/retry.do - org.wso2.carbon.identity.sts.passive.utils.NoPersistenceTokenStore - true - - - - - false - ${Ports.ThriftEntitlementReceivePort} - 10000 - - ${carbon.home}/repository/resources/security/wso2carbon.jks - wso2carbon - - - ${carbon.host} - - - - - - ${carbon.protocol}://${carbon.host}:${carbon.management.port}/wso2/scim/Users - ${carbon.protocol}://${carbon.host}:${carbon.management.port}/wso2/scim/Groups - - - 5 - - - 10 - local://services - - - - - - - - - - - - - org.wso2.carbon.identity.governance.store.JDBCIdentityDataStore - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /permission/admin/manage/identity/identitymgt - - - - - - /permission/admin/manage/identity/usermgt/view - - - /permission/admin/manage/identity/usermgt/view - - - - /permission/admin/manage/identity/configmgt/list - - - - /permission/admin/manage/identity/configmgt/add - - - /permission/admin/manage/identity/configmgt/update - - - - /permission/admin/manage/identity/configmgt/delete - - - - /permission/admin/manage/identity/configmgt/add - - - /permission/admin/manage/identity/configmgt/update - - - - /permission/admin/manage/identity/configmgt/delete - - - - /permission/admin/manage/identity/configmgt/add - - - /permission/admin/manage/identity/configmgt/update - - - - /permission/admin/manage/identity/configmgt/delete - - - - - - - /permission/admin/manage/identity/consentmgt/add - - - - /permission/admin/manage/identity/consentmgt/delete - - - - /permission/admin/manage/identity/consentmgt/add - - - - /permission/admin/manage/identity/consentmgt/delete - - - - /permission/admin/manage/identity/consentmgt/add - - - - /permission/admin/manage/identity/consentmgt/delete - - - - /permission/admin/manage/identity/identitymgt - - - - /permission/admin/manage/identity/applicationmgt/create - - - /permission/admin/manage/identity/applicationmgt/delete - - - /permission/admin/manage/identity/applicationmgt/update - - - /permission/admin/manage/identity/applicationmgt/view - - - /permission/admin/manage/identity/applicationmgt/delete - - - /permission/admin/manage/identity/applicationmgt/create - - - /permission/admin/manage/identity/applicationmgt/view - - - /permission/admin/manage/identity/pep - - - /permission/admin/manage/identity/usermgt/create - - - /permission/admin/manage/identity/usermgt/list - - - /permission/admin/manage/identity/rolemgt/create - - - /permission/admin/manage/identity/rolemgt/view - - - /permission/admin/manage/identity/usermgt/view - - - /permission/admin/manage/identity/usermgt/update - - - /permission/admin/manage/identity/usermgt/update - - - /permission/admin/manage/identity/usermgt/delete - - - /permission/admin/manage/identity/rolemgt/view - - - /permission/admin/manage/identity/rolemgt/update - - - /permission/admin/manage/identity/rolemgt/update - - - /permission/admin/manage/identity/rolemgt/delete - - - /permission/admin/login - - - /permission/admin/manage/identity/usermgt/delete - - - /permission/admin/login - - - /permission/admin/login - - - /permission/admin/manage/identity/usermgt/create - - - - - - - - - /permission/admin/manage/identity/usermgt - - - /permission/admin/manage/identity/applicationmgt - - - - - - - /permission/admin/manage/identity/usermgt/update - - - - - - /permission/admin/manage/humantask/viewtasks - - - /permission/admin/login - - - /permission/admin/manage/identity/usermgt - - - /permission/admin/manage/identity/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /api/identity/user/v0.9 - /api/identity/recovery/v0.9 - /oauth2 - /api/identity/entitlement - - - /identity/(.*) - - - - - - applications,connections - - - - 300 - diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/resources/testng.xml b/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/resources/testng.xml deleted file mode 100644 index f88424f98508..000000000000 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/resources/testng.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/components/entitlement/pom.xml b/components/entitlement/pom.xml index 013ac5b3a2ce..c555f126527f 100644 --- a/components/entitlement/pom.xml +++ b/components/entitlement/pom.xml @@ -21,7 +21,7 @@ org.wso2.carbon.identity.framework identity-framework - 7.6.20-SNAPSHOT + 7.7.0-SNAPSHOT ../../pom.xml diff --git a/components/extension-mgt/org.wso2.carbon.identity.extension.mgt/pom.xml b/components/extension-mgt/org.wso2.carbon.identity.extension.mgt/pom.xml index 939ae1bca0fe..e82bf79e818f 100644 --- a/components/extension-mgt/org.wso2.carbon.identity.extension.mgt/pom.xml +++ b/components/extension-mgt/org.wso2.carbon.identity.extension.mgt/pom.xml @@ -20,7 +20,7 @@ org.wso2.carbon.identity.framework extension-mgt - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../pom.xml diff --git a/components/extension-mgt/pom.xml b/components/extension-mgt/pom.xml index f25e01730c4f..eb0fcb2f6ee1 100644 --- a/components/extension-mgt/pom.xml +++ b/components/extension-mgt/pom.xml @@ -20,7 +20,7 @@ org.wso2.carbon.identity.framework identity-framework - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../../pom.xml diff --git a/components/functions-library-mgt/org.wso2.carbon.identity.functions.library.mgt.ui/pom.xml b/components/functions-library-mgt/org.wso2.carbon.identity.functions.library.mgt.ui/pom.xml index 3dfccebcdbb2..dc20785c48a1 100644 --- a/components/functions-library-mgt/org.wso2.carbon.identity.functions.library.mgt.ui/pom.xml +++ b/components/functions-library-mgt/org.wso2.carbon.identity.functions.library.mgt.ui/pom.xml @@ -21,7 +21,7 @@ functions-library-mgt org.wso2.carbon.identity.framework - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../pom.xml 4.0.0 diff --git a/components/functions-library-mgt/org.wso2.carbon.identity.functions.library.mgt/pom.xml b/components/functions-library-mgt/org.wso2.carbon.identity.functions.library.mgt/pom.xml index 3684dd9abb77..9c5e893a498a 100644 --- a/components/functions-library-mgt/org.wso2.carbon.identity.functions.library.mgt/pom.xml +++ b/components/functions-library-mgt/org.wso2.carbon.identity.functions.library.mgt/pom.xml @@ -21,7 +21,7 @@ functions-library-mgt org.wso2.carbon.identity.framework - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../pom.xml 4.0.0 diff --git a/components/functions-library-mgt/pom.xml b/components/functions-library-mgt/pom.xml index e53682e865ed..30659968bbd7 100644 --- a/components/functions-library-mgt/pom.xml +++ b/components/functions-library-mgt/pom.xml @@ -21,7 +21,7 @@ org.wso2.carbon.identity.framework identity-framework - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../../pom.xml diff --git a/components/identity-core/org.wso2.carbon.identity.base/pom.xml b/components/identity-core/org.wso2.carbon.identity.base/pom.xml index bcb0baef20cf..dec3beed0988 100644 --- a/components/identity-core/org.wso2.carbon.identity.base/pom.xml +++ b/components/identity-core/org.wso2.carbon.identity.base/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.identity.framework identity-core - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../pom.xml diff --git a/components/identity-core/org.wso2.carbon.identity.core.ui/pom.xml b/components/identity-core/org.wso2.carbon.identity.core.ui/pom.xml index 776ddb4a2dc3..4218f0d35988 100644 --- a/components/identity-core/org.wso2.carbon.identity.core.ui/pom.xml +++ b/components/identity-core/org.wso2.carbon.identity.core.ui/pom.xml @@ -21,7 +21,7 @@ org.wso2.carbon.identity.framework identity-core - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../pom.xml diff --git a/components/identity-core/org.wso2.carbon.identity.core/pom.xml b/components/identity-core/org.wso2.carbon.identity.core/pom.xml index 082ca7b3f489..19a6d3cf8e7f 100644 --- a/components/identity-core/org.wso2.carbon.identity.core/pom.xml +++ b/components/identity-core/org.wso2.carbon.identity.core/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.identity.framework identity-core - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../pom.xml diff --git a/components/identity-core/org.wso2.carbon.identity.core/src/test/resources/identity.xml b/components/identity-core/org.wso2.carbon.identity.core/src/test/resources/identity.xml index 79b52c5aeb70..cb4429f44eaf 100644 --- a/components/identity-core/org.wso2.carbon.identity.core/src/test/resources/identity.xml +++ b/components/identity-core/org.wso2.carbon.identity.core/src/test/resources/identity.xml @@ -170,7 +170,6 @@ - diff --git a/components/identity-core/org.wso2.carbon.identity.core/src/test/resources/identity_err1.xml b/components/identity-core/org.wso2.carbon.identity.core/src/test/resources/identity_err1.xml index 9103d2afe87b..a3fe914b9ca1 100644 --- a/components/identity-core/org.wso2.carbon.identity.core/src/test/resources/identity_err1.xml +++ b/components/identity-core/org.wso2.carbon.identity.core/src/test/resources/identity_err1.xml @@ -151,7 +151,6 @@ - diff --git a/components/identity-core/org.wso2.carbon.identity.core/src/test/resources/identity_err2.xml b/components/identity-core/org.wso2.carbon.identity.core/src/test/resources/identity_err2.xml index 6b47c3321ba0..cfa71948c73f 100644 --- a/components/identity-core/org.wso2.carbon.identity.core/src/test/resources/identity_err2.xml +++ b/components/identity-core/org.wso2.carbon.identity.core/src/test/resources/identity_err2.xml @@ -157,7 +157,6 @@ - diff --git a/components/identity-core/pom.xml b/components/identity-core/pom.xml index 12c79001fc84..59c0594f89e3 100644 --- a/components/identity-core/pom.xml +++ b/components/identity-core/pom.xml @@ -20,7 +20,7 @@ org.wso2.carbon.identity.framework identity-framework - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../../pom.xml diff --git a/components/identity-event/org.wso2.carbon.identity.event/pom.xml b/components/identity-event/org.wso2.carbon.identity.event/pom.xml index 68860e0c6bcf..4f99d3a9a25d 100644 --- a/components/identity-event/org.wso2.carbon.identity.event/pom.xml +++ b/components/identity-event/org.wso2.carbon.identity.event/pom.xml @@ -21,7 +21,7 @@ org.wso2.carbon.identity.framework identity-event - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../pom.xml diff --git a/components/identity-event/pom.xml b/components/identity-event/pom.xml index f17d04f41b01..89e32a8565a3 100644 --- a/components/identity-event/pom.xml +++ b/components/identity-event/pom.xml @@ -21,7 +21,7 @@ org.wso2.carbon.identity.framework identity-framework - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../../pom.xml diff --git a/components/identity-mgt/org.wso2.carbon.identity.mgt.endpoint.util/pom.xml b/components/identity-mgt/org.wso2.carbon.identity.mgt.endpoint.util/pom.xml index 5e4b9a91d8ca..458788051a50 100644 --- a/components/identity-mgt/org.wso2.carbon.identity.mgt.endpoint.util/pom.xml +++ b/components/identity-mgt/org.wso2.carbon.identity.mgt.endpoint.util/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.identity.framework identity-mgt - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../pom.xml diff --git a/components/identity-mgt/org.wso2.carbon.identity.mgt.endpoint.util/src/main/java/org/wso2/carbon/identity/mgt/endpoint/util/client/OrganizationDiscoveryConfigDataRetrievalClient.java b/components/identity-mgt/org.wso2.carbon.identity.mgt.endpoint.util/src/main/java/org/wso2/carbon/identity/mgt/endpoint/util/client/OrganizationDiscoveryConfigDataRetrievalClient.java new file mode 100644 index 000000000000..59ecda3de2f7 --- /dev/null +++ b/components/identity-mgt/org.wso2.carbon.identity.mgt.endpoint.util/src/main/java/org/wso2/carbon/identity/mgt/endpoint/util/client/OrganizationDiscoveryConfigDataRetrievalClient.java @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. 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.wso2.carbon.identity.mgt.endpoint.util.client; + +import org.apache.commons.codec.binary.Base64; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpRequestBase; +import org.apache.http.impl.client.CloseableHttpClient; +import org.json.JSONArray; +import org.json.JSONObject; +import org.json.JSONTokener; +import org.wso2.carbon.identity.mgt.endpoint.util.IdentityManagementEndpointUtil; +import org.wso2.carbon.identity.mgt.endpoint.util.IdentityManagementServiceUtil; +import org.wso2.carbon.utils.HTTPClientUtils; + +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.Charset; +import java.util.HashMap; +import java.util.Map; + +/** + * Client which interacts with the organization discovery configuration API + * to retrieve organization discovery configuration data. + */ +public class OrganizationDiscoveryConfigDataRetrievalClient { + + private static final String CLIENT = "Client "; + private static final String ORG_DISCOVERY_CONFIG_ENDPOINT = "/api/server/v1/organization-configs/discovery"; + private static final String PROPERTIES = "properties"; + private static final String VALUE = "value"; + private static final String KEY = "key"; + private static final String AUTHORIZATION_HEADER = "Authorization"; + + /** + * Retrieves organization discovery configuration data for a given organization. + * + * @param tenantDomain Tenant domain. + * @return Organization discovery configuration data. + * @throws OrganizationDiscoveryConfigDataRetrievalClientException If an error occurs while retrieving organization + * discovery configuration data. + */ + public Map getDiscoveryConfiguration(String tenantDomain) + throws OrganizationDiscoveryConfigDataRetrievalClientException { + + Map organizationDiscoveryConfig = new HashMap<>(); + + try (CloseableHttpClient httpClient = HTTPClientUtils.createClientWithCustomVerifier().build()) { + HttpGet request = new HttpGet(getOrganizationDiscoveryConfigEndpoint(tenantDomain)); + setAuthorizationHeader(request); + + try (CloseableHttpResponse httpResponse = httpClient.execute(request)) { + if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { + JSONObject configObject = new JSONObject(new JSONTokener(new InputStreamReader( + httpResponse.getEntity().getContent()))); + + if (configObject.has(PROPERTIES) && configObject.get(PROPERTIES) instanceof JSONArray) { + JSONArray properties = configObject.getJSONArray(PROPERTIES); + for (int i = 0; i < properties.length(); i++) { + JSONObject property = properties.getJSONObject(i); + organizationDiscoveryConfig.put(property.getString(KEY), property.getString(VALUE)); + } + } + } + return organizationDiscoveryConfig; + } finally { + request.releaseConnection(); + } + } catch (IOException e) { + throw new OrganizationDiscoveryConfigDataRetrievalClientException("Error while retrieving organization " + + "discovery configuration for tenant: " + tenantDomain, e); + } + + } + + private String getOrganizationDiscoveryConfigEndpoint(String tenantDomain) + throws OrganizationDiscoveryConfigDataRetrievalClientException { + + try { + return IdentityManagementEndpointUtil.getBasePath(tenantDomain, ORG_DISCOVERY_CONFIG_ENDPOINT); + } catch (ApiException e) { + throw new OrganizationDiscoveryConfigDataRetrievalClientException("Error while building url for context: " + + ORG_DISCOVERY_CONFIG_ENDPOINT); + } + } + + private void setAuthorizationHeader(HttpRequestBase httpMethod) { + + String toEncode = IdentityManagementServiceUtil.getInstance().getAppName() + ":" + + String.valueOf(IdentityManagementServiceUtil.getInstance().getAppPassword()); + byte[] encoding = Base64.encodeBase64(toEncode.getBytes()); + String authHeader = new String(encoding, Charset.defaultCharset()); + httpMethod.addHeader(AUTHORIZATION_HEADER, CLIENT + authHeader); + } +} diff --git a/components/identity-mgt/org.wso2.carbon.identity.mgt.endpoint.util/src/main/java/org/wso2/carbon/identity/mgt/endpoint/util/client/OrganizationDiscoveryConfigDataRetrievalClientException.java b/components/identity-mgt/org.wso2.carbon.identity.mgt.endpoint.util/src/main/java/org/wso2/carbon/identity/mgt/endpoint/util/client/OrganizationDiscoveryConfigDataRetrievalClientException.java new file mode 100644 index 000000000000..b9676ed52741 --- /dev/null +++ b/components/identity-mgt/org.wso2.carbon.identity.mgt.endpoint.util/src/main/java/org/wso2/carbon/identity/mgt/endpoint/util/client/OrganizationDiscoveryConfigDataRetrievalClientException.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. 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.wso2.carbon.identity.mgt.endpoint.util.client; + +import org.wso2.carbon.identity.base.IdentityException; + +/** + * Exception for organization discovery config data retrieval. + */ +public class OrganizationDiscoveryConfigDataRetrievalClientException extends IdentityException { + + /** + * Client Exception with error message. + * + * @param message Error message. + */ + public OrganizationDiscoveryConfigDataRetrievalClientException(String message) { + + super(message); + } + + /** + * Client exception with message and a throwable. + * + * @param message Error message. + * @param throwable Throwable. + */ + public OrganizationDiscoveryConfigDataRetrievalClientException(String message, Throwable throwable) { + + super(message, throwable); + } + + /** + * Client exception with error code, message and a throwable. + * + * @param errorCode Error code. + * @param message Error message. + * @param throwable Throwable. + */ + public OrganizationDiscoveryConfigDataRetrievalClientException(String errorCode, String message, + Throwable throwable) { + + super(errorCode, message, throwable); + } + +} diff --git a/components/identity-mgt/org.wso2.carbon.identity.mgt.endpoint.util/src/test/java/org/wso2/carbon/identity/mgt/endpoint/util/OrganizationDiscoveryConfigDataRetrievalClientTest.java b/components/identity-mgt/org.wso2.carbon.identity.mgt.endpoint.util/src/test/java/org/wso2/carbon/identity/mgt/endpoint/util/OrganizationDiscoveryConfigDataRetrievalClientTest.java new file mode 100644 index 000000000000..0191118f23ca --- /dev/null +++ b/components/identity-mgt/org.wso2.carbon.identity.mgt.endpoint.util/src/test/java/org/wso2/carbon/identity/mgt/endpoint/util/OrganizationDiscoveryConfigDataRetrievalClientTest.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. 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.wso2.carbon.identity.mgt.endpoint.util; + +import org.mockito.MockedStatic; +import org.testng.Assert; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; +import org.wso2.carbon.identity.mgt.endpoint.util.client.OrganizationDiscoveryConfigDataRetrievalClient; +import org.wso2.carbon.utils.HTTPClientUtils; + +import java.io.IOException; +import java.util.Map; + +import static org.mockito.Mockito.mockStatic; + +/** + * Unit tests for OrganizationDiscoveryConfigDataRetrievalClient class. + */ +public class OrganizationDiscoveryConfigDataRetrievalClientTest extends RetrievalClientBaseTest { + + private final OrganizationDiscoveryConfigDataRetrievalClient orgDiscoveryConfigDataRetrievalClient = + new OrganizationDiscoveryConfigDataRetrievalClient(); + + @BeforeTest + public void setMockData() throws IOException { + + setMockJsonResponse(readResource("OrganizationDiscoveryConfigResponse.json")); + } + + @Test + public void testGetDiscoveryConfiguration() throws Exception { + + try (MockedStatic identityMgtServiceUtil = mockStatic( + IdentityManagementServiceUtil.class); + MockedStatic httpclientUtil = mockStatic(HTTPClientUtils.class)) { + identityMgtServiceUtil.when(IdentityManagementServiceUtil::getInstance) + .thenReturn(identityManagementServiceUtil); + httpclientUtil.when(HTTPClientUtils::createClientWithCustomVerifier).thenReturn(httpClientBuilder); + Map result = + orgDiscoveryConfigDataRetrievalClient.getDiscoveryConfiguration(SUPER_TENANT_DOMAIN); + Assert.assertEquals(result.size(), 2); + Assert.assertEquals(result.get("emailDomain.enable"), "true"); + Assert.assertEquals(result.get("emailDomainBasedSelfSignup.enable"), "true"); + } + } +} diff --git a/components/identity-mgt/org.wso2.carbon.identity.mgt.endpoint.util/src/test/resources/responses/OrganizationDiscoveryConfigResponse.json b/components/identity-mgt/org.wso2.carbon.identity.mgt.endpoint.util/src/test/resources/responses/OrganizationDiscoveryConfigResponse.json new file mode 100644 index 000000000000..78b735f95385 --- /dev/null +++ b/components/identity-mgt/org.wso2.carbon.identity.mgt.endpoint.util/src/test/resources/responses/OrganizationDiscoveryConfigResponse.json @@ -0,0 +1,12 @@ +{ + "properties": [ + { + "key": "emailDomain.enable", + "value": "true" + }, + { + "key": "emailDomainBasedSelfSignup.enable", + "value": "true" + } + ] +} diff --git a/components/identity-mgt/org.wso2.carbon.identity.mgt.endpoint.util/src/test/resources/testng.xml b/components/identity-mgt/org.wso2.carbon.identity.mgt.endpoint.util/src/test/resources/testng.xml index f3ab9359f19b..47519f450816 100644 --- a/components/identity-mgt/org.wso2.carbon.identity.mgt.endpoint.util/src/test/resources/testng.xml +++ b/components/identity-mgt/org.wso2.carbon.identity.mgt.endpoint.util/src/test/resources/testng.xml @@ -31,6 +31,7 @@ + diff --git a/components/identity-mgt/org.wso2.carbon.identity.mgt.ui/pom.xml b/components/identity-mgt/org.wso2.carbon.identity.mgt.ui/pom.xml index f98f0d43df50..d4d67ab3a7db 100644 --- a/components/identity-mgt/org.wso2.carbon.identity.mgt.ui/pom.xml +++ b/components/identity-mgt/org.wso2.carbon.identity.mgt.ui/pom.xml @@ -23,7 +23,7 @@ org.wso2.carbon.identity.framework identity-mgt - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../pom.xml diff --git a/components/identity-mgt/org.wso2.carbon.identity.mgt/pom.xml b/components/identity-mgt/org.wso2.carbon.identity.mgt/pom.xml index c0d2367524ff..15e1684e8d67 100644 --- a/components/identity-mgt/org.wso2.carbon.identity.mgt/pom.xml +++ b/components/identity-mgt/org.wso2.carbon.identity.mgt/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.identity.framework identity-mgt - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../pom.xml diff --git a/components/identity-mgt/pom.xml b/components/identity-mgt/pom.xml index 8d539da681ad..2c54df8a0814 100644 --- a/components/identity-mgt/pom.xml +++ b/components/identity-mgt/pom.xml @@ -21,7 +21,7 @@ org.wso2.carbon.identity.framework identity-framework - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../../pom.xml diff --git a/components/idp-mgt/org.wso2.carbon.idp.mgt.ui/pom.xml b/components/idp-mgt/org.wso2.carbon.idp.mgt.ui/pom.xml index 84db9481e496..e3dd50af898b 100644 --- a/components/idp-mgt/org.wso2.carbon.idp.mgt.ui/pom.xml +++ b/components/idp-mgt/org.wso2.carbon.idp.mgt.ui/pom.xml @@ -21,7 +21,7 @@ org.wso2.carbon.identity.framework identity-provider-management - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../pom.xml diff --git a/components/idp-mgt/org.wso2.carbon.idp.mgt/pom.xml b/components/idp-mgt/org.wso2.carbon.idp.mgt/pom.xml index 6b40470f1f2c..acfa7a124c52 100644 --- a/components/idp-mgt/org.wso2.carbon.idp.mgt/pom.xml +++ b/components/idp-mgt/org.wso2.carbon.idp.mgt/pom.xml @@ -20,7 +20,7 @@ org.wso2.carbon.identity.framework identity-provider-management - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../pom.xml diff --git a/components/idp-mgt/pom.xml b/components/idp-mgt/pom.xml index 1c82a30c48c4..b01d5d189978 100644 --- a/components/idp-mgt/pom.xml +++ b/components/idp-mgt/pom.xml @@ -21,7 +21,7 @@ org.wso2.carbon.identity.framework identity-framework - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../../pom.xml diff --git a/components/input-validation-mgt/org.wso2.carbon.identity.input.validation.mgt/pom.xml b/components/input-validation-mgt/org.wso2.carbon.identity.input.validation.mgt/pom.xml index 97ee8beebb1a..3da71a4c9ac1 100644 --- a/components/input-validation-mgt/org.wso2.carbon.identity.input.validation.mgt/pom.xml +++ b/components/input-validation-mgt/org.wso2.carbon.identity.input.validation.mgt/pom.xml @@ -21,7 +21,7 @@ org.wso2.carbon.identity.framework input-validation-mgt - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../pom.xml diff --git a/components/input-validation-mgt/pom.xml b/components/input-validation-mgt/pom.xml index f3acda9738a8..c7f3fc0d0507 100644 --- a/components/input-validation-mgt/pom.xml +++ b/components/input-validation-mgt/pom.xml @@ -21,7 +21,7 @@ org.wso2.carbon.identity.framework identity-framework - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../../pom.xml diff --git a/components/multi-attribute-login/org.wso2.carbon.identity.multi.attribute.login.mgt/pom.xml b/components/multi-attribute-login/org.wso2.carbon.identity.multi.attribute.login.mgt/pom.xml index 233b1e659e06..8daf86a19e4a 100644 --- a/components/multi-attribute-login/org.wso2.carbon.identity.multi.attribute.login.mgt/pom.xml +++ b/components/multi-attribute-login/org.wso2.carbon.identity.multi.attribute.login.mgt/pom.xml @@ -21,7 +21,7 @@ multi-attribute-login org.wso2.carbon.identity.framework - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../pom.xml 4.0.0 diff --git a/components/multi-attribute-login/org.wso2.carbon.identity.unique.claim.mgt/pom.xml b/components/multi-attribute-login/org.wso2.carbon.identity.unique.claim.mgt/pom.xml index eb831a9a71fc..830069b0b233 100644 --- a/components/multi-attribute-login/org.wso2.carbon.identity.unique.claim.mgt/pom.xml +++ b/components/multi-attribute-login/org.wso2.carbon.identity.unique.claim.mgt/pom.xml @@ -21,7 +21,7 @@ multi-attribute-login org.wso2.carbon.identity.framework - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../pom.xml 4.0.0 diff --git a/components/multi-attribute-login/pom.xml b/components/multi-attribute-login/pom.xml index 005415b48c08..a1f1160b65ca 100644 --- a/components/multi-attribute-login/pom.xml +++ b/components/multi-attribute-login/pom.xml @@ -21,7 +21,7 @@ identity-framework org.wso2.carbon.identity.framework - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../../pom.xml 4.0.0 diff --git a/components/notification-mgt/org.wso2.carbon.identity.notification.mgt/pom.xml b/components/notification-mgt/org.wso2.carbon.identity.notification.mgt/pom.xml index cef413db7be8..6a7dc18673ad 100644 --- a/components/notification-mgt/org.wso2.carbon.identity.notification.mgt/pom.xml +++ b/components/notification-mgt/org.wso2.carbon.identity.notification.mgt/pom.xml @@ -23,7 +23,7 @@ org.wso2.carbon.identity.framework notification-mgt - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../pom.xml diff --git a/components/notification-mgt/pom.xml b/components/notification-mgt/pom.xml index c67b33574bd1..2ba834e5c135 100644 --- a/components/notification-mgt/pom.xml +++ b/components/notification-mgt/pom.xml @@ -21,7 +21,7 @@ org.wso2.carbon.identity.framework identity-framework - 7.6.20-SNAPSHOT + 7.7.16-SNAPSHOT ../../pom.xml diff --git a/components/policy-editor/org.wso2.carbon.policyeditor.ui/pom.xml b/components/policy-editor/org.wso2.carbon.policyeditor.ui/pom.xml index 25708d0d5b2a..960e0a516e2d 100644 --- a/components/policy-editor/org.wso2.carbon.policyeditor.ui/pom.xml +++ b/components/policy-editor/org.wso2.carbon.policyeditor.ui/pom.xml @@ -21,7 +21,7 @@ org.wso2.carbon.identity.framework policy-editor - 7.6.20-SNAPSHOT + 7.7.0-SNAPSHOT ../pom.xml diff --git a/components/policy-editor/org.wso2.carbon.policyeditor.ui/src/main/resources/org/wso2/carbon/policyeditor/ui/i18n/JSResources.properties b/components/policy-editor/org.wso2.carbon.policyeditor.ui/src/main/resources/org/wso2/carbon/policyeditor/ui/i18n/JSResources.properties deleted file mode 100644 index e817f8c46022..000000000000 --- a/components/policy-editor/org.wso2.carbon.policyeditor.ui/src/main/resources/org/wso2/carbon/policyeditor/ui/i18n/JSResources.properties +++ /dev/null @@ -1,30 +0,0 @@ -# -# Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -# -# WSO2 Inc. 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. -# - -sorry.editing.not.supported=Sorry! Editing this type of element is not supported at the moment. -element.updated=Element updated -policy.content.blank=Policy content is blank. Please create a valid policy! -add.element.to.document=Add Element to Document -update.element=Update Element -the.element=The element -does.not.have.editable.attributes=does not seem to have editable attributes. -adding.new.element=Adding new element -editing.element=Editing element -add.policy.element=Add Policy Element > -add.policy.attribute=Add Policy Attribute > -delete.this.element=Delete This Element diff --git a/components/policy-editor/org.wso2.carbon.policyeditor.ui/src/main/resources/org/wso2/carbon/policyeditor/ui/i18n/Resources.properties b/components/policy-editor/org.wso2.carbon.policyeditor.ui/src/main/resources/org/wso2/carbon/policyeditor/ui/i18n/Resources.properties deleted file mode 100644 index 0ed33726ad2d..000000000000 --- a/components/policy-editor/org.wso2.carbon.policyeditor.ui/src/main/resources/org/wso2/carbon/policyeditor/ui/i18n/Resources.properties +++ /dev/null @@ -1,24 +0,0 @@ -# -# Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -# -# WSO2 Inc. 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. -# - -policy.editor=Policy Editor -source.view=Source View -design.view=Design View -tip.for.more.operations.right.click.the.tree.nodes.in.the.panel.below=Tip: For more operations, right click the Tree Nodes in the panel below. -save.policy=Save Policy -go.back=Cancel diff --git a/components/policy-editor/org.wso2.carbon.policyeditor.ui/src/main/resources/web/policyeditor/css/local-styles.css b/components/policy-editor/org.wso2.carbon.policyeditor.ui/src/main/resources/web/policyeditor/css/local-styles.css deleted file mode 100644 index 176733fdb3d2..000000000000 --- a/components/policy-editor/org.wso2.carbon.policyeditor.ui/src/main/resources/web/policyeditor/css/local-styles.css +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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. - */ - -.main-container { - padding-right: 10px; - padding-bottom: 10px; -} - -.policy-tree { - height: 610px; - width: 40%; - border: solid; - border-width: 1px; - overflow: auto; - float: left; -} - -.policy-input-gatherer { - float: left; - padding-left: 10px; -} - -.button-panel-container { - float: right; - padding-right: 5px; -} - -.raw-policy-tree { - width: 100%; - height: 650px; -} - -.button { - width: 100px; -} \ No newline at end of file diff --git a/components/policy-editor/org.wso2.carbon.policyeditor.ui/src/main/resources/web/policyeditor/index.jsp b/components/policy-editor/org.wso2.carbon.policyeditor.ui/src/main/resources/web/policyeditor/index.jsp deleted file mode 100644 index 64d7f07e9166..000000000000 --- a/components/policy-editor/org.wso2.carbon.policyeditor.ui/src/main/resources/web/policyeditor/index.jsp +++ /dev/null @@ -1,234 +0,0 @@ -<%-- - ~ Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - ~ - ~ WSO2 Inc. 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. ---%> -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> -<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %> -<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %> -<%@ page import="org.owasp.encoder.Encode" %> - -<%----%> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    -

    -
    -
    - - -
    -
    -
    -
      -
    • -
    • -
    -
    -
    - - - - - - - - - - - -
    - -
    - " - onclick="savePolicyXML();"> - " - onclick="goBack();"> - -
    -
    -
    - - - - - - - - - - - - - -
    -
    - -
    -
    -
    - -
    -
    -
    - -
    -
    -
    - " - onclick="savePolicyXML();"> - " - onclick="goBack();"> -
    -
    -
    -
    - - - -
    - -<% - String policyURL = request.getParameter("url"); - - String policyText = ""; - String policyId = ""; - - if (policyURL == null) { - if (request.getParameter("policy") != null) { - policyText = request.getParameter("policy").replaceAll("\r\n", "") - .replaceAll("\n", ""); - policyText=policyText.replace("'", "\""); - policyId = request.getParameter("policyid"); - } - } -%> - - -
    -
    - -
    \ No newline at end of file diff --git a/components/policy-editor/org.wso2.carbon.policyeditor.ui/src/main/resources/web/policyeditor/js/policy-editor-service-stub.js b/components/policy-editor/org.wso2.carbon.policyeditor.ui/src/main/resources/web/policyeditor/js/policy-editor-service-stub.js deleted file mode 100644 index ef503d30942b..000000000000 --- a/components/policy-editor/org.wso2.carbon.policyeditor.ui/src/main/resources/web/policyeditor/js/policy-editor-service-stub.js +++ /dev/null @@ -1,925 +0,0 @@ -/* - * Copyright (c) 2006, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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. - */ - -// Example stubs for PolicyEditorService operations. This function is not intended -// to be called, but rather as a source for copy-and-paste development. - -// Note that this stub has been generated for use in DOM environments. - - -function stubs() { - // formatXML operation - try { - /* string */ var formatXMLReturn = PolicyEditorService.formatXML(/* string */ param_xml); - } catch (e) { - // fault handling - } - - // getAvailableSchemas operation - try { - /* string */ var getAvailableSchemasReturn = PolicyEditorService.getAvailableSchemas(); - } catch (e) { - // fault handling - } - - // getPolicyDoc operation - try { - /* string */ var getPolicyDocReturn = PolicyEditorService.getPolicyDoc(/* string */ param_policyURL); - } catch (e) { - // fault handling - } - - // getSchema operation - try { - /* string */ var getSchemaReturn = PolicyEditorService.getSchema(/* string */ param_fileName); - } catch (e) { - // fault handling - } - -} -stubs.visible = false; - -var PolicyEditorService = new WebService("PolicyEditorServiceHttpsSoap12Endpoint"); - -PolicyEditorService.formatXML = - function formatXML(/* string */ _xml) - { - var isAsync, request, response, resultValue; - this._options = new Array(); - isAsync = (this.formatXML.callback != null && typeof(this.formatXML.callback) == 'function'); - request = this.formatXML_payload(/* string */ _xml); - - if (isAsync) { - try { - this._call( - "formatXML", - "http://www.w3.org/ns/wsdl/in-out", - request, - function(thisRequest, callbacks) { - if (thisRequest.error != null) { - callbacks[1](thisRequest.error); - } else { - response = thisRequest.responseXML; - if (response == null) { - resultValue = null; - } else { - var extractedValue = WSRequest.util._stringValue(response.documentElement); - resultValue = /* string */ extractedValue; - } - callbacks[0](resultValue); - } - }, - new Array(this.formatXML.callback, this.formatXML.onError) - ); - } catch (e) { - var error; - if (WebServiceError.prototype.isPrototypeOf(e)) { - error = e; - } else if (e.name != null) { - // Mozilla - error = new WebServiceError(e.name, e.message + " (" + e.fileName + "#" + e.lineNumber + ")"); - } else if (e.description != null) { - // IE - error = new WebServiceError(e.description, e.number, e.number); - } else { - error = new WebServiceError(e, "Internal Error"); - } - this.formatXML.onError(error); - } - } else { - try { - response = this._call("formatXML", "http://www.w3.org/ns/wsdl/in-out", request); - var extractedValue = WSRequest.util._stringValue(response.documentElement); - resultValue = /* string */ extractedValue; - return resultValue; - } catch (e) { - if (typeof(e) == "string") throw(e); - if (e.message) throw(e.message); - throw (e.reason); - } - } - return null; // Suppress warnings when there is no return. - } -PolicyEditorService.formatXML_payload = - function (/* string */ _xml) { - - return '' + - (_xml == null ? '' : '' + this._encodeXML(_xml) + '') + - '' ; - } -PolicyEditorService.formatXML_payload.visible = false; -PolicyEditorService.formatXML.callback = null; - -PolicyEditorService.getAvailableSchemas = - function getAvailableSchemas() - { - var isAsync, request, response, resultValue; - this._options = new Array(); - isAsync = (this.getAvailableSchemas.callback != null && typeof(this.getAvailableSchemas.callback) == 'function'); - request = this.getAvailableSchemas_payload(); - - if (isAsync) { - try { - this._call( - "getAvailableSchemas", - "http://www.w3.org/ns/wsdl/in-out", - request, - function(thisRequest, callbacks) { - if (thisRequest.error != null) { - callbacks[1](thisRequest.error); - } else { - response = thisRequest.responseXML; - if (response == null) { - resultValue = null; - } else { - var extractedValue = WSRequest.util._stringValue(response.documentElement); - resultValue = /* string */ extractedValue; - } - callbacks[0](resultValue); - } - }, - new Array(this.getAvailableSchemas.callback, this.getAvailableSchemas.onError) - ); - } catch (e) { - var error; - if (WebServiceError.prototype.isPrototypeOf(e)) { - error = e; - } else if (e.name != null) { - // Mozilla - error = new WebServiceError(e.name, e.message + " (" + e.fileName + "#" + e.lineNumber + ")"); - } else if (e.description != null) { - // IE - error = new WebServiceError(e.description, e.number, e.number); - } else { - error = new WebServiceError(e, "Internal Error"); - } - this.getAvailableSchemas.onError(error); - } - } else { - try { - response = this._call("getAvailableSchemas", "http://www.w3.org/ns/wsdl/in-out", request); - var extractedValue = WSRequest.util._stringValue(response.documentElement); - resultValue = /* string */ extractedValue; - return resultValue; - } catch (e) { - if (typeof(e) == "string") throw(e); - if (e.message) throw(e.message); - throw (e.reason); - } - } - return null; // Suppress warnings when there is no return. - } -PolicyEditorService.getAvailableSchemas_payload = - function () { - - return null; - } -PolicyEditorService.getAvailableSchemas_payload.visible = false; -PolicyEditorService.getAvailableSchemas.callback = null; - -PolicyEditorService.getPolicyDoc = - function getPolicyDoc(/* string */ _policyURL) - { - var isAsync, request, response, resultValue; - this._options = new Array(); - isAsync = (this.getPolicyDoc.callback != null && typeof(this.getPolicyDoc.callback) == 'function'); - request = this.getPolicyDoc_payload(/* string */ _policyURL); - - if (isAsync) { - try { - this._call( - "getPolicyDoc", - "http://www.w3.org/ns/wsdl/in-out", - request, - function(thisRequest, callbacks) { - if (thisRequest.error != null) { - callbacks[1](thisRequest.error); - } else { - response = thisRequest.responseXML; - if (response == null) { - resultValue = null; - } else { - var extractedValue = WSRequest.util._stringValue(response.documentElement); - resultValue = /* string */ extractedValue; - } - callbacks[0](resultValue); - } - }, - new Array(this.getPolicyDoc.callback, this.getPolicyDoc.onError) - ); - } catch (e) { - var error; - if (WebServiceError.prototype.isPrototypeOf(e)) { - error = e; - } else if (e.name != null) { - // Mozilla - error = new WebServiceError(e.name, e.message + " (" + e.fileName + "#" + e.lineNumber + ")"); - } else if (e.description != null) { - // IE - error = new WebServiceError(e.description, e.number, e.number); - } else { - error = new WebServiceError(e, "Internal Error"); - } - this.getPolicyDoc.onError(error); - } - } else { - try { - response = this._call("getPolicyDoc", "http://www.w3.org/ns/wsdl/in-out", request); - var extractedValue = WSRequest.util._stringValue(response.documentElement); - resultValue = /* string */ extractedValue; - return resultValue; - } catch (e) { - if (typeof(e) == "string") throw(e); - if (e.message) throw(e.message); - throw (e.reason); - } - } - return null; // Suppress warnings when there is no return. - } -PolicyEditorService.getPolicyDoc_payload = - function (/* string */ _policyURL) { - - return '' + - (_policyURL == null ? '' : '' + this._encodeXML(_policyURL) + '') + - '' ; - } -PolicyEditorService.getPolicyDoc_payload.visible = false; -PolicyEditorService.getPolicyDoc.callback = null; - -PolicyEditorService.getSchema = - function getSchema(/* string */ _fileName) - { - var isAsync, request, response, resultValue; - this._options = new Array(); - isAsync = (this.getSchema.callback != null && typeof(this.getSchema.callback) == 'function'); - request = this.getSchema_payload(/* string */ _fileName); - - if (isAsync) { - try { - this._call( - "getSchema", - "http://www.w3.org/ns/wsdl/in-out", - request, - function(thisRequest, callbacks) { - if (thisRequest.error != null) { - callbacks[1](thisRequest.error); - } else { - response = thisRequest.responseXML; - if (response == null) { - resultValue = null; - } else { - var extractedValue = WSRequest.util._stringValue(response.documentElement); - resultValue = /* string */ extractedValue; - } - callbacks[0](resultValue); - } - }, - new Array(this.getSchema.callback, this.getSchema.onError) - ); - } catch (e) { - var error; - if (WebServiceError.prototype.isPrototypeOf(e)) { - error = e; - } else if (e.name != null) { - // Mozilla - error = new WebServiceError(e.name, e.message + " (" + e.fileName + "#" + e.lineNumber + ")"); - } else if (e.description != null) { - // IE - error = new WebServiceError(e.description, e.number, e.number); - } else { - error = new WebServiceError(e, "Internal Error"); - } - this.getSchema.onError(error); - } - } else { - try { - response = this._call("getSchema", "http://www.w3.org/ns/wsdl/in-out", request); - var extractedValue = WSRequest.util._stringValue(response.documentElement); - resultValue = /* string */ extractedValue; - return resultValue; - } catch (e) { - if (typeof(e) == "string") throw(e); - if (e.message) throw(e.message); - throw (e.reason); - } - } - return null; // Suppress warnings when there is no return. - } -PolicyEditorService.getSchema_payload = - function (/* string */ _fileName) { - - return '' + - (_fileName == null ? '' : '' + this._encodeXML(_fileName) + '') + - '' ; - } -PolicyEditorService.getSchema_payload.visible = false; -PolicyEditorService.getSchema.callback = null; - - - -// WebService object. -function WebService(endpointName) -{ - this.readyState = 0; - this.onreadystatechange = null; - this.scriptInjectionCallback = null; - this.proxyAddress = null; - - //public accessors for manually intervening in setting the address (e.g. supporting tcpmon) - this.getAddress = function (endpointName) - { - return this._endpointDetails[endpointName].address; - } - - this.setAddress = function (endpointName, address) - { - this._endpointDetails[endpointName].address = address; - } - - // private helper functions - this._getWSRequest = function() - { - var wsrequest; - try { - wsrequest = new WSRequest(); - // try to set the proxyAddress based on the context of the stub - browser or Mashup Server - try { - wsrequest.proxyEngagedCallback = this.scriptInjectionCallback; - wsrequest.proxyAddress = this.proxyAddress; - } catch (e) { - try { - wsrequest.proxyEngagedCallback = this.scriptInjectionCallback; - wsrequest.proxyAddress = this.proxyAddress; - } catch (e) { } - } - } catch(e) { - try { - wsrequest = new ActiveXObject("WSRequest"); - } catch(e) { - try { - wsrequest = new SOAPHttpRequest(); - - } catch (e) { - throw new WebServiceError("WSRequest object not defined.", "WebService._getWSRequest() cannot instantiate WSRequest object."); - } - } - } - return wsrequest; - } - - this._endpointDetails = - { - "PolicyEditorServiceHttpSoap12Endpoint": { - "type" : "SOAP12", - "address" : "http://localhost:9763/services/PolicyEditorService.PolicyEditorServiceHttpSoap12Endpoint/", - "action" : { - "getAvailableSchemas" : "urn:getAvailableSchemas", - "getPolicyDoc" : "urn:getPolicyDoc", - "getSchema" : "urn:getSchema", - "formatXML" : "urn:formatXML" - }, - "soapaction" : { - "getAvailableSchemas" : "urn:getAvailableSchemas", - "getPolicyDoc" : "urn:getPolicyDoc", - "getSchema" : "urn:getSchema", - "formatXML" : "urn:formatXML" - } - }, - "PolicyEditorServiceHttpsSoap12Endpoint": { - "type" : "SOAP12", - "address" : "https://localhost:9443/services/PolicyEditorService.PolicyEditorServiceHttpsSoap12Endpoint/", - "action" : { - "getAvailableSchemas" : "urn:getAvailableSchemas", - "getPolicyDoc" : "urn:getPolicyDoc", - "getSchema" : "urn:getSchema", - "formatXML" : "urn:formatXML" - }, - "soapaction" : { - "getAvailableSchemas" : "urn:getAvailableSchemas", - "getPolicyDoc" : "urn:getPolicyDoc", - "getSchema" : "urn:getSchema", - "formatXML" : "urn:formatXML" - } - }, - "PolicyEditorServiceHttpSoap11Endpoint": { - "type" : "SOAP11", - "address" : "http://localhost:9763/services/PolicyEditorService.PolicyEditorServiceHttpSoap11Endpoint/", - "action" : { - "getAvailableSchemas" : "urn:getAvailableSchemas", - "getPolicyDoc" : "urn:getPolicyDoc", - "getSchema" : "urn:getSchema", - "formatXML" : "urn:formatXML" - }, - "soapaction" : { - "getAvailableSchemas" : "urn:getAvailableSchemas", - "getPolicyDoc" : "urn:getPolicyDoc", - "getSchema" : "urn:getSchema", - "formatXML" : "urn:formatXML" - } - }, - "PolicyEditorServiceHttpsSoap11Endpoint": { - "type" : "SOAP11", - "address" : "https://localhost:9443/services/PolicyEditorService.PolicyEditorServiceHttpsSoap11Endpoint/", - "action" : { - "getAvailableSchemas" : "urn:getAvailableSchemas", - "getPolicyDoc" : "urn:getPolicyDoc", - "getSchema" : "urn:getSchema", - "formatXML" : "urn:formatXML" - }, - "soapaction" : { - "getAvailableSchemas" : "urn:getAvailableSchemas", - "getPolicyDoc" : "urn:getPolicyDoc", - "getSchema" : "urn:getSchema", - "formatXML" : "urn:formatXML" - } - }, - "PolicyEditorServiceHttpEndpoint": { - "type" : "HTTP", - "address" : "http://localhost:9763/services/PolicyEditorService.PolicyEditorServiceHttpEndpoint/", - "httplocation" : { - "getAvailableSchemas" : "getAvailableSchemas", - "getPolicyDoc" : "getPolicyDoc", - "getSchema" : "getSchema", - "formatXML" : "formatXML" - }, - "httpmethod" : { - "getAvailableSchemas" : "POST", - "getPolicyDoc" : "POST", - "getSchema" : "POST", - "formatXML" : "POST" - }, - "fitsInURLParams" : { - "getAvailableSchemas" : true, - "getPolicyDoc" : true, - "getSchema" : true, - "formatXML" : true - } - }, - "PolicyEditorServiceHttpsEndpoint": { - "type" : "HTTP", - "address" : "https://localhost:9443/services/PolicyEditorService.PolicyEditorServiceHttpsEndpoint/", - "httplocation" : { - "getAvailableSchemas" : "getAvailableSchemas", - "getPolicyDoc" : "getPolicyDoc", - "getSchema" : "getSchema", - "formatXML" : "formatXML" - }, - "httpmethod" : { - "getAvailableSchemas" : "POST", - "getPolicyDoc" : "POST", - "getSchema" : "POST", - "formatXML" : "POST" - }, - "fitsInURLParams" : { - "getAvailableSchemas" : true, - "getPolicyDoc" : true, - "getSchema" : true, - "formatXML" : true - } - } - }; - this.endpoint = endpointName; - - this.username = null; - this.password = null; - - this._encodeXML = function (value) { - var str = value.toString(); - str = str.replace(/&/g, "&"); - str = str.replace(/= 48 && buffer.charCodeAt(p) <= 57) p++; - } else { - millisecond = 0; - } - } else { - hour = 0; - minute = 0; - second = 0; - millisecond = 0; - } - - var tzhour = 0; - var tzminute = 0; - // parse time zone - if (buffer.charAt(p) != 'Z' && buffer.charAt(p) != '') { - var sign = (buffer.charAt(p) == '-' ? -1 : +1); - p++; - tzhour = sign * buffer.substr(p,2); - p += 3; - tzminute = sign * buffer.substr(p,2); - } - - var thisDate = new Date(); - thisDate.setUTCFullYear(year); - thisDate.setUTCMonth(month-1); - thisDate.setUTCDate(day); - thisDate.setUTCHours(hour); - thisDate.setUTCMinutes(minute); - thisDate.setUTCSeconds(second); - thisDate.setUTCMilliseconds(millisecond); - thisDate.setUTCHours(thisDate.getUTCHours() - tzhour); - thisDate.setUTCMinutes(thisDate.getUTCMinutes() - tzminute); - return thisDate; - }, - - _nextPrefixNumber : 0, - - _QNameNamespaceDecl : function (qn) { - if (qn.uri == null) return ""; - var prefix = qn.localName.substring(0, qn.localName.indexOf(":")); - if (prefix == "") { - prefix = "n" + ++this._nextPrefixNumber; - } - return ' xmlns:' + prefix + '="' + qn.uri + '"'; - }, - - _QNameValue : function(qn) { - if (qn.uri == null) return qn.localName; - var prefix, localName; - if (qn.localName.indexOf(":") >= 0) { - prefix = qn.localName.substring(0, qn.localName.indexOf(":")); - localName = qn.localName.substring(qn.localName.indexOf(":")+1); - } else { - prefix = "n" + this._nextPrefixNumber; - localName = qn.localName; - } - return prefix + ":" + localName; - }, - - scheme : function (url) { - var s = url.substring(0, url.indexOf(':')); - return s; - }, - - domain : function (url) { - var d = url.substring(url.indexOf('://') + 3, url.indexOf('/',url.indexOf('://')+3)); - return d; - }, - - domainPort : function (url) { - var d = this.domain(url); - if (d.indexOf(":") >= 0) - d = d.substring(d.indexOf(':') +1); - return d; - }, - - domainNoPort : function (url) { - var d = this.domain(url); - if (d.indexOf(":") >= 0) - d = d.substring(0, d.indexOf(':')); - return d; - }, - - _serializeAnytype : function (name, value, namespace, optional) { - // dynamically serialize an anyType value in xml, including setting xsi:type. - if (optional && value == null) return ""; - var type = "xs:string"; - if (value == null) { - value = ""; - } else if (typeof(value) == "number") { - type = "xs:double"; - } else if (typeof(value) == "object" && value.nodeType != undefined) { - type = "xs:anyType"; - value = WebService.utils._serializeXML(value); - } else if (typeof(value) == "boolean") { - type = "xs:boolean"; - } else if (typeof(value) == "object" && Date.prototype.isPrototypeOf(value)) { - type = "xs:dateTime"; - value = WebService.utils.toXSdateTime(value); - } else if (value.match(/^\s*true\s*$/g) != null) { - type = "xs:boolean"; - } else if (value.match(/^\s*false\s*$/g) != null) { - type = "xs:boolean"; - } else if (!isNaN(Date.parse(value))) { - type = "xs:dateTime"; - value = WebService.utils.toXSdateTime(new Date(Date.parse(value))); - } else if (value.match(/^\s*\-?\d*\-\d\d\-\d\dZ?\s*$/g) != null) { - type = "xs:date"; - } else if (value.match(/^\s*\-?\d*\-\d\d\-\d\d[\+\-]\d\d:\d\d\s*$/g) != null) { - type = "xs:date"; - } else if (value.match(/^\s*\d\d:\d\d:\d\d\.?\d*Z?\s*$/g) != null) { - type = "xs:time"; - } else if (value.match(/^\s*\d\d:\d\d:\d\d\.?\d*[\+\-]\d\d:\d\d\s*$/g) != null) { - type = "xs:time"; - } else if (value.match(/^\s*\-?\d*\-\d\d\-\d\dT\d\d:\d\d:\d\d\.?\d*Z?\s*$/g) != null) { - type = "xs:dateTime"; - } else if (value.match(/^\s*\-?\d*\-\d\d\-\d\dT\d\d:\d\d:\d\d\.?\d*[\+\-]\d\d:\d\d\s*$/g) != null) { - type = "xs:dateTime"; - } else if (value.match(/^\s*\d\d*\.?\d*\s*$/g) != null) { - type = "xs:double"; - } else if (value.match(/^\s*\d*\.?\d\d*\s*$/g) != null) { - type = "xs:double"; - } else if (value.match(/^\s*\"; - var endtag = ""; - return starttag + value + endtag; - }, - - _serializeXML : function(payload) { - var browser = WSRequest.util._getBrowser(); - switch (browser) { - case "gecko": - case "safari": - var serializer = new XMLSerializer(); - return serializer.serializeToString(payload); - break; - case "ie": - case "ie7": - return payload.xml; - break; - case "opera": - var xmlSerializer = document.implementation.createLSSerializer(); - return xmlSerializer.writeToString(payload); - break; - case "undefined": - throw new WebServiceError("Unknown browser", "WSRequest.util._serializeToString doesn't recognize the browser, to invoke browser-specific serialization code."); - } - }, - - // library function for dynamically converting an element with js:type annotation to a Javascript type. - _convertJSType : function (element, isWrapped) { - if (element == null) return ""; - var extractedValue = WSRequest.util._stringValue(element); - var resultValue, i; - var type = element.getAttribute("js:type"); - if (type == null) { - type = "#raw"; - } else { - type = type.toString(); - } - switch (type) { - case "string": - return extractedValue; - break; - case "number": - return parseFloat(extractedValue); - break; - case "boolean": - return extractedValue == "true" || extractedValue == "1"; - break; - case "date": - return WebService.utils.parseXSdateTime(extractedValue); - break; - case "array": - resultValue = new Array(); - for (i=0; i - candidateString = candidateString.substring(0, candidateString.length - 3); - } else if (candidateString.substring(0, 12) == "<![CDATA[") { - //Removing <![CDATA[ - candidateString = candidateString.substring(12, candidateString.length); - //Removing ]]< - candidateString = candidateString.substring(0, candidateString.length - 6); - } - - return candidateString; -} - -/** - * Synchronizes the Raw Policy (Text) view using the changes done to the in-memory policy document - * - * @param policyDocument - */ -function syncRawPolicyView(policyDocument) { - - var rawPolicyTextArea = document.getElementById("raw-policy"); - - if (policyDocument.indexOf("?>") > -1) { - policyDocument = policyDocument.substring(policyDocument.indexOf("?>") + 2); - } - - try { - var parser = new DOMImplementation(); - currentPolicyDoc = parser.loadXML(policyDocument); - - var browser = WSRequest.util._getBrowser(); - if (browser == "gecko") { - // Gecko has inbuilt E4X. This formats XML nicely - editAreaLoader.setValue("raw-policy","" + new XML(policyDocument)); - } else { - // There's no known way to format in the client side. Sending to the backend - formatXMLUsingService(policyDocument); - } - - if (editAreaLoader.getValue("raw-policy") == "") { - editAreaLoader.setValue("raw-policy",''); - } - } catch(e) { - //alert("Failed to parse the policy XML. Please check. [" + e.toString() + "]"); - editAreaLoader.setValue("raw-policy","" + policyDocument); - } -} - -/** - * Formats a given XML using the backend service - * - * @param xml - */ -function formatXMLUsingService(xml) { - editAreaLoader.setValue("raw-policy",removeCDATA(PolicyEditorService.formatXML(xml))); -} - -/** - * Synchronizes the Policy Tree using the in-memory Policy document - * - */ -function syncPolicyTreeView() { - var rawPolicy = editAreaLoader.getValue("raw-policy"); - - if (rawPolicy.indexOf("?>") > -1) { - rawPolicy = rawPolicy.substring(rawPolicy.indexOf("?>") + 2); - } - - buildTreeView(rawPolicy); -} - -/** - * Generates HTML UI elements required to gather input from the user in order to add/update - * an element. - * - * @param targetElement - To which elements the updations should be commited to - * @param schemaElement - The remplate schema element to use to generate the UI - * @param namespaceURI - The namespace URI to use for the new element - * @param mode - Mode can be either 'add' or 'edit' - */ -function generateGathererUI(targetElement, schemaElement, namespaceURI, mode) { - // Store the target element globally - currentUITargetElement = targetElement; - - var actionName = ""; - if (mode == "add") { - actionName = jsi18n["adding.new.element"] + " "; - } else if (mode == "edit") { - actionName = jsi18n["editing.element"] + " "; - } - - var prefix = schemaElement.prefix; - - // Start processing the attributes - var elementAttributes = schemaElement.getElementsByTagName(prefix + ":attribute"); - - if (elementAttributes.length > 0) { - - var uiHTML = "
    "; - - for (var x = 0; x < elementAttributes.length; x++) { - - var attrbuteName = elementAttributes.item(x).getAttribute("name"); - if (attrbuteName != undefined) { - uiHTML = uiHTML + ""; - - var attributeType = elementAttributes.item(x).getAttribute("type"); - if ((attributeType == prefix + ":anyURI") || (attributeType == prefix + ":float") || - (attributeType == prefix + ":decimal") || - (attributeType == prefix + ":double") || - (attributeType == prefix + ":QName") || - (attributeType == prefix + ":base64Binary") || - (attributeType == prefix + ":integer")) { - - // decide what to put as the default value - var defaultVal = ""; - if (mode == "add") { - defaultVal = elementAttributes.item(x).getAttribute("default") - if (defaultVal == undefined) { - defaultVal = attributeType; - } - } else if (mode == "edit") { - // In this case, the default value should be whatever is already there - try { - defaultVal = - targetElement.getAttributes().getNamedItem(attrbuteName).getNodeValue(); - } catch(ex) { - } - } - // Display a Text Box to collect data - uiHTML = - uiHTML + ""; - } else if (attributeType == prefix + ":date") { - // This is a date type. The XML date format is "YYYY-MM-DD" - //todo: Implement with a date-picker component - } - } - } - - // Add the button panel - uiHTML = uiHTML + - "
    " + actionName + - schemaElement.getAttribute("name") + - "
    " + attrbuteName + "
    "; - - if (mode == "add") { - uiHTML = uiHTML + - ""; - } else if (mode == "edit") { - uiHTML = uiHTML + - ""; - } - - uiHTML = uiHTML + "
    "; - - document.getElementById("divPolicyInputGatherer").innerHTML = uiHTML; - - } else { - document.getElementById("divPolicyInputGatherer").innerHTML = - jsi18n["the.element"] + " '" + schemaElement.getAttribute("name") + - "' " + jsi18n["does.not.have.editable.attributes"]; - } -} - -/** - * Updates the current UI target element with inputs from the UI - */ -function updateElementFromUIdata() { - // Collect inputs from UI - var inputTags = document.getElementById("element-attribs").getElementsByTagName("input"); - - // Update the target element - for (var x = 0; x < inputTags.length; x++) { - var attributeName = inputTags[x].id; - var attributeValue = inputTags[x].value; - // Store the attribute in element - currentUITargetElement.setAttribute(attributeName, attributeValue); - } - - // Refresh and sync - syncRawPolicyView(currentPolicyDoc.toString()); - buildTreeView(currentPolicyDoc.toString()); - - CARBON.showInfoDialog(jsi18n["element.updated"]); -} - -/** - * Creates a document element from the data available in the UI - * - * @param elementName - The tag name of the new element - * @param namespaceURI - Namespace URI to use - */ -function createElementFromUIData(elementName, namespaceURI) { - var newXMLElement; - - var inputTags = document.getElementById("element-attribs").getElementsByTagName("input"); - - // Create the element - if (namespaceURI != "") { - var prefix = namespaceMap[namespaceURI]; - - if (prefix == undefined) { - // We need to define a prefix for this URI - prefix = "poled" + Math.floor(Math.random() * 10001); - - newXMLElement = - currentPolicyDoc.createElement(prefix + ":" + elementName); - newXMLElement.setAttribute("xmlns:" + prefix, namespaceURI); - - // Add the new URI to map - namespaceMap[namespaceURI] = prefix; - } else { - newXMLElement = - currentPolicyDoc.createElement(prefix + ":" + elementName); - } - } else { - newXMLElement = - currentPolicyDoc.createElement(elementName); - } - - for (var x = 0; x < inputTags.length; x++) { - var attributeName = inputTags[x].id; - var attributeValue = inputTags[x].value; - // Store the attribute in element - newXMLElement.setAttribute(attributeName, attributeValue); - } - - // Append the new element to the document - currentUITargetElement.appendChild(newXMLElement); - - // Refresh and sync - syncRawPolicyView(currentPolicyDoc.toString()); - buildTreeView(currentPolicyDoc.toString()); - - // Clear UI components - document.getElementById("divPolicyInputGatherer").innerHTML = ""; -} - - -/** - * Loads the schema fragment for a named element - * - * @param elementName - */ -function getSchemaForElement(elementName) { - // searching the element array - for (var x = 0; x < elements.length; x++) { - if (elements[x].schemaElement.getAttribute("name") == elementName) { - return elements[x].schemaElement; - } - } - - // searching the attributes array - for (x = 0; x < attributes.length; x++) { - if (attributes[x].schemaElement.getAttribute("name") == elementName) { - return attributes[x].schemaElement; - } - } - - return null; -} - -/** - * Saves the modified Policy Document using the backend service. - * - */ -var xt="",h3OK=1; -function checkErrorXML(x) { - xt = "" - h3OK = 1 - checkXML(x) -} - -function checkXML(n) -{ - var l,i,nam - nam = n.nodeName - if (nam == "h3") - { - if (h3OK == 0) - { - return; - } - h3OK = 0 - } - if (nam == "#text") - { - xt = xt + n.nodeValue + "\n" - } - l = n.childNodes.length - for (i = 0; i < l; i++) - { - checkXML(n.childNodes[i]) - } -} -function validateXML(txt) -{ - // code for IE - var error = ""; - if (window.ActiveXObject) - { - var xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); - xmlDoc.async = "false"; - xmlDoc.loadXML(txt); - - if (xmlDoc.parseError.errorCode != 0) - { - txt = "Error Code: " + xmlDoc.parseError.errorCode + "\n"; - txt = txt + "Error Reason: " + xmlDoc.parseError.reason; - txt = txt + "Error Line: " + xmlDoc.parseError.line; - error = txt; - } - } - // code for Mozilla, Firefox, Opera, etc. - else if (document.implementation.createDocument) - { - var parser = new DOMParser(); - var text = txt; - var xmlDoc = parser.parseFromString(text, "text/xml"); - - if (xmlDoc.getElementsByTagName("parsererror").length > 0) - { - checkErrorXML(xmlDoc.getElementsByTagName("parsererror")[0]); - error = xt; - } - - } - return error; - -} -function savePolicyXML() { - // Ensure the in memory policy is in sync with the UI - var rawPolicy = editAreaLoader.getValue("raw-policy"); - if (rawPolicy.indexOf("?>") > -1) { - rawPolicy = rawPolicy.substring(rawPolicy.indexOf("?>") + 2); - } - var error = validateXML(rawPolicy); - if(error!=""){ - CARBON.showErrorDialog(error); - return; - } - - var domParser = new DOMImplementation(); - currentPolicyDoc = domParser.loadXML(rawPolicy); - - - // check whether the root policy was removed - if (currentPolicyDoc.getXML() == "") { - CARBON.showErrorDialog(jsi18n["policy.content.blank"]); - } else { - - if (currentPolicyURL != "null") { - var body_xml = '' + - '' + currentPolicyURL + '' + - '' + currentPolicyDoc.toString() + '' + - ''; - - var callURL = serviceBaseURL + "PolicyEditorService"; - - new wso2.wsf.WSRequest(callURL, "savePolicyXML", body_xml, savePolicyXMLCallback); - } else { - postbackUpdatedPolicy(); - } - } -} - -function savePolicyXMLCallback() { - -} - -/** - * POSTs an updated Policy document to a given URL via a dynamically generated Form. - * - */ -function postbackUpdatedPolicy() { - var formEl = document.getElementById("post-back-form"); - var formContentHTML = formEl.innerHTML; - - formEl.innerHTML = - formContentHTML + '' - + ''; - - YAHOO.util.Event.onDOMReady(function() { - document.getElementById("policy-content").value = btoa(currentPolicyDoc.toString()); - document.postbackForm.submit(); - }); - -} - -/** - * Allows the user to return to the page prior to the Policy Editor page. - * - */ -function goBack() { - var redirectURL = document.getElementById("post-back-form").getAttribute("action"); - - cleanBreadCrumb(); - - // Redirecting to the url - location.href = redirectURL; -} - -/** - * Utility function to create a Cookie - * - * @param name - * @param value - * @param days - How many days before the cookie expires - */ -function createCookie(name, value, days) { - if (days) { - var date = new Date(); - date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); - var expires = "; expires=" + date.toGMTString(); - } - else var expires = ""; - document.cookie = name + "=" + value + expires + "; path=/"; -} - -/** - * Utility function to read a cookie value - * - * @param name - */ -function readCookie(name) { - var nameEQ = name + "="; - var ca = document.cookie.split(';'); - for (var i = 0; i < ca.length; i++) { - var c = ca[i]; - while (c.charAt(0) == ' ') c = c.substring(1, c.length); - if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length); - } - return null; -} - -/** - * The breadcome behaves weirdly by showing the proxy page. This function removes that by - * manipulating the breadcrumb cookie. - * - */ -function cleanBreadCrumb() { - // Read the existing breadcrumb value - var breadCrumb = readCookie("current-breadcrumb"); - - // Set the new value after removing policy pages - var newBreadCrumb = breadCrumb.split("*")[0]; - - // Workaround for module management page - var parts = newBreadCrumb.split("%23"); - if (parts.length > 1) { - if (parts[1].indexOf("policy_editor_proxy") > -1) { - newBreadCrumb = parts[0] + "%23"; - } - } - - createCookie("current-breadcrumb", newBreadCrumb); -} - -/** - * Sometimes the ending breadcrumb link is activated, which is unorthodox. - * Killing the last link to prevent it. - * - */ -function disableLastBreadcrumbLink() { - - var breadCrumbLinks = document.getElementById("breadcrumb-div").getElementsByTagName("a"); - for (var x = 0; x < breadCrumbLinks.length; x++) { - var currentLinkText = breadCrumbLinks[x].firstChild.nodeValue; - if (currentLinkText == "Policy") { - breadCrumbLinks[x].href = "#"; - } - } -} -/* javascript prety printing */ -function format_xml(str) -{ - var xml = ''; - - // add newlines - str = str.replace(/(>)(<)(\/*)/g,"$1\r$2$3"); - - // add indents - var pad = 0; - var indent; - var node; - - // split the string - var strArr = str.split("\r"); - - // check the various tag states - for (var i = 0; i < strArr.length; i++) { - indent = 0; - node = strArr[i]; - - if(node.match(/.+<\/\w[^>]*>$/)){ //open and closing in the same line - indent = 0; - } else if(node.match(/^<\/\w/)){ // closing tag - if (pad > 0){pad -= 1;} - } else if (node.match(/^<\w[^>]*[^\/]>.*$/)){ //opening tag - indent = 1; - } else - indent = 0; - //} - - xml += spaces(pad) + node + "\r"; - pad += indent; - } - xml = xml.replace(/(>)/g, ">"); - xml = xml.replace(/(<)/g, "<"); - return xml; -} \ No newline at end of file diff --git a/components/policy-editor/org.wso2.carbon.policyeditor.ui/src/main/resources/web/policyeditor/js/sax-policy-menu.js b/components/policy-editor/org.wso2.carbon.policyeditor.ui/src/main/resources/web/policyeditor/js/sax-policy-menu.js deleted file mode 100644 index 1f2ef78f7524..000000000000 --- a/components/policy-editor/org.wso2.carbon.policyeditor.ui/src/main/resources/web/policyeditor/js/sax-policy-menu.js +++ /dev/null @@ -1,317 +0,0 @@ -/* - * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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. - */ - -var elements = new Array(); // Stores all the document elements - -var attributes = new Array(); // Stores all the document attributes - -// Stores supported types from most commont simple to complex the UI will only support these types. -// A textbox will appear for unsupported types. -var types = new Array(); - -var currentTextNode; // Stores the currently selected tree node, who triggered the menu - -// Holds the target element of the document with which the UI has to work with -var currentUITargetElement = ""; - -var schemaCollection = new Array(); // Temporariliy holds schemas - -// Global variable which holds the context menu -var policyMenu = null; - - -function storeSchema(schemaDefXML) { - schemaCollection[schemaCollection.length] = schemaDefXML; -} - -function buildPolicyMenu() { - - if (policyMenu == null) { - // Clear existing arrays - elements = new Array(); - attributes = new Array(); - types = new Array(); - - // Process all stored schemas - for (var x = 0; x < schemaCollection.length; x++) { - var schemaDefXML = schemaCollection[x] - - // Clearing unnecerssary stuff if present at the beginning - if (schemaDefXML.indexOf("?>") > -1) { - schemaDefXML = schemaDefXML.substring(schemaDefXML.indexOf("?>") + 2); - } - - // instantiate the W3C DOM Parser - var parser = new DOMImplementation(); - - // load the XML into the parser and get the DOMDocument - try { - var domDoc = parser.loadXML(schemaDefXML); - var docRoot = domDoc.getDocumentElement(); - var namespaceURI = getSchemaTargetNamespace(docRoot); - var currentNode = docRoot.firstChild; - - while (currentNode) { - var elementLocalName = currentNode.localName; - - if (elementLocalName != "") { - processNode(currentNode, namespaceURI) - } - - currentNode = currentNode.nextSibling; - } - } catch(e) { - // alert(parser.translateErrCode(e.code)); - } - - } - - // Render the menu with new data - renderPolicyMenu(); - } -} - -function getSchemaTargetNamespace(documentRoot) { - return documentRoot.getAttributes().getNamedItem("targetNamespace").getNodeValue().toString(); -} - -function processNode(node, namespaceURI) { - var nodeName = node.localName; - - var menuElement = {name: nodeName, namespace: namespaceURI, schemaElement: node}; - - if (nodeName == "element") { - elements[elements.length] = menuElement; - } else if (nodeName == "attribute") { - attributes[attributes.length] = menuElement; - } else if (nodeName == "complexType") { - types[types.length] = menuElement; - } -} - -function renderPolicyMenu() { - - var menuRootItems = new Array(); - var submenuElements = new Array(); - var submenuAttributes = new Array(); - - // Process Elements - for (var x = 0; x < elements.length; x++) { - // creating the JSON object for this menu item - var elMenuItem = { - text: '\"' + elements[x].schemaElement.getAttribute("name") + '\"', - onclick: { fn: renderInputGatherer, obj: [elements[x].schemaElement, elements[x].namespace] } - }; - submenuElements[submenuElements.length] = elMenuItem; - } - //Creating the Elements sub-menu - var elSubMenu = { - text: jsi18n["add.policy.element"], - url: "#add-element", - submenu: { - id: "elements", - itemdata: submenuElements - } - }; - // adding to root menu - menuRootItems[menuRootItems.length] = elSubMenu; - - // Process Attributes - for (x = 0; x < attributes.length; x++) { - // creating the JSON object for this menu item - var elAttributeItem = { - text: '\"' + attributes[x].schemaElement.getAttribute("name") + '\"', - onclick: { fn: renderInputGatherer, obj: [attributes[x].schemaElement, attributes[x].namespace ] } - } - submenuAttributes[submenuAttributes.length] = elAttributeItem; - } - //Creating the Elements sub-menu - var atSubMenu = { - text: jsi18n["add.policy.attribute"], - url: "#add-attribute", - submenu: { - id: "attributes", - itemdata: submenuAttributes - } - }; - // adding to root menu - menuRootItems[menuRootItems.length] = atSubMenu; - - // Adding the delete menu option - var deleteNode = { - text: jsi18n["delete.this.element"], - onclick: { fn: deletePolicyElement } - }; - menuRootItems[menuRootItems.length] = deleteNode; - - policyMenu = new YAHOO.widget.ContextMenu("policy-menu", { - trigger: "divPolicyDocTree", - container: "tab2", // This property has to be set to a parent div, other than the treeview container div for IE to render properly - itemdata: menuRootItems, - lazyload: true - }); - - /* - Subscribe to the "contextmenu" event for the element(s) - specified as the "trigger" for the ContextMenu instance. - */ - policyMenu.subscribe("triggerContextMenu", onTriggerContextMenu); -} - -/* - "contextmenu" event handler for the element(s) that - triggered the display of the ContextMenu instance - used - to set a reference to the TextNode instance that triggered - the display of the ContextMenu instance. -*/ -function onTriggerContextMenu(p_oEvent) { - - var oTarget = this.contextEventTarget, - Dom = YAHOO.util.Dom; - - /* - Get the TextNode instance that that triggered the - display of the ContextMenu instance. - */ - var oTextNode = Dom.hasClass(oTarget, "ygtvlabel") ? - oTarget : Dom.getAncestorByClassName(oTarget, "ygtvlabel"); - - if (oTextNode) { - currentTextNode = textNodeMap[oTarget.id]; - } - else { - // Cancel the display of the ContextMenu instance. - this.cancel(); - } -} - -function deletePolicyElement(p_sType, p_aArgs, p_oValue) { - - //todo add verification before deleting elements - - var docRoot = currentPolicyDoc.getDocumentElement(); - var results = docRoot.getElementsByTagName(currentTextNode.label); - - var targetElement = results.item(0); - if (results.length > 1) { - // If there are more than one element, we need to figure out which one of these elements - // is the correct element using XPath - targetElement = isolateTargetElement(results, currentTextNode.xpath); - } - - if (targetElement != null) { - targetElement.getParentNode().removeChild(targetElement); - syncRawPolicyView(currentPolicyDoc.toString()) - buildTreeView(currentPolicyDoc.toString()); - } - -} - -function renderInputGatherer(p_sType, p_aArgs, p_oValue) { - // Clear existing ui elements - document.getElementById("divPolicyInputGatherer").innerHTML = ""; - - var schemaElement = p_oValue[0]; - var namespaceURI = p_oValue[1]; - - var newXMLElement; - - var docRoot = currentPolicyDoc.getDocumentElement(); - var results = docRoot.getElementsByTagName(currentTextNode.label); - - var targetElement = results.item(0); - if (results.length > 1) { - // If there are more than one element, we need to figure out which one of these elements - // is the correct element using XPath - targetElement = isolateTargetElement(results, currentTextNode.xpath); - } - - if (targetElement != null) { - - if (schemaElement.getElementsByTagName(schemaElement.prefix + ":attribute").length == 0) { - // This is just a wrapper element no input from the user is required - if (namespaceURI != "") { - var prefix = namespaceMap[namespaceURI]; - - if (prefix == undefined) { - // We need to define a prefix for this URI - prefix = "poled" + Math.floor(Math.random() * 10001); - - newXMLElement = - currentPolicyDoc.createElement(prefix + ":" + - schemaElement.getAttribute("name")); - newXMLElement.setAttribute("xmlns:" + prefix, namespaceURI); - - // Add the new URI to map - namespaceMap[namespaceURI] = prefix; - } else { - newXMLElement = - currentPolicyDoc.createElement(prefix + ":" + - schemaElement.getAttribute("name")); - } - } else { - newXMLElement = - currentPolicyDoc.createElement(schemaElement.getAttribute("name")); - } - - targetElement.appendChild(newXMLElement); - syncRawPolicyView(currentPolicyDoc.toString()) - buildTreeView(currentPolicyDoc.toString()); - } else { - // This needs a ui to get input. Calling the big guns - generateGathererUI(targetElement, schemaElement, namespaceURI, "add"); - } - } -} - - -function isolateTargetElement(elementsList, targetXPath) { - for (var x = 0; x < elementsList.length; x++) { - if (getElementXPath(elementsList.item(x)) == targetXPath) { - return elementsList.item(x); - } - } - - return null; -} - -function getElementXPath(elt) -{ - var path = ""; - for (; elt && elt.nodeType == 1; elt = elt.parentNode) - { - var idx = getElementIdx(elt); - var xname = elt.tagName; - if (idx > 1) xname += "[" + idx + "]"; - path = "/" + xname + path; - } - - return path; -} - -function getElementIdx(elt) -{ - var count = 1; - for (var sib = elt.previousSibling; sib; sib = sib.previousSibling) - { - if (sib.nodeType == 1 && sib.tagName == elt.tagName) count++ - } - - return count; -} - diff --git a/components/policy-editor/org.wso2.carbon.policyeditor.ui/src/main/resources/web/policyeditor/js/sax-tree.js b/components/policy-editor/org.wso2.carbon.policyeditor.ui/src/main/resources/web/policyeditor/js/sax-tree.js deleted file mode 100644 index 00cacbb87fd2..000000000000 --- a/components/policy-editor/org.wso2.carbon.policyeditor.ui/src/main/resources/web/policyeditor/js/sax-tree.js +++ /dev/null @@ -1,335 +0,0 @@ -/* - * Copyright (c) 2006, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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. - */ - -var xmlTextArray; -var xmlCDataArray; -var xmlAttrArray; -var xmlPathArray; -var xmlCMENTArray; - -// create tree root node -var policyTree; - -// Curent node to which the elements are added while parsing -var currentNode; - -var textNodeMap = {}; - -var currentPolicyDoc; - -var namespaceMap = {}; // Holds all the namespace URIs mapped to prefixes found on this document - -function buildTreeView(policyXML) { - - try { - namespaceMap = {}; - var domParser = new DOMImplementation(); - - // First storing the policyXML globally - currentPolicyDoc = domParser.loadXML(policyXML); - - var parser = new SAXDriver(); - - // pass handlers to the sax2 parser - var handler = new xmlHandler(); - parser.setDocumentHandler(handler); - parser.setErrorHandler(handler); - parser.setLexicalHandler(handler); - - // Creating the tree - policyTree = new YAHOO.widget.TreeView("divPolicyDocTree"); - - // Subscribing to the click event - policyTree.subscribe("labelClick", function(node) { - currentTextNode = node; - editPolicyElement(); - }); - - // start parsing - parser.parse(policyXML); - - // get errors from sax2 parser - var err = handler.getError(); - if (!err) { - // stores node element info in arrays - xmlTextArray = handler.getText_Array(); - xmlCDataArray = handler.getCDATA_Array(); - xmlAttrArray = handler.getAttr_Array(); - xmlPathArray = handler.getPath_Array(); - xmlCMENTArray = handler.getCMENT_Array(); - } else { - // alert(err); - CARBON.showErrorDialog(e); - } - } catch(e) { - // alert(domParser.translateErrCode(e.code)); - } -} - -function editPolicyElement() { - // Extract the element from the document - var selectedElement = isolateTargetElement(currentPolicyDoc.getElementsByTagName(currentTextNode.label), currentTextNode.xpath); - - // find the template schema element matching this element from elements and attributes arrays - var elementLocalName = currentTextNode.label; - if (elementLocalName.indexOf(":") > -1) { - elementLocalName = elementLocalName.substring(elementLocalName.indexOf(":") + 1); - } - - var correspondingSchemaElement = getSchemaForElement(elementLocalName); - if (correspondingSchemaElement == null) { - // Not supported - document.getElementById("divPolicyInputGatherer").innerHTML = jsi18n["sorry.editing.not.supported"]; - } else { - - // Find the namespace uri of the target element - var elementNamespaceURI = selectedElement.getNamespaceURI(); - - // Display the UI to gathe inputs - generateGathererUI(selectedElement, correspondingSchemaElement, elementNamespaceURI, "edit"); - } -} - -function showTagInfo(id) { - var src = '' - - // get Text, Comment and CDATA information - if (xmlTextArray[id]) { - src += 'TEXT: \n' + (xmlTextArray[id] || '') + '\n'; - } - - if (xmlCMENTArray[id]) { - src += 'COMMENT:\n ' + (xmlCMENTArray[id] || '') + '\n\n'; - } - - if (xmlCDataArray[id]) { - src += 'CDATA:\n ' + (xmlCDataArray[id] || '') + '\n\n'; - } - - // get attribute info - if (xmlAttrArray[id]) { - var arr = xmlAttrArray[id]; - var atts = ''; - for (var i in arr) { - // name = value - atts += i + '=' + arr[i] + '\n'; - } - src += 'ATTRIBUTES:\n ' + atts; - } - - // display node info - // alert('NODE: ' + xmlPathArray[id] + '\n\n' + src); - CARBON.showErrorDialog('NODE: ' + xmlPathArray[id] + '\n\n' + src); - -} - -var xmlHandler = function() { - this.m_strError = ''; - this.m_treeNodes = []; // stores nodes - this.m_treePaths = []; // stores path info - this.m_xPath = ['']; // stores current path info - this.m_text = ['']; // stores node text info - this.m_cdata = ['']; // stores node cdata info - this.m_comment = ['']; // stores node comment info - this.m_attr = ['']; // stores node attribute info - this.m_pi = ['']; // store pi info - not used - this.cdata = false; - this.curpath = ''; - this.cnt = 0; - -} - -xmlHandler.prototype.characters = function(data, start, length) { - // capture characters from CDATA and Text entities - var text = data.substr(start, length); - if (text == '\n') { - return null // get ride of blank text lines - } - - if (this.m_treeNodes[this.m_xPath.join('/')]) { - if (!this.cdata) { - if (!this.m_text[this.cnt]) { - this.m_text[this.cnt] = ''; - } - this.m_text[this.cnt] += text; - } - else { - if (!this.m_cdata[this.cnt]) { - this.m_cdata[this.cnt] = ''; - } - this.m_cdata[this.cnt] += text; - } - } -} - -xmlHandler.prototype.comment = function(data, start, length) { - this.m_comment[this.cnt] = data.substr(start, length); -} - - -xmlHandler.prototype.endCDATA = function() { - // end of CDATA entity - this.cdata = false; - -} - -xmlHandler.prototype.endDocument = function() { - // Draw the tree to canvas - policyTree.draw(); - - // Retrieve schemas from the back-end and build the policy menu - getPolicSchemaDefs(); - - // Expand the tree - policyTree.expandAll(); -} - - -xmlHandler.prototype.endElement = function(name) { - this.m_xPath = this.m_xPath.slice(0, -1); -} - -xmlHandler.prototype.error = function(exception) { - this.m_strError += 'Error:' + exception.getMessage() + '\n'; -} - -xmlHandler.prototype.fatalError = function(exception) { - this.m_strError += 'fata error:' + exception.getMessage() + '\n'; -} - -xmlHandler.prototype.getAttr_Array = function() { - return this.m_attr; -} - - -xmlHandler.prototype.getCDATA_Array = function() { - return this.m_cdata; -} - - -xmlHandler.prototype.getCMENT_Array = function() { - return this.m_comment; -} - -xmlHandler.prototype.getError = function() { - return this.m_strError; -} - -xmlHandler.prototype.getPath_Array = function() { - return this.m_treePaths; -} - - -xmlHandler.prototype.getText_Array = function() { - return this.m_text; -} - -xmlHandler.prototype.processingInstruction = function(target, data) { - -} - - -xmlHandler.prototype.setDocumentLocator = function(locator) { - this.m_locator = locator; -} - - -xmlHandler.prototype.startCDATA = function() { - this.cdata = true; -} - -xmlHandler.prototype.startDocument = function() { - -} - -xmlHandler.prototype.startElement = function(name, atts) { - // Note: the following code is used to store info about the node - // into arrays for use in the tree node layout - - var ppath; - var att_count = atts.getLength(); - var pnode; - var node; - - // get previous path - ppath = this.m_xPath.join('/'); - if (!ppath) ppath = "/"; - // get current path - this.m_xPath[this.m_xPath.length] = name; - this.curpath = this.m_xPath.join('/'); - - this.cnt++; - this.m_treePaths[this.cnt] = this.curpath; - - pnode = this.m_treeNodes[ppath]; - if (!pnode) { - var root = policyTree.getRoot(); - var nodeObj = { label: name, href:"#" }; - pnode = new YAHOO.widget.TextNode(nodeObj, root, false); - pnode.xpath = ppath; - - this.m_treeNodes[this.curpath] = pnode; - - // Adding this node to the map - textNodeMap[pnode.labelElId] = pnode; - - if ((currentTextNode != undefined) && (pnode.xpath == currentTextNode.xpath)) { - currentTextNode = node; - } - } - else { - nodeObj = { label: name, href:"#" }; - node = new YAHOO.widget.TextNode(nodeObj, pnode, false); - node.xpath = this.curpath; - - this.m_treeNodes[this.curpath] = node; - - // Adding this node to the map - textNodeMap[node.labelElId] = node; - - if ((currentTextNode != undefined) && (node.xpath == currentTextNode.xpath)) { - currentTextNode = node; - } - } - - // get attributes - if (att_count) { - var attr = []; - for (var i = 0; i < att_count; i++) { - attr[atts.getName(i)] = atts.getValue(i); - // Check attributes for namespaces - processAttribute(atts.getName(i), atts.getValue(i)); - } - this.m_attr[this.cnt] = attr; - } - - -} - -xmlHandler.prototype.warning = function(exception) { - this.m_strError += 'Warning:' + exception.getMessage() + '\n'; -} - -function processAttribute(attName, value) { - var idx = attName.indexOf("xmlns:"); - if (idx > -1) { - // This is an xml namespace - var prefix = attName.split(":")[1]; - namespaceMap[value.toString()] = prefix; - } -} diff --git a/components/policy-editor/org.wso2.carbon.policyeditor.ui/src/main/resources/web/policyeditor/js/xml-for-script/tinyxmlsax.js b/components/policy-editor/org.wso2.carbon.policyeditor.ui/src/main/resources/web/policyeditor/js/xml-for-script/tinyxmlsax.js deleted file mode 100755 index 1e0cc73ce4ee..000000000000 --- a/components/policy-editor/org.wso2.carbon.policyeditor.ui/src/main/resources/web/policyeditor/js/xml-for-script/tinyxmlsax.js +++ /dev/null @@ -1,245 +0,0 @@ -// ========================================================================= -// -// tinyxmlsax.js - an XML SAX parser in JavaScript compressed for downloading -// -// version 3.1 -// -// ========================================================================= -// -// Copyright (C) 2000 - 2002, 2003 Michael Houghton (mike@idle.org), Raymond Irving and David Joham (djoham@yahoo.com) -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. - -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. - -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// Visit the XML for "; - Q.src = "data:text/html;charset=utf-8," + encodeURIComponent(S); - } - Q.id = "_yuiResizeMonitor"; - Q.style.position = "absolute"; - Q.style.visibility = "hidden"; - var R = document.body.firstChild; - if (R) { - document.body.insertBefore(Q, R); - } else { - document.body.appendChild(Q); - } - Q.style.width = "10em"; - Q.style.height = "10em"; - Q.style.top = (-1 * Q.offsetHeight) + "px"; - Q.style.left = (-1 * Q.offsetWidth) + "px"; - Q.style.borderWidth = "0"; - Q.style.visibility = "visible"; - if (YAHOO.env.ua.webkit) { - P = Q.contentWindow.document; - P.open(); - P.close(); - } - } - if (Q && Q.contentWindow) { - G.textResizeEvent.subscribe(this.onDomResize, this, true); - if (!G.textResizeInitialized) { - if (!M.on(Q.contentWindow, "resize", T)) { - M.on(Q, "resize", T); - } - G.textResizeInitialized = true; - } - this.resizeMonitor = Q; - } - } - },onDomResize:function(S, R) { - var Q = -1 * this.resizeMonitor.offsetWidth,P = -1 * this.resizeMonitor.offsetHeight; - this.resizeMonitor.style.top = P + "px"; - this.resizeMonitor.style.left = Q + "px"; - },setHeader:function(Q) { - var P = this.header || (this.header = J()); - if (typeof Q == "string") { - P.innerHTML = Q; - } else { - P.innerHTML = ""; - P.appendChild(Q); - } - this.changeHeaderEvent.fire(Q); - this.changeContentEvent.fire(); - },appendToHeader:function(Q) { - var P = this.header || (this.header = J()); - P.appendChild(Q); - this.changeHeaderEvent.fire(Q); - this.changeContentEvent.fire(); - },setBody:function(Q) { - var P = this.body || (this.body = B()); - if (typeof Q == "string") { - P.innerHTML = Q; - } else { - P.innerHTML = ""; - P.appendChild(Q); - } - this.changeBodyEvent.fire(Q); - this.changeContentEvent.fire(); - },appendToBody:function(Q) { - var P = this.body || (this.body = B()); - P.appendChild(Q); - this.changeBodyEvent.fire(Q); - this.changeContentEvent.fire(); - },setFooter:function(Q) { - var P = this.footer || (this.footer = C()); - if (typeof Q == "string") { - P.innerHTML = Q; - } else { - P.innerHTML = ""; - P.appendChild(Q); - } - this.changeFooterEvent.fire(Q); - this.changeContentEvent.fire(); - },appendToFooter:function(Q) { - var P = this.footer || (this.footer = C()); - P.appendChild(Q); - this.changeFooterEvent.fire(Q); - this.changeContentEvent.fire(); - },render:function(R, P) { - var S = this,T; - function Q(U) { - if (typeof U == "string") { - U = document.getElementById(U); - } - if (U) { - S._addToParent(U, S.element); - S.appendEvent.fire(); - } - } - this.beforeRenderEvent.fire(); - if (!P) { - P = this.element; - } - if (R) { - Q(R); - } else { - if (!F.inDocument(this.element)) { - return false; - } - } - if (this.header && !F.inDocument(this.header)) { - T = P.firstChild; - if (T) { - P.insertBefore(this.header, T); - } else { - P.appendChild(this.header); - } - } - if (this.body && !F.inDocument(this.body)) { - if (this.footer && F.isAncestor(this.moduleElement, this.footer)) { - P.insertBefore(this.body, this.footer); - } else { - P.appendChild(this.body); - } - } - if (this.footer && !F.inDocument(this.footer)) { - P.appendChild(this.footer); - } - this.renderEvent.fire(); - return true; - },destroy:function() { - var P,Q; - if (this.element) { - M.purgeElement(this.element, true); - P = this.element.parentNode; - } - if (P) { - P.removeChild(this.element); - } - this.element = null; - this.header = null; - this.body = null; - this.footer = null; - G.textResizeEvent.unsubscribe(this.onDomResize, this); - this.cfg.destroy(); - this.cfg = null; - this.destroyEvent.fire(); - for (Q in this) { - if (Q instanceof L) { - Q.unsubscribeAll(); - } - } - },show:function() { - this.cfg.setProperty("visible", true); - },hide:function() { - this.cfg.setProperty("visible", false); - },configVisible:function(Q, P, R) { - var S = P[0]; - if (S) { - this.beforeShowEvent.fire(); - F.setStyle(this.element, "display", "block"); - this.showEvent.fire(); - } else { - this.beforeHideEvent.fire(); - F.setStyle(this.element, "display", "none"); - this.hideEvent.fire(); - } - },configMonitorResize:function(R, Q, S) { - var P = Q[0]; - if (P) { - this.initResizeMonitor(); - } else { - G.textResizeEvent.unsubscribe(this.onDomResize, this, true); - this.resizeMonitor = null; - } - },_addToParent:function(P, Q) { - if (!this.cfg.getProperty("appendtodocumentbody") && P === document.body && P.firstChild) { - P.insertBefore(Q, P.firstChild); - } else { - P.appendChild(Q); - } - },toString:function() { - return"Module " + this.id; - }}; - YAHOO.lang.augmentProto(G, YAHOO.util.EventProvider); -}()); -(function() { - YAHOO.widget.Overlay = function(L, K) { - YAHOO.widget.Overlay.superclass.constructor.call(this, L, K); - }; - var F = YAHOO.lang,I = YAHOO.util.CustomEvent,E = YAHOO.widget.Module,J = YAHOO.util.Event,D = YAHOO.util.Dom,C = YAHOO.util.Config,B = YAHOO.widget.Overlay,G,A = {"BEFORE_MOVE":"beforeMove","MOVE":"move"},H = {"X":{key:"x",validator:F.isNumber,suppressEvent:true,supercedes:["iframe"]},"Y":{key:"y",validator:F.isNumber,suppressEvent:true,supercedes:["iframe"]},"XY":{key:"xy",suppressEvent:true,supercedes:["iframe"]},"CONTEXT":{key:"context",suppressEvent:true,supercedes:["iframe"]},"FIXED_CENTER":{key:"fixedcenter",value:false,validator:F.isBoolean,supercedes:["iframe","visible"]},"WIDTH":{key:"width",suppressEvent:true,supercedes:["context","fixedcenter","iframe"]},"HEIGHT":{key:"height",suppressEvent:true,supercedes:["context","fixedcenter","iframe"]},"ZINDEX":{key:"zindex",value:null},"CONSTRAIN_TO_VIEWPORT":{key:"constraintoviewport",value:false,validator:F.isBoolean,supercedes:["iframe","x","y","xy"]},"IFRAME":{key:"iframe",value:( - YAHOO.env.ua.ie == 6 ? true : false),validator:F.isBoolean,supercedes:["zindex"]}}; - B.IFRAME_SRC = "javascript:false;"; - B.IFRAME_OFFSET = 3; - B.TOP_LEFT = "tl"; - B.TOP_RIGHT = "tr"; - B.BOTTOM_LEFT = "bl"; - B.BOTTOM_RIGHT = "br"; - B.CSS_OVERLAY = "yui-overlay"; - B.windowScrollEvent = new I("windowScroll"); - B.windowResizeEvent = new I("windowResize"); - B.windowScrollHandler = function(K) { - if (YAHOO.env.ua.ie) { - if (!window.scrollEnd) { - window.scrollEnd = -1; - } - clearTimeout(window.scrollEnd); - window.scrollEnd = setTimeout(function() { - B.windowScrollEvent.fire(); - }, 1); - } else { - B.windowScrollEvent.fire(); - } - }; - B.windowResizeHandler = function(K) { - if (YAHOO.env.ua.ie) { - if (!window.resizeEnd) { - window.resizeEnd = -1; - } - clearTimeout(window.resizeEnd); - window.resizeEnd = setTimeout(function() { - B.windowResizeEvent.fire(); - }, 100); - } else { - B.windowResizeEvent.fire(); - } - }; - B._initialized = null; - if (B._initialized === null) { - J.on(window, "scroll", B.windowScrollHandler); - J.on(window, "resize", B.windowResizeHandler); - B._initialized = true; - } - YAHOO.extend(B, E, {init:function(L, K) { - B.superclass.init.call(this, L); - this.beforeInitEvent.fire(B); - D.addClass(this.element, B.CSS_OVERLAY); - if (K) { - this.cfg.applyConfig(K, true); - } - if (this.platform == "mac" && YAHOO.env.ua.gecko) { - if (!C.alreadySubscribed(this.showEvent, this.showMacGeckoScrollbars, this)) { - this.showEvent.subscribe(this.showMacGeckoScrollbars, this, true); - } - if (!C.alreadySubscribed(this.hideEvent, this.hideMacGeckoScrollbars, this)) { - this.hideEvent.subscribe(this.hideMacGeckoScrollbars, this, true); - } - } - this.initEvent.fire(B); - },initEvents:function() { - B.superclass.initEvents.call(this); - var K = I.LIST; - this.beforeMoveEvent = this.createEvent(A.BEFORE_MOVE); - this.beforeMoveEvent.signature = K; - this.moveEvent = this.createEvent(A.MOVE); - this.moveEvent.signature = K; - },initDefaultConfig:function() { - B.superclass.initDefaultConfig.call(this); - this.cfg.addProperty(H.X.key, {handler:this.configX,validator:H.X.validator,suppressEvent:H.X.suppressEvent,supercedes:H.X.supercedes}); - this.cfg.addProperty(H.Y.key, {handler:this.configY,validator:H.Y.validator,suppressEvent:H.Y.suppressEvent,supercedes:H.Y.supercedes}); - this.cfg.addProperty(H.XY.key, {handler:this.configXY,suppressEvent:H.XY.suppressEvent,supercedes:H.XY.supercedes}); - this.cfg.addProperty(H.CONTEXT.key, {handler:this.configContext,suppressEvent:H.CONTEXT.suppressEvent,supercedes:H.CONTEXT.supercedes}); - this.cfg.addProperty(H.FIXED_CENTER.key, {handler:this.configFixedCenter,value:H.FIXED_CENTER.value,validator:H.FIXED_CENTER.validator,supercedes:H.FIXED_CENTER.supercedes}); - this.cfg.addProperty(H.WIDTH.key, {handler:this.configWidth,suppressEvent:H.WIDTH.suppressEvent,supercedes:H.WIDTH.supercedes}); - this.cfg.addProperty(H.HEIGHT.key, {handler:this.configHeight,suppressEvent:H.HEIGHT.suppressEvent,supercedes:H.HEIGHT.supercedes}); - this.cfg.addProperty(H.ZINDEX.key, {handler:this.configzIndex,value:H.ZINDEX.value}); - this.cfg.addProperty(H.CONSTRAIN_TO_VIEWPORT.key, {handler:this.configConstrainToViewport,value:H.CONSTRAIN_TO_VIEWPORT.value,validator:H.CONSTRAIN_TO_VIEWPORT.validator,supercedes:H.CONSTRAIN_TO_VIEWPORT.supercedes}); - this.cfg.addProperty(H.IFRAME.key, {handler:this.configIframe,value:H.IFRAME.value,validator:H.IFRAME.validator,supercedes:H.IFRAME.supercedes}); - },moveTo:function(K, L) { - this.cfg.setProperty("xy", [K,L]); - },hideMacGeckoScrollbars:function() { - D.removeClass(this.element, "show-scrollbars"); - D.addClass(this.element, "hide-scrollbars"); - },showMacGeckoScrollbars:function() { - D.removeClass(this.element, "hide-scrollbars"); - D.addClass(this.element, "show-scrollbars"); - },configVisible:function(N, K, T) { - var M = K[0],O = D.getStyle(this.element, "visibility"),U = this.cfg.getProperty("effect"),R = [],Q = (this.platform == - "mac" && - YAHOO.env.ua.gecko),b = C.alreadySubscribed,S,L,a,Y,X,W,Z,V,P; - if (O == "inherit") { - a = this.element.parentNode; - while (a.nodeType != 9 && a.nodeType != 11) { - O = D.getStyle(a, "visibility"); - if (O != "inherit") { - break; - } - a = a.parentNode; - } - if (O == "inherit") { - O = "visible"; - } - } - if (U) { - if (U instanceof Array) { - V = U.length; - for (Y = 0; Y < V; Y++) { - S = U[Y]; - R[R.length] = S.effect(this, S.duration); - } - } else { - R[R.length] = U.effect(this, U.duration); - } - } - if (M) { - if (Q) { - this.showMacGeckoScrollbars(); - } - if (U) { - if (M) { - if (O != "visible" || O === "") { - this.beforeShowEvent.fire(); - P = R.length; - for (X = 0; X < P; X++) { - L = R[X]; - if (X === 0 && - !b(L.animateInCompleteEvent, this.showEvent.fire, this.showEvent)) { - L.animateInCompleteEvent.subscribe(this.showEvent.fire, this.showEvent, true); - } - L.animateIn(); - } - } - } - } else { - if (O != "visible" || O === "") { - this.beforeShowEvent.fire(); - D.setStyle(this.element, "visibility", "visible"); - this.cfg.refireEvent("iframe"); - this.showEvent.fire(); - } - } - } else { - if (Q) { - this.hideMacGeckoScrollbars(); - } - if (U) { - if (O == "visible") { - this.beforeHideEvent.fire(); - P = R.length; - for (W = 0; W < P; W++) { - Z = R[W]; - if (W === 0 && - !b(Z.animateOutCompleteEvent, this.hideEvent.fire, this.hideEvent)) { - Z.animateOutCompleteEvent.subscribe(this.hideEvent.fire, this.hideEvent, true); - } - Z.animateOut(); - } - } else { - if (O === "") { - D.setStyle(this.element, "visibility", "hidden"); - } - } - } else { - if (O == "visible" || O === "") { - this.beforeHideEvent.fire(); - D.setStyle(this.element, "visibility", "hidden"); - this.hideEvent.fire(); - } - } - } - },doCenterOnDOMEvent:function() { - if (this.cfg.getProperty("visible")) { - this.center(); - } - },configFixedCenter:function(O, M, P) { - var Q = M[0],L = C.alreadySubscribed,N = B.windowResizeEvent,K = B.windowScrollEvent; - if (Q) { - this.center(); - if (!L(this.beforeShowEvent, this.center, this)) { - this.beforeShowEvent.subscribe(this.center); - } - if (!L(N, this.doCenterOnDOMEvent, this)) { - N.subscribe(this.doCenterOnDOMEvent, this, true); - } - if (!L(K, this.doCenterOnDOMEvent, this)) { - K.subscribe(this.doCenterOnDOMEvent, this, true); - } - } else { - this.beforeShowEvent.unsubscribe(this.center); - N.unsubscribe(this.doCenterOnDOMEvent, this); - K.unsubscribe(this.doCenterOnDOMEvent, this); - } - },configHeight:function(N, L, O) { - var K = L[0],M = this.element; - D.setStyle(M, "height", K); - this.cfg.refireEvent("iframe"); - },configWidth:function(N, K, O) { - var M = K[0],L = this.element; - D.setStyle(L, "width", M); - this.cfg.refireEvent("iframe"); - },configzIndex:function(M, K, N) { - var O = K[0],L = this.element; - if (!O) { - O = D.getStyle(L, "zIndex"); - if (!O || isNaN(O)) { - O = 0; - } - } - if (this.iframe || this.cfg.getProperty("iframe") === true) { - if (O <= 0) { - O = 1; - } - } - D.setStyle(L, "zIndex", O); - this.cfg.setProperty("zIndex", O, true); - if (this.iframe) { - this.stackIframe(); - } - },configXY:function(M, L, N) { - var P = L[0],K = P[0],O = P[1]; - this.cfg.setProperty("x", K); - this.cfg.setProperty("y", O); - this.beforeMoveEvent.fire([K,O]); - K = this.cfg.getProperty("x"); - O = this.cfg.getProperty("y"); - this.cfg.refireEvent("iframe"); - this.moveEvent.fire([K,O]); - },configX:function(M, L, N) { - var K = L[0],O = this.cfg.getProperty("y"); - this.cfg.setProperty("x", K, true); - this.cfg.setProperty("y", O, true); - this.beforeMoveEvent.fire([K,O]); - K = this.cfg.getProperty("x"); - O = this.cfg.getProperty("y"); - D.setX(this.element, K, true); - this.cfg.setProperty("xy", [K,O], true); - this.cfg.refireEvent("iframe"); - this.moveEvent.fire([K,O]); - },configY:function(M, L, N) { - var K = this.cfg.getProperty("x"),O = L[0]; - this.cfg.setProperty("x", K, true); - this.cfg.setProperty("y", O, true); - this.beforeMoveEvent.fire([K,O]); - K = this.cfg.getProperty("x"); - O = this.cfg.getProperty("y"); - D.setY(this.element, O, true); - this.cfg.setProperty("xy", [K,O], true); - this.cfg.refireEvent("iframe"); - this.moveEvent.fire([K,O]); - },showIframe:function() { - var L = this.iframe,K; - if (L) { - K = this.element.parentNode; - if (K != L.parentNode) { - this._addToParent(K, L); - } - L.style.display = "block"; - } - },hideIframe:function() { - if (this.iframe) { - this.iframe.style.display = "none"; - } - },syncIframe:function() { - var K = this.iframe,M = this.element,O = B.IFRAME_OFFSET,L = (O * 2),N; - if (K) { - K.style.width = (M.offsetWidth + L + "px"); - K.style.height = (M.offsetHeight + L + "px"); - N = this.cfg.getProperty("xy"); - if (!F.isArray(N) || (isNaN(N[0]) || isNaN(N[1]))) { - this.syncPosition(); - N = this.cfg.getProperty("xy"); - } - D.setXY(K, [(N[0] - O),(N[1] - O)]); - } - },stackIframe:function() { - if (this.iframe) { - var K = D.getStyle(this.element, "zIndex"); - if (!YAHOO.lang.isUndefined(K) && !isNaN(K)) { - D.setStyle(this.iframe, "zIndex", (K - 1)); - } - } - },configIframe:function(N, M, O) { - var K = M[0]; - function P() { - var R = this.iframe,S = this.element,U,T; - if (!R) { - if (!G) { - G = document.createElement("iframe"); - if (this.isSecure) { - G.src = B.IFRAME_SRC; - } - if (YAHOO.env.ua.ie) { - G.style.filter = "alpha(opacity=0)"; - G.frameBorder = 0; - } else { - G.style.opacity = "0"; - } - G.style.position = "absolute"; - G.style.border = "none"; - G.style.margin = "0"; - G.style.padding = "0"; - G.style.display = "none"; - } - R = G.cloneNode(false); - U = S.parentNode; - var Q = U || document.body; - this._addToParent(Q, R); - this.iframe = R; - } - this.showIframe(); - this.syncIframe(); - this.stackIframe(); - if (!this._hasIframeEventListeners) { - this.showEvent.subscribe(this.showIframe); - this.hideEvent.subscribe(this.hideIframe); - this.changeContentEvent.subscribe(this.syncIframe); - this._hasIframeEventListeners = true; - } - } - function L() { - P.call(this); - this.beforeShowEvent.unsubscribe(L); - this._iframeDeferred = false; - } - if (K) { - if (this.cfg.getProperty("visible")) { - P.call(this); - } else { - if (!this._iframeDeferred) { - this.beforeShowEvent.subscribe(L); - this._iframeDeferred = true; - } - } - } else { - this.hideIframe(); - if (this._hasIframeEventListeners) { - this.showEvent.unsubscribe(this.showIframe); - this.hideEvent.unsubscribe(this.hideIframe); - this.changeContentEvent.unsubscribe(this.syncIframe); - this._hasIframeEventListeners = false; - } - } - },configConstrainToViewport:function(L, K, M) { - var N = K[0]; - if (N) { - if (!C.alreadySubscribed(this.beforeMoveEvent, this.enforceConstraints, this)) { - this.beforeMoveEvent.subscribe(this.enforceConstraints, this, true); - } - } else { - this.beforeMoveEvent.unsubscribe(this.enforceConstraints, this); - } - },configContext:function(M, L, O) { - var Q = L[0],N,P,K; - if (Q) { - N = Q[0]; - P = Q[1]; - K = Q[2]; - if (N) { - if (typeof N == "string") { - this.cfg.setProperty("context", [document.getElementById(N),P,K], true); - } - if (P && K) { - this.align(P, K); - } - } - } - },align:function(L, K) { - var Q = this.cfg.getProperty("context"),P = this,O,N,R; - function M(S, T) { - switch (L) {case B.TOP_LEFT:P.moveTo(T, S);break;case B.TOP_RIGHT:P.moveTo((T - - N.offsetWidth), S);break;case B.BOTTOM_LEFT:P.moveTo(T, (S - - N.offsetHeight));break;case B.BOTTOM_RIGHT:P.moveTo((T - - N.offsetWidth), (S - - N.offsetHeight));break;} - } - if (Q) { - O = Q[0]; - N = this.element; - P = this; - if (!L) { - L = Q[1]; - } - if (!K) { - K = Q[2]; - } - if (N && O) { - R = D.getRegion(O); - switch (K) {case B.TOP_LEFT:M(R.top, R.left); - break;case B.TOP_RIGHT:M(R.top, R.right);break;case B.BOTTOM_LEFT:M(R.bottom, R.left);break;case B.BOTTOM_RIGHT:M(R.bottom, R.right);break;} - } - } - },enforceConstraints:function(S, R, O) { - var U = R[0],W = U[0],V = U[1],L = this.element.offsetHeight,Q = this.element.offsetWidth,T = D.getViewportWidth(),N = D.getViewportHeight(),Z = D.getDocumentScrollLeft(),X = D.getDocumentScrollTop(),M = X + - 10,P = Z + - 10,K = X + - N - - L - - 10,Y = Z + - T - - Q - - 10; - if (W < P) { - W = P; - } else { - if (W > Y) { - W = Y; - } - } - if (V < M) { - V = M; - } else { - if (V > K) { - V = K; - } - } - this.cfg.setProperty("x", W, true); - this.cfg.setProperty("y", V, true); - this.cfg.setProperty("xy", [W,V], true); - },center:function() { - var Q = D.getDocumentScrollLeft(),O = D.getDocumentScrollTop(),L = D.getClientWidth(),P = D.getClientHeight(),N = this.element.offsetWidth,M = this.element.offsetHeight,K = (L / - 2) - - (N / - 2) + - Q,R = (P / - 2) - - (M / - 2) + - O; - this.cfg.setProperty("xy", [parseInt(K, 10),parseInt(R, 10)]); - this.cfg.refireEvent("iframe"); - },syncPosition:function() { - var K = D.getXY(this.element); - this.cfg.setProperty("x", K[0], true); - this.cfg.setProperty("y", K[1], true); - this.cfg.setProperty("xy", K, true); - },onDomResize:function(M, L) { - var K = this; - B.superclass.onDomResize.call(this, M, L); - setTimeout(function() { - K.syncPosition(); - K.cfg.refireEvent("iframe"); - K.cfg.refireEvent("context"); - }, 0); - },bringToTop:function() { - var N = [],M = this.element; - function P(T, S) { - var V = D.getStyle(T, "zIndex"),U = D.getStyle(S, "zIndex"),R = (!V || isNaN(V)) ? 0 : - parseInt(V, 10),Q = - (!U || isNaN(U)) ? 0 : parseInt(U, 10); - if (R > Q) { - return -1; - } else { - if (R < Q) { - return 1; - } else { - return 0; - } - } - } - function L(S) { - var Q = D.hasClass(S, B.CSS_OVERLAY),R = YAHOO.widget.Panel; - if (Q && !D.isAncestor(M, Q)) { - if (R && D.hasClass(S, R.CSS_PANEL)) { - N[N.length] = S.parentNode; - } else { - N[N.length] = S; - } - } - } - D.getElementsBy(L, "DIV", document.body); - N.sort(P); - var K = N[0],O; - if (K) { - O = D.getStyle(K, "zIndex"); - if (!isNaN(O) && K != M) { - this.cfg.setProperty("zindex", (parseInt(O, 10) + 2)); - } - } - },destroy:function() { - if (this.iframe) { - this.iframe.parentNode.removeChild(this.iframe); - } - this.iframe = null; - B.windowResizeEvent.unsubscribe(this.doCenterOnDOMEvent, this); - B.windowScrollEvent.unsubscribe(this.doCenterOnDOMEvent, this); - B.superclass.destroy.call(this); - },toString:function() { - return"Overlay " + this.id; - }}); -}()); -(function() { - YAHOO.widget.OverlayManager = function(G) { - this.init(G); - }; - var D = YAHOO.widget.Overlay,C = YAHOO.util.Event,E = YAHOO.util.Dom,B = YAHOO.util.Config,F = YAHOO.util.CustomEvent,A = YAHOO.widget.OverlayManager; - A.CSS_FOCUSED = "focused"; - A.prototype = {constructor:A,overlays:null,initDefaultConfig:function() { - this.cfg.addProperty("overlays", {suppressEvent:true}); - this.cfg.addProperty("focusevent", {value:"mousedown"}); - },init:function(I) { - this.cfg = new B(this); - this.initDefaultConfig(); - if (I) { - this.cfg.applyConfig(I, true); - } - this.cfg.fireQueue(); - var H = null; - this.getActive = function() { - return H; - }; - this.focus = function(J) { - var K = this.find(J); - if (K) { - if (H != K) { - if (H) { - H.blur(); - } - this.bringToTop(K); - H = K; - E.addClass(H.element, A.CSS_FOCUSED); - K.focusEvent.fire(); - } - } - }; - this.remove = function(K) { - var M = this.find(K),J; - if (M) { - if (H == M) { - H = null; - } - var L = (M.element === null && M.cfg === null) ? true : false; - if (!L) { - J = E.getStyle(M.element, "zIndex"); - M.cfg.setProperty("zIndex", -1000, true); - } - this.overlays.sort(this.compareZIndexDesc); - this.overlays = this.overlays.slice(0, (this.overlays.length - 1)); - M.hideEvent.unsubscribe(M.blur); - M.destroyEvent.unsubscribe(this._onOverlayDestroy, M); - if (!L) { - C.removeListener(M.element, this.cfg.getProperty("focusevent"), this._onOverlayElementFocus); - M.cfg.setProperty("zIndex", J, true); - M.cfg.setProperty("manager", null); - } - M.focusEvent.unsubscribeAll(); - M.blurEvent.unsubscribeAll(); - M.focusEvent = null; - M.blurEvent = null; - M.focus = null; - M.blur = null; - } - }; - this.blurAll = function() { - var K = this.overlays.length,J; - if (K > 0) { - J = K - 1; - do{ - this.overlays[J].blur(); - } while (J--); - } - }; - this._onOverlayBlur = function(K, J) { - H = null; - }; - var G = this.cfg.getProperty("overlays"); - if (!this.overlays) { - this.overlays = []; - } - if (G) { - this.register(G); - this.overlays.sort(this.compareZIndexDesc); - } - },_onOverlayElementFocus:function(I) { - var G = C.getTarget(I),H = this.close; - if (H && (G == H || E.isAncestor(H, G))) { - this.blur(); - } else { - this.focus(); - } - },_onOverlayDestroy:function(H, G, I) { - this.remove(I); - },register:function(G) { - var K = this,L,I,H,J; - if (G instanceof D) { - G.cfg.addProperty("manager", {value:this}); - G.focusEvent = G.createEvent("focus"); - G.focusEvent.signature = F.LIST; - G.blurEvent = G.createEvent("blur"); - G.blurEvent.signature = F.LIST; - G.focus = function() { - K.focus(this); - }; - G.blur = function() { - if (K.getActive() == this) { - E.removeClass(this.element, A.CSS_FOCUSED); - this.blurEvent.fire(); - } - }; - G.blurEvent.subscribe(K._onOverlayBlur); - G.hideEvent.subscribe(G.blur); - G.destroyEvent.subscribe(this._onOverlayDestroy, G, this); - C.on(G.element, this.cfg.getProperty("focusevent"), this._onOverlayElementFocus, null, G); - L = E.getStyle(G.element, "zIndex"); - if (!isNaN(L)) { - G.cfg.setProperty("zIndex", parseInt(L, 10)); - } else { - G.cfg.setProperty("zIndex", 0); - } - this.overlays.push(G); - this.bringToTop(G); - return true; - } else { - if (G instanceof Array) { - I = 0; - J = G.length; - for (H = 0; H < J; H++) { - if (this.register(G[H])) { - I++; - } - } - if (I > 0) { - return true; - } - } else { - return false; - } - } - },bringToTop:function(K) { - var H = this.find(K),J,G,I; - if (H) { - I = this.overlays; - I.sort(this.compareZIndexDesc); - G = I[0]; - if (G) { - J = E.getStyle(G.element, "zIndex"); - if (!isNaN(J) && G != H) { - H.cfg.setProperty("zIndex", (parseInt(J, 10) + 2)); - } - I.sort(this.compareZIndexDesc); - } - } - },find:function(G) { - var I = this.overlays,J = I.length,H; - if (J > 0) { - H = J - 1; - if (G instanceof D) { - do{ - if (I[H] == G) { - return I[H]; - } - } while (H--); - } else { - if (typeof G == "string") { - do{ - if (I[H].id == G) { - return I[H]; - } - } while (H--); - } - } - return null; - } - },compareZIndexDesc:function(J, I) { - var H = (J.cfg) ? J.cfg.getProperty("zIndex") : null,G = (I.cfg) ? - I.cfg.getProperty("zIndex") : null; - if (H === null && G === null) { - return 0; - } else { - if (H === null) { - return 1; - } else { - if (G === null) { - return -1; - } else { - if (H > G) { - return -1; - } else { - if (H < G) { - return 1; - } else { - return 0; - } - } - } - } - } - },showAll:function() { - var H = this.overlays,I = H.length,G; - if (I > 0) { - G = I - 1; - do{ - H[G].show(); - } while (G--); - } - },hideAll:function() { - var H = this.overlays,I = H.length,G; - if (I > 0) { - G = I - 1; - do{ - H[G].hide(); - } while (G--); - } - },toString:function() { - return"OverlayManager"; - }}; -}()); -(function() { - YAHOO.widget.Tooltip = function(L, K) { - YAHOO.widget.Tooltip.superclass.constructor.call(this, L, K); - }; - var D = YAHOO.lang,J = YAHOO.util.Event,B = YAHOO.util.Dom,F = YAHOO.widget.Tooltip,E,G = {"PREVENT_OVERLAP":{key:"preventoverlap",value:true,validator:D.isBoolean,supercedes:["x","y","xy"]},"SHOW_DELAY":{key:"showdelay",value:200,validator:D.isNumber},"AUTO_DISMISS_DELAY":{key:"autodismissdelay",value:5000,validator:D.isNumber},"HIDE_DELAY":{key:"hidedelay",value:250,validator:D.isNumber},"TEXT":{key:"text",suppressEvent:true},"CONTAINER":{key:"container"}}; - F.CSS_TOOLTIP = "yui-tt"; - function H(L, K, M) { - var P = M[0],N = M[1],O = this.cfg,Q = O.getProperty("width"); - if (Q == N) { - O.setProperty("width", P); - } - this.unsubscribe("hide", this._onHide, M); - } - function C(L, K) { - var M = document.body,Q = this.cfg,P = Q.getProperty("width"),N,O; - if ((!P || P == "auto") && - (Q.getProperty("container") != M || Q.getProperty("x") >= B.getViewportWidth() || - Q.getProperty("y") >= B.getViewportHeight())) { - O = this.element.cloneNode(true); - O.style.visibility = "hidden"; - O.style.top = "0px"; - O.style.left = "0px"; - M.appendChild(O); - N = (O.offsetWidth + "px"); - M.removeChild(O); - O = null; - Q.setProperty("width", N); - Q.refireEvent("xy"); - this.subscribe("hide", H, [(P || ""),N]); - } - } - function A(L, K, M) { - this.render(M); - } - function I() { - J.onDOMReady(A, this.cfg.getProperty("container"), this); - } - YAHOO.extend(F, YAHOO.widget.Overlay, {init:function(L, K) { - F.superclass.init.call(this, L); - this.beforeInitEvent.fire(F); - B.addClass(this.element, F.CSS_TOOLTIP); - if (K) { - this.cfg.applyConfig(K, true); - } - this.cfg.queueProperty("visible", false); - this.cfg.queueProperty("constraintoviewport", true); - this.setBody(""); - this.subscribe("beforeShow", C); - this.subscribe("init", I); - this.subscribe("render", this.onRender); - this.initEvent.fire(F); - },initDefaultConfig:function() { - F.superclass.initDefaultConfig.call(this); - this.cfg.addProperty(G.PREVENT_OVERLAP.key, {value:G.PREVENT_OVERLAP.value,validator:G.PREVENT_OVERLAP.validator,supercedes:G.PREVENT_OVERLAP.supercedes}); - this.cfg.addProperty(G.SHOW_DELAY.key, {handler:this.configShowDelay,value:200,validator:G.SHOW_DELAY.validator}); - this.cfg.addProperty(G.AUTO_DISMISS_DELAY.key, {handler:this.configAutoDismissDelay,value:G.AUTO_DISMISS_DELAY.value,validator:G.AUTO_DISMISS_DELAY.validator}); - this.cfg.addProperty(G.HIDE_DELAY.key, {handler:this.configHideDelay,value:G.HIDE_DELAY.value,validator:G.HIDE_DELAY.validator}); - this.cfg.addProperty(G.TEXT.key, {handler:this.configText,suppressEvent:G.TEXT.suppressEvent}); - this.cfg.addProperty(G.CONTAINER.key, {handler:this.configContainer,value:document.body}); - },configText:function(L, K, M) { - var N = K[0]; - if (N) { - this.setBody(N); - } - },configContainer:function(M, L, N) { - var K = L[0]; - if (typeof K == "string") { - this.cfg.setProperty("container", document.getElementById(K), true); - } - },_removeEventListeners:function() { - var N = this._context,K,M,L; - if (N) { - K = N.length; - if (K > 0) { - L = K - 1; - do{ - M = N[L]; - J.removeListener(M, "mouseover", this.onContextMouseOver); - J.removeListener(M, "mousemove", this.onContextMouseMove); - J.removeListener(M, "mouseout", this.onContextMouseOut); - } while (L--); - } - } - },configContext:function(P, L, Q) { - var O = L[0],R,K,N,M; - if (O) { - if (!(O instanceof Array)) { - if (typeof O == "string") { - this.cfg.setProperty("context", [document.getElementById(O)], true); - } else { - this.cfg.setProperty("context", [O], true); - } - O = this.cfg.getProperty("context"); - } - this._removeEventListeners(); - this._context = O; - R = this._context; - if (R) { - K = R.length; - if (K > 0) { - M = K - 1; - do{ - N = R[M]; - J.on(N, "mouseover", this.onContextMouseOver, this); - J.on(N, "mousemove", this.onContextMouseMove, this); - J.on(N, "mouseout", this.onContextMouseOut, this); - } while (M--); - } - } - } - },onContextMouseMove:function(L, K) { - K.pageX = J.getPageX(L); - K.pageY = J.getPageY(L); - },onContextMouseOver:function(M, L) { - var K = this; - if (L.hideProcId) { - clearTimeout(L.hideProcId); - L.hideProcId = null; - } - J.on(K, "mousemove", L.onContextMouseMove, L); - if (K.title) { - L._tempTitle = K.title; - K.title = ""; - } - L.showProcId = L.doShow(M, K); - },onContextMouseOut:function(M, L) { - var K = this; - if (L._tempTitle) { - K.title = L._tempTitle; - L._tempTitle = null; - } - if (L.showProcId) { - clearTimeout(L.showProcId); - L.showProcId = null; - } - if (L.hideProcId) { - clearTimeout(L.hideProcId); - L.hideProcId = null; - } - L.hideProcId = setTimeout(function() { - L.hide(); - }, L.cfg.getProperty("hidedelay")); - },doShow:function(M, K) { - var N = 25,L = this; - if (YAHOO.env.ua.opera && K.tagName && K.tagName.toUpperCase() == "A") { - N += 12; - } - return setTimeout(function() { - if (L._tempTitle) { - L.setBody(L._tempTitle); - } else { - L.cfg.refireEvent("text"); - } - L.moveTo(L.pageX, L.pageY + N); - if (L.cfg.getProperty("preventoverlap")) { - L.preventOverlap(L.pageX, L.pageY); - } - J.removeListener(K, "mousemove", L.onContextMouseMove); - L.show(); - L.hideProcId = L.doHide(); - }, this.cfg.getProperty("showdelay")); - },doHide:function() { - var K = this; - return setTimeout(function() { - K.hide(); - }, this.cfg.getProperty("autodismissdelay")); - },preventOverlap:function(O, N) { - var K = this.element.offsetHeight,M = new YAHOO.util.Point(O, N),L = B.getRegion(this.element); - L.top -= 5; - L.left -= 5; - L.right += 5; - L.bottom += 5; - if (L.contains(M)) { - this.cfg.setProperty("y", (N - K - 5)); - } - },onRender:function(O, N) { - function P() { - var S = this.element,R = this._shadow; - if (R) { - R.style.width = (S.offsetWidth + 6) + "px"; - R.style.height = (S.offsetHeight + 1) + "px"; - } - } - function L() { - B.addClass(this._shadow, "yui-tt-shadow-visible"); - } - function K() { - B.removeClass(this._shadow, "yui-tt-shadow-visible"); - } - function Q() { - var T = this._shadow,S,R,V,U; - if (!T) { - S = this.element; - R = YAHOO.widget.Module; - V = YAHOO.env.ua.ie; - U = this; - if (!E) { - E = document.createElement("div"); - E.className = "yui-tt-shadow"; - } - T = E.cloneNode(false); - S.appendChild(T); - this._shadow = T; - L.call(this); - this.subscribe("beforeShow", L); - this.subscribe("beforeHide", K); - if (V == 6 || (V == 7 && document.compatMode == "BackCompat")) { - window.setTimeout(function() { - P.call(U); - }, 0); - this.cfg.subscribeToConfigEvent("width", P); - this.cfg.subscribeToConfigEvent("height", P); - this.subscribe("changeContent", P); - R.textResizeEvent.subscribe(P, this, true); - this.subscribe("destroy", function() { - R.textResizeEvent.unsubscribe(P, this); - }); - } - } - } - function M() { - Q.call(this); - this.unsubscribe("beforeShow", M); - } - if (this.cfg.getProperty("visible")) { - Q.call(this); - } else { - this.subscribe("beforeShow", M); - } - },destroy:function() { - this._removeEventListeners(); - F.superclass.destroy.call(this); - },toString:function() { - return"Tooltip " + this.id; - }}); -}()); -(function() { - YAHOO.widget.Panel = function(U, T) { - YAHOO.widget.Panel.superclass.constructor.call(this, U, T); - }; - var G = YAHOO.lang,N = YAHOO.util.DD,A = YAHOO.util.Dom,S = YAHOO.util.Event,I = YAHOO.widget.Overlay,L = YAHOO.util.CustomEvent,J = YAHOO.util.Config,O = YAHOO.widget.Panel,H,Q,D,E = {"SHOW_MASK":"showMask","HIDE_MASK":"hideMask","DRAG":"drag"},M = {"CLOSE":{key:"close",value:true,validator:G.isBoolean,supercedes:["visible"]},"DRAGGABLE":{key:"draggable",value:( - N ? true : - false),validator:G.isBoolean,supercedes:["visible"]},"UNDERLAY":{key:"underlay",value:"shadow",supercedes:["visible"]},"MODAL":{key:"modal",value:false,validator:G.isBoolean,supercedes:["visible","zindex"]},"KEY_LISTENERS":{key:"keylisteners",suppressEvent:true,supercedes:["visible"]}}; - O.CSS_PANEL = "yui-panel"; - O.CSS_PANEL_CONTAINER = "yui-panel-container"; - function K(U, T) { - if (!this.header) { - this.setHeader(" "); - } - } - function R(U, T, V) { - var Y = V[0],W = V[1],X = this.cfg,Z = X.getProperty("width"); - if (Z == W) { - X.setProperty("width", Y); - } - this.unsubscribe("hide", R, V); - } - function C(U, T) { - var Y = YAHOO.env.ua.ie,X,W,V; - if (Y == 6 || (Y == 7 && document.compatMode == "BackCompat")) { - X = this.cfg; - W = X.getProperty("width"); - if (!W || W == "auto") { - V = (this.element.offsetWidth + "px"); - X.setProperty("width", V); - this.subscribe("hide", R, [(W || ""),V]); - } - } - } - function F() { - this.blur(); - } - function P(V, U) { - var W = this; - function T(Z) { - var Y = Z.tagName.toUpperCase(),X = false; - switch (Y) {case"A":case"BUTTON":case"SELECT":case"TEXTAREA":if (!A.isAncestor(W.element, Z)) { - S.on(Z, "focus", F, Z, true); - X = true; - }break;case"INPUT":if (Z.type != "hidden" && !A.isAncestor(W.element, Z)) { - S.on(Z, "focus", F, Z, true); - X = true; - }break;} - return X; - } - this.focusableElements = A.getElementsBy(T); - } - function B(V, U) { - var Y = this.focusableElements,T = Y.length,W,X; - for (X = 0; X < T; X++) { - W = Y[X]; - S.removeListener(W, "focus", F); - } - } - YAHOO.extend(O, I, {init:function(U, T) { - O.superclass.init.call(this, U); - this.beforeInitEvent.fire(O); - A.addClass(this.element, O.CSS_PANEL); - this.buildWrapper(); - if (T) { - this.cfg.applyConfig(T, true); - } - this.subscribe("showMask", P); - this.subscribe("hideMask", B); - if (this.cfg.getProperty("draggable")) { - this.subscribe("beforeRender", K); - } - this.initEvent.fire(O); - },initEvents:function() { - O.superclass.initEvents.call(this); - var T = L.LIST; - this.showMaskEvent = this.createEvent(E.SHOW_MASK); - this.showMaskEvent.signature = T; - this.hideMaskEvent = this.createEvent(E.HIDE_MASK); - this.hideMaskEvent.signature = T; - this.dragEvent = this.createEvent(E.DRAG); - this.dragEvent.signature = T; - },initDefaultConfig:function() { - O.superclass.initDefaultConfig.call(this); - this.cfg.addProperty(M.CLOSE.key, {handler:this.configClose,value:M.CLOSE.value,validator:M.CLOSE.validator,supercedes:M.CLOSE.supercedes}); - this.cfg.addProperty(M.DRAGGABLE.key, {handler:this.configDraggable,value:M.DRAGGABLE.value,validator:M.DRAGGABLE.validator,supercedes:M.DRAGGABLE.supercedes}); - this.cfg.addProperty(M.UNDERLAY.key, {handler:this.configUnderlay,value:M.UNDERLAY.value,supercedes:M.UNDERLAY.supercedes}); - this.cfg.addProperty(M.MODAL.key, {handler:this.configModal,value:M.MODAL.value,validator:M.MODAL.validator,supercedes:M.MODAL.supercedes}); - this.cfg.addProperty(M.KEY_LISTENERS.key, {handler:this.configKeyListeners,suppressEvent:M.KEY_LISTENERS.suppressEvent,supercedes:M.KEY_LISTENERS.supercedes}); - },configClose:function(V, T, X) { - var Y = T[0],U = this.close; - function W(a, Z) { - Z.hide(); - } - if (Y) { - if (!U) { - if (!D) { - D = document.createElement("span"); - D.innerHTML = " "; - D.className = "container-close"; - } - U = D.cloneNode(true); - this.innerElement.appendChild(U); - S.on(U, "click", W, this); - this.close = U; - } else { - U.style.display = "block"; - } - } else { - if (U) { - U.style.display = "none"; - } - } - },configDraggable:function(U, T, V) { - var W = T[0]; - if (W) { - if (!N) { - this.cfg.setProperty("draggable", false); - return; - } - if (this.header) { - A.setStyle(this.header, "cursor", "move"); - this.registerDragDrop(); - } - if (!J.alreadySubscribed(this.beforeRenderEvent, K, null)) { - this.subscribe("beforeRender", K); - } - this.subscribe("beforeShow", C); - } else { - if (this.dd) { - this.dd.unreg(); - } - if (this.header) { - A.setStyle(this.header, "cursor", "auto"); - } - this.unsubscribe("beforeRender", K); - this.unsubscribe("beforeShow", C); - } - },configUnderlay:function(c, b, X) { - var a = YAHOO.env.ua,Z = (this.platform == "mac" && - a.gecko),d = b[0].toLowerCase(),T = this.underlay,U = this.element; - function V() { - var e; - if (!T) { - if (!Q) { - Q = document.createElement("div"); - Q.className = "underlay"; - } - T = Q.cloneNode(false); - this.element.appendChild(T); - this.underlay = T; - e = a.ie; - if (e == 6 || (e == 7 && document.compatMode == "BackCompat")) { - this.sizeUnderlay(); - this.cfg.subscribeToConfigEvent("width", this.sizeUnderlay); - this.cfg.subscribeToConfigEvent("height", this.sizeUnderlay); - this.changeContentEvent.subscribe(this.sizeUnderlay); - YAHOO.widget.Module.textResizeEvent.subscribe(this.sizeUnderlay, this, true); - } - } - } - function Y() { - V.call(this); - this._underlayDeferred = false; - this.beforeShowEvent.unsubscribe(Y); - } - function W() { - if (this._underlayDeferred) { - this.beforeShowEvent.unsubscribe(Y); - this._underlayDeferred = false; - } - if (T) { - this.cfg.unsubscribeFromConfigEvent("width", this.sizeUnderlay); - this.cfg.unsubscribeFromConfigEvent("height", this.sizeUnderlay); - this.changeContentEvent.unsubscribe(this.sizeUnderlay); - YAHOO.widget.Module.textResizeEvent.unsubscribe(this.sizeUnderlay, this, true); - this.element.removeChild(T); - this.underlay = null; - } - } - switch (d) {case"shadow":A.removeClass(U, "matte");A.addClass(U, "shadow");break;case"matte":if (!Z) { - W.call(this); - }A.removeClass(U, "shadow");A.addClass(U, "matte");break;default:if (!Z) { - W.call(this); - }A.removeClass(U, "shadow");A.removeClass(U, "matte");break;} - if ((d == "shadow") || (Z && !T)) { - if (this.cfg.getProperty("visible")) { - V.call(this); - } else { - if (!this._underlayDeferred) { - this.beforeShowEvent.subscribe(Y); - this._underlayDeferred = true; - } - } - } - },configModal:function(U, T, W) { - var V = T[0]; - if (V) { - if (!this._hasModalityEventListeners) { - this.subscribe("beforeShow", this.buildMask); - this.subscribe("beforeShow", this.bringToTop); - this.subscribe("beforeShow", this.showMask); - this.subscribe("hide", this.hideMask); - I.windowResizeEvent.subscribe(this.sizeMask, this, true); - this._hasModalityEventListeners = true; - } - } else { - if (this._hasModalityEventListeners) { - if (this.cfg.getProperty("visible")) { - this.hideMask(); - this.removeMask(); - } - this.unsubscribe("beforeShow", this.buildMask); - this.unsubscribe("beforeShow", this.bringToTop); - this.unsubscribe("beforeShow", this.showMask); - this.unsubscribe("hide", this.hideMask); - I.windowResizeEvent.unsubscribe(this.sizeMask, this); - this._hasModalityEventListeners = false; - } - } - },removeMask:function() { - var U = this.mask,T; - if (U) { - this.hideMask(); - T = U.parentNode; - if (T) { - T.removeChild(U); - } - this.mask = null; - } - },configKeyListeners:function(W, T, Z) { - var V = T[0],Y,X,U; - if (V) { - if (V instanceof Array) { - X = V.length; - for (U = 0; U < X; U++) { - Y = V[U]; - if (!J.alreadySubscribed(this.showEvent, Y.enable, Y)) { - this.showEvent.subscribe(Y.enable, Y, true); - } - if (!J.alreadySubscribed(this.hideEvent, Y.disable, Y)) { - this.hideEvent.subscribe(Y.disable, Y, true); - this.destroyEvent.subscribe(Y.disable, Y, true); - } - } - } else { - if (!J.alreadySubscribed(this.showEvent, V.enable, V)) { - this.showEvent.subscribe(V.enable, V, true); - } - if (!J.alreadySubscribed(this.hideEvent, V.disable, V)) { - this.hideEvent.subscribe(V.disable, V, true); - this.destroyEvent.subscribe(V.disable, V, true); - } - } - } - },configHeight:function(W, U, X) { - var T = U[0],V = this.innerElement; - A.setStyle(V, "height", T); - this.cfg.refireEvent("iframe"); - },configWidth:function(W, T, X) { - var V = T[0],U = this.innerElement; - A.setStyle(U, "width", V); - this.cfg.refireEvent("iframe"); - },configzIndex:function(U, T, W) { - O.superclass.configzIndex.call(this, U, T, W); - if (this.mask || this.cfg.getProperty("modal") === true) { - var V = A.getStyle(this.element, "zIndex"); - if (!V || isNaN(V)) { - V = 0; - } - if (V === 0) { - this.cfg.setProperty("zIndex", 1); - } else { - this.stackMask(); - } - } - },buildWrapper:function() { - var V = this.element.parentNode,T = this.element,U = document.createElement("div"); - U.className = O.CSS_PANEL_CONTAINER; - U.id = T.id + "_c"; - if (V) { - V.insertBefore(U, T); - } - U.appendChild(T); - this.element = U; - this.innerElement = T; - A.setStyle(this.innerElement, "visibility", "inherit"); - },sizeUnderlay:function() { - var U = this.underlay,T; - if (U) { - T = this.element; - U.style.width = T.offsetWidth + "px"; - U.style.height = T.offsetHeight + "px"; - } - },registerDragDrop:function() { - var T = this; - if (this.header) { - if (!N) { - return; - } - this.dd = new N(this.element.id, this.id); - if (!this.header.id) { - this.header.id = this.id + "_h"; - } - this.dd.startDrag = function() { - var V,Z,a,X,d,b,W,Y,U,c; - if (YAHOO.env.ua.ie == 6) { - A.addClass(T.element, "drag"); - } - if (T.cfg.getProperty("constraintoviewport")) { - V = T.element.offsetHeight; - Z = T.element.offsetWidth; - a = A.getViewportWidth(); - X = A.getViewportHeight(); - d = A.getDocumentScrollLeft(); - b = A.getDocumentScrollTop(); - W = b + 10; - Y = d + 10; - U = b + X - V - 10; - c = d + a - Z - 10; - this.minX = Y; - this.maxX = c; - this.constrainX = true; - this.minY = W; - this.maxY = U; - this.constrainY = true; - } else { - this.constrainX = false; - this.constrainY = false; - } - T.dragEvent.fire("startDrag", arguments); - }; - this.dd.onDrag = function() { - T.syncPosition(); - T.cfg.refireEvent("iframe"); - if (this.platform == "mac" && YAHOO.env.ua.gecko) { - this.showMacGeckoScrollbars(); - } - T.dragEvent.fire("onDrag", arguments); - }; - this.dd.endDrag = function() { - if (YAHOO.env.ua.ie == 6) { - A.removeClass(T.element, "drag"); - } - T.dragEvent.fire("endDrag", arguments); - T.moveEvent.fire(T.cfg.getProperty("xy")); - }; - this.dd.setHandleElId(this.header.id); - this.dd.addInvalidHandleType("INPUT"); - this.dd.addInvalidHandleType("SELECT"); - this.dd.addInvalidHandleType("TEXTAREA"); - } - },buildMask:function() { - var T = this.mask; - if (!T) { - if (!H) { - H = document.createElement("div"); - H.className = "mask"; - H.innerHTML = " "; - } - T = H.cloneNode(true); - T.id = this.id + "_mask"; - document.body.insertBefore(T, document.body.firstChild); - this.mask = T; - this.stackMask(); - } - },hideMask:function() { - if (this.cfg.getProperty("modal") && this.mask) { - this.mask.style.display = "none"; - this.hideMaskEvent.fire(); - A.removeClass(document.body, "masked"); - } - },showMask:function() { - if (this.cfg.getProperty("modal") && this.mask) { - A.addClass(document.body, "masked"); - this.sizeMask(); - this.mask.style.display = "block"; - this.showMaskEvent.fire(); - } - },sizeMask:function() { - if (this.mask) { - this.mask.style.height = A.getDocumentHeight() + "px"; - this.mask.style.width = A.getDocumentWidth() + "px"; - } - },stackMask:function() { - if (this.mask) { - var T = A.getStyle(this.element, "zIndex"); - if (!YAHOO.lang.isUndefined(T) && !isNaN(T)) { - A.setStyle(this.mask, "zIndex", T - 1); - } - } - },render:function(T) { - return O.superclass.render.call(this, T, this.innerElement); - },destroy:function() { - I.windowResizeEvent.unsubscribe(this.sizeMask, this); - this.removeMask(); - if (this.close) { - S.purgeElement(this.close); - } - O.superclass.destroy.call(this); - },toString:function() { - return"Panel " + this.id; - }}); -}()); -(function() { - YAHOO.widget.Dialog = function(L, K) { - YAHOO.widget.Dialog.superclass.constructor.call(this, L, K); - }; - var J = YAHOO.util.Event,I = YAHOO.util.CustomEvent,D = YAHOO.util.Dom,B = YAHOO.util.KeyListener,H = YAHOO.util.Connect,F = YAHOO.widget.Dialog,E = YAHOO.lang,A = {"BEFORE_SUBMIT":"beforeSubmit","SUBMIT":"submit","MANUAL_SUBMIT":"manualSubmit","ASYNC_SUBMIT":"asyncSubmit","FORM_SUBMIT":"formSubmit","CANCEL":"cancel"},G = {"POST_METHOD":{key:"postmethod",value:"async"},"BUTTONS":{key:"buttons",value:"none"}}; - F.CSS_DIALOG = "yui-dialog"; - function C() { - var N = this._aButtons,L,M,K; - if (E.isArray(N)) { - L = N.length; - if (L > 0) { - K = L - 1; - do{ - M = N[K]; - if (YAHOO.widget.Button && M instanceof YAHOO.widget.Button) { - M.destroy(); - } else { - if (M.tagName.toUpperCase() == "BUTTON") { - J.purgeElement(M); - J.purgeElement(M, false); - } - } - } while (K--); - } - } - } - YAHOO.extend(F, YAHOO.widget.Panel, {form:null,initDefaultConfig:function() { - F.superclass.initDefaultConfig.call(this); - this.callback = {success:null,failure:null,argument:null}; - this.cfg.addProperty(G.POST_METHOD.key, {handler:this.configPostMethod,value:G.POST_METHOD.value,validator:function( - K) { - if (K != "form" && K != "async" && K != "none" && K != "manual") { - return false; - } else { - return true; - } - }}); - this.cfg.addProperty(G.BUTTONS.key, {handler:this.configButtons,value:G.BUTTONS.value}); - },initEvents:function() { - F.superclass.initEvents.call(this); - var K = I.LIST; - this.beforeSubmitEvent = this.createEvent(A.BEFORE_SUBMIT); - this.beforeSubmitEvent.signature = K; - this.submitEvent = this.createEvent(A.SUBMIT); - this.submitEvent.signature = K; - this.manualSubmitEvent = this.createEvent(A.MANUAL_SUBMIT); - this.manualSubmitEvent.signature = K; - this.asyncSubmitEvent = this.createEvent(A.ASYNC_SUBMIT); - this.asyncSubmitEvent.signature = K; - this.formSubmitEvent = this.createEvent(A.FORM_SUBMIT); - this.formSubmitEvent.signature = K; - this.cancelEvent = this.createEvent(A.CANCEL); - this.cancelEvent.signature = K; - },init:function(L, K) { - F.superclass.init.call(this, L); - this.beforeInitEvent.fire(F); - D.addClass(this.element, F.CSS_DIALOG); - this.cfg.setProperty("visible", false); - if (K) { - this.cfg.applyConfig(K, true); - } - this.showEvent.subscribe(this.focusFirst, this, true); - this.beforeHideEvent.subscribe(this.blurButtons, this, true); - this.subscribe("changeBody", this.registerForm); - this.initEvent.fire(F); - },doSubmit:function() { - var Q = this.form,O = false,N = false,P,K,M,L; - switch (this.cfg.getProperty("postmethod")) {case"async":P = Q.elements;K = P.length;if (K > - 0) { - M = K - 1; - do{ - if (P[M].type == "file") { - O = true; - break; - } - } while (M--); - }if (O && YAHOO.env.ua.ie && this.isSecure) { - N = true; - }L = (Q.getAttribute("method") || "POST").toUpperCase(); - H.setForm(Q, O, N);H.asyncRequest(L, Q.getAttribute("action"), this.callback);this.asyncSubmitEvent.fire();break;case"form":Q.submit();this.formSubmitEvent.fire();break;case"none":case"manual":this.manualSubmitEvent.fire();break;} - },registerForm:function() { - var M = this.element.getElementsByTagName("form")[0],L = this,K,N; - if (this.form) { - if (this.form == M && D.isAncestor(this.element, this.form)) { - return; - } else { - J.purgeElement(this.form); - this.form = null; - } - } - if (!M) { - M = document.createElement("form"); - M.name = "frm_" + this.id; - this.body.appendChild(M); - } - if (M) { - this.form = M; - J.on(M, "submit", function(O) { - J.stopEvent(O); - this.submit(); - this.form.blur(); - }, this, true); - this.firstFormElement = function() { - var Q,P,O = M.elements.length; - for (Q = 0; Q < O; Q++) { - P = M.elements[Q]; - if (P.focus && !P.disabled && P.type != "hidden") { - return P; - } - } - return null; - }(); - this.lastFormElement = function() { - var Q,P,O = M.elements.length; - for (Q = O - 1; Q >= 0; Q--) { - P = M.elements[Q]; - if (P.focus && !P.disabled && P.type != "hidden") { - return P; - } - } - return null; - }(); - if (this.cfg.getProperty("modal")) { - K = this.firstFormElement || this.firstButton; - if (K) { - this.preventBackTab = - new B(K, {shift:true,keys:9}, {fn:L.focusLast,scope:L,correctScope:true}); - this.showEvent.subscribe(this.preventBackTab.enable, this.preventBackTab, true); - this.hideEvent.subscribe(this.preventBackTab.disable, this.preventBackTab, true); - } - N = this.lastButton || this.lastFormElement; - if (N) { - this.preventTabOut = - new B(N, {shift:false,keys:9}, {fn:L.focusFirst,scope:L,correctScope:true}); - this.showEvent.subscribe(this.preventTabOut.enable, this.preventTabOut, true); - this.hideEvent.subscribe(this.preventTabOut.disable, this.preventTabOut, true); - } - } - } - },configClose:function(M, K, N) { - var O = K[0]; - function L(Q, P) { - P.cancel(); - } - if (O) { - if (!this.close) { - this.close = document.createElement("div"); - D.addClass(this.close, "container-close"); - this.close.innerHTML = " "; - this.innerElement.appendChild(this.close); - J.on(this.close, "click", L, this); - } else { - this.close.style.display = "block"; - } - } else { - if (this.close) { - this.close.style.display = "none"; - } - } - },configButtons:function(U, T, O) { - var P = YAHOO.widget.Button,W = T[0],M = this.innerElement,V,R,L,S,Q,K,N; - C.call(this); - this._aButtons = null; - if (E.isArray(W)) { - Q = document.createElement("span"); - Q.className = "button-group"; - S = W.length; - this._aButtons = []; - for (N = 0; N < S; N++) { - V = W[N]; - if (P) { - L = new P({label:V.text,container:Q}); - R = L.get("element"); - if (V.isDefault) { - L.addClass("default"); - this.defaultHtmlButton = R; - } - if (E.isFunction(V.handler)) { - L.set("onclick", {fn:V.handler,obj:this,scope:this}); - } else { - if (E.isObject(V.handler) && E.isFunction(V.handler.fn)) { - L.set("onclick", {fn:V.handler.fn,obj:((!E.isUndefined(V.handler.obj)) ? - V.handler.obj : - this),scope:(V.handler.scope || - this)}); - } - } - this._aButtons[this._aButtons.length] = L; - } else { - R = document.createElement("button"); - R.setAttribute("type", "button"); - if (V.isDefault) { - R.className = "default"; - this.defaultHtmlButton = R; - } - R.innerHTML = V.text; - if (E.isFunction(V.handler)) { - J.on(R, "click", V.handler, this, true); - } else { - if (E.isObject(V.handler) && E.isFunction(V.handler.fn)) { - J.on(R, "click", V.handler.fn, ((!E.isUndefined(V.handler.obj)) ? - V.handler.obj : - this), (V.handler.scope || this)); - } - } - Q.appendChild(R); - this._aButtons[this._aButtons.length] = R; - } - V.htmlButton = R; - if (N === 0) { - this.firstButton = R; - } - if (N == (S - 1)) { - this.lastButton = R; - } - } - this.setFooter(Q); - K = this.footer; - if (D.inDocument(this.element) && !D.isAncestor(M, K)) { - M.appendChild(K); - } - this.buttonSpan = Q; - } else { - Q = this.buttonSpan; - K = this.footer; - if (Q && K) { - K.removeChild(Q); - this.buttonSpan = null; - this.firstButton = null; - this.lastButton = null; - this.defaultHtmlButton = null; - } - } - this.cfg.refireEvent("iframe"); - this.cfg.refireEvent("underlay"); - },getButtons:function() { - var K = this._aButtons; - if (K) { - return K; - } - },focusFirst:function(N, L, P) { - var M = this.firstFormElement,K; - if (L) { - K = L[1]; - if (K) { - J.stopEvent(K); - } - } - if (M) { - try { - M.focus(); - } catch(O) { - } - } else { - this.focusDefaultButton(); - } - },focusLast:function(N, L, P) { - var Q = this.cfg.getProperty("buttons"),M = this.lastFormElement,K; - if (L) { - K = L[1]; - if (K) { - J.stopEvent(K); - } - } - if (Q && E.isArray(Q)) { - this.focusLastButton(); - } else { - if (M) { - try { - M.focus(); - } catch(O) { - } - } - } - },focusDefaultButton:function() { - var K = this.defaultHtmlButton; - if (K) { - try { - K.focus(); - } catch(L) { - } - } - },blurButtons:function() { - var P = this.cfg.getProperty("buttons"),M,O,L,K; - if (P && E.isArray(P)) { - M = P.length; - if (M > 0) { - K = (M - 1); - do{ - O = P[K]; - if (O) { - L = O.htmlButton; - if (L) { - try { - L.blur(); - } catch(N) { - } - } - } - } while (K--); - } - } - },focusFirstButton:function() { - var N = this.cfg.getProperty("buttons"),M,K; - if (N && E.isArray(N)) { - M = N[0]; - if (M) { - K = M.htmlButton; - if (K) { - try { - K.focus(); - } catch(L) { - } - } - } - } - },focusLastButton:function() { - var O = this.cfg.getProperty("buttons"),L,N,K; - if (O && E.isArray(O)) { - L = O.length; - if (L > 0) { - N = O[(L - 1)]; - if (N) { - K = N.htmlButton; - if (K) { - try { - K.focus(); - } catch(M) { - } - } - } - } - } - },configPostMethod:function(M, L, N) { - var K = L[0]; - this.registerForm(); - },validate:function() { - return true; - },submit:function() { - if (this.validate()) { - this.beforeSubmitEvent.fire(); - this.doSubmit(); - this.submitEvent.fire(); - this.hide(); - return true; - } else { - return false; - } - },cancel:function() { - this.cancelEvent.fire(); - this.hide(); - },getData:function() { - var a = this.form,M,T,W,O,U,R,Q,L,X,N,Y,b,K,P,c,Z,V; - function S(e) { - var d = e.tagName.toUpperCase(); - return((d == "INPUT" || d == "TEXTAREA" || d == "SELECT") && e.name == O); - } - if (a) { - M = a.elements; - T = M.length; - W = {}; - for (Z = 0; Z < T; Z++) { - O = M[Z].name; - U = D.getElementsBy(S, "*", a); - R = U.length; - if (R > 0) { - if (R == 1) { - U = U[0]; - Q = U.type; - L = U.tagName.toUpperCase(); - switch (L) {case"INPUT":if (Q == "checkbox") { - W[O] = U.checked; - } else { - if (Q != "radio") { - W[O] = U.value; - } - }break;case"TEXTAREA":W[O] = U.value;break;case"SELECT":X = U.options;N = - X.length;Y = - [];for ( - V = 0; V < N; V++) { - b = X[V]; - if (b.selected) { - K = b.value; - if (!K || K === "") { - K = b.text; - } - Y[Y.length] = K; - } - }W[O] = Y;break;} - } else { - Q = U[0].type; - switch (Q) {case"radio":for (V = 0; V < R; V++) { - P = U[V]; - if (P.checked) { - W[O] = P.value; - break; - } - }break;case"checkbox":Y = [];for (V = 0; V < R; V++) { - c = U[V]; - if (c.checked) { - Y[Y.length] = c.value; - } - }W[O] = Y;break;} - } - } - } - } - return W; - },destroy:function() { - C.call(this); - this._aButtons = null; - var K = this.element.getElementsByTagName("form"),L; - if (K.length > 0) { - L = K[0]; - if (L) { - J.purgeElement(L); - if (L.parentNode) { - L.parentNode.removeChild(L); - } - this.form = null; - } - } - F.superclass.destroy.call(this); - },toString:function() { - return"Dialog " + this.id; - }}); -}()); -(function() { - YAHOO.widget.SimpleDialog = function(E, D) { - YAHOO.widget.SimpleDialog.superclass.constructor.call(this, E, D); - }; - var C = YAHOO.util.Dom,B = YAHOO.widget.SimpleDialog,A = {"ICON":{key:"icon",value:"none",suppressEvent:true},"TEXT":{key:"text",value:"",suppressEvent:true,supercedes:["icon"]}}; - B.ICON_BLOCK = "blckicon"; - B.ICON_ALARM = "alrticon"; - B.ICON_HELP = "hlpicon"; - B.ICON_INFO = "infoicon"; - B.ICON_WARN = "warnicon"; - B.ICON_TIP = "tipicon"; - B.ICON_CSS_CLASSNAME = "yui-icon"; - B.CSS_SIMPLEDIALOG = "yui-simple-dialog"; - YAHOO.extend(B, YAHOO.widget.Dialog, {initDefaultConfig:function() { - B.superclass.initDefaultConfig.call(this); - this.cfg.addProperty(A.ICON.key, {handler:this.configIcon,value:A.ICON.value,suppressEvent:A.ICON.suppressEvent}); - this.cfg.addProperty(A.TEXT.key, {handler:this.configText,value:A.TEXT.value,suppressEvent:A.TEXT.suppressEvent,supercedes:A.TEXT.supercedes}); - },init:function(E, D) { - B.superclass.init.call(this, E); - this.beforeInitEvent.fire(B); - C.addClass(this.element, B.CSS_SIMPLEDIALOG); - this.cfg.queueProperty("postmethod", "manual"); - if (D) { - this.cfg.applyConfig(D, true); - } - this.beforeRenderEvent.subscribe(function() { - if (!this.body) { - this.setBody(""); - } - }, this, true); - this.initEvent.fire(B); - },registerForm:function() { - B.superclass.registerForm.call(this); - this.form.innerHTML += ""; - },configIcon:function(F, E, J) { - var K = E[0],D = this.body,I = B.ICON_CSS_CLASSNAME,H,G; - if (K && K != "none") { - H = C.getElementsByClassName(I, "*", D); - if (H) { - G = H.parentNode; - if (G) { - G.removeChild(H); - H = null; - } - } - if (K.indexOf(".") == -1) { - H = document.createElement("span"); - H.className = (I + " " + K); - H.innerHTML = " "; - } else { - H = document.createElement("img"); - H.src = (this.imageRoot + K); - H.className = I; - } - if (H) { - D.insertBefore(H, D.firstChild); - } - } - },configText:function(E, D, F) { - var G = D[0]; - if (G) { - this.setBody(G); - this.cfg.refireEvent("icon"); - } - },toString:function() { - return"SimpleDialog " + this.id; - }}); -}()); -(function() { - YAHOO.widget.ContainerEffect = function(F, I, H, E, G) { - if (!G) { - G = YAHOO.util.Anim; - } - this.overlay = F; - this.attrIn = I; - this.attrOut = H; - this.targetElement = E || F.element; - this.animClass = G; - }; - var B = YAHOO.util.Dom,D = YAHOO.util.CustomEvent,C = YAHOO.util.Easing,A = YAHOO.widget.ContainerEffect; - A.FADE = function(E, F) { - var G = new A(E, {attributes:{opacity:{from:0,to:1}},duration:F,method:C.easeIn}, {attributes:{opacity:{to:0}},duration:F,method:C.easeOut}, E.element); - G.handleStartAnimateIn = function(I, H, J) { - B.addClass(J.overlay.element, "hide-select"); - if (!J.overlay.underlay) { - J.overlay.cfg.refireEvent("underlay"); - } - if (J.overlay.underlay) { - J.initialUnderlayOpacity = B.getStyle(J.overlay.underlay, "opacity"); - J.overlay.underlay.style.filter = null; - } - B.setStyle(J.overlay.element, "visibility", "visible"); - B.setStyle(J.overlay.element, "opacity", 0); - }; - G.handleCompleteAnimateIn = function(I, H, J) { - B.removeClass(J.overlay.element, "hide-select"); - if (J.overlay.element.style.filter) { - J.overlay.element.style.filter = null; - } - if (J.overlay.underlay) { - B.setStyle(J.overlay.underlay, "opacity", J.initialUnderlayOpacity); - } - J.overlay.cfg.refireEvent("iframe"); - J.animateInCompleteEvent.fire(); - }; - G.handleStartAnimateOut = function(I, H, J) { - B.addClass(J.overlay.element, "hide-select"); - if (J.overlay.underlay) { - J.overlay.underlay.style.filter = null; - } - }; - G.handleCompleteAnimateOut = function(I, H, J) { - B.removeClass(J.overlay.element, "hide-select"); - if (J.overlay.element.style.filter) { - J.overlay.element.style.filter = null; - } - B.setStyle(J.overlay.element, "visibility", "hidden"); - B.setStyle(J.overlay.element, "opacity", 1); - J.overlay.cfg.refireEvent("iframe"); - J.animateOutCompleteEvent.fire(); - }; - G.init(); - return G; - }; - A.SLIDE = function(G, I) { - var F = G.cfg.getProperty("x") || B.getX(G.element),K = G.cfg.getProperty("y") || - B.getY(G.element),J = B.getClientWidth(),H = G.element.offsetWidth,E = new A(G, {attributes:{points:{to:[F,K]}},duration:I,method:C.easeIn}, {attributes:{points:{to:[(J + - 25),K]}},duration:I,method:C.easeOut}, G.element, YAHOO.util.Motion); - E.handleStartAnimateIn = function(M, L, N) { - N.overlay.element.style.left = ((-25) - H) + "px"; - N.overlay.element.style.top = K + "px"; - }; - E.handleTweenAnimateIn = function(O, N, P) { - var Q = B.getXY(P.overlay.element),M = Q[0],L = Q[1]; - if (B.getStyle(P.overlay.element, "visibility") == "hidden" && M < F) { - B.setStyle(P.overlay.element, "visibility", "visible"); - } - P.overlay.cfg.setProperty("xy", [M,L], true); - P.overlay.cfg.refireEvent("iframe"); - }; - E.handleCompleteAnimateIn = function(M, L, N) { - N.overlay.cfg.setProperty("xy", [F,K], true); - N.startX = F; - N.startY = K; - N.overlay.cfg.refireEvent("iframe"); - N.animateInCompleteEvent.fire(); - }; - E.handleStartAnimateOut = function(N, M, Q) { - var O = B.getViewportWidth(),R = B.getXY(Q.overlay.element),P = R[1],L = Q.animOut.attributes.points.to; - Q.animOut.attributes.points.to = [(O + 25),P]; - }; - E.handleTweenAnimateOut = function(N, M, O) { - var Q = B.getXY(O.overlay.element),L = Q[0],P = Q[1]; - O.overlay.cfg.setProperty("xy", [L,P], true); - O.overlay.cfg.refireEvent("iframe"); - }; - E.handleCompleteAnimateOut = function(M, L, N) { - B.setStyle(N.overlay.element, "visibility", "hidden"); - N.overlay.cfg.setProperty("xy", [F,K]); - N.animateOutCompleteEvent.fire(); - }; - E.init(); - return E; - }; - A.prototype = {init:function() { - this.beforeAnimateInEvent = this.createEvent("beforeAnimateIn"); - this.beforeAnimateInEvent.signature = D.LIST; - this.beforeAnimateOutEvent = this.createEvent("beforeAnimateOut"); - this.beforeAnimateOutEvent.signature = D.LIST; - this.animateInCompleteEvent = this.createEvent("animateInComplete"); - this.animateInCompleteEvent.signature = D.LIST; - this.animateOutCompleteEvent = this.createEvent("animateOutComplete"); - this.animateOutCompleteEvent.signature = D.LIST; - this.animIn = - new this.animClass(this.targetElement, this.attrIn.attributes, this.attrIn.duration, this.attrIn.method); - this.animIn.onStart.subscribe(this.handleStartAnimateIn, this); - this.animIn.onTween.subscribe(this.handleTweenAnimateIn, this); - this.animIn.onComplete.subscribe(this.handleCompleteAnimateIn, this); - this.animOut = - new this.animClass(this.targetElement, this.attrOut.attributes, this.attrOut.duration, this.attrOut.method); - this.animOut.onStart.subscribe(this.handleStartAnimateOut, this); - this.animOut.onTween.subscribe(this.handleTweenAnimateOut, this); - this.animOut.onComplete.subscribe(this.handleCompleteAnimateOut, this); - },animateIn:function() { - this.beforeAnimateInEvent.fire(); - this.animIn.animate(); - },animateOut:function() { - this.beforeAnimateOutEvent.fire(); - this.animOut.animate(); - },handleStartAnimateIn:function(F, E, G) { - },handleTweenAnimateIn:function(F, E, G) { - },handleCompleteAnimateIn:function(F, E, G) { - },handleStartAnimateOut:function(F, E, G) { - },handleTweenAnimateOut:function(F, E, G) { - },handleCompleteAnimateOut:function(F, E, G) { - },toString:function() { - var E = "ContainerEffect"; - if (this.overlay) { - E += " [" + this.overlay.toString() + "]"; - } - return E; - }}; - YAHOO.lang.augmentProto(A, YAHOO.util.EventProvider); -})(); -YAHOO.register("container", YAHOO.widget.Module, {version:"2.3.1",build:"541"}); \ No newline at end of file diff --git a/components/policy-editor/org.wso2.carbon.policyeditor.ui/src/main/resources/web/policyeditor/js/yui/container/container_core-min.js b/components/policy-editor/org.wso2.carbon.policyeditor.ui/src/main/resources/web/policyeditor/js/yui/container/container_core-min.js deleted file mode 100644 index c018c7a37421..000000000000 --- a/components/policy-editor/org.wso2.carbon.policyeditor.ui/src/main/resources/web/policyeditor/js/yui/container/container_core-min.js +++ /dev/null @@ -1,1477 +0,0 @@ -/* -Copyright (c) 2007, Yahoo! Inc. All rights reserved. -Code licensed under the BSD License: -http://developer.yahoo.net/yui/license.txt -version: 2.3.1 -*/ -(function() { - YAHOO.util.Config = function(D) { - if (D) { - this.init(D); - } - if (!D) { - } - }; - var B = YAHOO.lang,C = YAHOO.util.CustomEvent,A = YAHOO.util.Config; - A.CONFIG_CHANGED_EVENT = "configChanged"; - A.BOOLEAN_TYPE = "boolean"; - A.prototype = - {owner:null,queueInProgress:false,config:null,initialConfig:null,eventQueue:null,configChangedEvent:null,init:function( - D) { - this.owner = D; - this.configChangedEvent = this.createEvent(A.CONFIG_CHANGED_EVENT); - this.configChangedEvent.signature = C.LIST; - this.queueInProgress = false; - this.config = {}; - this.initialConfig = {}; - this.eventQueue = []; - },checkBoolean:function(D) { - return(typeof D == A.BOOLEAN_TYPE); - },checkNumber:function(D) { - return(!isNaN(D)); - },fireEvent:function(D, F) { - var E = this.config[D]; - if (E && E.event) { - E.event.fire(F); - } - },addProperty:function(E, D) { - E = E.toLowerCase(); - this.config[E] = D; - D.event = this.createEvent(E, {scope:this.owner}); - D.event.signature = C.LIST; - D.key = E; - if (D.handler) { - D.event.subscribe(D.handler, this.owner); - } - this.setProperty(E, D.value, true); - if (!D.suppressEvent) { - this.queueProperty(E, D.value); - } - },getConfig:function() { - var D = {},F,E; - for (F in this.config) { - E = this.config[F]; - if (E && E.event) { - D[F] = E.value; - } - } - return D; - },getProperty:function(D) { - var E = this.config[D.toLowerCase()]; - if (E && E.event) { - return E.value; - } else { - return undefined; - } - },resetProperty:function(D) { - D = D.toLowerCase(); - var E = this.config[D]; - if (E && E.event) { - if (this.initialConfig[D] && !B.isUndefined(this.initialConfig[D])) { - this.setProperty(D, this.initialConfig[D]); - return true; - } - } else { - return false; - } - },setProperty:function(E, G, D) { - var F; - E = E.toLowerCase(); - if (this.queueInProgress && !D) { - this.queueProperty(E, G); - return true; - } else { - F = this.config[E]; - if (F && F.event) { - if (F.validator && !F.validator(G)) { - return false; - } else { - F.value = G; - if (!D) { - this.fireEvent(E, G); - this.configChangedEvent.fire([E,G]); - } - return true; - } - } else { - return false; - } - } - },queueProperty:function(S, P) { - S = S.toLowerCase(); - var R = this.config[S],K = false,J,G,H,I,O,Q,F,M,N,D,L,T,E; - if (R && R.event) { - if (!B.isUndefined(P) && R.validator && !R.validator(P)) { - return false; - } else { - if (!B.isUndefined(P)) { - R.value = P; - } else { - P = R.value; - } - K = false; - J = this.eventQueue.length; - for (L = 0; L < J; L++) { - G = this.eventQueue[L]; - if (G) { - H = G[0]; - I = G[1]; - if (H == S) { - this.eventQueue[L] = null; - this.eventQueue.push([S,(!B.isUndefined(P) ? P : I)]); - K = true; - break; - } - } - } - if (!K && !B.isUndefined(P)) { - this.eventQueue.push([S,P]); - } - } - if (R.supercedes) { - O = R.supercedes.length; - for (T = 0; T < O; T++) { - Q = R.supercedes[T]; - F = this.eventQueue.length; - for (E = 0; E < F; E++) { - M = this.eventQueue[E]; - if (M) { - N = M[0]; - D = M[1]; - if (N == Q.toLowerCase()) { - this.eventQueue.push([N,D]); - this.eventQueue[E] = null; - break; - } - } - } - } - } - return true; - } else { - return false; - } - },refireEvent:function(D) { - D = D.toLowerCase(); - var E = this.config[D]; - if (E && E.event && !B.isUndefined(E.value)) { - if (this.queueInProgress) { - this.queueProperty(D); - } else { - this.fireEvent(D, E.value); - } - } - },applyConfig:function(E, H) { - var G,D,F; - if (H) { - F = {}; - for (G in E) { - if (B.hasOwnProperty(E, G)) { - F[G.toLowerCase()] = E[G]; - } - } - this.initialConfig = F; - } - for (G in E) { - if (B.hasOwnProperty(E, G)) { - this.queueProperty(G, E[G]); - } - } - },refresh:function() { - var D; - for (D in this.config) { - this.refireEvent(D); - } - },fireQueue:function() { - var E,H,D,G,F; - this.queueInProgress = true; - for (E = 0; E < this.eventQueue.length; E++) { - H = this.eventQueue[E]; - if (H) { - D = H[0]; - G = H[1]; - F = this.config[D]; - F.value = G; - this.fireEvent(D, G); - } - } - this.queueInProgress = false; - this.eventQueue = []; - },subscribeToConfigEvent:function(E, F, H, D) { - var G = this.config[E.toLowerCase()]; - if (G && G.event) { - if (!A.alreadySubscribed(G.event, F, H)) { - G.event.subscribe(F, H, D); - } - return true; - } else { - return false; - } - },unsubscribeFromConfigEvent:function(D, E, G) { - var F = this.config[D.toLowerCase()]; - if (F && F.event) { - return F.event.unsubscribe(E, G); - } else { - return false; - } - },toString:function() { - var D = "Config"; - if (this.owner) { - D += " [" + this.owner.toString() + "]"; - } - return D; - },outputEventQueue:function() { - var D = "",G,E,F = this.eventQueue.length; - for (E = 0; E < F; E++) { - G = this.eventQueue[E]; - if (G) { - D += G[0] + "=" + G[1] + ", "; - } - } - return D; - },destroy:function() { - var E = this.config,D,F; - for (D in E) { - if (B.hasOwnProperty(E, D)) { - F = E[D]; - F.event.unsubscribeAll(); - F.event = null; - } - } - this.configChangedEvent.unsubscribeAll(); - this.configChangedEvent = null; - this.owner = null; - this.config = null; - this.initialConfig = null; - this.eventQueue = null; - }}; - A.alreadySubscribed = function(E, H, I) { - var F = E.subscribers.length,D,G; - if (F > 0) { - G = F - 1; - do{ - D = E.subscribers[G]; - if (D && D.obj == I && D.fn == H) { - return true; - } - } while (G--); - } - return false; - }; - YAHOO.lang.augmentProto(A, YAHOO.util.EventProvider); -}()); -(function() { - YAHOO.widget.Module = function(Q, P) { - if (Q) { - this.init(Q, P); - } else { - } - }; - var F = YAHOO.util.Dom,D = YAHOO.util.Config,M = YAHOO.util.Event,L = YAHOO.util.CustomEvent,G = YAHOO.widget.Module,H,O,N,E,A = {"BEFORE_INIT":"beforeInit","INIT":"init","APPEND":"append","BEFORE_RENDER":"beforeRender","RENDER":"render","CHANGE_HEADER":"changeHeader","CHANGE_BODY":"changeBody","CHANGE_FOOTER":"changeFooter","CHANGE_CONTENT":"changeContent","DESTORY":"destroy","BEFORE_SHOW":"beforeShow","SHOW":"show","BEFORE_HIDE":"beforeHide","HIDE":"hide"},I = {"VISIBLE":{key:"visible",value:true,validator:YAHOO.lang.isBoolean},"EFFECT":{key:"effect",suppressEvent:true,supercedes:["visible"]},"MONITOR_RESIZE":{key:"monitorresize",value:true},"APPEND_TO_DOCUMENT_BODY":{key:"appendtodocumentbody",value:false}}; - G.IMG_ROOT = null; - G.IMG_ROOT_SSL = null; - G.CSS_MODULE = "yui-module"; - G.CSS_HEADER = "hd"; - G.CSS_BODY = "bd"; - G.CSS_FOOTER = "ft"; - G.RESIZE_MONITOR_SECURE_URL = "javascript:false;"; - G.textResizeEvent = new L("textResize"); - function K() { - if (!H) { - H = document.createElement("div"); - H.innerHTML = ("
    "); - O = H.firstChild; - N = O.nextSibling; - E = N.nextSibling; - } - return H; - } - function J() { - if (!O) { - K(); - } - return(O.cloneNode(false)); - } - function B() { - if (!N) { - K(); - } - return(N.cloneNode(false)); - } - function C() { - if (!E) { - K(); - } - return(E.cloneNode(false)); - } - G.prototype = - {constructor:G,element:null,header:null,body:null,footer:null,id:null,imageRoot:G.IMG_ROOT,initEvents:function() { - var P = L.LIST; - this.beforeInitEvent = this.createEvent(A.BEFORE_INIT); - this.beforeInitEvent.signature = P; - this.initEvent = this.createEvent(A.INIT); - this.initEvent.signature = P; - this.appendEvent = this.createEvent(A.APPEND); - this.appendEvent.signature = P; - this.beforeRenderEvent = this.createEvent(A.BEFORE_RENDER); - this.beforeRenderEvent.signature = P; - this.renderEvent = this.createEvent(A.RENDER); - this.renderEvent.signature = P; - this.changeHeaderEvent = this.createEvent(A.CHANGE_HEADER); - this.changeHeaderEvent.signature = P; - this.changeBodyEvent = this.createEvent(A.CHANGE_BODY); - this.changeBodyEvent.signature = P; - this.changeFooterEvent = this.createEvent(A.CHANGE_FOOTER); - this.changeFooterEvent.signature = P; - this.changeContentEvent = this.createEvent(A.CHANGE_CONTENT); - this.changeContentEvent.signature = P; - this.destroyEvent = this.createEvent(A.DESTORY); - this.destroyEvent.signature = P; - this.beforeShowEvent = this.createEvent(A.BEFORE_SHOW); - this.beforeShowEvent.signature = P; - this.showEvent = this.createEvent(A.SHOW); - this.showEvent.signature = P; - this.beforeHideEvent = this.createEvent(A.BEFORE_HIDE); - this.beforeHideEvent.signature = P; - this.hideEvent = this.createEvent(A.HIDE); - this.hideEvent.signature = P; - },platform:function() { - var P = navigator.userAgent.toLowerCase(); - if (P.indexOf("windows") != -1 || P.indexOf("win32") != -1) { - return"windows"; - } else { - if (P.indexOf("macintosh") != -1) { - return"mac"; - } else { - return false; - } - } - }(),browser:function() { - var P = navigator.userAgent.toLowerCase(); - if (P.indexOf("opera") != -1) { - return"opera"; - } else { - if (P.indexOf("msie 7") != -1) { - return"ie7"; - } else { - if (P.indexOf("msie") != -1) { - return"ie"; - } else { - if (P.indexOf("safari") != -1) { - return"safari"; - } else { - if (P.indexOf("gecko") != -1) { - return"gecko"; - } else { - return false; - } - } - } - } - } - }(),isSecure:function() { - if (window.location.href.toLowerCase().indexOf("https") === 0) { - return true; - } else { - return false; - } - }(),initDefaultConfig:function() { - this.cfg.addProperty(I.VISIBLE.key, {handler:this.configVisible,value:I.VISIBLE.value,validator:I.VISIBLE.validator}); - this.cfg.addProperty(I.EFFECT.key, {suppressEvent:I.EFFECT.suppressEvent,supercedes:I.EFFECT.supercedes}); - this.cfg.addProperty(I.MONITOR_RESIZE.key, {handler:this.configMonitorResize,value:I.MONITOR_RESIZE.value}); - this.cfg.addProperty(I.APPEND_TO_DOCUMENT_BODY.key, {value:I.APPEND_TO_DOCUMENT_BODY.value}); - },init:function(V, U) { - var R,T,W; - this.initEvents(); - this.beforeInitEvent.fire(G); - this.cfg = new D(this); - if (this.isSecure) { - this.imageRoot = G.IMG_ROOT_SSL; - } - if (typeof V == "string") { - R = V; - V = document.getElementById(V); - if (!V) { - V = (K()).cloneNode(false); - V.id = R; - } - } - this.element = V; - if (V.id) { - this.id = V.id; - } - W = this.element.firstChild; - if (W) { - var Q = false,P = false,S = false; - do{ - if (1 == W.nodeType) { - if (!Q && F.hasClass(W, G.CSS_HEADER)) { - this.header = W; - Q = true; - } else { - if (!P && F.hasClass(W, G.CSS_BODY)) { - this.body = W; - P = true; - } else { - if (!S && F.hasClass(W, G.CSS_FOOTER)) { - this.footer = W; - S = true; - } - } - } - } - } while ((W = W.nextSibling)); - } - this.initDefaultConfig(); - F.addClass(this.element, G.CSS_MODULE); - if (U) { - this.cfg.applyConfig(U, true); - } - if (!D.alreadySubscribed(this.renderEvent, this.cfg.fireQueue, this.cfg)) { - this.renderEvent.subscribe(this.cfg.fireQueue, this.cfg, true); - } - this.initEvent.fire(G); - },initResizeMonitor:function() { - var P,Q,S; - function T() { - G.textResizeEvent.fire(); - } - if (!YAHOO.env.ua.opera) { - Q = F.get("_yuiResizeMonitor"); - if (!Q) { - Q = document.createElement("iframe"); - if (this.isSecure && G.RESIZE_MONITOR_SECURE_URL && YAHOO.env.ua.ie) { - Q.src = G.RESIZE_MONITOR_SECURE_URL; - } - if (YAHOO.env.ua.gecko) { - S = - ""; - Q.src = "data:text/html;charset=utf-8," + encodeURIComponent(S); - } - Q.id = "_yuiResizeMonitor"; - Q.style.position = "absolute"; - Q.style.visibility = "hidden"; - var R = document.body.firstChild; - if (R) { - document.body.insertBefore(Q, R); - } else { - document.body.appendChild(Q); - } - Q.style.width = "10em"; - Q.style.height = "10em"; - Q.style.top = (-1 * Q.offsetHeight) + "px"; - Q.style.left = (-1 * Q.offsetWidth) + "px"; - Q.style.borderWidth = "0"; - Q.style.visibility = "visible"; - if (YAHOO.env.ua.webkit) { - P = Q.contentWindow.document; - P.open(); - P.close(); - } - } - if (Q && Q.contentWindow) { - G.textResizeEvent.subscribe(this.onDomResize, this, true); - if (!G.textResizeInitialized) { - if (!M.on(Q.contentWindow, "resize", T)) { - M.on(Q, "resize", T); - } - G.textResizeInitialized = true; - } - this.resizeMonitor = Q; - } - } - },onDomResize:function(S, R) { - var Q = -1 * this.resizeMonitor.offsetWidth,P = -1 * this.resizeMonitor.offsetHeight; - this.resizeMonitor.style.top = P + "px"; - this.resizeMonitor.style.left = Q + "px"; - },setHeader:function(Q) { - var P = this.header || (this.header = J()); - if (typeof Q == "string") { - P.innerHTML = Q; - } else { - P.innerHTML = ""; - P.appendChild(Q); - } - this.changeHeaderEvent.fire(Q); - this.changeContentEvent.fire(); - },appendToHeader:function(Q) { - var P = this.header || (this.header = J()); - P.appendChild(Q); - this.changeHeaderEvent.fire(Q); - this.changeContentEvent.fire(); - },setBody:function(Q) { - var P = this.body || (this.body = B()); - if (typeof Q == "string") { - P.innerHTML = Q; - } else { - P.innerHTML = ""; - P.appendChild(Q); - } - this.changeBodyEvent.fire(Q); - this.changeContentEvent.fire(); - },appendToBody:function(Q) { - var P = this.body || (this.body = B()); - P.appendChild(Q); - this.changeBodyEvent.fire(Q); - this.changeContentEvent.fire(); - },setFooter:function(Q) { - var P = this.footer || (this.footer = C()); - if (typeof Q == "string") { - P.innerHTML = Q; - } else { - P.innerHTML = ""; - P.appendChild(Q); - } - this.changeFooterEvent.fire(Q); - this.changeContentEvent.fire(); - },appendToFooter:function(Q) { - var P = this.footer || (this.footer = C()); - P.appendChild(Q); - this.changeFooterEvent.fire(Q); - this.changeContentEvent.fire(); - },render:function(R, P) { - var S = this,T; - function Q(U) { - if (typeof U == "string") { - U = document.getElementById(U); - } - if (U) { - S._addToParent(U, S.element); - S.appendEvent.fire(); - } - } - this.beforeRenderEvent.fire(); - if (!P) { - P = this.element; - } - if (R) { - Q(R); - } else { - if (!F.inDocument(this.element)) { - return false; - } - } - if (this.header && !F.inDocument(this.header)) { - T = P.firstChild; - if (T) { - P.insertBefore(this.header, T); - } else { - P.appendChild(this.header); - } - } - if (this.body && !F.inDocument(this.body)) { - if (this.footer && F.isAncestor(this.moduleElement, this.footer)) { - P.insertBefore(this.body, this.footer); - } else { - P.appendChild(this.body); - } - } - if (this.footer && !F.inDocument(this.footer)) { - P.appendChild(this.footer); - } - this.renderEvent.fire(); - return true; - },destroy:function() { - var P,Q; - if (this.element) { - M.purgeElement(this.element, true); - P = this.element.parentNode; - } - if (P) { - P.removeChild(this.element); - } - this.element = null; - this.header = null; - this.body = null; - this.footer = null; - G.textResizeEvent.unsubscribe(this.onDomResize, this); - this.cfg.destroy(); - this.cfg = null; - this.destroyEvent.fire(); - for (Q in this) { - if (Q instanceof L) { - Q.unsubscribeAll(); - } - } - },show:function() { - this.cfg.setProperty("visible", true); - },hide:function() { - this.cfg.setProperty("visible", false); - },configVisible:function(Q, P, R) { - var S = P[0]; - if (S) { - this.beforeShowEvent.fire(); - F.setStyle(this.element, "display", "block"); - this.showEvent.fire(); - } else { - this.beforeHideEvent.fire(); - F.setStyle(this.element, "display", "none"); - this.hideEvent.fire(); - } - },configMonitorResize:function(R, Q, S) { - var P = Q[0]; - if (P) { - this.initResizeMonitor(); - } else { - G.textResizeEvent.unsubscribe(this.onDomResize, this, true); - this.resizeMonitor = null; - } - },_addToParent:function(P, Q) { - if (!this.cfg.getProperty("appendtodocumentbody") && P === document.body && P.firstChild) { - P.insertBefore(Q, P.firstChild); - } else { - P.appendChild(Q); - } - },toString:function() { - return"Module " + this.id; - }}; - YAHOO.lang.augmentProto(G, YAHOO.util.EventProvider); -}()); -(function() { - YAHOO.widget.Overlay = function(L, K) { - YAHOO.widget.Overlay.superclass.constructor.call(this, L, K); - }; - var F = YAHOO.lang,I = YAHOO.util.CustomEvent,E = YAHOO.widget.Module,J = YAHOO.util.Event,D = YAHOO.util.Dom,C = YAHOO.util.Config,B = YAHOO.widget.Overlay,G,A = {"BEFORE_MOVE":"beforeMove","MOVE":"move"},H = {"X":{key:"x",validator:F.isNumber,suppressEvent:true,supercedes:["iframe"]},"Y":{key:"y",validator:F.isNumber,suppressEvent:true,supercedes:["iframe"]},"XY":{key:"xy",suppressEvent:true,supercedes:["iframe"]},"CONTEXT":{key:"context",suppressEvent:true,supercedes:["iframe"]},"FIXED_CENTER":{key:"fixedcenter",value:false,validator:F.isBoolean,supercedes:["iframe","visible"]},"WIDTH":{key:"width",suppressEvent:true,supercedes:["context","fixedcenter","iframe"]},"HEIGHT":{key:"height",suppressEvent:true,supercedes:["context","fixedcenter","iframe"]},"ZINDEX":{key:"zindex",value:null},"CONSTRAIN_TO_VIEWPORT":{key:"constraintoviewport",value:false,validator:F.isBoolean,supercedes:["iframe","x","y","xy"]},"IFRAME":{key:"iframe",value:( - YAHOO.env.ua.ie == 6 ? true : false),validator:F.isBoolean,supercedes:["zindex"]}}; - B.IFRAME_SRC = "javascript:false;"; - B.IFRAME_OFFSET = 3; - B.TOP_LEFT = "tl"; - B.TOP_RIGHT = "tr"; - B.BOTTOM_LEFT = "bl"; - B.BOTTOM_RIGHT = "br"; - B.CSS_OVERLAY = "yui-overlay"; - B.windowScrollEvent = new I("windowScroll"); - B.windowResizeEvent = new I("windowResize"); - B.windowScrollHandler = function(K) { - if (YAHOO.env.ua.ie) { - if (!window.scrollEnd) { - window.scrollEnd = -1; - } - clearTimeout(window.scrollEnd); - window.scrollEnd = setTimeout(function() { - B.windowScrollEvent.fire(); - }, 1); - } else { - B.windowScrollEvent.fire(); - } - }; - B.windowResizeHandler = function(K) { - if (YAHOO.env.ua.ie) { - if (!window.resizeEnd) { - window.resizeEnd = -1; - } - clearTimeout(window.resizeEnd); - window.resizeEnd = setTimeout(function() { - B.windowResizeEvent.fire(); - }, 100); - } else { - B.windowResizeEvent.fire(); - } - }; - B._initialized = null; - if (B._initialized === null) { - J.on(window, "scroll", B.windowScrollHandler); - J.on(window, "resize", B.windowResizeHandler); - B._initialized = true; - } - YAHOO.extend(B, E, {init:function(L, K) { - B.superclass.init.call(this, L); - this.beforeInitEvent.fire(B); - D.addClass(this.element, B.CSS_OVERLAY); - if (K) { - this.cfg.applyConfig(K, true); - } - if (this.platform == "mac" && YAHOO.env.ua.gecko) { - if (!C.alreadySubscribed(this.showEvent, this.showMacGeckoScrollbars, this)) { - this.showEvent.subscribe(this.showMacGeckoScrollbars, this, true); - } - if (!C.alreadySubscribed(this.hideEvent, this.hideMacGeckoScrollbars, this)) { - this.hideEvent.subscribe(this.hideMacGeckoScrollbars, this, true); - } - } - this.initEvent.fire(B); - },initEvents:function() { - B.superclass.initEvents.call(this); - var K = I.LIST; - this.beforeMoveEvent = this.createEvent(A.BEFORE_MOVE); - this.beforeMoveEvent.signature = K; - this.moveEvent = this.createEvent(A.MOVE); - this.moveEvent.signature = K; - },initDefaultConfig:function() { - B.superclass.initDefaultConfig.call(this); - this.cfg.addProperty(H.X.key, {handler:this.configX,validator:H.X.validator,suppressEvent:H.X.suppressEvent,supercedes:H.X.supercedes}); - this.cfg.addProperty(H.Y.key, {handler:this.configY,validator:H.Y.validator,suppressEvent:H.Y.suppressEvent,supercedes:H.Y.supercedes}); - this.cfg.addProperty(H.XY.key, {handler:this.configXY,suppressEvent:H.XY.suppressEvent,supercedes:H.XY.supercedes}); - this.cfg.addProperty(H.CONTEXT.key, {handler:this.configContext,suppressEvent:H.CONTEXT.suppressEvent,supercedes:H.CONTEXT.supercedes}); - this.cfg.addProperty(H.FIXED_CENTER.key, {handler:this.configFixedCenter,value:H.FIXED_CENTER.value,validator:H.FIXED_CENTER.validator,supercedes:H.FIXED_CENTER.supercedes}); - this.cfg.addProperty(H.WIDTH.key, {handler:this.configWidth,suppressEvent:H.WIDTH.suppressEvent,supercedes:H.WIDTH.supercedes}); - this.cfg.addProperty(H.HEIGHT.key, {handler:this.configHeight,suppressEvent:H.HEIGHT.suppressEvent,supercedes:H.HEIGHT.supercedes}); - this.cfg.addProperty(H.ZINDEX.key, {handler:this.configzIndex,value:H.ZINDEX.value}); - this.cfg.addProperty(H.CONSTRAIN_TO_VIEWPORT.key, {handler:this.configConstrainToViewport,value:H.CONSTRAIN_TO_VIEWPORT.value,validator:H.CONSTRAIN_TO_VIEWPORT.validator,supercedes:H.CONSTRAIN_TO_VIEWPORT.supercedes}); - this.cfg.addProperty(H.IFRAME.key, {handler:this.configIframe,value:H.IFRAME.value,validator:H.IFRAME.validator,supercedes:H.IFRAME.supercedes}); - },moveTo:function(K, L) { - this.cfg.setProperty("xy", [K,L]); - },hideMacGeckoScrollbars:function() { - D.removeClass(this.element, "show-scrollbars"); - D.addClass(this.element, "hide-scrollbars"); - },showMacGeckoScrollbars:function() { - D.removeClass(this.element, "hide-scrollbars"); - D.addClass(this.element, "show-scrollbars"); - },configVisible:function(N, K, T) { - var M = K[0],O = D.getStyle(this.element, "visibility"),U = this.cfg.getProperty("effect"),R = [],Q = (this.platform == - "mac" && - YAHOO.env.ua.gecko),b = C.alreadySubscribed,S,L,a,Y,X,W,Z,V,P; - if (O == "inherit") { - a = this.element.parentNode; - while (a.nodeType != 9 && a.nodeType != 11) { - O = D.getStyle(a, "visibility"); - if (O != "inherit") { - break; - } - a = a.parentNode; - } - if (O == "inherit") { - O = "visible"; - } - } - if (U) { - if (U instanceof Array) { - V = U.length; - for (Y = 0; Y < V; Y++) { - S = U[Y]; - R[R.length] = S.effect(this, S.duration); - } - } else { - R[R.length] = U.effect(this, U.duration); - } - } - if (M) { - if (Q) { - this.showMacGeckoScrollbars(); - } - if (U) { - if (M) { - if (O != "visible" || O === "") { - this.beforeShowEvent.fire(); - P = R.length; - for (X = 0; X < P; X++) { - L = R[X]; - if (X === 0 && - !b(L.animateInCompleteEvent, this.showEvent.fire, this.showEvent)) { - L.animateInCompleteEvent.subscribe(this.showEvent.fire, this.showEvent, true); - } - L.animateIn(); - } - } - } - } else { - if (O != "visible" || O === "") { - this.beforeShowEvent.fire(); - D.setStyle(this.element, "visibility", "visible"); - this.cfg.refireEvent("iframe"); - this.showEvent.fire(); - } - } - } else { - if (Q) { - this.hideMacGeckoScrollbars(); - } - if (U) { - if (O == "visible") { - this.beforeHideEvent.fire(); - P = R.length; - for (W = 0; W < P; W++) { - Z = R[W]; - if (W === 0 && - !b(Z.animateOutCompleteEvent, this.hideEvent.fire, this.hideEvent)) { - Z.animateOutCompleteEvent.subscribe(this.hideEvent.fire, this.hideEvent, true); - } - Z.animateOut(); - } - } else { - if (O === "") { - D.setStyle(this.element, "visibility", "hidden"); - } - } - } else { - if (O == "visible" || O === "") { - this.beforeHideEvent.fire(); - D.setStyle(this.element, "visibility", "hidden"); - this.hideEvent.fire(); - } - } - } - },doCenterOnDOMEvent:function() { - if (this.cfg.getProperty("visible")) { - this.center(); - } - },configFixedCenter:function(O, M, P) { - var Q = M[0],L = C.alreadySubscribed,N = B.windowResizeEvent,K = B.windowScrollEvent; - if (Q) { - this.center(); - if (!L(this.beforeShowEvent, this.center, this)) { - this.beforeShowEvent.subscribe(this.center); - } - if (!L(N, this.doCenterOnDOMEvent, this)) { - N.subscribe(this.doCenterOnDOMEvent, this, true); - } - if (!L(K, this.doCenterOnDOMEvent, this)) { - K.subscribe(this.doCenterOnDOMEvent, this, true); - } - } else { - this.beforeShowEvent.unsubscribe(this.center); - N.unsubscribe(this.doCenterOnDOMEvent, this); - K.unsubscribe(this.doCenterOnDOMEvent, this); - } - },configHeight:function(N, L, O) { - var K = L[0],M = this.element; - D.setStyle(M, "height", K); - this.cfg.refireEvent("iframe"); - },configWidth:function(N, K, O) { - var M = K[0],L = this.element; - D.setStyle(L, "width", M); - this.cfg.refireEvent("iframe"); - },configzIndex:function(M, K, N) { - var O = K[0],L = this.element; - if (!O) { - O = D.getStyle(L, "zIndex"); - if (!O || isNaN(O)) { - O = 0; - } - } - if (this.iframe || this.cfg.getProperty("iframe") === true) { - if (O <= 0) { - O = 1; - } - } - D.setStyle(L, "zIndex", O); - this.cfg.setProperty("zIndex", O, true); - if (this.iframe) { - this.stackIframe(); - } - },configXY:function(M, L, N) { - var P = L[0],K = P[0],O = P[1]; - this.cfg.setProperty("x", K); - this.cfg.setProperty("y", O); - this.beforeMoveEvent.fire([K,O]); - K = this.cfg.getProperty("x"); - O = this.cfg.getProperty("y"); - this.cfg.refireEvent("iframe"); - this.moveEvent.fire([K,O]); - },configX:function(M, L, N) { - var K = L[0],O = this.cfg.getProperty("y"); - this.cfg.setProperty("x", K, true); - this.cfg.setProperty("y", O, true); - this.beforeMoveEvent.fire([K,O]); - K = this.cfg.getProperty("x"); - O = this.cfg.getProperty("y"); - D.setX(this.element, K, true); - this.cfg.setProperty("xy", [K,O], true); - this.cfg.refireEvent("iframe"); - this.moveEvent.fire([K,O]); - },configY:function(M, L, N) { - var K = this.cfg.getProperty("x"),O = L[0]; - this.cfg.setProperty("x", K, true); - this.cfg.setProperty("y", O, true); - this.beforeMoveEvent.fire([K,O]); - K = this.cfg.getProperty("x"); - O = this.cfg.getProperty("y"); - D.setY(this.element, O, true); - this.cfg.setProperty("xy", [K,O], true); - this.cfg.refireEvent("iframe"); - this.moveEvent.fire([K,O]); - },showIframe:function() { - var L = this.iframe,K; - if (L) { - K = this.element.parentNode; - if (K != L.parentNode) { - this._addToParent(K, L); - } - L.style.display = "block"; - } - },hideIframe:function() { - if (this.iframe) { - this.iframe.style.display = "none"; - } - },syncIframe:function() { - var K = this.iframe,M = this.element,O = B.IFRAME_OFFSET,L = (O * 2),N; - if (K) { - K.style.width = (M.offsetWidth + L + "px"); - K.style.height = (M.offsetHeight + L + "px"); - N = this.cfg.getProperty("xy"); - if (!F.isArray(N) || (isNaN(N[0]) || isNaN(N[1]))) { - this.syncPosition(); - N = this.cfg.getProperty("xy"); - } - D.setXY(K, [(N[0] - O),(N[1] - O)]); - } - },stackIframe:function() { - if (this.iframe) { - var K = D.getStyle(this.element, "zIndex"); - if (!YAHOO.lang.isUndefined(K) && !isNaN(K)) { - D.setStyle(this.iframe, "zIndex", (K - 1)); - } - } - },configIframe:function(N, M, O) { - var K = M[0]; - function P() { - var R = this.iframe,S = this.element,U,T; - if (!R) { - if (!G) { - G = document.createElement("iframe"); - if (this.isSecure) { - G.src = B.IFRAME_SRC; - } - if (YAHOO.env.ua.ie) { - G.style.filter = "alpha(opacity=0)"; - G.frameBorder = 0; - } else { - G.style.opacity = "0"; - } - G.style.position = "absolute"; - G.style.border = "none"; - G.style.margin = "0"; - G.style.padding = "0"; - G.style.display = "none"; - } - R = G.cloneNode(false); - U = S.parentNode; - var Q = U || document.body; - this._addToParent(Q, R); - this.iframe = R; - } - this.showIframe(); - this.syncIframe(); - this.stackIframe(); - if (!this._hasIframeEventListeners) { - this.showEvent.subscribe(this.showIframe); - this.hideEvent.subscribe(this.hideIframe); - this.changeContentEvent.subscribe(this.syncIframe); - this._hasIframeEventListeners = true; - } - } - function L() { - P.call(this); - this.beforeShowEvent.unsubscribe(L); - this._iframeDeferred = false; - } - if (K) { - if (this.cfg.getProperty("visible")) { - P.call(this); - } else { - if (!this._iframeDeferred) { - this.beforeShowEvent.subscribe(L); - this._iframeDeferred = true; - } - } - } else { - this.hideIframe(); - if (this._hasIframeEventListeners) { - this.showEvent.unsubscribe(this.showIframe); - this.hideEvent.unsubscribe(this.hideIframe); - this.changeContentEvent.unsubscribe(this.syncIframe); - this._hasIframeEventListeners = false; - } - } - },configConstrainToViewport:function(L, K, M) { - var N = K[0]; - if (N) { - if (!C.alreadySubscribed(this.beforeMoveEvent, this.enforceConstraints, this)) { - this.beforeMoveEvent.subscribe(this.enforceConstraints, this, true); - } - } else { - this.beforeMoveEvent.unsubscribe(this.enforceConstraints, this); - } - },configContext:function(M, L, O) { - var Q = L[0],N,P,K; - if (Q) { - N = Q[0]; - P = Q[1]; - K = Q[2]; - if (N) { - if (typeof N == "string") { - this.cfg.setProperty("context", [document.getElementById(N),P,K], true); - } - if (P && K) { - this.align(P, K); - } - } - } - },align:function(L, K) { - var Q = this.cfg.getProperty("context"),P = this,O,N,R; - function M(S, T) { - switch (L) {case B.TOP_LEFT:P.moveTo(T, S);break;case B.TOP_RIGHT:P.moveTo((T - - N.offsetWidth), S);break;case B.BOTTOM_LEFT:P.moveTo(T, (S - - N.offsetHeight));break;case B.BOTTOM_RIGHT:P.moveTo((T - - N.offsetWidth), (S - - N.offsetHeight));break;} - } - if (Q) { - O = Q[0]; - N = this.element; - P = this; - if (!L) { - L = Q[1]; - } - if (!K) { - K = Q[2]; - } - if (N && O) { - R = D.getRegion(O); - switch (K) {case B.TOP_LEFT:M(R.top, R.left); - break;case B.TOP_RIGHT:M(R.top, R.right);break;case B.BOTTOM_LEFT:M(R.bottom, R.left);break;case B.BOTTOM_RIGHT:M(R.bottom, R.right);break;} - } - } - },enforceConstraints:function(S, R, O) { - var U = R[0],W = U[0],V = U[1],L = this.element.offsetHeight,Q = this.element.offsetWidth,T = D.getViewportWidth(),N = D.getViewportHeight(),Z = D.getDocumentScrollLeft(),X = D.getDocumentScrollTop(),M = X + - 10,P = Z + - 10,K = X + - N - - L - - 10,Y = Z + - T - - Q - - 10; - if (W < P) { - W = P; - } else { - if (W > Y) { - W = Y; - } - } - if (V < M) { - V = M; - } else { - if (V > K) { - V = K; - } - } - this.cfg.setProperty("x", W, true); - this.cfg.setProperty("y", V, true); - this.cfg.setProperty("xy", [W,V], true); - },center:function() { - var Q = D.getDocumentScrollLeft(),O = D.getDocumentScrollTop(),L = D.getClientWidth(),P = D.getClientHeight(),N = this.element.offsetWidth,M = this.element.offsetHeight,K = (L / - 2) - - (N / - 2) + - Q,R = (P / - 2) - - (M / - 2) + - O; - this.cfg.setProperty("xy", [parseInt(K, 10),parseInt(R, 10)]); - this.cfg.refireEvent("iframe"); - },syncPosition:function() { - var K = D.getXY(this.element); - this.cfg.setProperty("x", K[0], true); - this.cfg.setProperty("y", K[1], true); - this.cfg.setProperty("xy", K, true); - },onDomResize:function(M, L) { - var K = this; - B.superclass.onDomResize.call(this, M, L); - setTimeout(function() { - K.syncPosition(); - K.cfg.refireEvent("iframe"); - K.cfg.refireEvent("context"); - }, 0); - },bringToTop:function() { - var N = [],M = this.element; - function P(T, S) { - var V = D.getStyle(T, "zIndex"),U = D.getStyle(S, "zIndex"),R = (!V || isNaN(V)) ? 0 : - parseInt(V, 10),Q = - (!U || isNaN(U)) ? 0 : parseInt(U, 10); - if (R > Q) { - return -1; - } else { - if (R < Q) { - return 1; - } else { - return 0; - } - } - } - function L(S) { - var Q = D.hasClass(S, B.CSS_OVERLAY),R = YAHOO.widget.Panel; - if (Q && !D.isAncestor(M, Q)) { - if (R && D.hasClass(S, R.CSS_PANEL)) { - N[N.length] = S.parentNode; - } else { - N[N.length] = S; - } - } - } - D.getElementsBy(L, "DIV", document.body); - N.sort(P); - var K = N[0],O; - if (K) { - O = D.getStyle(K, "zIndex"); - if (!isNaN(O) && K != M) { - this.cfg.setProperty("zindex", (parseInt(O, 10) + 2)); - } - } - },destroy:function() { - if (this.iframe) { - this.iframe.parentNode.removeChild(this.iframe); - } - this.iframe = null; - B.windowResizeEvent.unsubscribe(this.doCenterOnDOMEvent, this); - B.windowScrollEvent.unsubscribe(this.doCenterOnDOMEvent, this); - B.superclass.destroy.call(this); - },toString:function() { - return"Overlay " + this.id; - }}); -}()); -(function() { - YAHOO.widget.OverlayManager = function(G) { - this.init(G); - }; - var D = YAHOO.widget.Overlay,C = YAHOO.util.Event,E = YAHOO.util.Dom,B = YAHOO.util.Config,F = YAHOO.util.CustomEvent,A = YAHOO.widget.OverlayManager; - A.CSS_FOCUSED = "focused"; - A.prototype = {constructor:A,overlays:null,initDefaultConfig:function() { - this.cfg.addProperty("overlays", {suppressEvent:true}); - this.cfg.addProperty("focusevent", {value:"mousedown"}); - },init:function(I) { - this.cfg = new B(this); - this.initDefaultConfig(); - if (I) { - this.cfg.applyConfig(I, true); - } - this.cfg.fireQueue(); - var H = null; - this.getActive = function() { - return H; - }; - this.focus = function(J) { - var K = this.find(J); - if (K) { - if (H != K) { - if (H) { - H.blur(); - } - this.bringToTop(K); - H = K; - E.addClass(H.element, A.CSS_FOCUSED); - K.focusEvent.fire(); - } - } - }; - this.remove = function(K) { - var M = this.find(K),J; - if (M) { - if (H == M) { - H = null; - } - var L = (M.element === null && M.cfg === null) ? true : false; - if (!L) { - J = E.getStyle(M.element, "zIndex"); - M.cfg.setProperty("zIndex", -1000, true); - } - this.overlays.sort(this.compareZIndexDesc); - this.overlays = this.overlays.slice(0, (this.overlays.length - 1)); - M.hideEvent.unsubscribe(M.blur); - M.destroyEvent.unsubscribe(this._onOverlayDestroy, M); - if (!L) { - C.removeListener(M.element, this.cfg.getProperty("focusevent"), this._onOverlayElementFocus); - M.cfg.setProperty("zIndex", J, true); - M.cfg.setProperty("manager", null); - } - M.focusEvent.unsubscribeAll(); - M.blurEvent.unsubscribeAll(); - M.focusEvent = null; - M.blurEvent = null; - M.focus = null; - M.blur = null; - } - }; - this.blurAll = function() { - var K = this.overlays.length,J; - if (K > 0) { - J = K - 1; - do{ - this.overlays[J].blur(); - } while (J--); - } - }; - this._onOverlayBlur = function(K, J) { - H = null; - }; - var G = this.cfg.getProperty("overlays"); - if (!this.overlays) { - this.overlays = []; - } - if (G) { - this.register(G); - this.overlays.sort(this.compareZIndexDesc); - } - },_onOverlayElementFocus:function(I) { - var G = C.getTarget(I),H = this.close; - if (H && (G == H || E.isAncestor(H, G))) { - this.blur(); - } else { - this.focus(); - } - },_onOverlayDestroy:function(H, G, I) { - this.remove(I); - },register:function(G) { - var K = this,L,I,H,J; - if (G instanceof D) { - G.cfg.addProperty("manager", {value:this}); - G.focusEvent = G.createEvent("focus"); - G.focusEvent.signature = F.LIST; - G.blurEvent = G.createEvent("blur"); - G.blurEvent.signature = F.LIST; - G.focus = function() { - K.focus(this); - }; - G.blur = function() { - if (K.getActive() == this) { - E.removeClass(this.element, A.CSS_FOCUSED); - this.blurEvent.fire(); - } - }; - G.blurEvent.subscribe(K._onOverlayBlur); - G.hideEvent.subscribe(G.blur); - G.destroyEvent.subscribe(this._onOverlayDestroy, G, this); - C.on(G.element, this.cfg.getProperty("focusevent"), this._onOverlayElementFocus, null, G); - L = E.getStyle(G.element, "zIndex"); - if (!isNaN(L)) { - G.cfg.setProperty("zIndex", parseInt(L, 10)); - } else { - G.cfg.setProperty("zIndex", 0); - } - this.overlays.push(G); - this.bringToTop(G); - return true; - } else { - if (G instanceof Array) { - I = 0; - J = G.length; - for (H = 0; H < J; H++) { - if (this.register(G[H])) { - I++; - } - } - if (I > 0) { - return true; - } - } else { - return false; - } - } - },bringToTop:function(K) { - var H = this.find(K),J,G,I; - if (H) { - I = this.overlays; - I.sort(this.compareZIndexDesc); - G = I[0]; - if (G) { - J = E.getStyle(G.element, "zIndex"); - if (!isNaN(J) && G != H) { - H.cfg.setProperty("zIndex", (parseInt(J, 10) + 2)); - } - I.sort(this.compareZIndexDesc); - } - } - },find:function(G) { - var I = this.overlays,J = I.length,H; - if (J > 0) { - H = J - 1; - if (G instanceof D) { - do{ - if (I[H] == G) { - return I[H]; - } - } while (H--); - } else { - if (typeof G == "string") { - do{ - if (I[H].id == G) { - return I[H]; - } - } while (H--); - } - } - return null; - } - },compareZIndexDesc:function(J, I) { - var H = (J.cfg) ? J.cfg.getProperty("zIndex") : null,G = (I.cfg) ? - I.cfg.getProperty("zIndex") : null; - if (H === null && G === null) { - return 0; - } else { - if (H === null) { - return 1; - } else { - if (G === null) { - return -1; - } else { - if (H > G) { - return -1; - } else { - if (H < G) { - return 1; - } else { - return 0; - } - } - } - } - } - },showAll:function() { - var H = this.overlays,I = H.length,G; - if (I > 0) { - G = I - 1; - do{ - H[G].show(); - } while (G--); - } - },hideAll:function() { - var H = this.overlays,I = H.length,G; - if (I > 0) { - G = I - 1; - do{ - H[G].hide(); - } while (G--); - } - },toString:function() { - return"OverlayManager"; - }}; -}()); -(function() { - YAHOO.widget.ContainerEffect = function(F, I, H, E, G) { - if (!G) { - G = YAHOO.util.Anim; - } - this.overlay = F; - this.attrIn = I; - this.attrOut = H; - this.targetElement = E || F.element; - this.animClass = G; - }; - var B = YAHOO.util.Dom,D = YAHOO.util.CustomEvent,C = YAHOO.util.Easing,A = YAHOO.widget.ContainerEffect; - A.FADE = function(E, F) { - var G = new A(E, {attributes:{opacity:{from:0,to:1}},duration:F,method:C.easeIn}, {attributes:{opacity:{to:0}},duration:F,method:C.easeOut}, E.element); - G.handleStartAnimateIn = function(I, H, J) { - B.addClass(J.overlay.element, "hide-select"); - if (!J.overlay.underlay) { - J.overlay.cfg.refireEvent("underlay"); - } - if (J.overlay.underlay) { - J.initialUnderlayOpacity = B.getStyle(J.overlay.underlay, "opacity"); - J.overlay.underlay.style.filter = null; - } - B.setStyle(J.overlay.element, "visibility", "visible"); - B.setStyle(J.overlay.element, "opacity", 0); - }; - G.handleCompleteAnimateIn = function(I, H, J) { - B.removeClass(J.overlay.element, "hide-select"); - if (J.overlay.element.style.filter) { - J.overlay.element.style.filter = null; - } - if (J.overlay.underlay) { - B.setStyle(J.overlay.underlay, "opacity", J.initialUnderlayOpacity); - } - J.overlay.cfg.refireEvent("iframe"); - J.animateInCompleteEvent.fire(); - }; - G.handleStartAnimateOut = function(I, H, J) { - B.addClass(J.overlay.element, "hide-select"); - if (J.overlay.underlay) { - J.overlay.underlay.style.filter = null; - } - }; - G.handleCompleteAnimateOut = function(I, H, J) { - B.removeClass(J.overlay.element, "hide-select"); - if (J.overlay.element.style.filter) { - J.overlay.element.style.filter = null; - } - B.setStyle(J.overlay.element, "visibility", "hidden"); - B.setStyle(J.overlay.element, "opacity", 1); - J.overlay.cfg.refireEvent("iframe"); - J.animateOutCompleteEvent.fire(); - }; - G.init(); - return G; - }; - A.SLIDE = function(G, I) { - var F = G.cfg.getProperty("x") || B.getX(G.element),K = G.cfg.getProperty("y") || - B.getY(G.element),J = B.getClientWidth(),H = G.element.offsetWidth,E = new A(G, {attributes:{points:{to:[F,K]}},duration:I,method:C.easeIn}, {attributes:{points:{to:[(J + - 25),K]}},duration:I,method:C.easeOut}, G.element, YAHOO.util.Motion); - E.handleStartAnimateIn = function(M, L, N) { - N.overlay.element.style.left = ((-25) - H) + "px"; - N.overlay.element.style.top = K + "px"; - }; - E.handleTweenAnimateIn = function(O, N, P) { - var Q = B.getXY(P.overlay.element),M = Q[0],L = Q[1]; - if (B.getStyle(P.overlay.element, "visibility") == "hidden" && M < F) { - B.setStyle(P.overlay.element, "visibility", "visible"); - } - P.overlay.cfg.setProperty("xy", [M,L], true); - P.overlay.cfg.refireEvent("iframe"); - }; - E.handleCompleteAnimateIn = function(M, L, N) { - N.overlay.cfg.setProperty("xy", [F,K], true); - N.startX = F; - N.startY = K; - N.overlay.cfg.refireEvent("iframe"); - N.animateInCompleteEvent.fire(); - }; - E.handleStartAnimateOut = function(N, M, Q) { - var O = B.getViewportWidth(),R = B.getXY(Q.overlay.element),P = R[1],L = Q.animOut.attributes.points.to; - Q.animOut.attributes.points.to = [(O + 25),P]; - }; - E.handleTweenAnimateOut = function(N, M, O) { - var Q = B.getXY(O.overlay.element),L = Q[0],P = Q[1]; - O.overlay.cfg.setProperty("xy", [L,P], true); - O.overlay.cfg.refireEvent("iframe"); - }; - E.handleCompleteAnimateOut = function(M, L, N) { - B.setStyle(N.overlay.element, "visibility", "hidden"); - N.overlay.cfg.setProperty("xy", [F,K]); - N.animateOutCompleteEvent.fire(); - }; - E.init(); - return E; - }; - A.prototype = {init:function() { - this.beforeAnimateInEvent = this.createEvent("beforeAnimateIn"); - this.beforeAnimateInEvent.signature = D.LIST; - this.beforeAnimateOutEvent = this.createEvent("beforeAnimateOut"); - this.beforeAnimateOutEvent.signature = D.LIST; - this.animateInCompleteEvent = this.createEvent("animateInComplete"); - this.animateInCompleteEvent.signature = D.LIST; - this.animateOutCompleteEvent = this.createEvent("animateOutComplete"); - this.animateOutCompleteEvent.signature = D.LIST; - this.animIn = - new this.animClass(this.targetElement, this.attrIn.attributes, this.attrIn.duration, this.attrIn.method); - this.animIn.onStart.subscribe(this.handleStartAnimateIn, this); - this.animIn.onTween.subscribe(this.handleTweenAnimateIn, this); - this.animIn.onComplete.subscribe(this.handleCompleteAnimateIn, this); - this.animOut = - new this.animClass(this.targetElement, this.attrOut.attributes, this.attrOut.duration, this.attrOut.method); - this.animOut.onStart.subscribe(this.handleStartAnimateOut, this); - this.animOut.onTween.subscribe(this.handleTweenAnimateOut, this); - this.animOut.onComplete.subscribe(this.handleCompleteAnimateOut, this); - },animateIn:function() { - this.beforeAnimateInEvent.fire(); - this.animIn.animate(); - },animateOut:function() { - this.beforeAnimateOutEvent.fire(); - this.animOut.animate(); - },handleStartAnimateIn:function(F, E, G) { - },handleTweenAnimateIn:function(F, E, G) { - },handleCompleteAnimateIn:function(F, E, G) { - },handleStartAnimateOut:function(F, E, G) { - },handleTweenAnimateOut:function(F, E, G) { - },handleCompleteAnimateOut:function(F, E, G) { - },toString:function() { - var E = "ContainerEffect"; - if (this.overlay) { - E += " [" + this.overlay.toString() + "]"; - } - return E; - }}; - YAHOO.lang.augmentProto(A, YAHOO.util.EventProvider); -})(); -YAHOO.register("container_core", YAHOO.widget.Module, {version:"2.3.1",build:"541"}); \ No newline at end of file diff --git a/components/policy-editor/org.wso2.carbon.policyeditor.ui/src/main/resources/web/policyeditor/js/yui/element/element-beta-min.js b/components/policy-editor/org.wso2.carbon.policyeditor.ui/src/main/resources/web/policyeditor/js/yui/element/element-beta-min.js deleted file mode 100644 index babdd5ca34af..000000000000 --- a/components/policy-editor/org.wso2.carbon.policyeditor.ui/src/main/resources/web/policyeditor/js/yui/element/element-beta-min.js +++ /dev/null @@ -1,8 +0,0 @@ -/* -Copyright (c) 2007, Yahoo! Inc. All rights reserved. -Code licensed under the BSD License: -http://developer.yahoo.net/yui/license.txt -version: 2.3.1 -*/ -YAHOO.util.Attribute=function(B,A){if(A){this.owner=A;this.configure(B,true);}};YAHOO.util.Attribute.prototype={name:undefined,value:null,owner:null,readOnly:false,writeOnce:false,_initialConfig:null,_written:false,method:null,validator:null,getValue:function(){return this.value;},setValue:function(F,B){var E;var A=this.owner;var C=this.name;var D={type:C,prevValue:this.getValue(),newValue:F};if(this.readOnly||(this.writeOnce&&this._written)){return false;}if(this.validator&&!this.validator.call(A,F)){return false;}if(!B){E=A.fireBeforeChangeEvent(D);if(E===false){return false;}}if(this.method){this.method.call(A,F);}this.value=F;this._written=true;D.type=C;if(!B){this.owner.fireChangeEvent(D);}return true;},configure:function(B,C){B=B||{};this._written=false;this._initialConfig=this._initialConfig||{};for(var A in B){if(A&&YAHOO.lang.hasOwnProperty(B,A)){this[A]=B[A];if(C){this._initialConfig[A]=B[A];}}}},resetValue:function(){return this.setValue(this._initialConfig.value);},resetConfig:function(){this.configure(this._initialConfig);},refresh:function(A){this.setValue(this.value,A);}};(function(){var A=YAHOO.util.Lang;YAHOO.util.AttributeProvider=function(){};YAHOO.util.AttributeProvider.prototype={_configs:null,get:function(C){this._configs=this._configs||{};var B=this._configs[C];if(!B){return undefined;}return B.value;},set:function(D,E,B){this._configs=this._configs||{};var C=this._configs[D];if(!C){return false;}return C.setValue(E,B);},getAttributeKeys:function(){this._configs=this._configs;var D=[];var B;for(var C in this._configs){B=this._configs[C];if(A.hasOwnProperty(this._configs,C)&&!A.isUndefined(B)){D[D.length]=C;}}return D;},setAttributes:function(D,B){for(var C in D){if(A.hasOwnProperty(D,C)){this.set(C,D[C],B);}}},resetValue:function(C,B){this._configs=this._configs||{};if(this._configs[C]){this.set(C,this._configs[C]._initialConfig.value,B);return true;}return false;},refresh:function(E,C){this._configs=this._configs;E=((A.isString(E))?[E]:E)||this.getAttributeKeys();for(var D=0,B=E.length;D element used for a menu's shadow is appended - to its root element via JavaScript once it has been rendered. The - code that creates the shadow lives in the menu's public "onRender" - event handler that is a prototype method of YAHOO.widget.Menu. - Implementers wishing to remove a menu's shadow or add any other markup - required for a given skin for menu should override the "onRender" method. -*/ - -.yui-menu-shadow { - - position: absolute; - z-index: -1; - -} - - - -/* - -There are two known issues with YAHOO.widget.Overlay (the superclass class of -Menu) that manifest in Gecko-based browsers on Mac OS X: - - 1) Elements with scrollbars will poke through Overlay instances floating - above them. - - 2) An Overlay's scrollbars and the scrollbars of its child nodes remain - visible when the Overlay is hidden. - -To fix these bugs in Menu (a subclass of YAHOO.widget.Overlay): - - 1) The "overflow" property of a Menu instance's shadow element and child - nodes is toggled between "hidden" and "auto" (through the application - and removal of the "hide-scrollbars" and "show-scrollbars" CSS classes) - as its "visibility" configuration property is toggled between - "false" and "true." - - 2) The "display" property of