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 f2c63a12284a..42f55775c818 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.10-SNAPSHOT + 7.7.63-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/internal/ActionExecutionServiceComponent.java b/components/action-mgt/org.wso2.carbon.identity.action.execution/src/main/java/org/wso2/carbon/identity/action/execution/internal/ActionExecutionServiceComponent.java index 02e3efc2a81d..94c1e40a3719 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.execution/src/main/java/org/wso2/carbon/identity/action/execution/internal/ActionExecutionServiceComponent.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.execution/src/main/java/org/wso2/carbon/identity/action/execution/internal/ActionExecutionServiceComponent.java @@ -34,7 +34,7 @@ import org.wso2.carbon.identity.action.execution.impl.ActionExecutionRequestBuilderFactory; import org.wso2.carbon.identity.action.execution.impl.ActionExecutionResponseProcessorFactory; import org.wso2.carbon.identity.action.execution.impl.ActionExecutorServiceImpl; -import org.wso2.carbon.identity.action.management.ActionManagementService; +import org.wso2.carbon.identity.action.management.service.ActionManagementService; /** * OSGI service component for the Action execution. diff --git a/components/action-mgt/org.wso2.carbon.identity.action.execution/src/main/java/org/wso2/carbon/identity/action/execution/internal/ActionExecutionServiceComponentHolder.java b/components/action-mgt/org.wso2.carbon.identity.action.execution/src/main/java/org/wso2/carbon/identity/action/execution/internal/ActionExecutionServiceComponentHolder.java index 83be753ef413..8163a538354a 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.execution/src/main/java/org/wso2/carbon/identity/action/execution/internal/ActionExecutionServiceComponentHolder.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.execution/src/main/java/org/wso2/carbon/identity/action/execution/internal/ActionExecutionServiceComponentHolder.java @@ -18,7 +18,7 @@ package org.wso2.carbon.identity.action.execution.internal; -import org.wso2.carbon.identity.action.management.ActionManagementService; +import org.wso2.carbon.identity.action.management.service.ActionManagementService; /** * This class holds references for dependent services required for Action Execution Service to function. 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..f3414560a6e3 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 @@ -60,11 +60,11 @@ import org.wso2.carbon.identity.action.execution.util.ActionExecutionDiagnosticLogger; import org.wso2.carbon.identity.action.execution.util.ActionExecutorConfig; import org.wso2.carbon.identity.action.execution.util.RequestFilter; -import org.wso2.carbon.identity.action.management.ActionManagementService; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.action.management.model.Authentication; import org.wso2.carbon.identity.action.management.model.EndpointConfig; +import org.wso2.carbon.identity.action.management.service.ActionManagementService; import org.wso2.carbon.identity.central.log.mgt.utils.LoggerUtils; import java.lang.reflect.Field; @@ -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 80cc06b93d9e..70c6ff373c9b 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.10-SNAPSHOT + 7.7.63-SNAPSHOT ../pom.xml @@ -41,6 +41,10 @@ org.wso2.carbon.identity.framework org.wso2.carbon.identity.secret.mgt.core + + org.wso2.carbon.identity.framework + org.wso2.carbon.identity.certificate.management + org.json.wso2 json @@ -54,6 +58,7 @@ org.mockito mockito-core + test org.wso2.carbon.identity.framework @@ -84,19 +89,18 @@ ${project.artifactId} + org.wso2.carbon.identity.action.management.constant, + org.wso2.carbon.identity.action.management.dao.*, org.wso2.carbon.identity.action.management.internal, - org.wso2.carbon.identity.action.management.cache, - org.wso2.carbon.identity.action.management.dao, - org.wso2.carbon.identity.action.management.dao.impl, + org.wso2.carbon.identity.action.management.service.impl, org.wso2.carbon.identity.action.management.util - !org.wso2.carbon.identity.action.management.internal, - !org.wso2.carbon.identity.action.management.cache, - !org.wso2.carbon.identity.action.management.dao, - !org.wso2.carbon.identity.action.management.dao.impl, - !org.wso2.carbon.identity.action.management.util, - org.wso2.carbon.identity.action.management.*; version="${carbon.identity.package.export.version}" + org.wso2.carbon.identity.action.management.cache, + org.wso2.carbon.identity.action.management.constant.error, + org.wso2.carbon.identity.action.management.exception, + org.wso2.carbon.identity.action.management.model, + org.wso2.carbon.identity.action.management.service; version="${carbon.identity.package.export.version}" org.apache.commons.lang; version="${commons-lang.wso2.osgi.version.range}", @@ -175,16 +179,11 @@ LINE COVEREDRATIO - - 0.70 + 0.80 COMPLEXITY COVEREDRATIO - 0.60 diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/cache/ActionCacheEntry.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/cache/ActionCacheEntry.java index 4ed821e43765..cec36a14b47a 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/cache/ActionCacheEntry.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/cache/ActionCacheEntry.java @@ -28,6 +28,7 @@ */ public class ActionCacheEntry extends CacheEntry { + private static final long serialVersionUID = 2789265346825849739L; private List actionsOfActionType; public ActionCacheEntry(List actionsOfActionType) { diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/cache/ActionTypeCacheKey.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/cache/ActionTypeCacheKey.java index 98fd51cf3dfc..76609a0e866d 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/cache/ActionTypeCacheKey.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/cache/ActionTypeCacheKey.java @@ -25,6 +25,7 @@ */ public class ActionTypeCacheKey extends CacheKey { + private static final long serialVersionUID = 8132735629148475983L; private final String actionType; public ActionTypeCacheKey(String actionType) { diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtConstants.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtConstants.java index 5eff6fda6669..9da7b6b3f5c3 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtConstants.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtConstants.java @@ -23,8 +23,8 @@ */ public class ActionMgtConstants { - public static final String URI_ATTRIBUTE = "uri"; - public static final String AUTHN_TYPE_ATTRIBUTE = "authnType"; + public static final String URI_PROPERTY = "uri"; + public static final String AUTHN_TYPE_PROPERTY = "authnType"; public static final String IDN_SECRET_TYPE_ACTION_SECRETS = "ACTION_API_ENDPOINT_AUTH_SECRETS"; public static final String ACTION_NAME_FIELD = "Action name"; @@ -36,84 +36,6 @@ public class ActionMgtConstants { public static final String API_KEY_HEADER_FIELD = "API key header name"; public static final String API_KEY_VALUE_FIELD = "API key value"; - /** - * Error messages. - */ - public enum ErrorMessages { - - // Client errors. - ERROR_INVALID_ACTION_TYPE("60001", "Invalid action type.", - "Invalid action type used for path parameter."), - ERROR_MAXIMUM_ACTIONS_PER_ACTION_TYPE_REACHED("60002", "Unable to create an Action.", - "Maximum number of actions per action type is reached."), - ERROR_NO_ACTION_CONFIGURED_ON_GIVEN_ACTION_TYPE_AND_ID("60003", - "Unable to perform the operation.", - "No Action is configured on the given Action Type and Id."), - ERROR_EMPTY_ACTION_REQUEST_FIELD("60004", "Invalid request.", - "%s is empty."), - ERROR_INVALID_ACTION_REQUEST_FIELD("60005", "Invalid request.", - "%s is invalid."), - - // Server errors. - ERROR_WHILE_ADDING_ACTION("65001", "Error while adding Action.", - "Error while persisting Action in the system."), - ERROR_WHILE_ADDING_ENDPOINT_PROPERTIES("65002", "Error while adding Endpoint properties", - "Error while persisting Action Endpoint properties in the system."), - ERROR_WHILE_RETRIEVING_ACTION_ENDPOINT_PROPERTIES("65003", - "Error while retrieving Action Endpoint properties", - "Error while retrieving Action Endpoint properties from the system."), - ERROR_WHILE_RETRIEVING_ACTIONS_BY_ACTION_TYPE("65004", - "Error while retrieving Actions by Action Type", - "Error while retrieving Actions by Action Type from the system."), - ERROR_WHILE_UPDATING_ENDPOINT_PROPERTIES("65005", - "Error while updating Action Endpoint properties", - "Error while updating Action Endpoint properties in the system."), - ERROR_WHILE_UPDATING_ACTION("65006", "Error while updating Action.", - "Error while updating Action in the system."), - ERROR_WHILE_DELETING_ACTION("65007", "Error while deleting Action.", - "Error while deleting Action from the system."), - ERROR_WHILE_UPDATING_ACTION_STATUS("65008", "Error while updating Action status.", - "Error while updating Action status in the system."), - ERROR_WHILE_RETRIEVING_ACTION_BY_ID("65009", "Error while retrieving Action by ID.", - "Error while retrieving Action from the system."), - ERROR_WHILE_RETRIEVING_ACTIONS_COUNT_PER_TYPE("65010", - "Error while retrieving count of Actions per Action Type.", - "Error while retrieving count of Actions per Action Type from the system."), - ERROR_WHILE_RETRIEVING_ACTION_BASIC_INFO("65011", "Error while retrieving Action basic info.", - "Error while retrieving Action basic info from the system."), - ERROR_WHILE_DECRYPTING_ACTION_ENDPOINT_AUTH_PROPERTIES("65012", - "Error while decrypting Action Endpoint Authentication properties", - "Error while decrypting Action Endpoint Authentication properties in the system."), - ERROR_NO_AUTHENTICATION_TYPE("65013", - "Error while retrieving Action Endpoint Authentication configurations", - "Authentication type is not defined for the Action Endpoint."), - ERROR_WHILE_UPDATING_ACTION_BASIC_INFO("65014", "Error while updating basic Action information", - "Error while updating basic Action information in the system."); - - private final String code; - private final String message; - private final String description; - - ErrorMessages(String code, String message, String description) { - - this.code = code; - this.message = message; - this.description = description; - } - - public String getCode() { - - return code; - } - - public String getMessage() { - - return message; - } - - public String getDescription() { - - return description; - } + private ActionMgtConstants() { } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtSQLConstants.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtSQLConstants.java index b41fb5282228..8f6ae2c77200 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtSQLConstants.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/ActionMgtSQLConstants.java @@ -38,9 +38,9 @@ public static class Column { public static final String ACTION_DESCRIPTION = "DESCRIPTION"; public static final String ACTION_STATUS = "STATUS"; public static final String ACTION_COUNT = "COUNT"; - public static final String ACTION_ENDPOINT_UUID = "ACTION_UUID"; - public static final String ACTION_ENDPOINT_PROPERTY_NAME = "PROPERTY_NAME"; - public static final String ACTION_ENDPOINT_PROPERTY_VALUE = "PROPERTY_VALUE"; + public static final String ACTION_PROPERTIES_UUID = "ACTION_UUID"; + public static final String ACTION_PROPERTIES_PROPERTY_NAME = "PROPERTY_NAME"; + public static final String ACTION_PROPERTIES_PROPERTY_VALUE = "PROPERTY_VALUE"; public static final String TENANT_ID = "TENANT_ID"; private Column() { @@ -55,26 +55,26 @@ public static class Query { public static final String ADD_ACTION_TO_ACTION_TYPE = "INSERT INTO IDN_ACTION (UUID, TYPE, NAME, " + "DESCRIPTION, STATUS, TENANT_ID) VALUES (:UUID;, :TYPE;, :NAME;, :DESCRIPTION;, :STATUS;, :TENANT_ID;)"; - public static final String ADD_ACTION_ENDPOINT_PROPERTIES = "INSERT INTO IDN_ACTION_ENDPOINT (ACTION_UUID, " + + public static final String ADD_ACTION_PROPERTIES = "INSERT INTO IDN_ACTION_PROPERTIES (ACTION_UUID, " + "PROPERTY_NAME, PROPERTY_VALUE, TENANT_ID) VALUES (:ACTION_UUID;, :PROPERTY_NAME;, :PROPERTY_VALUE;, " + ":TENANT_ID;)"; public static final String GET_ACTION_BASIC_INFO_BY_ID = "SELECT TYPE, NAME, DESCRIPTION, STATUS FROM " + "IDN_ACTION WHERE TYPE = :TYPE; AND UUID = :UUID; AND TENANT_ID = :TENANT_ID;"; - public static final String GET_ACTION_ENDPOINT_INFO_BY_ID = "SELECT PROPERTY_NAME, PROPERTY_VALUE FROM " + - "IDN_ACTION_ENDPOINT WHERE ACTION_UUID = :ACTION_UUID; AND TENANT_ID = :TENANT_ID;"; + public static final String GET_ACTION_PROPERTIES_INFO_BY_ID = "SELECT PROPERTY_NAME, PROPERTY_VALUE FROM " + + "IDN_ACTION_PROPERTIES WHERE ACTION_UUID = :ACTION_UUID; AND TENANT_ID = :TENANT_ID;"; public static final String GET_ACTIONS_BASIC_INFO_BY_ACTION_TYPE = "SELECT UUID, TYPE, NAME, DESCRIPTION," + " STATUS FROM IDN_ACTION WHERE TYPE = :TYPE; AND TENANT_ID = :TENANT_ID;"; public static final String UPDATE_ACTION_BASIC_INFO = "UPDATE IDN_ACTION SET NAME = :NAME;, DESCRIPTION = " + ":DESCRIPTION; WHERE UUID = :UUID; AND TYPE = :TYPE; AND TENANT_ID = :TENANT_ID;"; - public static final String DELETE_ACTION_ENDPOINT_PROPERTIES = "DELETE FROM IDN_ACTION_ENDPOINT WHERE " + - "ACTION_UUID = :ACTION_UUID; AND TENANT_ID = :TENANT_ID;"; + public static final String DELETE_ACTION_PROPERTY = "DELETE FROM IDN_ACTION_PROPERTIES WHERE " + + "PROPERTY_NAME = :PROPERTY_NAME; AND ACTION_UUID = :ACTION_UUID; AND TENANT_ID = :TENANT_ID;"; public static final String DELETE_ACTION = "DELETE FROM IDN_ACTION WHERE UUID = :UUID; AND TYPE = :TYPE;" + " AND TENANT_ID = :TENANT_ID;"; public static final String CHANGE_ACTION_STATUS = "UPDATE IDN_ACTION SET STATUS = :STATUS; WHERE UUID = " + ":UUID; AND TYPE = :TYPE; AND TENANT_ID = :TENANT_ID;"; public static final String GET_ACTIONS_COUNT_PER_ACTION_TYPE = "SELECT TYPE, COUNT(UUID) AS COUNT" + " FROM IDN_ACTION WHERE TENANT_ID = :TENANT_ID; GROUP BY TYPE"; - public static final String UPDATE_ACTION_ENDPOINT_PROPERTIES = "UPDATE IDN_ACTION_ENDPOINT SET " + + public static final String UPDATE_ACTION_PROPERTY = "UPDATE IDN_ACTION_PROPERTIES SET " + "PROPERTY_VALUE = :PROPERTY_VALUE; WHERE ACTION_UUID = :ACTION_UUID; AND " + "TENANT_ID = :TENANT_ID; AND PROPERTY_NAME = :PROPERTY_NAME;"; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/error/ErrorMessage.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/error/ErrorMessage.java new file mode 100644 index 000000000000..f13e723d0110 --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/constant/error/ErrorMessage.java @@ -0,0 +1,85 @@ +/* + * 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.action.management.constant.error; + +/** + * Error messages. + */ +public enum ErrorMessage { + + // Client errors. + ERROR_INVALID_ACTION_TYPE("60001", "Invalid action type.", + "Invalid action type used for path parameter."), + ERROR_MAXIMUM_ACTIONS_PER_ACTION_TYPE_REACHED("60002", "Unable to create an Action.", + "Maximum number of actions per action type is reached."), + ERROR_NO_ACTION_CONFIGURED_ON_GIVEN_ACTION_TYPE_AND_ID("60003", "Unable to perform the operation.", + "No Action is configured on the given Action Type and Id."), + ERROR_EMPTY_ACTION_REQUEST_FIELD("60004", "Invalid request.", "%s is empty."), + ERROR_INVALID_ACTION_REQUEST_FIELD("60005", "Invalid request.", "%s is invalid."), + ERROR_INVALID_ACTION_PROPERTIES("60006", "Provided Action Properties are invalid.", "%s"), + + // Server errors. + ERROR_WHILE_ADDING_ACTION("65001", "Error while adding Action.", + "Error while persisting Action in the system."), + ERROR_WHILE_RETRIEVING_ACTIONS_BY_ACTION_TYPE("65002", + "Error while retrieving Actions by Action Type", + "Error while retrieving Actions by Action Type from the system."), + ERROR_WHILE_RETRIEVING_ACTION_BY_ID("65003", "Error while retrieving Action by ID.", + "Error while retrieving Action from the system."), + ERROR_WHILE_UPDATING_ACTION("65004", "Error while updating Action.", + "Error while updating Action in the system."), + ERROR_WHILE_DELETING_ACTION("65005", "Error while deleting Action.", + "Error while deleting Action from the system."), + ERROR_WHILE_ACTIVATING_ACTION("65006", "Error while activating Action.", + "Error while updating Action status to ACTIVE."), + ERROR_WHILE_DEACTIVATING_ACTION("65007", "Error while deactivating Action.", + "Error while updating Action status to INACTIVE."), + ERROR_WHILE_RETRIEVING_ACTIONS_COUNT_PER_TYPE("65008", + "Error while retrieving count of Actions per Action Type.", + "Error while retrieving count of Actions per Action Type from the system."), + ERROR_WHILE_DECRYPTING_ACTION_ENDPOINT_AUTH_PROPERTIES("65009", + "Error while decrypting Action Endpoint Authentication properties", + "Error while decrypting Action Endpoint Authentication properties in the system."); + + private final String code; + private final String message; + private final String description; + + ErrorMessage(String code, String message, String description) { + + this.code = code; + this.message = message; + this.description = description; + } + + public String getCode() { + + return code; + } + + public String getMessage() { + + return message; + } + + public String getDescription() { + + return description; + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAO.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAO.java index 9def55c4247b..d61a94d5932d 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAO.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAO.java @@ -19,29 +19,24 @@ package org.wso2.carbon.identity.action.management.dao; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; -import org.wso2.carbon.identity.action.management.model.Action; -import org.wso2.carbon.identity.action.management.model.Authentication; -import org.wso2.carbon.identity.action.management.model.EndpointConfig; +import org.wso2.carbon.identity.action.management.model.ActionDTO; import java.util.List; import java.util.Map; /** - * This interface performs CRUD operations for {@link Action}. + * This interface performs CRUD operations for {@link ActionDTO}. */ public interface ActionManagementDAO { /** - * Create a new {@link Action}. + * Create a new {@link ActionDTO}. * - * @param actionType Action Type. - * @param actionId Action Id. - * @param action Action creation model. - * @param tenantId Tenant Id. - * @return Created Action. + * @param actionDTO Action creation model. + * @param tenantId Tenant Id. * @throws ActionMgtException If an error occurs while adding the Action. */ - Action addAction(String actionType, String actionId, Action action, Integer tenantId) throws ActionMgtException; + void addAction(ActionDTO actionDTO, Integer tenantId) throws ActionMgtException; /** * Retrieve the Actions configured for the given type. @@ -51,46 +46,51 @@ public interface ActionManagementDAO { * @return List of Action. * @throws ActionMgtException If an error occurs while retrieving the Actions of a given Action Type. */ - List getActionsByActionType(String actionType, Integer tenantId) throws ActionMgtException; + List getActionsByActionType(String actionType, Integer tenantId) throws ActionMgtException; /** - * Update {@link Action} by given Action type and Action ID. + * Get {@link ActionDTO} of a given Action Type and Action ID. * - * @param actionType Action Type. - * @param actionId Action ID. - * @param updatingAction Action update model. - * @param existingAction Existing Action. - * @param tenantId Tenant Id. - * @return Updated Action. + * @param actionId Action ID. + * @param tenantId Tenant Id. + * @return Action. + * @throws ActionMgtException If an error occurs while retrieving the Action of a given Action ID. + */ + ActionDTO getActionByActionId(String actionType, String actionId, Integer tenantId) throws ActionMgtException; + + /** + * Update {@link ActionDTO} by given Action type and Action ID. + * + * @param updatingActionDTO Action update model. + * @param existingActionDTO Existing Action. + * @param tenantId Tenant Id. * @throws ActionMgtException If an error occurs while updating the Action. */ - Action updateAction(String actionType, String actionId, Action updatingAction, Action existingAction, - Integer tenantId) throws ActionMgtException; + void updateAction(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, Integer tenantId) + throws ActionMgtException; /** - * Delete {@link Action} by given Action Type. + * Delete {@link ActionDTO} by given Action Type. * - * @param actionType Action Type. - * @param actionId Action Id. - * @param action Action to be deleted. - * @param tenantId Tenant Id. + * @param deletingActionDTO Action to be deleted. + * @param tenantId Tenant Id. * @throws ActionMgtException If an error occurs while deleting Action. */ - void deleteAction(String actionType, String actionId, Action action, Integer tenantId) throws ActionMgtException; + void deleteAction(ActionDTO deletingActionDTO, Integer tenantId) throws ActionMgtException; /** - * Activate {@link Action} by given Action Type and Action ID. + * Activate {@link org.wso2.carbon.identity.action.management.model.Action} by given Action Type and Action ID. * - * @param actionType Action Type. - * @param actionId Action ID. + * @param actionType Action Type. + * @param actionId Action ID. * @param tenantId Tenant Id. * @return Activated Action. * @throws ActionMgtException If an error occurs while activating the Action. */ - Action activateAction(String actionType, String actionId, Integer tenantId) throws ActionMgtException; + ActionDTO activateAction(String actionType, String actionId, Integer tenantId) throws ActionMgtException; /** - * Deactivate {@link Action} by given Action Type and Action ID. + * Deactivate {@link org.wso2.carbon.identity.action.management.model.Action} by given Action Type and Action ID. * * @param actionType Action Type. * @param actionId Action ID. @@ -98,7 +98,7 @@ Action updateAction(String actionType, String actionId, Action updatingAction, A * @return Deactivated Action. * @throws ActionMgtException If an error occurs while deactivating the Action. */ - Action deactivateAction(String actionType, String actionId, Integer tenantId) throws ActionMgtException; + ActionDTO deactivateAction(String actionType, String actionId, Integer tenantId) throws ActionMgtException; /** * Get Actions count per Action Type. @@ -108,40 +108,4 @@ Action updateAction(String actionType, String actionId, Action updatingAction, A * @throws ActionMgtException If an error occurs while retrieving the Actions count. */ Map getActionsCountPerType(Integer tenantId) throws ActionMgtException; - - /** - * Get {@link Action} of a given Action Type and Action ID. - * - * @param actionId Action ID. - * @param tenantId Tenant Id. - * @return Action. - * @throws ActionMgtException If an error occurs while retrieving the Action of a given Action ID. - */ - Action getActionByActionId(String actionType, String actionId, Integer tenantId) throws ActionMgtException; - - /** - * Update the endpoint authentication properties of an {@link Action} by given Action ID. - * - * @param actionId Action ID. - * @param authentication Authentication information to be updated. - * @param tenantId Tenant Id. - * @return Updated Action. - * @throws ActionMgtException If an error occurs while updating the Action endpoint authentication properties. - */ - Action updateActionEndpointAuthProperties(String actionType, String actionId, Authentication authentication, - int tenantId) throws ActionMgtException; - - /** - * Update the endpoint authentication properties of an {@link Action} by given Action ID. - * - * @param actionType Action Type. - * @param actionId Action ID. - * @param endpoint Endpoint information to be updated. - * @param currentAuthentication Current Action endpoint authentication information. - * @param tenantId Tenant Id. - * @return Updated Action. - * @throws ActionMgtException If an error occurs while updating the Action endpoint. - */ - Action updateActionEndpoint(String actionType, String actionId, EndpointConfig endpoint, - Authentication currentAuthentication, int tenantId) throws ActionMgtException; } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionDTOModelResolverFactory.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionDTOModelResolverFactory.java new file mode 100644 index 000000000000..be9285259a11 --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionDTOModelResolverFactory.java @@ -0,0 +1,61 @@ +/* + * 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.action.management.dao.impl; + +import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.service.ActionDTOModelResolver; + +import java.util.EnumMap; +import java.util.Map; + +/** + * This class defines the ActionDTO Model Resolver Factory. + * ActionDTO Model Resolver Factory is the component that is responsible for providing the + * {@link ActionDTOModelResolver} based on the action type. + */ +public class ActionDTOModelResolverFactory { + + private static final Map actionDTOModelResolvers = + new EnumMap<>(Action.ActionTypes.class); + + private ActionDTOModelResolverFactory() { + } + + public static ActionDTOModelResolver getActionDTOModelResolver(Action.ActionTypes actionType) { + + switch (actionType) { + case PRE_UPDATE_PASSWORD: + return actionDTOModelResolvers.get(Action.ActionTypes.PRE_UPDATE_PASSWORD); + case PRE_ISSUE_ACCESS_TOKEN: + return actionDTOModelResolvers.get(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN); + default: + return null; + } + } + + public static void registerActionDTOModelResolver(ActionDTOModelResolver actionDTOModelResolver) { + + actionDTOModelResolvers.put(actionDTOModelResolver.getSupportedActionType(), actionDTOModelResolver); + } + + public static void unregisterActionDTOModelResolver(ActionDTOModelResolver actionDTOModelResolver) { + + actionDTOModelResolvers.remove(actionDTOModelResolver.getSupportedActionType()); + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java new file mode 100644 index 000000000000..76ca02ba9aea --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOFacade.java @@ -0,0 +1,418 @@ +/* + * 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.action.management.dao.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.database.utils.jdbc.NamedJdbcTemplate; +import org.wso2.carbon.database.utils.jdbc.exceptions.TransactionException; +import org.wso2.carbon.identity.action.management.constant.error.ErrorMessage; +import org.wso2.carbon.identity.action.management.dao.ActionManagementDAO; +import org.wso2.carbon.identity.action.management.exception.ActionDTOModelResolverClientException; +import org.wso2.carbon.identity.action.management.exception.ActionDTOModelResolverException; +import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; +import org.wso2.carbon.identity.action.management.exception.ActionMgtException; +import org.wso2.carbon.identity.action.management.exception.ActionMgtServerException; +import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.ActionDTO; +import org.wso2.carbon.identity.action.management.model.AuthProperty; +import org.wso2.carbon.identity.action.management.model.Authentication; +import org.wso2.carbon.identity.action.management.model.EndpointConfig; +import org.wso2.carbon.identity.action.management.service.ActionDTOModelResolver; +import org.wso2.carbon.identity.action.management.util.ActionDTOBuilder; +import org.wso2.carbon.identity.action.management.util.ActionManagementExceptionHandler; +import org.wso2.carbon.identity.action.management.util.ActionSecretProcessor; +import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; +import org.wso2.carbon.identity.core.util.IdentityTenantUtil; +import org.wso2.carbon.identity.secret.mgt.core.exception.SecretManagementException; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * Facade class for Action Management DAO. + * ActionManagementDAOFacade is responsible for handling external service integrations. + */ +public class ActionManagementDAOFacade implements ActionManagementDAO { + + private static final Log LOG = LogFactory.getLog(ActionManagementDAOFacade.class); + + private final ActionManagementDAO actionManagementDAO; + private final ActionSecretProcessor actionSecretProcessor; + + public ActionManagementDAOFacade(ActionManagementDAO actionManagementDAO) { + + this.actionManagementDAO = actionManagementDAO; + this.actionSecretProcessor = new ActionSecretProcessor(); + } + + @Override + public void addAction(ActionDTO actionDTO, Integer tenantId) throws ActionMgtException { + + NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); + try { + jdbcTemplate.withTransaction(template -> { + ActionDTOBuilder actionDTOBuilder = new ActionDTOBuilder(actionDTO); + // Encrypt authentication secrets + encryptAddingAuthSecrets(actionDTOBuilder); + // Resolve action properties + ActionDTO resolvedActionDTO = getResolvedActionDTOForAddOperation(actionDTOBuilder.build(), + tenantId); + + actionManagementDAO.addAction(resolvedActionDTO, tenantId); + return null; + }); + } catch (TransactionException e) { + // Since exceptions thrown are wrapped with TransactionException, extracting the actual cause. + handleActionPropertyResolverClientException(e.getCause()); + LOG.debug("Error while creating the Action of Action Type: " + actionDTO.getType().getDisplayName() + + " in Tenant Domain: " + IdentityTenantUtil.getTenantDomain(tenantId) + + ". Rolling back created action information, authentication secrets and action properties."); + throw ActionManagementExceptionHandler.handleServerException(ErrorMessage.ERROR_WHILE_ADDING_ACTION, e); + } + } + + @Override + public List getActionsByActionType(String actionType, Integer tenantId) throws ActionMgtException { + + try { + List actionDTOS = actionManagementDAO.getActionsByActionType(actionType, tenantId); + + return getResolvedActionDTOsForGetOperation(actionType, actionDTOS, tenantId); + } catch (ActionMgtException | ActionDTOModelResolverException e) { + throw ActionManagementExceptionHandler.handleServerException( + ErrorMessage.ERROR_WHILE_RETRIEVING_ACTIONS_BY_ACTION_TYPE, e); + } + } + + @Override + public ActionDTO getActionByActionId(String actionType, String actionId, Integer tenantId) + throws ActionMgtException { + + try { + ActionDTO actionDTO = actionManagementDAO.getActionByActionId(actionType, actionId, tenantId); + if (actionDTO == null) { + return null; + } + + // Populate action properties + return getResolvedActionDTOForGetOperation(actionDTO, tenantId); + } catch (ActionMgtException | ActionDTOModelResolverException e) { + throw ActionManagementExceptionHandler.handleServerException( + ErrorMessage.ERROR_WHILE_RETRIEVING_ACTION_BY_ID, e); + } + } + + @Override + public void updateAction(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, Integer tenantId) + throws ActionMgtException { + + NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); + try { + jdbcTemplate.withTransaction(template -> { + ActionDTOBuilder updatingActionDTOBuilder = new ActionDTOBuilder(updatingActionDTO); + // Encrypt authentication secrets + encryptUpdatingAuthSecrets(updatingActionDTOBuilder, existingActionDTO); + // Resolve action properties + ActionDTO resolvedUpdatingActionDTO = + getResolvedActionDTOForUpdateOperation(updatingActionDTOBuilder.build(), existingActionDTO, + tenantId); + + actionManagementDAO.updateAction(resolvedUpdatingActionDTO, existingActionDTO, tenantId); + return null; + }); + } catch (TransactionException e) { + // Since exceptions thrown are wrapped with TransactionException, extracting the actual cause. + handleActionPropertyResolverClientException(e.getCause()); + LOG.debug("Error while updating the Action of Action Type: " + + updatingActionDTO.getType().getDisplayName() + " and Action ID: " + updatingActionDTO.getId() + + " in Tenant Domain: " + IdentityTenantUtil.getTenantDomain(tenantId) + + ". Rolling back updated action information"); + throw ActionManagementExceptionHandler.handleServerException(ErrorMessage.ERROR_WHILE_UPDATING_ACTION, e); + } + } + + @Override + public void deleteAction(ActionDTO deletingActionDTO, Integer tenantId) throws ActionMgtException { + + NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); + try { + jdbcTemplate.withTransaction(template -> { + actionManagementDAO.deleteAction(deletingActionDTO, tenantId); + // Encrypt authentication secrets + deleteAuthenticationSecrets(deletingActionDTO); + // Resolve action properties + deleteProperties(deletingActionDTO, tenantId); + + return null; + }); + } catch (TransactionException e) { + LOG.debug("Error while deleting the Action of Action Type: " + + deletingActionDTO.getType().getDisplayName() + " and Action ID: " + deletingActionDTO.getId() + + " in Tenant Domain: " + IdentityTenantUtil.getTenantDomain(tenantId) + + ". Rolling back deleted action information"); + throw ActionManagementExceptionHandler.handleServerException(ErrorMessage.ERROR_WHILE_DELETING_ACTION, e); + } + } + + @Override + public ActionDTO activateAction(String actionType, String actionId, Integer tenantId) throws ActionMgtException { + + try { + return actionManagementDAO.activateAction(actionType, actionId, tenantId); + } catch (ActionMgtException e) { + throw ActionManagementExceptionHandler.handleServerException(ErrorMessage.ERROR_WHILE_ACTIVATING_ACTION, e); + } + } + + @Override + public ActionDTO deactivateAction(String actionType, String actionId, Integer tenantId) throws ActionMgtException { + + try { + return actionManagementDAO.deactivateAction(actionType, actionId, tenantId); + } catch (ActionMgtException e) { + throw ActionManagementExceptionHandler.handleServerException( + ErrorMessage.ERROR_WHILE_DEACTIVATING_ACTION, e); + } + } + + @Override + public Map getActionsCountPerType(Integer tenantId) throws ActionMgtException { + + try { + return actionManagementDAO.getActionsCountPerType(tenantId); + } catch (ActionMgtException e) { + throw ActionManagementExceptionHandler.handleServerException( + ErrorMessage.ERROR_WHILE_RETRIEVING_ACTIONS_COUNT_PER_TYPE, e); + } + } + + /** + * Encrypt and store the authentication secrets of the Action Endpoint Authentication. + * + * @param actionDTOBuilder ActionDTOBuilder object. + * @throws ActionMgtException If an error occurs while encrypting the authentication secrets. + */ + private void encryptAddingAuthSecrets(ActionDTOBuilder actionDTOBuilder) throws ActionMgtException { + + try { + List encryptedProperties = actionSecretProcessor.encryptAssociatedSecrets( + actionDTOBuilder.getEndpoint().getAuthentication(), actionDTOBuilder.getId()); + + addEncryptedAuthSecretsToBuilder(actionDTOBuilder, encryptedProperties); + } catch (SecretManagementException e) { + throw new ActionMgtServerException("Error while encrypting Action Endpoint Authentication Secrets.", e); + } + } + + /** + * Encrypt and update the authentication secrets of the Action Endpoint Authentication. + * If the authentication type is changed, delete the existing authentication secrets and add new secrets. + * If the authentication properties are updated, update the existing authentication secrets. + * + * @param updatingActionDTOBuilder ActionDTOBuilder object. + * @param existingActionDTO Existing ActionDTO object. + * @throws ActionMgtException If an error occurs while encrypting the authentication secrets. + */ + private void encryptUpdatingAuthSecrets(ActionDTOBuilder updatingActionDTOBuilder, + ActionDTO existingActionDTO) + throws ActionMgtException { + + if (updatingActionDTOBuilder.getEndpoint() == null || + updatingActionDTOBuilder.getEndpoint().getAuthentication() == null) { + return; + } + + Authentication updatingAuthentication = updatingActionDTOBuilder.getEndpoint().getAuthentication(); + Authentication existingAuthentication = existingActionDTO.getEndpoint().getAuthentication(); + + try { + if (updatingAuthentication.getType() != existingAuthentication.getType()) { + actionSecretProcessor.deleteAssociatedSecrets(existingAuthentication, existingActionDTO.getId()); + } + List encryptedProperties = actionSecretProcessor.encryptAssociatedSecrets( + updatingAuthentication, updatingActionDTOBuilder.getId()); + + addEncryptedAuthSecretsToBuilder(updatingActionDTOBuilder, encryptedProperties); + } catch (SecretManagementException e) { + throw new ActionMgtServerException("Error while updating Action Endpoint Authentication Secrets.", e); + } + } + + /** + * Delete the authentication secrets of the Action Endpoint Authentication. + * + * @param deletingActionDTO ActionDTO object. + * @throws ActionMgtException If an error occurs while deleting the authentication secrets. + */ + private void deleteAuthenticationSecrets(ActionDTO deletingActionDTO) throws ActionMgtException { + + try { + actionSecretProcessor.deleteAssociatedSecrets(deletingActionDTO.getEndpoint().getAuthentication(), + deletingActionDTO.getId()); + } catch (SecretManagementException e) { + throw new ActionMgtServerException("Error while deleting Action Endpoint Authentication Secrets.", e); + } + } + + /** + * Add the encrypted authentication secrets and replace the input authentication properties in the ActionDTOBuilder + * object. + * + * @param actionDTOBuilder ActionDTOBuilder object. + * @param encryptedProperties List of encrypted AuthProperty objects. + */ + private void addEncryptedAuthSecretsToBuilder(ActionDTOBuilder actionDTOBuilder, + List encryptedProperties) { + + Map encryptedPropertyMap = encryptedProperties.stream() + .collect(Collectors.toMap(AuthProperty::getName, AuthProperty::getValue)); + + actionDTOBuilder.endpoint(new EndpointConfig.EndpointConfigBuilder() + .uri(actionDTOBuilder.getEndpoint().getUri()) + .authentication(new Authentication.AuthenticationBuilder() + .type(actionDTOBuilder.getEndpoint().getAuthentication().getType()) + .properties(encryptedPropertyMap) + .build()) + .build()); + } + + /** + * Get the ActionDTO with resolved adding properties that needs to be added in the Action Management Service. + * + * @param actionDTO ActionDTO object. + * @param tenantId Tenant ID. + * @return ActionDTO object with resolved adding properties. + * @throws ActionDTOModelResolverException If an error occurs while resolving the adding properties. + */ + private ActionDTO getResolvedActionDTOForAddOperation(ActionDTO actionDTO, Integer tenantId) + throws ActionDTOModelResolverException { + + ActionDTOModelResolver actionDTOModelResolver = + ActionDTOModelResolverFactory.getActionDTOModelResolver(actionDTO.getType()); + if (actionDTOModelResolver == null) { + return actionDTO; + } + + return actionDTOModelResolver.resolveForAddOperation(actionDTO, IdentityTenantUtil.getTenantDomain(tenantId)); + } + + /** + * Get the ActionDTO list with populated properties according to the references stored in the Action Management + * Service. + * + * @param actionType Action type. + * @param actionDTOs List of ActionDTO objects. + * @param tenantId Tenant ID. + * @return List of ActionDTO objects with populated properties. + * @throws ActionDTOModelResolverException If an error occurs while populating the properties. + */ + private List getResolvedActionDTOsForGetOperation(String actionType, List actionDTOs, + Integer tenantId) + throws ActionDTOModelResolverException { + + ActionDTOModelResolver actionDTOModelResolver = + ActionDTOModelResolverFactory.getActionDTOModelResolver(Action.ActionTypes.valueOf(actionType)); + if (actionDTOModelResolver == null) { + return actionDTOs; + } + + return actionDTOModelResolver.resolveForGetOperation(actionDTOs, IdentityTenantUtil.getTenantDomain(tenantId)); + } + + /** + * Get the ActionDTO with populated properties according to the references stored in the Action Management Service. + * + * @param actionDTO ActionDTO object. + * @param tenantId Tenant ID. + * @return ActionDTO object with populated properties. + * @throws ActionDTOModelResolverException If an error occurs while populating the properties. + */ + private ActionDTO getResolvedActionDTOForGetOperation(ActionDTO actionDTO, Integer tenantId) + throws ActionDTOModelResolverException { + + ActionDTOModelResolver actionDTOModelResolver = + ActionDTOModelResolverFactory.getActionDTOModelResolver(actionDTO.getType()); + if (actionDTOModelResolver == null) { + return actionDTO; + } + + return actionDTOModelResolver.resolveForGetOperation(actionDTO, IdentityTenantUtil.getTenantDomain(tenantId)); + } + + /** + * Get the ActionDTO with resolved updating properties that needs to be updated in the Action Management Service. + * + * @param updatingActionDTO Updating ActionDTO object. + * @param existingActionDTO Existing ActionDTO object. + * @param tenantId Tenant ID. + * @return ActionDTO object with resolved updating properties. + * @throws ActionDTOModelResolverException If an error occurs while resolving the updating properties. + */ + private ActionDTO getResolvedActionDTOForUpdateOperation(ActionDTO updatingActionDTO, + ActionDTO existingActionDTO, Integer tenantId) + throws ActionDTOModelResolverException { + + ActionDTOModelResolver actionDTOModelResolver = + ActionDTOModelResolverFactory.getActionDTOModelResolver(updatingActionDTO.getType()); + if (actionDTOModelResolver == null) { + return updatingActionDTO; + } + + return actionDTOModelResolver.resolveForUpdateOperation(updatingActionDTO, existingActionDTO, + IdentityTenantUtil.getTenantDomain(tenantId)); + } + + /** + * Delete the properties that are deleted in the Action Management Service. + * + * @param deletingActionDTO Deleting ActionDTO object. + * @param tenantId Tenant ID. + * @throws ActionDTOModelResolverException If an error occurs while deleting the properties. + */ + private void deleteProperties(ActionDTO deletingActionDTO, Integer tenantId) + throws ActionDTOModelResolverException { + + ActionDTOModelResolver actionDTOModelResolver = + ActionDTOModelResolverFactory.getActionDTOModelResolver(deletingActionDTO.getType()); + if (actionDTOModelResolver == null) { + return; + } + + actionDTOModelResolver.resolveForDeleteOperation(deletingActionDTO, + IdentityTenantUtil.getTenantDomain(tenantId)); + } + + /** + * Handle the ActionPropertyResolverClientException and throw the relevant ActionMgtClientException. + * + * @param throwable Throwable object. + * @throws ActionMgtClientException If an error occurs while handling the ActionPropertyResolverClientException. + */ + private static void handleActionPropertyResolverClientException(Throwable throwable) + throws ActionMgtClientException { + + if (throwable instanceof ActionDTOModelResolverClientException) { + ActionDTOModelResolverClientException clientException = (ActionDTOModelResolverClientException) throwable; + throw new ActionMgtClientException(clientException.getMessage(), clientException.getDescription(), + ErrorMessage.ERROR_INVALID_ACTION_PROPERTIES.getCode()); + } + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java index 95bc2f54917a..59850e7efc8d 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/ActionManagementDAOImpl.java @@ -18,182 +18,140 @@ package org.wso2.carbon.identity.action.management.dao.impl; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.wso2.carbon.database.utils.jdbc.NamedJdbcTemplate; -import org.wso2.carbon.database.utils.jdbc.exceptions.DataAccessException; +import org.wso2.carbon.database.utils.jdbc.NamedPreparedStatement; import org.wso2.carbon.database.utils.jdbc.exceptions.TransactionException; -import org.wso2.carbon.identity.action.management.ActionSecretProcessor; -import org.wso2.carbon.identity.action.management.constant.ActionMgtConstants; import org.wso2.carbon.identity.action.management.constant.ActionMgtSQLConstants; import org.wso2.carbon.identity.action.management.dao.ActionManagementDAO; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; -import org.wso2.carbon.identity.action.management.exception.ActionMgtRuntimeException; import org.wso2.carbon.identity.action.management.exception.ActionMgtServerException; import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.ActionDTO; import org.wso2.carbon.identity.action.management.model.AuthProperty; import org.wso2.carbon.identity.action.management.model.Authentication; import org.wso2.carbon.identity.action.management.model.EndpointConfig; -import org.wso2.carbon.identity.action.management.util.ActionManagementUtil; +import org.wso2.carbon.identity.action.management.util.ActionDTOBuilder; import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; -import org.wso2.carbon.identity.core.util.IdentityTenantUtil; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; +import static org.wso2.carbon.identity.action.management.constant.ActionMgtConstants.AUTHN_TYPE_PROPERTY; +import static org.wso2.carbon.identity.action.management.constant.ActionMgtConstants.URI_PROPERTY; + /** * This class implements the {@link ActionManagementDAO} interface. */ public class ActionManagementDAOImpl implements ActionManagementDAO { - private static final Log LOG = LogFactory.getLog(ActionManagementDAOImpl.class); - private final ActionSecretProcessor actionSecretProcessor; - - public ActionManagementDAOImpl() { - - this.actionSecretProcessor = new ActionSecretProcessor(); + @Override + public void addAction(ActionDTO actionDTO, Integer tenantId) throws ActionMgtException { + + // Add action basic information. + addBasicInfo(actionDTO, tenantId); + // Add action endpoint. + addEndpoint(actionDTO, tenantId); + // Add action properties. + addProperties(actionDTO, tenantId); } @Override - public Action addAction(String actionType, String actionId, Action action, Integer tenantId) - throws ActionMgtException { - - NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); - try { - jdbcTemplate.withTransaction(template -> { - template.executeInsert(ActionMgtSQLConstants.Query.ADD_ACTION_TO_ACTION_TYPE, - statement -> { - statement.setString(ActionMgtSQLConstants.Column.ACTION_UUID, actionId); - statement.setString(ActionMgtSQLConstants.Column.ACTION_TYPE, actionType); - statement.setString(ActionMgtSQLConstants.Column.ACTION_NAME, action.getName()); - statement.setString(ActionMgtSQLConstants.Column.ACTION_DESCRIPTION, action.getDescription()); - statement.setString(ActionMgtSQLConstants.Column.ACTION_STATUS, - String.valueOf(Action.Status.ACTIVE)); - statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); - }, action, false); - - // Encrypt secrets. - List encryptedAuthProperties = actionSecretProcessor - .encryptAssociatedSecrets(action.getEndpoint().getAuthentication(), actionId); - - // Add Endpoint configuration properties. - addEndpointProperties(actionId, getEndpointProperties(action.getEndpoint().getUri(), - action.getEndpoint().getAuthentication().getType().name(), encryptedAuthProperties), tenantId); - - return null; - }); - - return getActionByActionId(actionType, actionId, tenantId); - } catch (TransactionException e) { - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Error while creating the Action of Action Type: %s in Tenant Domain: %s." + - " Rolling back created action information and deleting added secrets.", actionType, - IdentityTenantUtil.getTenantDomain(tenantId))); + public List getActionsByActionType(String actionType, Integer tenantId) throws ActionMgtException { + + List actionDTOS = new ArrayList<>(); + try (Connection dbConnection = IdentityDatabaseUtil.getDBConnection(false); + NamedPreparedStatement statement = new NamedPreparedStatement(dbConnection, + ActionMgtSQLConstants.Query.GET_ACTIONS_BASIC_INFO_BY_ACTION_TYPE)) { + + statement.setString(ActionMgtSQLConstants.Column.ACTION_TYPE, actionType); + statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); + + try (ResultSet rs = statement.executeQuery()) { + while (rs.next()) { + String actionId = rs.getString(ActionMgtSQLConstants.Column.ACTION_UUID); + ActionDTO actionDTO = new ActionDTOBuilder() + .id(actionId) + .type(org.wso2.carbon.identity.action.management.model.Action.ActionTypes.valueOf( + rs.getString(ActionMgtSQLConstants.Column.ACTION_TYPE))) + .name(rs.getString(ActionMgtSQLConstants.Column.ACTION_NAME)) + .description(rs.getString(ActionMgtSQLConstants.Column.ACTION_DESCRIPTION)) + .status(org.wso2.carbon.identity.action.management.model.Action.Status.valueOf( + rs.getString(ActionMgtSQLConstants.Column.ACTION_STATUS))) + .setEndpointAndProperties(getActionPropertiesFromDB(actionId, tenantId)) + .build(); + + actionDTOS.add(actionDTO); + } } - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_ADDING_ACTION, e); + + return actionDTOS; + } catch (SQLException e) { + throw new ActionMgtServerException("Error while retrieving Actions information by Action Type from " + + "the system.", e); } } @Override - public List getActionsByActionType(String actionType, Integer tenantId) throws ActionMgtException { + public ActionDTO getActionByActionId(String actionType, String actionId, Integer tenantId) + throws ActionMgtException { - NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); - try { - return jdbcTemplate.executeQuery(ActionMgtSQLConstants.Query.GET_ACTIONS_BASIC_INFO_BY_ACTION_TYPE, - (resultSet, rowNumber) -> new Action.ActionResponseBuilder() - .id(resultSet.getString(ActionMgtSQLConstants.Column.ACTION_UUID)) - .type(Action.ActionTypes - .valueOf(resultSet.getString(ActionMgtSQLConstants.Column.ACTION_TYPE))) - .name(resultSet.getString(ActionMgtSQLConstants.Column.ACTION_NAME)) - .description(resultSet.getString(ActionMgtSQLConstants.Column.ACTION_DESCRIPTION)) - .status(Action.Status - .valueOf(resultSet.getString(ActionMgtSQLConstants.Column.ACTION_STATUS))) - .endpoint(getActionEndpointConfigById( - resultSet.getString(ActionMgtSQLConstants.Column.ACTION_UUID), tenantId)) - .build(), - statement -> { - statement.setString(ActionMgtSQLConstants.Column.ACTION_TYPE, actionType); - statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); - }); - } catch (ActionMgtRuntimeException | DataAccessException e) { - /** - * Handling {@link ActionMgtRuntimeException}, which is intentionally thrown to represent underlying - * exceptions from the {@link #getActionEndpointConfigById(String, Integer)} method. - */ - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_RETRIEVING_ACTIONS_BY_ACTION_TYPE, e); + ActionDTOBuilder actionBuilder = getBasicInfo(actionType, actionId, tenantId); + if (actionBuilder == null) { + return null; } + actionBuilder.setEndpointAndProperties(getActionPropertiesFromDB(actionId, tenantId)); + + return actionBuilder.build(); } @Override - public Action updateAction(String actionType, String actionId, Action updatingAction, Action existingAction, - Integer tenantId) throws ActionMgtException { - - NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); - try { - jdbcTemplate.withTransaction(template -> { - // Update Basic Info. - updateBasicInfo(actionType, actionId, updatingAction, existingAction, tenantId); - // Update Endpoint URI and Authentication. - updateEndpointUriAndAuthentication(actionId, updatingAction, existingAction, tenantId); - - return null; - }); + public void updateAction(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, Integer tenantId) + throws ActionMgtException { - return getActionByActionId(actionType, actionId, tenantId); - } catch (TransactionException e) { - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Error while updating the Action of Action Type: %s and Action ID: %s in" + - " Tenant Domain: %s. Rolling back updated action information.", actionType, actionId, - IdentityTenantUtil.getTenantDomain(tenantId))); - } - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_UPDATING_ACTION, e); - } + // Update action basic information. + updateBasicInfo(updatingActionDTO, existingActionDTO, tenantId); + // Update Action Endpoint. + updateEndpoint(updatingActionDTO, existingActionDTO, tenantId); + // Update Action Properties. + updateProperties(updatingActionDTO, existingActionDTO, tenantId); } @Override - public void deleteAction(String actionType, String actionId, Action action, Integer tenantId) - throws ActionMgtException { + public void deleteAction(ActionDTO deletingActionDTO, Integer tenantId) throws ActionMgtException { NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); try { jdbcTemplate.withTransaction(template -> { template.executeUpdate(ActionMgtSQLConstants.Query.DELETE_ACTION, statement -> { - statement.setString(ActionMgtSQLConstants.Column.ACTION_UUID, actionId); - statement.setString(ActionMgtSQLConstants.Column.ACTION_TYPE, actionType); + statement.setString(ActionMgtSQLConstants.Column.ACTION_UUID, deletingActionDTO.getId()); + statement.setString(ActionMgtSQLConstants.Column.ACTION_TYPE, + deletingActionDTO.getType().getActionType()); statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); }); - // Delete action endpoint authentication related secrets. - actionSecretProcessor.deleteAssociatedSecrets(action.getEndpoint().getAuthentication(), actionId); return null; }); } catch (TransactionException e) { - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Error while deleting the Action of Action Type: %s and Action ID: %s in" + - " Tenant Domain: %s. Rolling back deleted action information.", actionType, actionId, - IdentityTenantUtil.getTenantDomain(tenantId))); - } - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_DELETING_ACTION, e); + throw new ActionMgtServerException("Error while deleting Action information in the system.", e); } } @Override - public Action activateAction(String actionType, String actionId, Integer tenantId) throws ActionMgtException { + public ActionDTO activateAction(String actionType, String actionId, Integer tenantId) throws ActionMgtException { return changeActionStatus(actionType, actionId, String.valueOf(Action.Status.ACTIVE), tenantId); - } @Override - public Action deactivateAction(String actionType, String actionId, Integer tenantId) throws ActionMgtException { + public ActionDTO deactivateAction(String actionType, String actionId, Integer tenantId) throws ActionMgtException { return changeActionStatus(actionType, actionId, String.valueOf(Action.Status.INACTIVE), tenantId); } @@ -203,433 +161,455 @@ public Map getActionsCountPerType(Integer tenantId) throws Acti Map actionTypesCountMap = new HashMap<>(); NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); try { - jdbcTemplate.executeQuery(ActionMgtSQLConstants.Query.GET_ACTIONS_COUNT_PER_ACTION_TYPE, - (resultSet, rowNumber) -> { - actionTypesCountMap.put(resultSet.getString(ActionMgtSQLConstants.Column.ACTION_TYPE), - resultSet.getInt(ActionMgtSQLConstants.Column.ACTION_COUNT)); - return null; - }, statement -> statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId)); + jdbcTemplate.withTransaction(template -> + template.executeQuery(ActionMgtSQLConstants.Query.GET_ACTIONS_COUNT_PER_ACTION_TYPE, + (resultSet, rowNumber) -> { + actionTypesCountMap.put(resultSet.getString(ActionMgtSQLConstants.Column.ACTION_TYPE), + resultSet.getInt(ActionMgtSQLConstants.Column.ACTION_COUNT)); + return null; + }, statement -> statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId))); return actionTypesCountMap; - } catch (DataAccessException e) { - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_RETRIEVING_ACTIONS_COUNT_PER_TYPE, e); + } catch (TransactionException e) { + throw new ActionMgtServerException("Error while retrieving Actions count per Action Type from the system.", + e); } } - @Override - public Action getActionByActionId(String actionType, String actionId, Integer tenantId) throws ActionMgtException { + /** + * Add Basic Information of an {@link ActionDTO} to the Database. + * + * @param actionDTO ActionDTO object with basic information. + * @param tenantId Tenant ID. + * @throws ActionMgtException If an error occurs while adding action basic information in the database. + */ + private void addBasicInfo(ActionDTO actionDTO, Integer tenantId) throws ActionMgtException { + NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); try { - Action action = getActionBasicInfoById(actionType, actionId, tenantId); - if (action != null) { - action = new Action.ActionResponseBuilder() - .id(actionId) - .type(Action.ActionTypes.valueOf(actionType)) - .name(action.getName()) - .description(action.getDescription()) - .status(action.getStatus()) - .endpoint(getActionEndpointConfigById(actionId, tenantId)) - .build(); - } - - return action; - } catch (ActionMgtException | ActionMgtRuntimeException e) { - /** - * Handling {@link ActionMgtRuntimeException}, which is intentionally thrown to represent underlying - * exceptions from the {@link #getActionEndpointConfigById(String, Integer)} method. - */ - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_RETRIEVING_ACTION_BY_ID, e); + jdbcTemplate.withTransaction(template -> + template.executeInsert(ActionMgtSQLConstants.Query.ADD_ACTION_TO_ACTION_TYPE, + statement -> { + statement.setString(ActionMgtSQLConstants.Column.ACTION_UUID, actionDTO.getId()); + statement.setString(ActionMgtSQLConstants.Column.ACTION_TYPE, + actionDTO.getType().getActionType()); + statement.setString(ActionMgtSQLConstants.Column.ACTION_NAME, actionDTO.getName()); + statement.setString(ActionMgtSQLConstants.Column.ACTION_DESCRIPTION, + actionDTO.getDescription()); + statement.setString(ActionMgtSQLConstants.Column.ACTION_STATUS, + String.valueOf(Action.Status.ACTIVE)); + statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); + }, actionDTO, false)); + } catch (TransactionException e) { + throw new ActionMgtServerException("Error while adding Action Basic information in the system.", e); } } - @Override - public Action updateActionEndpointAuthProperties(String actionType, String actionId, Authentication authentication, - int tenantId) throws ActionMgtException { - - updateActionEndpointAuthProperties(actionId, authentication, tenantId); - return getActionByActionId(actionType, actionId, tenantId); - } - - @Override - public Action updateActionEndpoint(String actionType, String actionId, EndpointConfig endpoint, - Authentication currentAuthentication, int tenantId) - throws ActionMgtException { - - updateActionEndpoint(actionId, endpoint, currentAuthentication, tenantId); - return getActionByActionId(actionType, actionId, tenantId); - } - /** - * Update the endpoint authentication properties of an {@link Action} by given Action ID. + * Update the basic information of an {@link ActionDTO} by given Action ID. * - * @param actionId Action ID. - * @param authentication Authentication information to be updated. - * @param tenantId Tenant Id. - * @throws ActionMgtServerException If an error occurs while updating the Action endpoint authentication properties. + * @param updatingActionDTO Information to be updated. + * @param existingActionDTO Existing Action information. + * @param tenantId Tenant ID. + * @throws ActionMgtException If an error occurs while updating the Action basic information in the database. */ - private void updateActionEndpointAuthProperties(String actionId, Authentication authentication, int tenantId) - throws ActionMgtServerException { + private void updateBasicInfo(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, Integer tenantId) + throws ActionMgtException { + + if (updatingActionDTO.getName() == null && updatingActionDTO.getDescription() == null) { + return; + } NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); try { - Map nonSecretEndpointProperties = authentication.getProperties().stream() - .filter(property -> !property.getIsConfidential()) - .collect(Collectors.toMap(AuthProperty::getName, AuthProperty::getValue)); - jdbcTemplate.withTransaction(template -> { - // Update non-secret endpoint properties. - updateActionEndpointProperties(actionId, nonSecretEndpointProperties, tenantId); - // Encrypt and update secret endpoint properties. - actionSecretProcessor.encryptAssociatedSecrets(authentication, actionId); + template.executeUpdate(ActionMgtSQLConstants.Query.UPDATE_ACTION_BASIC_INFO, + statement -> { + statement.setString(ActionMgtSQLConstants.Column.ACTION_NAME, + updatingActionDTO.getName() == null ? existingActionDTO.getName() + : updatingActionDTO.getName()); + statement.setString(ActionMgtSQLConstants.Column.ACTION_DESCRIPTION, + updatingActionDTO.getDescription() == null ? existingActionDTO.getDescription() + : updatingActionDTO.getDescription()); + statement.setString(ActionMgtSQLConstants.Column.ACTION_UUID, updatingActionDTO.getId()); + statement.setString(ActionMgtSQLConstants.Column.ACTION_TYPE, + updatingActionDTO.getType().getActionType()); + statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); + }); + return null; }); } catch (TransactionException e) { - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Error while updating the Action Endpoint Authentication Properties of " + - "Auth type: %s and Action ID: %s in Tenant Domain: %s. Rolling back updated action" + - " endpoint authentication properties.", authentication.getType(), actionId, - IdentityTenantUtil.getTenantDomain(tenantId))); - } - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_UPDATING_ENDPOINT_PROPERTIES, e); + throw new ActionMgtServerException("Error while updating Action Basic information in the system.", e); } } /** - * Update the endpoint information of an {@link Action} by given Action ID. + * Get Action Basic Info by Action ID. * - * @param actionId Action ID. - * @param endpoint Endpoint information to be updated. - * @param currentAuthentication Current Action endpoint authentication information. - * @param tenantId Tenant Id. - * @throws ActionMgtServerException If an error occurs while updating the Action endpoint. + * @param actionId UUID of the created Action. + * @param tenantId Tenant ID. + * @return ActionDTO Builder with action basic information. + * @throws ActionMgtException If an error occurs while retrieving action basic info from the database. */ - private void updateActionEndpoint(String actionId, EndpointConfig endpoint, Authentication currentAuthentication, - int tenantId) throws ActionMgtServerException { + private ActionDTOBuilder getBasicInfo(String actionType, String actionId, Integer tenantId) + throws ActionMgtException { NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); try { - jdbcTemplate.withTransaction(template -> { - template.executeUpdate(ActionMgtSQLConstants.Query.DELETE_ACTION_ENDPOINT_PROPERTIES, + return jdbcTemplate.withTransaction(template -> + template.fetchSingleRecord(ActionMgtSQLConstants.Query.GET_ACTION_BASIC_INFO_BY_ID, + (resultSet, rowNumber) -> new ActionDTOBuilder() + .id(actionId) + .type(Action.ActionTypes.valueOf( + resultSet.getString(ActionMgtSQLConstants.Column.ACTION_TYPE))) + .name(resultSet.getString(ActionMgtSQLConstants.Column.ACTION_NAME)) + .description(resultSet.getString(ActionMgtSQLConstants.Column.ACTION_DESCRIPTION)) + .status(Action.Status.valueOf( + resultSet.getString(ActionMgtSQLConstants.Column.ACTION_STATUS))), statement -> { - statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_UUID, actionId); + statement.setString(ActionMgtSQLConstants.Column.ACTION_TYPE, actionType); + statement.setString(ActionMgtSQLConstants.Column.ACTION_UUID, actionId); statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); - }); - - // Add new Endpoint configuration properties. - Map propertiesMap = getEndpointProperties(endpoint.getUri(), - endpoint.getAuthentication().getType().name(), - endpoint.getAuthentication().getPropertiesWithSecretReferences(actionId)); - addEndpointProperties(actionId, propertiesMap, tenantId); - // Encrypt and add new endpoint properties secrets. - actionSecretProcessor.encryptAssociatedSecrets(endpoint.getAuthentication(), actionId); - - // Delete old secrets. - actionSecretProcessor.deleteAssociatedSecrets(currentAuthentication, actionId); - return null; - }); + })); } catch (TransactionException e) { - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Error while updating the Action Endpoint Authentication from Auth type: %s" + - " to Auth type: %s of Action ID: %s in Tenant Domain: %s. Rolling back updated" + - " action endpoint authentication.", currentAuthentication.getType(), - endpoint.getAuthentication().getType(), actionId, - IdentityTenantUtil.getTenantDomain(tenantId))); - } - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_UPDATING_ENDPOINT_PROPERTIES, e); + throw new ActionMgtServerException("Error while retrieving Action Basic information from the system.", e); } } /** - * Add Action Endpoint properties to the Database. + * Add Action Endpoint Configurations. * - * @param actionId UUID of the created Action. - * @param endpointProperties Endpoint properties of the Action. - * @param tenantId Tenant ID. - * @throws ActionMgtServerException If an error occurs while adding endpoint properties to the database. + * @param actionDTO ActionDTO object with endpoint information. + * @param tenantId Tenant ID. + * @throws ActionMgtException If an error occurs while adding action endpoint. */ - private void addEndpointProperties(String actionId, Map endpointProperties, Integer tenantId) - throws ActionMgtException { + private void addEndpoint(ActionDTO actionDTO, Integer tenantId) throws ActionMgtException { - NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); + EndpointConfig endpoint = actionDTO.getEndpoint(); + Map endpointProperties = new HashMap<>(); try { - jdbcTemplate.withTransaction(template -> { - template.executeBatchInsert(ActionMgtSQLConstants.Query.ADD_ACTION_ENDPOINT_PROPERTIES, - statement -> { - for (Map.Entry property : endpointProperties.entrySet()) { - statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_UUID, actionId); - statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); - statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_NAME, - property.getKey()); - statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_VALUE, - property.getValue()); - statement.addBatch(); - } - }, null); - return null; - }); + endpointProperties.put(URI_PROPERTY, endpoint.getUri()); + endpointProperties.put(AUTHN_TYPE_PROPERTY, endpoint.getAuthentication().getType().name()); + endpoint.getAuthentication().getProperties().forEach( + authProperty -> endpointProperties.put(authProperty.getName(), authProperty.getValue())); + + addActionPropertiesToDB(actionDTO.getId(), endpointProperties, tenantId); } catch (TransactionException e) { - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_ADDING_ENDPOINT_PROPERTIES, e); + throw new ActionMgtServerException("Error while adding Action Endpoint configurations in the system.", e); } } /** - * Get Action Basic Info by Action ID. + * Update Action Endpoint Configurations. * - * @param actionId UUID of the created Action. - * @param tenantId Tenant ID. - * @return Action Basic Info. - * @throws ActionMgtException If an error occurs while retrieving action basic info from the database. + * @param updatingActionDTO Updating ActionDTO object with endpoint information. + * @param existingActionDTO Existing ActionDTO object with endpoint information. + * @param tenantId Tenant ID. + * @throws ActionMgtException If an error occurs while updating action endpoint. */ - private Action getActionBasicInfoById(String actionType, String actionId, Integer tenantId) + private void updateEndpoint(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, Integer tenantId) throws ActionMgtException { - NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); + EndpointConfig updatingEndpoint = updatingActionDTO.getEndpoint(); + if (updatingEndpoint == null) { + return; + } + try { - return jdbcTemplate.fetchSingleRecord(ActionMgtSQLConstants.Query.GET_ACTION_BASIC_INFO_BY_ID, - (resultSet, rowNumber) -> new Action.ActionResponseBuilder() - .id(actionId) - .type(Action.ActionTypes.valueOf(resultSet.getString(ActionMgtSQLConstants.Column.ACTION_TYPE))) - .name(resultSet.getString(ActionMgtSQLConstants.Column.ACTION_NAME)) - .description(resultSet.getString(ActionMgtSQLConstants.Column.ACTION_DESCRIPTION)) - .status(Action.Status.valueOf(resultSet.getString(ActionMgtSQLConstants.Column.ACTION_STATUS))) - .build(), - statement -> { - statement.setString(ActionMgtSQLConstants.Column.ACTION_TYPE, actionType); - statement.setString(ActionMgtSQLConstants.Column.ACTION_UUID, actionId); - statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); - }); - } catch (DataAccessException e) { - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_RETRIEVING_ACTION_BASIC_INFO, e); + if (updatingEndpoint.getUri() != null) { + updateActionPropertiesInDB(updatingActionDTO.getId(), + Collections.singletonMap(URI_PROPERTY, updatingEndpoint.getUri()), tenantId); + } + + updateEndpointAuthentication(updatingActionDTO.getId(), updatingEndpoint.getAuthentication(), + existingActionDTO.getEndpoint().getAuthentication(), tenantId); + } catch (ActionMgtException | TransactionException e) { + throw new ActionMgtServerException("Error while updating Action Endpoint information in the system.", e); } } /** - * Get Action Endpoint properties by ID. + * Update Action Endpoint Authentication. * - * @param actionUUID UUID of the created Action. - * @param tenantId Tenant ID. - * @return Endpoint Configuration. - * @throws ActionMgtRuntimeException If an error occurs while retrieving endpoint properties from the database. + * @param actionId UUID of the created Action. + * @param updatingAuthentication Authentication object with updated configurations. + * @param existingAuthentication Existing Authentication object. + * @param tenantId Tenant ID. + * @throws ActionMgtException If an error occurs while updating action endpoint authentication. */ - private EndpointConfig getActionEndpointConfigById(String actionUUID, Integer tenantId) - throws ActionMgtRuntimeException { + private void updateEndpointAuthentication(String actionId, Authentication updatingAuthentication, + Authentication existingAuthentication, Integer tenantId) + throws ActionMgtException { - NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); - try { - Map actionEndpointProperties = new HashMap<>(); - jdbcTemplate.executeQuery(ActionMgtSQLConstants.Query.GET_ACTION_ENDPOINT_INFO_BY_ID, - (resultSet, rowNumber) -> { - actionEndpointProperties.put( - resultSet.getString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_NAME), - resultSet.getString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_VALUE)); - return null; - }, - statement -> { - statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_UUID, actionUUID); - statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); - }); + if (updatingAuthentication == null) { + return; + } - Authentication authentication = null; - if (actionEndpointProperties.containsKey(ActionMgtConstants.AUTHN_TYPE_ATTRIBUTE)) { - authentication = new Authentication.AuthenticationBuilder() - .type(Authentication.Type.valueOf( - actionEndpointProperties.get(ActionMgtConstants.AUTHN_TYPE_ATTRIBUTE))) - .properties(actionEndpointProperties) - .build(); + try { + if (updatingAuthentication.getType() == existingAuthentication.getType()) { + updateAuthentication(actionId, updatingAuthentication, tenantId); } else { - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_NO_AUTHENTICATION_TYPE, null); + // Delete existing authentication configurations. + deleteAuthentication(actionId, existingAuthentication, tenantId); + // Add new authentication configurations. + addAuthentication(actionId, updatingAuthentication, tenantId); } - - return new EndpointConfig.EndpointConfigBuilder() - .uri(actionEndpointProperties.get(ActionMgtConstants.URI_ATTRIBUTE)) - .authentication(authentication).build(); - } catch (ActionMgtServerException | DataAccessException e) { - /** - * Throwing a runtime exception because {@link ActionMgtServerException} and {@link DataAccessException} - * is not handled in {@link org.wso2.carbon.database.utils.jdbc.RowMapper} of - * {@link NamedJdbcTemplate#executeQuery(String, org.wso2.carbon.database.utils.jdbc.RowMapper, - * org.wso2.carbon.database.utils.jdbc.NamedQueryFilter)} - */ - throw ActionManagementUtil.handleRuntimeException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_RETRIEVING_ACTION_ENDPOINT_PROPERTIES.getMessage(), e); + } catch (TransactionException e) { + throw new ActionMgtServerException("Error while updating Action Endpoint Authentication.", e); } } /** - * Get Action Endpoint properties Map. + * Add Authentication Configurations of a new Authentication type. * - * @param endpointUri Endpoint URI of the Action. - * @param authType Authentication Type of the Action. - * @param authProperties Authentication Properties of the Endpoint. - * @return Endpoint Properties Map. + * @param actionId UUID of the created Action. + * @param updatingAuthentication Authentication object with updated configurations. + * @param tenantId Tenant ID. + * @throws TransactionException If an error occurs while adding action authentication. */ - private Map getEndpointProperties(String endpointUri, String authType, - List authProperties) { + private void addAuthentication(String actionId, Authentication updatingAuthentication, Integer tenantId) + throws TransactionException { - Map endpointProperties = new HashMap<>(); - if (endpointUri != null) { - endpointProperties.put(ActionMgtConstants.URI_ATTRIBUTE, endpointUri); + Map authenticationProperties = updatingAuthentication.getProperties().stream() + .collect(Collectors.toMap(AuthProperty::getName, AuthProperty::getValue)); + authenticationProperties.put(AUTHN_TYPE_PROPERTY, updatingAuthentication.getType().name()); + + addActionPropertiesToDB(actionId, authenticationProperties, tenantId); + } + + /** + * Delete Authentication Configurations of an existing Authentication type. + * + * @param actionId UUID of the created Action. + * @param existingAuthentication Existing Authentication object. + * @param tenantId Tenant ID. + * @throws TransactionException If an error occurs while deleting action authentication. + */ + private void deleteAuthentication(String actionId, Authentication existingAuthentication, Integer tenantId) + throws TransactionException { + + List deletingProperties = existingAuthentication.getProperties().stream() + .map(AuthProperty::getName) + .collect(Collectors.toList()); + deletingProperties.add(AUTHN_TYPE_PROPERTY); + + deleteActionPropertiesInDB(actionId, deletingProperties, tenantId); + } + + /** + * Update Authentication Configurations of an existing Authentication type. + * + * @param actionId UUID of the created Action. + * @param updatingAuthentication Authentication object with updated configurations. + * @param tenantId Tenant ID. + * @throws TransactionException If an error occurs while updating action authentication. + */ + private void updateAuthentication(String actionId, Authentication updatingAuthentication, Integer tenantId) + throws TransactionException { + + Map nonSecretAuthenticationProperties = updatingAuthentication.getProperties().stream() + .filter(property -> !property.getIsConfidential()) + .collect(Collectors.toMap(AuthProperty::getName, AuthProperty::getValue)); + // Update non-secret endpoint properties. + updateActionPropertiesInDB(actionId, nonSecretAuthenticationProperties, tenantId); + } + + /** + * Add Action properties. + * + * @param actionDTO ActionDTO object with properties. + * @param tenantId Tenant ID. + * @throws ActionMgtException If an error occurs while adding action properties. + */ + private void addProperties(ActionDTO actionDTO, Integer tenantId) throws ActionMgtException { + + Map propertiesMap = actionDTO.getProperties(); + if (propertiesMap == null) { + return; } - if (authType != null) { - endpointProperties.put(ActionMgtConstants.AUTHN_TYPE_ATTRIBUTE, authType); + + Map actionProperties = propertiesMap.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, entry -> (String) entry.getValue())); + try { + addActionPropertiesToDB(actionDTO.getId(), actionProperties, tenantId); + } catch (TransactionException e) { + throw new ActionMgtServerException("Error while adding Action Properties in the system.", e); } - if (authProperties != null) { - for (AuthProperty property : authProperties) { - endpointProperties.put(property.getName(), property.getValue()); - } + } + + /** + * Update Action properties. + * + * @param updatingActionDTO Updating ActionDTO object with properties. + * @param existingActionDTO Existing ActionDTO object with properties. + * @param tenantId Tenant ID. + * @throws ActionMgtException If an error occurs while updating action properties. + */ + private void updateProperties(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, + Integer tenantId) throws ActionMgtException { + + Map propertiesMap = updatingActionDTO.getProperties(); + if (propertiesMap == null) { + return; } - return endpointProperties; + Map updatingProperties = propertiesMap.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, entry -> (String) entry.getValue())); + try { + // Delete existing properties. + deleteActionPropertiesInDB(updatingActionDTO.getId(), + new ArrayList<>(existingActionDTO.getProperties().keySet()), tenantId); + // Add updated properties. + addActionPropertiesToDB(updatingActionDTO.getId(), updatingProperties, tenantId); + } catch (TransactionException e) { + throw new ActionMgtServerException("Error while updating Action Properties in the system.", e); + } } /** - * Update Action Endpoint properties. + * Add Action properties to the Database. * - * @param actionId UUID of the created Action. - * @param endpointProperties Endpoint Properties to be updated. - * @param tenantId Tenant ID. + * @param actionId UUID of the created Action. + * @param actionProperties Properties of the Action. + * @param tenantId Tenant ID. + * @throws TransactionException If an error occurs while persisting action properties to the database. */ - private void updateActionEndpointProperties(String actionId, Map endpointProperties, - Integer tenantId) throws ActionMgtException { + private void addActionPropertiesToDB(String actionId, Map actionProperties, Integer tenantId) + throws TransactionException { NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); - try { - jdbcTemplate.withTransaction(template -> { - template.executeBatchInsert(ActionMgtSQLConstants.Query.UPDATE_ACTION_ENDPOINT_PROPERTIES, + jdbcTemplate.withTransaction(template -> { + template.executeBatchInsert(ActionMgtSQLConstants.Query.ADD_ACTION_PROPERTIES, statement -> { - for (Map.Entry property : endpointProperties.entrySet()) { - statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_VALUE, - property.getValue()); - statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_PROPERTY_NAME, - property.getKey()); - statement.setString(ActionMgtSQLConstants.Column.ACTION_ENDPOINT_UUID, actionId); + for (Map.Entry property : actionProperties.entrySet()) { + statement.setString(ActionMgtSQLConstants.Column.ACTION_PROPERTIES_UUID, actionId); statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); + statement.setString(ActionMgtSQLConstants.Column.ACTION_PROPERTIES_PROPERTY_NAME, + property.getKey()); + statement.setString(ActionMgtSQLConstants.Column.ACTION_PROPERTIES_PROPERTY_VALUE, + property.getValue()); statement.addBatch(); } }, null); - return null; - }); - } catch (TransactionException e) { - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_UPDATING_ENDPOINT_PROPERTIES, e); - } + return null; + }); } /** - * Update Action Status. + * Get Action properties by ID. * - * @param actionType Action Type. - * @param actionId UUID of the Action. - * @param status Action status to be updated. - * @param tenantId Tenant ID. - * @throws ActionMgtException If an error occurs while updating the Action status. + * @param actionId UUID of the created Action. + * @param tenantId Tenant ID. + * @return A map of action properties, including any additional data based on action type. + * @throws ActionMgtException If an error occurs while retrieving action properties from the database. */ - private Action changeActionStatus(String actionType, String actionId, String status, Integer tenantId) - throws ActionMgtException { + private Map getActionPropertiesFromDB(String actionId, Integer tenantId) throws ActionMgtException { NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); + Map actionEndpointProperties = new HashMap<>(); try { - jdbcTemplate.executeUpdate(ActionMgtSQLConstants.Query.CHANGE_ACTION_STATUS, - statement -> { - statement.setString(ActionMgtSQLConstants.Column.ACTION_STATUS, status); - statement.setString(ActionMgtSQLConstants.Column.ACTION_UUID, actionId); - statement.setString(ActionMgtSQLConstants.Column.ACTION_TYPE, actionType); - statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); - }); + jdbcTemplate.withTransaction(template -> + template.executeQuery(ActionMgtSQLConstants.Query.GET_ACTION_PROPERTIES_INFO_BY_ID, + (resultSet, rowNumber) -> { + actionEndpointProperties.put( + resultSet.getString(ActionMgtSQLConstants.Column.ACTION_PROPERTIES_PROPERTY_NAME), + resultSet.getString(ActionMgtSQLConstants.Column.ACTION_PROPERTIES_PROPERTY_VALUE)); + return null; + }, + statement -> { + statement.setString(ActionMgtSQLConstants.Column.ACTION_PROPERTIES_UUID, actionId); + statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); + })); - return getActionBasicInfoById(actionType, actionId, tenantId); - } catch (DataAccessException e) { - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_UPDATING_ACTION_STATUS, e); + return actionEndpointProperties; + } catch (TransactionException e) { + throw new ActionMgtServerException("Error while retrieving Action Properties from the system.", e); } } /** - * Update the basic information of an {@link Action} by given Action ID. + * Update the given property of an {@link ActionDTO} by given Action ID. * - * @param actionType Action Type. - * @param actionId Action ID. - * @param updatingAction Information to be updated. - * @param existingAction Existing Action information. - * @param tenantId Tenant ID. - * @throws ActionMgtServerException If an error occurs while updating the Action basic information. + * @param actionId UUID of the created Action. + * @param updatingProperties Action properties to be updated. + * @param tenantId Tenant ID. + * @throws TransactionException If an error occurs while updating the Action properties in the database. */ - private void updateBasicInfo(String actionType, String actionId, Action updatingAction, Action existingAction, - Integer tenantId) throws ActionMgtServerException { + private void updateActionPropertiesInDB(String actionId, Map updatingProperties, + Integer tenantId) throws TransactionException { - if (updatingAction.getName() == null && updatingAction.getDescription() == null) { - return; - } + NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); + jdbcTemplate.withTransaction(template -> + template.executeBatchInsert(ActionMgtSQLConstants.Query.UPDATE_ACTION_PROPERTY, + statement -> { + for (Map.Entry property : updatingProperties.entrySet()) { + statement.setString(ActionMgtSQLConstants.Column.ACTION_PROPERTIES_PROPERTY_VALUE, + property.getValue()); + statement.setString(ActionMgtSQLConstants.Column.ACTION_PROPERTIES_PROPERTY_NAME, + property.getKey()); + statement.setString(ActionMgtSQLConstants.Column.ACTION_PROPERTIES_UUID, actionId); + statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); + statement.addBatch(); + } + }, null)); + } + + /** + * Delete the given properties of an {@link ActionDTO} by given Action ID. + * + * @param actionId UUID of the created Action. + * @param deletingProperties Action properties to be deleted. + * @param tenantId Tenant ID. + * @throws TransactionException If an error occurs while deleting the Action properties in the database. + */ + private void deleteActionPropertiesInDB(String actionId, List deletingProperties, Integer tenantId) + throws TransactionException { NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); - try { - jdbcTemplate.executeUpdate(ActionMgtSQLConstants.Query.UPDATE_ACTION_BASIC_INFO, + jdbcTemplate.withTransaction(template -> + template.executeBatchInsert(ActionMgtSQLConstants.Query.DELETE_ACTION_PROPERTY, statement -> { - statement.setString(ActionMgtSQLConstants.Column.ACTION_NAME, - updatingAction.getName() == null ? existingAction.getName() : updatingAction.getName()); - statement.setString(ActionMgtSQLConstants.Column.ACTION_DESCRIPTION, - updatingAction.getDescription() == null ? existingAction.getDescription() - : updatingAction.getDescription()); - statement.setString(ActionMgtSQLConstants.Column.ACTION_UUID, actionId); - statement.setString(ActionMgtSQLConstants.Column.ACTION_TYPE, actionType); - statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); - }); - } catch (DataAccessException e) { - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_UPDATING_ACTION_BASIC_INFO, e); - } + for (String property : deletingProperties) { + statement.setString(ActionMgtSQLConstants.Column.ACTION_PROPERTIES_PROPERTY_NAME, + property); + statement.setString(ActionMgtSQLConstants.Column.ACTION_PROPERTIES_UUID, actionId); + statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); + statement.addBatch(); + } + }, null)); } /** - * Update the endpoint URI and authentication properties of an {@link Action} by given Action ID. + * Update Action Status. * - * @param actionId Action ID. - * @param updatingAction Information to be updated. - * @param existingAction Existing Action information. - * @param tenantId Tenant ID. - * @throws ActionMgtException If an error occurs while updating the Action endpoint. + * @param actionType Action Type. + * @param actionId UUID of the Action. + * @param status Action status to be updated. + * @param tenantId Tenant ID. + * @return Updated ActionDTO with basic information. + * @throws ActionMgtException If an error occurs while updating the Action status. */ - private void updateEndpointUriAndAuthentication(String actionId, Action updatingAction, Action existingAction, - Integer tenantId) throws ActionMgtException { + private ActionDTO changeActionStatus(String actionType, String actionId, String status, Integer tenantId) + throws ActionMgtException { - EndpointConfig updatingEndpoint = updatingAction.getEndpoint(); - if (updatingEndpoint == null) { - // No update needed if there's no endpoint configuration in the updating action. - return; - } + NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); + try { + jdbcTemplate.withTransaction(template -> { + template.executeUpdate(ActionMgtSQLConstants.Query.CHANGE_ACTION_STATUS, + statement -> { + statement.setString(ActionMgtSQLConstants.Column.ACTION_STATUS, status); + statement.setString(ActionMgtSQLConstants.Column.ACTION_UUID, actionId); + statement.setString(ActionMgtSQLConstants.Column.ACTION_TYPE, actionType); + statement.setInt(ActionMgtSQLConstants.Column.TENANT_ID, tenantId); + }); - Authentication updatingAuthentication = updatingEndpoint.getAuthentication(); - if (updatingAuthentication == null) { - // When updating action, updates the URI only. - updateActionEndpointProperties(actionId, getEndpointProperties(updatingEndpoint.getUri(), null, - null), tenantId); - return; - } + return null; + }); - Authentication existingAuthentication = existingAction.getEndpoint().getAuthentication(); - if (updatingAuthentication.getType().equals(existingAuthentication.getType())) { - // When updating action, updates the URI and the authentication properties only. - if (updatingEndpoint.getUri() != null) { - updateActionEndpointProperties(actionId, getEndpointProperties(updatingEndpoint.getUri(), null, - null), tenantId); - } - updateActionEndpointAuthProperties(actionId, updatingAuthentication, tenantId); - return; + return getBasicInfo(actionType, actionId, tenantId).build(); + } catch (TransactionException e) { + throw new ActionMgtServerException("Error while updating Action Status to " + status, e); } - - // When updating action, updates the entire endpoint. - updatingEndpoint = StringUtils.isNotEmpty(updatingEndpoint.getUri()) ? updatingEndpoint : - new EndpointConfig.EndpointConfigBuilder() - .uri(existingAction.getEndpoint().getUri()) - .authentication(updatingAuthentication) - .build(); - updateActionEndpoint(actionId, updatingEndpoint, existingAuthentication, tenantId); } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionDTOModelResolverClientException.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionDTOModelResolverClientException.java new file mode 100644 index 000000000000..f8d4700358d5 --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionDTOModelResolverClientException.java @@ -0,0 +1,32 @@ +/* + * 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.action.management.exception; + +/** + * Client Exception class for ActionDTO Model Resolver. + * This exception is thrown when there is any validation failures or client error in performing action type + * specific operations. + */ +public class ActionDTOModelResolverClientException extends ActionDTOModelResolverException { + + public ActionDTOModelResolverClientException(String message, String description) { + + super(message, description); + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionDTOModelResolverException.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionDTOModelResolverException.java new file mode 100644 index 000000000000..c144ff388164 --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionDTOModelResolverException.java @@ -0,0 +1,45 @@ +/* + * 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.action.management.exception; + +/** + * Exception class for ActionDTO Model Resolver. + * This exception is thrown when there is an issue in performing action type specific operations. + */ +public class ActionDTOModelResolverException extends Exception { + + private final String description; + + public ActionDTOModelResolverException(String message, String description) { + + super(message); + this.description = description; + } + + public ActionDTOModelResolverException(String message, String description, Throwable cause) { + + super(message, cause); + this.description = description; + } + + public String getDescription() { + + return this.description; + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionDTOModelResolverServerException.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionDTOModelResolverServerException.java new file mode 100644 index 000000000000..e8861ae0aff1 --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionDTOModelResolverServerException.java @@ -0,0 +1,36 @@ +/* + * 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.action.management.exception; + +/** + * Server Exception class for ActionDTO Model Resolver. + * This exception is thrown when there is an issue in performing action type specific operations in the system. + */ +public class ActionDTOModelResolverServerException extends ActionDTOModelResolverException { + + public ActionDTOModelResolverServerException(String message, String description) { + + super(message, description); + } + + public ActionDTOModelResolverServerException(String message, String description, Throwable cause) { + + super(message, description, cause); + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionMgtException.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionMgtException.java index 4b922602e35c..dc7ebd6886da 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionMgtException.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionMgtException.java @@ -31,16 +31,9 @@ public ActionMgtException(String message) { super(message); } - public ActionMgtException(String message, String errorCode) { - - super(message); - this.errorCode = errorCode; - } - - public ActionMgtException(String message, String errorCode, Throwable cause) { + public ActionMgtException(String message, Throwable cause) { super(message, cause); - this.errorCode = errorCode; } public ActionMgtException(String message, String description, String errorCode) { @@ -62,18 +55,8 @@ public String getErrorCode() { return this.errorCode; } - public void setErrorCode(String errorCode) { - - this.errorCode = errorCode; - } - public String getDescription() { return this.description; } - - public void setDescription(String description) { - - this.description = description; - } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionMgtServerException.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionMgtServerException.java index 3692b83eae40..95a83586ad8a 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionMgtServerException.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/exception/ActionMgtServerException.java @@ -23,29 +23,18 @@ */ public class ActionMgtServerException extends ActionMgtException { - public ActionMgtServerException(String message, String errorCode) { - - super(message, errorCode); - } - - public ActionMgtServerException(String message, String description, String errorCode) { + public ActionMgtServerException(String message) { - super(message, description, errorCode); + super(message); } - public ActionMgtServerException(String message, String errorCode, Throwable cause) { + public ActionMgtServerException(String message, Throwable cause) { - super(message, errorCode, cause); + super(message, cause); } - public ActionMgtServerException(String message, String description, String errorCode, - Throwable cause) { + public ActionMgtServerException(String message, String description, String errorCode, Throwable cause) { super(message, description, errorCode, cause); } - - public ActionMgtServerException(String message) { - - super(message); - } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java index 44fe7f894eac..8da0688e5a86 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/internal/ActionMgtServiceComponent.java @@ -28,8 +28,12 @@ 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.identity.action.management.ActionManagementService; -import org.wso2.carbon.identity.action.management.ActionManagementServiceImpl; +import org.wso2.carbon.identity.action.management.dao.impl.ActionDTOModelResolverFactory; +import org.wso2.carbon.identity.action.management.service.ActionConverter; +import org.wso2.carbon.identity.action.management.service.ActionDTOModelResolver; +import org.wso2.carbon.identity.action.management.service.ActionManagementService; +import org.wso2.carbon.identity.action.management.service.impl.ActionConverterFactory; +import org.wso2.carbon.identity.action.management.service.impl.CacheBackedActionManagementService; import org.wso2.carbon.identity.secret.mgt.core.SecretManager; import org.wso2.carbon.identity.secret.mgt.core.SecretResolveManager; @@ -49,7 +53,8 @@ protected void activate(ComponentContext context) { try { BundleContext bundleCtx = context.getBundleContext(); - bundleCtx.registerService(ActionManagementService.class, ActionManagementServiceImpl.getInstance(), null); + bundleCtx.registerService(ActionManagementService.class, CacheBackedActionManagementService.getInstance(), + null); LOG.debug("Action management bundle is activated"); } catch (Throwable e) { LOG.error("Error while initializing Action management component.", e); @@ -68,6 +73,55 @@ protected void deactivate(ComponentContext context) { } } + @Reference( + name = "action.converter", + service = ActionConverter.class, + cardinality = ReferenceCardinality.MULTIPLE, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetActionConverter" + ) + protected void setActionConverter(ActionConverter actionConverter) { + + LOG.debug("Registering ActionConverter: " + actionConverter.getClass().getName() + + " in the ActionMgtServiceComponent."); + ActionConverterFactory.registerActionConverter(actionConverter); + } + + protected void unsetActionConverter(ActionConverter actionConverter) { + + if (LOG.isDebugEnabled()) { + LOG.debug("Unregistering ActionConverter: " + actionConverter.getClass().getName() + + " in the ActionMgtServiceComponent."); + } + + ActionConverterFactory.unregisterActionConverter(actionConverter); + } + + @Reference( + name = "action.property.resolver", + service = ActionDTOModelResolver.class, + cardinality = ReferenceCardinality.MULTIPLE, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetActionPropertyResolver" + ) + protected void setActionPropertyResolver(ActionDTOModelResolver actionDTOModelResolver) { + + if (LOG.isDebugEnabled()) { + LOG.debug("Registering ActionPropertyResolver: " + actionDTOModelResolver.getClass().getName() + + " in the ActionMgtServiceComponent."); + } + ActionDTOModelResolverFactory.registerActionDTOModelResolver(actionDTOModelResolver); + } + + protected void unsetActionPropertyResolver(ActionDTOModelResolver actionDTOModelResolver) { + + if (LOG.isDebugEnabled()) { + LOG.debug("Unregistering ActionPropertyResolver: " + actionDTOModelResolver.getClass().getName() + + " in the ActionMgtServiceComponent."); + } + ActionDTOModelResolverFactory.unregisterActionDTOModelResolver(actionDTOModelResolver); + } + @Reference( name = "org.wso2.carbon.identity.secret.mgt.core.SecretManager", service = SecretManager.class, @@ -78,11 +132,13 @@ protected void deactivate(ComponentContext context) { private void setSecretManager(SecretManager secretManager) { ActionMgtServiceComponentHolder.getInstance().setSecretManager(secretManager); + LOG.debug("SecretManager set in ActionMgtServiceComponentHolder bundle."); } private void unsetSecretManager(SecretManager secretManager) { ActionMgtServiceComponentHolder.getInstance().setSecretManager(null); + LOG.debug("SecretManager unset in ActionMgtServiceComponentHolder bundle."); } @Reference( @@ -95,10 +151,12 @@ private void unsetSecretManager(SecretManager secretManager) { private void setSecretResolveManager(SecretResolveManager secretResolveManager) { ActionMgtServiceComponentHolder.getInstance().setSecretResolveManager(secretResolveManager); + LOG.debug("SecretResolveManager set in ActionMgtServiceComponentHolder bundle."); } private void unsetSecretResolveManager(SecretResolveManager secretResolveManager) { ActionMgtServiceComponentHolder.getInstance().setSecretResolveManager(null); + LOG.debug("SecretResolveManager unset in ActionMgtServiceComponentHolder bundle."); } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Action.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Action.java index 99fa95aee93d..dc1f3030bf47 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Action.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Action.java @@ -115,7 +115,7 @@ public static ActionTypes[] filterByCategory(Category category) { */ public enum Category { PRE_POST, - IN_FLOW; + IN_FLOW } } @@ -124,30 +124,10 @@ public enum Category { */ public enum Status { - ACTIVE("ACTIVE"), - INACTIVE("INACTIVE"); - - private final String value; - - Status(String v) { - this.value = v; - } - - public String value() { - return value; - } - - public static Status fromValue(String value) { - for (Status b : Status.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } + ACTIVE, + INACTIVE } - private String id; private ActionTypes type; private String name; @@ -155,9 +135,6 @@ public static Status fromValue(String value) { private Status status; private EndpointConfig endpointConfig; - public Action() { - } - public Action(ActionResponseBuilder actionResponseBuilder) { this.id = actionResponseBuilder.id; @@ -205,11 +182,6 @@ public EndpointConfig getEndpoint() { return endpointConfig; } - public void setEndpoint(EndpointConfig endpointConfig) { - - this.endpointConfig = endpointConfig; - } - /** * ActionResponseBuilder. */ @@ -222,9 +194,6 @@ public static class ActionResponseBuilder { private Status status; private EndpointConfig endpointConfig; - public ActionResponseBuilder() { - } - public ActionResponseBuilder id(String id) { this.id = id; @@ -276,9 +245,6 @@ public static class ActionRequestBuilder { private String description; private EndpointConfig endpointConfig; - public ActionRequestBuilder() { - } - public ActionRequestBuilder name(String name) { this.name = name; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/ActionDTO.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/ActionDTO.java new file mode 100644 index 000000000000..3351ee606f1b --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/ActionDTO.java @@ -0,0 +1,136 @@ +/* + * 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.action.management.model; + +import java.util.Map; + +/** + * Action Data Transfer Object. + */ +public class ActionDTO { + + private final String id; + private final Action.ActionTypes type; + private final String name; + private final String description; + private final Action.Status status; + private final EndpointConfig endpoint; + private final Map properties; + + public ActionDTO(Builder builder) { + + this.id = builder.id; + this.type = builder.type; + this.name = builder.name; + this.description = builder.description; + this.status = builder.status; + this.endpoint = builder.endpoint; + this.properties = builder.properties; + } + + public String getId() { + + return id; + } + + public Action.ActionTypes getType() { + + return type; + } + + public String getName() { + + return name; + } + + public String getDescription() { + + return description; + } + + public Action.Status getStatus() { + + return status; + } + + public EndpointConfig getEndpoint() { + + return endpoint; + } + + public Map getProperties() { + + return properties; + } + + public Object getProperty(String propertyName) { + + if (properties == null) { + return null; + } + + return properties.get(propertyName); + } + + /** + * Builder for ActionDTO. + */ + public static class Builder { + + private final String id; + private final Action.ActionTypes type; + private final String name; + private final String description; + private final Action.Status status; + private final EndpointConfig endpoint; + private Map properties; + + public Builder(ActionDTO actionDTO) { + + this.id = actionDTO.getId(); + this.type = actionDTO.getType(); + this.name = actionDTO.getName(); + this.description = actionDTO.getDescription(); + this.status = actionDTO.getStatus(); + this.endpoint = actionDTO.getEndpoint(); + this.properties = actionDTO.getProperties(); + } + + public Builder(Action action) { + + this.id = action.getId(); + this.type = action.getType(); + this.name = action.getName(); + this.description = action.getDescription(); + this.status = action.getStatus(); + this.endpoint = action.getEndpoint(); + } + + public Builder properties(Map properties) { + + this.properties = properties; + return this; + } + + public ActionDTO build() { + + return new ActionDTO(this); + } + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Authentication.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Authentication.java index 5608107befc7..98f34f31adcd 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Authentication.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/model/Authentication.java @@ -20,10 +20,10 @@ import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; -import org.wso2.carbon.identity.action.management.ActionSecretProcessor; -import org.wso2.carbon.identity.action.management.constant.ActionMgtConstants; +import org.wso2.carbon.identity.action.management.constant.error.ErrorMessage; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; -import org.wso2.carbon.identity.action.management.util.ActionManagementUtil; +import org.wso2.carbon.identity.action.management.util.ActionManagementExceptionHandler; +import org.wso2.carbon.identity.action.management.util.ActionSecretProcessor; import org.wso2.carbon.identity.secret.mgt.core.exception.SecretManagementException; import java.util.ArrayList; @@ -140,10 +140,10 @@ public List getPropertiesWithDecryptedValues(String actionId) thro try { return CollectionUtils.isEmpty(properties) ? properties : - secretProcessor.decryptAssociatedSecrets(properties, type.getName(), actionId); + secretProcessor.decryptAssociatedSecrets(this, actionId); } catch (SecretManagementException e) { - throw ActionManagementUtil.handleServerException( - ActionMgtConstants.ErrorMessages.ERROR_WHILE_DECRYPTING_ACTION_ENDPOINT_AUTH_PROPERTIES, e); + throw ActionManagementExceptionHandler.handleServerException( + ErrorMessage.ERROR_WHILE_DECRYPTING_ACTION_ENDPOINT_AUTH_PROPERTIES, e); } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionConverter.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionConverter.java new file mode 100644 index 000000000000..dc46635bb5a1 --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionConverter.java @@ -0,0 +1,48 @@ +/* + * 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.action.management.service; + +import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.ActionDTO; + +/** + * This interface defines the Action ActionConverter. + * Action ActionConverter is the component that is responsible for the conversions between Action and ExtendedAction + * objects. + */ +public interface ActionConverter { + + Action.ActionTypes getSupportedActionType(); + + /** + * Convert Action object into ActionDTO object. + * + * @param action Action object. + * @return ActionDTO object. + */ + ActionDTO buildActionDTO(Action action); + + /** + * Convert ActionDTO object into Action object. + * + * @param actionDTO ActionDTO object. + * @return Action object. + */ + Action buildAction(ActionDTO actionDTO); +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionDTOModelResolver.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionDTOModelResolver.java new file mode 100644 index 000000000000..abfc30170b09 --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionDTOModelResolver.java @@ -0,0 +1,102 @@ +/* + * 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.action.management.service; + +import org.wso2.carbon.identity.action.management.exception.ActionDTOModelResolverException; +import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.ActionDTO; + +import java.util.List; + +/** + * This interface defines the Action Property Resolver. + * Action Property Resolver is the component that is responsible for handling action type specific operations. + */ +public interface ActionDTOModelResolver { + + Action.ActionTypes getSupportedActionType(); + + /** + * Resolve the properties that need to be added in the Action Management Service. + * This method is responsible for performing necessary CRUD operations for the properties that need to be added + * using other external services. + * The Action Management Service ensures that only the properties returned by this method are stored. + * + * @param actionDTO ActionDTO object. + * @param tenantDomain Tenant domain. + * @return ActionDTO object with resolved properties. + * @throws ActionDTOModelResolverException If an error occurs while resolving the properties. + */ + ActionDTO resolveForAddOperation(ActionDTO actionDTO, String tenantDomain) throws ActionDTOModelResolverException; + + /** + * Populate the properties according to the references stored in the Action Management Service. + * This method is responsible for populating the properties that need to be retrieved using other external services. + * The Action Management Service ensures that only the properties populated by this method are included in the + * returned ActionDTO object. + * + * @param actionDTO ActionDTO object with properties references. + * @param tenantDomain Tenant domain. + * @return ActionDTO object with populated properties. + * @throws ActionDTOModelResolverException If an error occurs while populating the properties. + */ + ActionDTO resolveForGetOperation(ActionDTO actionDTO, String tenantDomain) throws ActionDTOModelResolverException; + + /** + * Populate the properties of the given ActionDTO list according to the references stored in the Action Management + * Service. + * This method is responsible for populating the properties that need to be retrieved using other external services. + * The Action Management Service ensures that only the properties populated by this method are included in the + * returned ActionDTO object list. + * + * @param actionDTOList List of ActionDTO objects with properties references. + * @param tenantDomain Tenant domain. + * @return List of ActionDTO objects with populated properties. + * @throws ActionDTOModelResolverException If an error occurs while populating the properties. + */ + List resolveForGetOperation(List actionDTOList, String tenantDomain) + throws ActionDTOModelResolverException; + + /** + * Resolve the properties that need to be updated in the Action Management Service. + * This method is responsible for performing necessary CRUD operations for the properties that need to be updated + * using other external services. + * The Action Management Service ensures that only the properties returned by this method are updated. + * + * @param updatingActionDTO ActionDTO object with updated properties. + * @param existingActionDTO ActionDTO object with existing properties. + * @param tenantDomain Tenant domain. + * @return ActionDTO object with resolved properties. + * @throws ActionDTOModelResolverException If an error occurs while resolving the properties. + */ + ActionDTO resolveForUpdateOperation(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, String tenantDomain) + throws ActionDTOModelResolverException; + + /** + * Delete the properties that need to be deleted in the Action Management Service. + * This method is responsible for performing necessary CRUD operations for the properties that need to be deleted + * using other external services. + * + * @param deletingActionDTO ActionDTO object with properties to be deleted. + * @param tenantDomain Tenant domain. + * @throws ActionDTOModelResolverException If an error occurs while deleting the properties. + */ + void resolveForDeleteOperation(ActionDTO deletingActionDTO, String tenantDomain) + throws ActionDTOModelResolverException; +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionManagementService.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionManagementService.java similarity index 98% rename from components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionManagementService.java rename to components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionManagementService.java index fe1851cb1b13..62b121127510 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionManagementService.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/ActionManagementService.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.identity.action.management; +package org.wso2.carbon.identity.action.management.service; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.model.Action; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionConverterFactory.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionConverterFactory.java new file mode 100644 index 000000000000..43388a915d6c --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionConverterFactory.java @@ -0,0 +1,60 @@ +/* + * 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.action.management.service.impl; + +import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.service.ActionConverter; + +import java.util.EnumMap; +import java.util.Map; + +/** + * This class defines the Action Converter Factory. + * Action Converter Factory is the component that is responsible for providing the {@link ActionConverter} + * based on the action type. + */ +public class ActionConverterFactory { + + private static final Map actionConverters = + new EnumMap<>(Action.ActionTypes.class); + + private ActionConverterFactory() { + } + + public static ActionConverter getActionConverter(Action.ActionTypes actionType) { + + switch (actionType) { + case PRE_UPDATE_PASSWORD: + return actionConverters.get(Action.ActionTypes.PRE_UPDATE_PASSWORD); + case PRE_ISSUE_ACCESS_TOKEN: + default: + return null; + } + } + + public static void registerActionConverter(ActionConverter actionConverter) { + + actionConverters.put(actionConverter.getSupportedActionType(), actionConverter); + } + + public static void unregisterActionConverter(ActionConverter actionConverter) { + + actionConverters.remove(actionConverter.getSupportedActionType()); + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImpl.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java similarity index 69% rename from components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImpl.java rename to components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java index 33fd7ca6a465..aaa8168b30e0 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImpl.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/ActionManagementServiceImpl.java @@ -16,20 +16,25 @@ * under the License. */ -package org.wso2.carbon.identity.action.management; +package org.wso2.carbon.identity.action.management.service.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.identity.action.management.constant.ActionMgtConstants; +import org.wso2.carbon.identity.action.management.constant.error.ErrorMessage; +import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOFacade; import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOImpl; -import org.wso2.carbon.identity.action.management.dao.impl.CacheBackedActionMgtDAO; import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.ActionDTO; import org.wso2.carbon.identity.action.management.model.Authentication; import org.wso2.carbon.identity.action.management.model.EndpointConfig; +import org.wso2.carbon.identity.action.management.service.ActionConverter; +import org.wso2.carbon.identity.action.management.service.ActionManagementService; +import org.wso2.carbon.identity.action.management.util.ActionDTOBuilder; import org.wso2.carbon.identity.action.management.util.ActionManagementAuditLogger; -import org.wso2.carbon.identity.action.management.util.ActionManagementUtil; +import org.wso2.carbon.identity.action.management.util.ActionManagementExceptionHandler; import org.wso2.carbon.identity.action.management.util.ActionValidator; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.core.util.IdentityUtil; @@ -38,6 +43,7 @@ import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.stream.Collectors; /** * Action management service. @@ -45,20 +51,10 @@ public class ActionManagementServiceImpl implements ActionManagementService { private static final Log LOG = LogFactory.getLog(ActionManagementServiceImpl.class); - private static final ActionManagementService INSTANCE = new ActionManagementServiceImpl(); - private static final CacheBackedActionMgtDAO CACHE_BACKED_DAO = - new CacheBackedActionMgtDAO(new ActionManagementDAOImpl()); + private static final ActionManagementDAOFacade DAO_FACADE = + new ActionManagementDAOFacade(new ActionManagementDAOImpl()); private static final ActionValidator ACTION_VALIDATOR = new ActionValidator(); private static final ActionManagementAuditLogger auditLogger = new ActionManagementAuditLogger(); - private static final ActionSecretProcessor ACTION_SECRET_PROCESSOR = new ActionSecretProcessor(); - - private ActionManagementServiceImpl() { - } - - public static ActionManagementService getInstance() { - - return INSTANCE; - } /** * Create a new action of the specified type in the given tenant. @@ -76,13 +72,16 @@ public Action addAction(String actionType, Action action, String tenantDomain) t LOG.debug(String.format("Adding Action for Action Type: %s.", actionType)); } String resolvedActionType = getActionTypeFromPath(actionType); + doPreAddActionValidations(action); // Check whether the maximum allowed actions per type is reached. validateMaxActionsPerType(resolvedActionType, tenantDomain); - doPreAddActionValidations(action); String generatedActionId = UUID.randomUUID().toString(); - Action createdAction = CACHE_BACKED_DAO.addAction(resolvedActionType, generatedActionId, action, - IdentityTenantUtil.getTenantId(tenantDomain)); - auditLogger.printAuditLog(ActionManagementAuditLogger.Operation.ADD, createdAction); + ActionDTO creatingActionDTO = buildActionDTO(resolvedActionType, generatedActionId, action); + + DAO_FACADE.addAction(creatingActionDTO, IdentityTenantUtil.getTenantId(tenantDomain)); + Action createdAction = getActionByActionId(actionType, generatedActionId, tenantDomain); + auditLogger.printAuditLog(ActionManagementAuditLogger.Operation.ADD, creatingActionDTO); + return createdAction; } @@ -100,8 +99,36 @@ public List getActionsByActionType(String actionType, String tenantDomai if (LOG.isDebugEnabled()) { LOG.debug(String.format("Retrieving Actions for Action Type: %s.", actionType)); } - return CACHE_BACKED_DAO.getActionsByActionType(getActionTypeFromPath(actionType), + String resolvedActionType = getActionTypeFromPath(actionType); + List actionDTOS = DAO_FACADE.getActionsByActionType(resolvedActionType, + IdentityTenantUtil.getTenantId(tenantDomain)); + + return actionDTOS.stream() + .map(actionDTO -> buildAction(resolvedActionType, actionDTO)) + .collect(Collectors.toList()); + } + + /** + * Retrieve an action by action ID. + * + * @param actionType Action type. + * @param actionId Action ID. + * @param tenantDomain Tenant domain. + * @return Action object. + * @throws ActionMgtException if an error occurred while retrieving the action. + */ + @Override + public Action getActionByActionId(String actionType, String actionId, String tenantDomain) + throws ActionMgtException { + + if (LOG.isDebugEnabled()) { + LOG.debug(String.format("Retrieving Action of Action ID: %s", actionId)); + } + String resolvedActionType = getActionTypeFromPath(actionType); + ActionDTO actionDTO = DAO_FACADE.getActionByActionId(resolvedActionType, actionId, IdentityTenantUtil.getTenantId(tenantDomain)); + + return buildAction(resolvedActionType, actionDTO); } /** @@ -125,12 +152,13 @@ public Action updateAction(String actionType, String actionId, Action action, St LOG.debug(String.format("Updating Action for Action Type: %s and Action ID: %s.", actionType, actionId)); } String resolvedActionType = getActionTypeFromPath(actionType); - Action existingAction = checkIfActionExists(resolvedActionType, actionId, tenantDomain); doPreUpdateActionValidations(action); - Action updatedAction = CACHE_BACKED_DAO.updateAction(resolvedActionType, actionId, action, existingAction, - IdentityTenantUtil.getTenantId(tenantDomain)); - auditLogger.printAuditLog(ActionManagementAuditLogger.Operation.UPDATE, actionId, action); - return updatedAction; + ActionDTO existingActionDTO = checkIfActionExists(resolvedActionType, actionId, tenantDomain); + ActionDTO updatingActionDTO = buildActionDTO(resolvedActionType, actionId, action); + + DAO_FACADE.updateAction(updatingActionDTO, existingActionDTO, IdentityTenantUtil.getTenantId(tenantDomain)); + auditLogger.printAuditLog(ActionManagementAuditLogger.Operation.UPDATE, updatingActionDTO); + return getActionByActionId(actionType, actionId, tenantDomain); } /** @@ -147,11 +175,12 @@ public void deleteAction(String actionType, String actionId, String tenantDomain if (LOG.isDebugEnabled()) { LOG.debug(String.format("Deleting Action for Action Type: %s and Action ID: %s", actionType, actionId)); } - String resolvedActionType = getActionTypeFromPath(actionType); - Action action = checkIfActionExists(resolvedActionType, actionId, tenantDomain); - CACHE_BACKED_DAO.deleteAction(resolvedActionType, actionId, action, + ActionDTO existingActionDTO = DAO_FACADE.getActionByActionId(getActionTypeFromPath(actionType), actionId, IdentityTenantUtil.getTenantId(tenantDomain)); - auditLogger.printAuditLog(ActionManagementAuditLogger.Operation.DELETE, actionType, actionId); + if (existingActionDTO != null) { + DAO_FACADE.deleteAction(existingActionDTO, IdentityTenantUtil.getTenantId(tenantDomain)); + auditLogger.printAuditLog(ActionManagementAuditLogger.Operation.DELETE, actionType, actionId); + } } /** @@ -161,7 +190,7 @@ public void deleteAction(String actionType, String actionId, String tenantDomain * @param actionId Action ID. * @param tenantDomain Tenant domain. * @return Activated action. - * @throws ActionMgtException if an error occurred while activating the action. + * @throws ActionMgtException If an error occurred while activating the action. */ @Override public Action activateAction(String actionType, String actionId, String tenantDomain) throws ActionMgtException { @@ -171,10 +200,10 @@ public Action activateAction(String actionType, String actionId, String tenantDo } String resolvedActionType = getActionTypeFromPath(actionType); checkIfActionExists(resolvedActionType, actionId, tenantDomain); - Action activatedAction = CACHE_BACKED_DAO.activateAction(resolvedActionType, actionId, + ActionDTO activatedActionDTO = DAO_FACADE.activateAction(resolvedActionType, actionId, IdentityTenantUtil.getTenantId(tenantDomain)); auditLogger.printAuditLog(ActionManagementAuditLogger.Operation.ACTIVATE, actionType, actionId); - return activatedAction; + return buildAction(resolvedActionType, activatedActionDTO); } /** @@ -184,7 +213,7 @@ public Action activateAction(String actionType, String actionId, String tenantDo * @param actionId Action ID. * @param tenantDomain Tenant domain. * @return deactivated action. - * @throws ActionMgtException if an error occurred while deactivating the action. + * @throws ActionMgtException If an error occurred while deactivating the action. */ @Override public Action deactivateAction(String actionType, String actionId, String tenantDomain) throws ActionMgtException { @@ -195,10 +224,10 @@ public Action deactivateAction(String actionType, String actionId, String tenant } String resolvedActionType = getActionTypeFromPath(actionType); checkIfActionExists(resolvedActionType, actionId, tenantDomain); - Action deactivatedAction = CACHE_BACKED_DAO.deactivateAction(resolvedActionType, actionId, + ActionDTO deactivatedActionDTO = DAO_FACADE.deactivateAction(resolvedActionType, actionId, IdentityTenantUtil.getTenantId(tenantDomain)); auditLogger.printAuditLog(ActionManagementAuditLogger.Operation.DEACTIVATE, actionType, actionId); - return deactivatedAction; + return buildAction(resolvedActionType, deactivatedActionDTO); } /** @@ -214,27 +243,7 @@ public Map getActionsCountPerType(String tenantDomain) throws A if (LOG.isDebugEnabled()) { LOG.debug("Retrieving Actions count per Type."); } - return CACHE_BACKED_DAO.getActionsCountPerType(IdentityTenantUtil.getTenantId(tenantDomain)); - } - - /** - * Retrieve an action by action ID. - * - * @param actionType Action type. - * @param actionId Action ID. - * @param tenantDomain Tenant domain. - * @return Action object. - * @throws ActionMgtException if an error occurred while retrieving the action. - */ - @Override - public Action getActionByActionId(String actionType, String actionId, String tenantDomain) - throws ActionMgtException { - - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Retrieving Action of Action ID: %s", actionId)); - } - return CACHE_BACKED_DAO.getActionByActionId(getActionTypeFromPath(actionType), actionId, - IdentityTenantUtil.getTenantId(tenantDomain)); + return DAO_FACADE.getActionsCountPerType(IdentityTenantUtil.getTenantId(tenantDomain)); } /** @@ -251,16 +260,13 @@ public Action getActionByActionId(String actionType, String actionId, String ten public Action updateActionEndpointAuthentication(String actionType, String actionId, Authentication authentication, String tenantDomain) throws ActionMgtException { - String resolvedActionType = getActionTypeFromPath(actionType); - Action existingAction = checkIfActionExists(resolvedActionType, actionId, tenantDomain); - doEndpointAuthenticationValidation(authentication); - if (existingAction.getEndpoint().getAuthentication().getType().equals(authentication.getType())) { - // Only need to update the properties since the authentication type is same. - return updateEndpointAuthenticationProperties(resolvedActionType, actionId, authentication, tenantDomain); - } else { - // Need to update the authentication type and properties. - return updateEndpoint(resolvedActionType, actionId, existingAction, authentication, tenantDomain); - } + Action updatingAction = new Action.ActionRequestBuilder() + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .authentication(authentication) + .build()) + .build(); + + return updateAction(actionType, actionId, updatingAction, tenantDomain); } /** @@ -276,8 +282,8 @@ private String getActionTypeFromPath(String actionType) throws ActionMgtClientEx .filter(type -> type.getPathParam().equals(actionType)) .map(Action.ActionTypes::getActionType) .findFirst() - .orElseThrow(() -> ActionManagementUtil.handleClientException( - ActionMgtConstants.ErrorMessages.ERROR_INVALID_ACTION_TYPE)); + .orElseThrow(() -> + ActionManagementExceptionHandler.handleClientException(ErrorMessage.ERROR_INVALID_ACTION_TYPE)); } /** @@ -289,11 +295,15 @@ private String getActionTypeFromPath(String actionType) throws ActionMgtClientEx */ private void validateMaxActionsPerType(String actionType, String tenantDomain) throws ActionMgtException { + // In-flow actions are not limited by the maximum actions per action type; eg: AUTHENTICATION action type. + if (Action.ActionTypes.Category.IN_FLOW.equals(Action.ActionTypes.valueOf(actionType).getCategory())) { + return; + } Map actionsCountPerType = getActionsCountPerType(tenantDomain); if (actionsCountPerType.containsKey(actionType) && actionsCountPerType.get(actionType) >= IdentityUtil.getMaximumActionsPerActionType()) { - throw ActionManagementUtil.handleClientException( - ActionMgtConstants.ErrorMessages.ERROR_MAXIMUM_ACTIONS_PER_ACTION_TYPE_REACHED); + throw ActionManagementExceptionHandler.handleClientException( + ErrorMessage.ERROR_MAXIMUM_ACTIONS_PER_ACTION_TYPE_REACHED); } } @@ -303,75 +313,27 @@ private void validateMaxActionsPerType(String actionType, String tenantDomain) t * @param actionType Action Type. * @param actionId Action ID. * @param tenantDomain Tenant Domain. + * @return ActionDTO if the action exists. * @throws ActionMgtException If the action does not exist. */ - private Action checkIfActionExists(String actionType, String actionId, String tenantDomain) + private ActionDTO checkIfActionExists(String actionType, String actionId, String tenantDomain) throws ActionMgtException { - Action action = CACHE_BACKED_DAO.getActionByActionId(actionType, actionId, + ActionDTO actionDTO = DAO_FACADE.getActionByActionId(actionType, actionId, IdentityTenantUtil.getTenantId(tenantDomain)); - if (action == null || !actionType.equals(action.getType().name())) { - throw ActionManagementUtil.handleClientException( - ActionMgtConstants.ErrorMessages.ERROR_NO_ACTION_CONFIGURED_ON_GIVEN_ACTION_TYPE_AND_ID); + if (actionDTO == null || !actionType.equals(actionDTO.getType().name())) { + throw ActionManagementExceptionHandler.handleClientException( + ErrorMessage.ERROR_NO_ACTION_CONFIGURED_ON_GIVEN_ACTION_TYPE_AND_ID); } - return action; - } - - /** - * Update the authentication type and properties of the action endpoint. - * - * @param actionType Action Type. - * @param actionId Action Id. - * @param existingAction Existing Action Information. - * @param authentication Authentication Information to be updated. - * @param tenantDomain Tenant Domain. - * @return Action response after update. - * @throws ActionMgtException If an error occurs while updating action endpoint authentication. - */ - private Action updateEndpoint(String actionType, String actionId, Action existingAction, - Authentication authentication, String tenantDomain) - throws ActionMgtException { - - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Updating endpoint authentication of Action Type: %s " + - "and Action ID: %s to Authentication Type: %s", actionType, actionId, - authentication.getType().name())); - } - EndpointConfig endpoint = new EndpointConfig.EndpointConfigBuilder() - .uri(existingAction.getEndpoint().getUri()) - .authentication(authentication).build(); - return CACHE_BACKED_DAO.updateActionEndpoint(actionType, actionId, endpoint, - existingAction.getEndpoint().getAuthentication(), IdentityTenantUtil.getTenantId(tenantDomain)); - } - - /** - * Update the authentication properties of the action endpoint. - * - * @param actionType Action Type. - * @param actionId Action Id. - * @param authentication Authentication Information to be updated. - * @param tenantDomain Tenant domain. - * @return Action response after update. - * @throws ActionMgtException If an error occurs while updating action endpoint authentication properties. - */ - private Action updateEndpointAuthenticationProperties(String actionType, String actionId, - Authentication authentication, String tenantDomain) - throws ActionMgtException { - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Updating endpoint authentication properties of Action Type: %s " + - "Action ID: %s and Authentication Type: %s", actionType, actionId, - authentication.getType().name())); - } - return CACHE_BACKED_DAO.updateActionEndpointAuthProperties(actionType, actionId, authentication, - IdentityTenantUtil.getTenantId(tenantDomain)); + return actionDTO; } /** * Perform pre validations on action model when creating an action. * - * @param action Action create model. - * @throws ActionMgtException if action model is invalid. + * @param action Action creation model. + * @throws ActionMgtClientException if action model is invalid. */ private void doPreAddActionValidations(Action action) throws ActionMgtClientException { @@ -384,8 +346,7 @@ private void doPreAddActionValidations(Action action) throws ActionMgtClientExce /** * Perform pre validations on action model when updating an existing action. - * This is specifically used during HTTP PATCH operation and - * only validate non-null and non-empty fields. + * This is specifically used during HTTP PATCH operation and only validate non-null and non-empty fields. * * @param action Action update model. * @throws ActionMgtClientException if action model is invalid. @@ -432,6 +393,50 @@ private void doEndpointAuthenticationValidation(Authentication authentication) t ACTION_VALIDATOR.validateForBlank(ActionMgtConstants.API_KEY_VALUE_FIELD, authentication.getProperty(Authentication.Property.VALUE).getValue()); break; + case NONE: + default: + break; + } + } + + private ActionDTO buildActionDTO(String actionType, String actionId, Action action) { + + ActionConverter actionConverter = + ActionConverterFactory.getActionConverter(Action.ActionTypes.valueOf(actionType)); + if (actionConverter != null) { + ActionDTO actionDTO = actionConverter.buildActionDTO(action); + + return new ActionDTOBuilder(actionDTO) + .id(actionId) + .type(Action.ActionTypes.valueOf(actionType)) + .build(); + } + + return new ActionDTOBuilder(action) + .id(actionId) + .type(Action.ActionTypes.valueOf(actionType)) + .build(); + } + + private Action buildAction(String actionType, ActionDTO actionDTO) { + + if (actionDTO == null) { + return null; } + + ActionConverter actionConverter = + ActionConverterFactory.getActionConverter(Action.ActionTypes.valueOf(actionType)); + if (actionConverter != null) { + return actionConverter.buildAction(actionDTO); + } + + return new Action.ActionResponseBuilder() + .id(actionDTO.getId()) + .type(actionDTO.getType()) + .name(actionDTO.getName()) + .description(actionDTO.getDescription()) + .status(actionDTO.getStatus()) + .endpoint(actionDTO.getEndpoint()) + .build(); } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/CacheBackedActionMgtDAO.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/CacheBackedActionManagementService.java similarity index 63% rename from components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/CacheBackedActionMgtDAO.java rename to components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/CacheBackedActionManagementService.java index 1ef2ff2d3ca3..616678aeb8e7 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/dao/impl/CacheBackedActionMgtDAO.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/service/impl/CacheBackedActionManagementService.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.identity.action.management.dao.impl; +package org.wso2.carbon.identity.action.management.service.impl; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; @@ -24,43 +24,47 @@ import org.wso2.carbon.identity.action.management.cache.ActionCacheByType; import org.wso2.carbon.identity.action.management.cache.ActionCacheEntry; import org.wso2.carbon.identity.action.management.cache.ActionTypeCacheKey; -import org.wso2.carbon.identity.action.management.dao.ActionManagementDAO; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; import org.wso2.carbon.identity.action.management.model.Action; import org.wso2.carbon.identity.action.management.model.Authentication; -import org.wso2.carbon.identity.action.management.model.EndpointConfig; +import org.wso2.carbon.identity.action.management.service.ActionManagementService; import java.util.List; import java.util.Map; /** - * This class implements the {@link ActionManagementDAO} interface. + * CacheBackedActionManagementService act as the caching layer for the Action Management Service. */ -public class CacheBackedActionMgtDAO implements ActionManagementDAO { +public class CacheBackedActionManagementService implements ActionManagementService { - private static final Log LOG = LogFactory.getLog(CacheBackedActionMgtDAO.class); + private static final CacheBackedActionManagementService INSTANCE = new CacheBackedActionManagementService(); + private static final Log LOG = LogFactory.getLog(CacheBackedActionManagementService.class); + private static final ActionManagementServiceImpl ACTION_MGT_SERVICE = new ActionManagementServiceImpl(); private final ActionCacheByType actionCacheByType; - private final ActionManagementDAO actionManagementDAO; - public CacheBackedActionMgtDAO(ActionManagementDAO actionManagementDAO) { + private CacheBackedActionManagementService() { - this.actionManagementDAO = actionManagementDAO; actionCacheByType = ActionCacheByType.getInstance(); } + public static CacheBackedActionManagementService getInstance() { + + return INSTANCE; + } + @Override - public Action addAction(String actionType, String actionId, Action action, Integer tenantId) - throws ActionMgtException { + public Action addAction(String actionType, Action action, String tenantDomain) throws ActionMgtException { - actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantId); - return actionManagementDAO.addAction(actionType, actionId, action, tenantId); + Action createdAction = ACTION_MGT_SERVICE.addAction(actionType, action, tenantDomain); + actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantDomain); + return createdAction; } @Override - public List getActionsByActionType(String actionType, Integer tenantId) throws ActionMgtException { + public List getActionsByActionType(String actionType, String tenantDomain) throws ActionMgtException { ActionTypeCacheKey cacheKey = new ActionTypeCacheKey(actionType); - ActionCacheEntry entry = actionCacheByType.getValueFromCache(cacheKey, tenantId); + ActionCacheEntry entry = actionCacheByType.getValueFromCache(cacheKey, tenantDomain); if (entry != null) { if (LOG.isDebugEnabled()) { @@ -68,72 +72,37 @@ public List getActionsByActionType(String actionType, Integer tenantId) } return entry.getActions(); } - if (LOG.isDebugEnabled()) { LOG.debug("Cache entry not found for Action Type " + actionType + ". Fetching entry from DB."); } - List actions = actionManagementDAO.getActionsByActionType(actionType, tenantId); + List actions = ACTION_MGT_SERVICE.getActionsByActionType(actionType, tenantDomain); if (actions != null && !actions.isEmpty()) { if (LOG.isDebugEnabled()) { LOG.debug("Entry fetched from DB for Action Type " + actionType + ". Updating cache."); } - actionCacheByType.addToCache(cacheKey, new ActionCacheEntry(actions), tenantId); + actionCacheByType.addToCache(cacheKey, new ActionCacheEntry(actions), tenantDomain); } else { if (LOG.isDebugEnabled()) { LOG.debug("Entry for Action Type " + actionType + " not found in cache or DB."); } } - return actions; - } - - @Override - public Action updateAction(String actionType, String actionId, Action updatingAction, Action existingAction, - Integer tenantId) throws ActionMgtException { - actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantId); - return actionManagementDAO.updateAction(actionType, actionId, updatingAction, existingAction, tenantId); + return actions; } @Override - public void deleteAction(String actionType, String actionId, Action action, Integer tenantId) + public Action getActionByActionId(String actionType, String actionId, String tenantDomain) throws ActionMgtException { - actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantId); - actionManagementDAO.deleteAction(actionType, actionId, action, tenantId); - } - - @Override - public Action activateAction(String actionType, String actionId, Integer tenantId) throws ActionMgtException { - - actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantId); - return actionManagementDAO.activateAction(actionType, actionId, tenantId); - } - - @Override - public Action deactivateAction(String actionType, String actionId, Integer tenantId) throws ActionMgtException { - - actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantId); - return actionManagementDAO.deactivateAction(actionType, actionId, tenantId); - } - - @Override - public Map getActionsCountPerType(Integer tenantId) throws ActionMgtException { - - return actionManagementDAO.getActionsCountPerType(tenantId); - } - - @Override - public Action getActionByActionId(String actionType, String actionId, Integer tenantId) throws ActionMgtException { - ActionTypeCacheKey cacheKey = new ActionTypeCacheKey(actionType); - ActionCacheEntry entry = actionCacheByType.getValueFromCache(cacheKey, tenantId); + ActionCacheEntry entry = actionCacheByType.getValueFromCache(cacheKey, tenantDomain); /* If the entry for the given action type is not null, get the action list from cache and iterate to get the action by matching action id. */ if (entry != null) { - for (Action action: entry.getActions()) { + for (Action action : entry.getActions()) { if (StringUtils.equals(action.getId(), actionId)) { LOG.debug("Action is found from the cache with action Id " + actionId); return action; @@ -145,9 +114,9 @@ public Action getActionByActionId(String actionType, String actionId, Integer te LOG.debug("Action is not found from the cache with action Id " + actionId + ". Fetching entry from DB."); } - Action action = actionManagementDAO.getActionByActionId(actionType, actionId, tenantId); + Action action = ACTION_MGT_SERVICE.getActionByActionId(actionType, actionId, tenantDomain); if (action != null) { - updateCache(action, entry, cacheKey, tenantId); + updateCache(action, entry, cacheKey, tenantDomain); } else { if (LOG.isDebugEnabled()) { LOG.debug("Action with action Id " + actionId + " is not found in cache or DB."); @@ -158,23 +127,54 @@ public Action getActionByActionId(String actionType, String actionId, Integer te } @Override - public Action updateActionEndpointAuthProperties(String actionType, String actionId, Authentication authentication, - int tenantId) throws ActionMgtException { + public Action updateAction(String actionType, String actionId, Action action, String tenantDomain) + throws ActionMgtException { - return actionManagementDAO.updateActionEndpointAuthProperties(actionType, actionId, authentication, tenantId); + Action updatedAction = ACTION_MGT_SERVICE.updateAction(actionType, actionId, action, tenantDomain); + actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantDomain); + return updatedAction; } @Override - public Action updateActionEndpoint(String actionType, String actionId, EndpointConfig endpoint, - Authentication currentAuthentication, int tenantId) - throws ActionMgtException { + public void deleteAction(String actionType, String actionId, String tenantDomain) throws ActionMgtException { + + actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantDomain); + ACTION_MGT_SERVICE.deleteAction(actionType, actionId, tenantDomain); + } + + @Override + public Action activateAction(String actionType, String actionId, String tenantDomain) throws ActionMgtException { + + Action activatedAction = ACTION_MGT_SERVICE.activateAction(actionType, actionId, tenantDomain); + actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantDomain); + return activatedAction; + } + + @Override + public Action deactivateAction(String actionType, String actionId, String tenantDomain) throws ActionMgtException { + + Action deactivatedAction = ACTION_MGT_SERVICE.deactivateAction(actionType, actionId, tenantDomain); + actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantDomain); + return deactivatedAction; + } + + @Override + public Map getActionsCountPerType(String tenantDomain) throws ActionMgtException { + + return ACTION_MGT_SERVICE.getActionsCountPerType(tenantDomain); + } + + @Override + public Action updateActionEndpointAuthentication(String actionType, String actionId, Authentication authentication, + String tenantDomain) throws ActionMgtException { - actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantId); - return actionManagementDAO.updateActionEndpoint(actionType, actionId, endpoint, currentAuthentication, - tenantId); + Action updatedAction = ACTION_MGT_SERVICE.updateActionEndpointAuthentication(actionType, actionId, + authentication, tenantDomain); + actionCacheByType.clearCacheEntry(new ActionTypeCacheKey(actionType), tenantDomain); + return updatedAction; } - private void updateCache(Action action, ActionCacheEntry entry, ActionTypeCacheKey cacheKey, int tenantId) { + private void updateCache(Action action, ActionCacheEntry entry, ActionTypeCacheKey cacheKey, String tenantDomain) { if (LOG.isDebugEnabled()) { LOG.debug("Entry fetched from DB for Action Id " + action.getId() + ". Updating cache."); @@ -184,8 +184,8 @@ private void updateCache(Action action, ActionCacheEntry entry, ActionTypeCacheK if (entry != null) { List actionsFromCache = entry.getActions(); actionsFromCache.add(action); - actionCacheByType.clearCacheEntry(cacheKey, tenantId); - actionCacheByType.addToCache(cacheKey, new ActionCacheEntry(actionsFromCache), tenantId); + actionCacheByType.clearCacheEntry(cacheKey, tenantDomain); + actionCacheByType.addToCache(cacheKey, new ActionCacheEntry(actionsFromCache), tenantDomain); } } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionDTOBuilder.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionDTOBuilder.java new file mode 100644 index 000000000000..9e852ee1aee2 --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionDTOBuilder.java @@ -0,0 +1,208 @@ +/* + * 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.action.management.util; + +import org.wso2.carbon.identity.action.management.constant.ActionMgtConstants; +import org.wso2.carbon.identity.action.management.exception.ActionMgtException; +import org.wso2.carbon.identity.action.management.exception.ActionMgtServerException; +import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.ActionDTO; +import org.wso2.carbon.identity.action.management.model.Authentication; +import org.wso2.carbon.identity.action.management.model.EndpointConfig; + +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * Internal Builder class for ActionDTO. + */ +public class ActionDTOBuilder { + + private String id; + private Action.ActionTypes type; + private String name; + private String description; + private Action.Status status; + private EndpointConfig endpoint; + private Map properties; + + public ActionDTOBuilder() { + + } + + public ActionDTOBuilder(ActionDTO actionDTO) { + + this.id = actionDTO.getId(); + this.type = actionDTO.getType(); + this.name = actionDTO.getName(); + this.description = actionDTO.getDescription(); + this.status = actionDTO.getStatus(); + this.endpoint = actionDTO.getEndpoint(); + this.properties = actionDTO.getProperties(); + } + + public ActionDTOBuilder(Action action) { + + this.id = action.getId(); + this.type = action.getType(); + this.name = action.getName(); + this.description = action.getDescription(); + this.status = action.getStatus(); + this.endpoint = action.getEndpoint(); + } + + public ActionDTOBuilder id(String id) { + + this.id = id; + return this; + } + + public String getId() { + + return this.id; + } + + public ActionDTOBuilder type(Action.ActionTypes type) { + + this.type = type; + return this; + } + + public Action.ActionTypes getType() { + + return this.type; + } + + public ActionDTOBuilder name(String name) { + + this.name = name; + return this; + } + + public String getName() { + + return this.name; + } + + public ActionDTOBuilder description(String description) { + + this.description = description; + return this; + } + + public String getDescription() { + + return this.description; + } + + public ActionDTOBuilder status(Action.Status status) { + + this.status = status; + return this; + } + + public Action.Status getStatus() { + + return this.status; + } + + public ActionDTOBuilder endpoint(EndpointConfig endpoint) { + + this.endpoint = endpoint; + return this; + } + + public EndpointConfig getEndpoint() { + + return this.endpoint; + } + + public ActionDTOBuilder setEndpointAndProperties(Map properties) throws + ActionMgtException { + + Authentication authentication; + Authentication.Type authnType = + Authentication.Type.valueOf(properties.remove(ActionMgtConstants.AUTHN_TYPE_PROPERTY)); + switch (authnType) { + case BASIC: + authentication = new Authentication.BasicAuthBuilder( + properties.remove(Authentication.Property.USERNAME.getName()), + properties.remove(Authentication.Property.PASSWORD.getName())).build(); + break; + case BEARER: + authentication = new Authentication.BearerAuthBuilder( + properties.remove(Authentication.Property.ACCESS_TOKEN.getName())).build(); + break; + case API_KEY: + authentication = new Authentication.APIKeyAuthBuilder( + properties.remove(Authentication.Property.HEADER.getName()), + properties.remove(Authentication.Property.VALUE.getName())).build(); + break; + case NONE: + authentication = new Authentication.NoneAuthBuilder().build(); + break; + default: + throw new ActionMgtServerException("Authentication type is not defined for the Action Endpoint."); + } + + this.endpoint = new EndpointConfig.EndpointConfigBuilder() + .uri(properties.remove(ActionMgtConstants.URI_PROPERTY)) + .authentication(authentication) + .build(); + // Add remaining properties as action properties. + this.properties = properties.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + return this; + } + + public ActionDTOBuilder properties(Map properties) { + + this.properties = properties; + return this; + } + + public Map getProperties() { + + return this.properties; + } + + public ActionDTOBuilder property(String propertyName, Object propertyValue) { + + if (this.properties == null) { + this.properties = new HashMap<>(); + } + this.properties.put(propertyName, propertyValue); + return this; + } + + public ActionDTO build() { + + Action action = new Action.ActionResponseBuilder() + .id(this.id) + .type(this.type) + .name(this.name) + .description(this.description) + .status(this.status) + .endpoint(this.endpoint) + .build(); + + return new ActionDTO.Builder(action).properties(this.properties).build(); + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementAuditLogger.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementAuditLogger.java index e28920ae8f2e..7dfd313fe95f 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementAuditLogger.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementAuditLogger.java @@ -22,7 +22,7 @@ import org.json.JSONObject; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.ActionDTO; import org.wso2.carbon.identity.action.management.model.Authentication; import org.wso2.carbon.identity.action.management.model.EndpointConfig; import org.wso2.carbon.identity.central.log.mgt.utils.LoggerUtils; @@ -31,6 +31,8 @@ import org.wso2.carbon.utils.AuditLog; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; +import java.util.Map; + import static org.wso2.carbon.identity.central.log.mgt.utils.LoggerUtils.jsonObjectToMap; import static org.wso2.carbon.identity.central.log.mgt.utils.LoggerUtils.triggerAuditLogEvent; @@ -43,30 +45,14 @@ public class ActionManagementAuditLogger { * Print action audit log related to the operation. * * @param operation Operation associated with the state change. - * @param action Action object to be logged. - */ - public void printAuditLog(Operation operation, Action action) { - - if (!LoggerUtils.isEnableV2AuditLogs()) { - return; - } - JSONObject data = createAuditLogEntry(action); - buildAuditLog(operation, data); - } - - /** - * Print action audit log related to the operation by action ID. - * - * @param operation Operation associated with the state change. - * @param actionId ID of the action to be logged. - * @param action Action object to be logged. + * @param actionDTO Action object to be logged. */ - public void printAuditLog(Operation operation, String actionId, Action action) { + public void printAuditLog(Operation operation, ActionDTO actionDTO) { if (!LoggerUtils.isEnableV2AuditLogs()) { return; } - JSONObject data = createAuditLogEntry(actionId, action); + JSONObject data = createAuditLogEntry(actionDTO); buildAuditLog(operation, data); } @@ -103,44 +89,28 @@ private void buildAuditLog(Operation operation, JSONObject data) { triggerAuditLogEvent(auditLogBuilder); } - /** - * Create audit log data with action. - * This method expects all the action fields to be non-null/non-empty. - * - * @param action Action to be logged. - * @return audit log data. - */ - private JSONObject createAuditLogEntry(Action action) { - - JSONObject data = new JSONObject(); - data.put(LogConstants.ACTION_TYPE_FIELD, action.getType()); - data.put(LogConstants.ACTION_ID_FIELD, action.getId()); - data.put(LogConstants.ACTION_NAME_FIELD, action.getName()); - data.put(LogConstants.ACTION_DESCRIPTION_FIELD, action.getDescription()); - data.put(LogConstants.ACTION_STATUS_FIELD, action.getStatus()); - data.put(LogConstants.ENDPOINT_CONFIG_FIELD, getAllEndpointData(action.getEndpoint())); - return data; - } - /** * Create audit log data with action and ID. * This method expects null/empty action fields. * - * @param actionId ID of the action to be logged. - * @param action Action to be logged. + * @param actionDTO Action to be logged. * @return audit log data. */ - private JSONObject createAuditLogEntry(String actionId, Action action) { + private JSONObject createAuditLogEntry(ActionDTO actionDTO) { JSONObject data = new JSONObject(); - data.put(LogConstants.ACTION_TYPE_FIELD, action.getType() != null ? action.getType() : JSONObject.NULL); - data.put(LogConstants.ACTION_ID_FIELD, actionId); - data.put(LogConstants.ACTION_NAME_FIELD, action.getName() != null ? action.getName() : JSONObject.NULL); + data.put(LogConstants.ACTION_TYPE_FIELD, actionDTO.getType() != null ? actionDTO.getType() : JSONObject.NULL); + data.put(LogConstants.ACTION_ID_FIELD, actionDTO.getId() != null ? actionDTO.getId() : JSONObject.NULL); + data.put(LogConstants.ACTION_NAME_FIELD, actionDTO.getName() != null ? actionDTO.getName() : JSONObject.NULL); data.put(LogConstants.ACTION_DESCRIPTION_FIELD, - action.getDescription() != null ? action.getDescription() : JSONObject.NULL); - data.put(LogConstants.ACTION_STATUS_FIELD, action.getStatus() != null ? action.getStatus() : JSONObject.NULL); - if (action.getEndpoint() != null) { - data.put(LogConstants.ENDPOINT_CONFIG_FIELD, getEndpointData(action.getEndpoint())); + actionDTO.getDescription() != null ? actionDTO.getDescription() : JSONObject.NULL); + data.put(LogConstants.ACTION_STATUS_FIELD, actionDTO.getStatus() != null ? actionDTO.getStatus() + : JSONObject.NULL); + if (actionDTO.getEndpoint() != null) { + data.put(LogConstants.ENDPOINT_CONFIG_FIELD, getEndpointData(actionDTO.getEndpoint())); + } + if (actionDTO.getProperties() != null && !actionDTO.getProperties().isEmpty()) { + data.put(LogConstants.ACTION_PROPERTIES, getPropertiesData(actionDTO.getProperties())); } return data; } @@ -161,36 +131,17 @@ private JSONObject createAuditLogEntry(String actionType, String actionId) { } /** - * Retrieve complete endpoint configuration data to be logged. + * Retrieve properties data to be logged. + * All the properties will be masked. * - * @param endpointConfig Endpoint data to be logged. - * @return endpoint config data. + * @param properties Properties to be logged. + * @return properties data. */ - private JSONObject getAllEndpointData(EndpointConfig endpointConfig) { + private JSONObject getPropertiesData(Map properties) { - JSONObject endpointData = new JSONObject(); - endpointData.put(LogConstants.ENDPOINT_URI_FIELD, endpointConfig.getUri()); - Authentication authentication = endpointConfig.getAuthentication(); - endpointData.put(LogConstants.AUTHENTICATION_SCHEME_FIELD, authentication.getType().getName()); - switch (authentication.getType()) { - case BASIC: - endpointData.put(LogConstants.USERNAME_FIELD, LoggerUtils.getMaskedContent(authentication. - getProperty(Authentication.Property.USERNAME).getValue())); - endpointData.put(LogConstants.PASSWORD_FIELD, LoggerUtils.getMaskedContent(authentication. - getProperty(Authentication.Property.PASSWORD).getValue())); - break; - case BEARER: - endpointData.put(LogConstants.ACCESS_TOKEN_FIELD, LoggerUtils.getMaskedContent(authentication. - getProperty(Authentication.Property.ACCESS_TOKEN).getValue())); - break; - case API_KEY: - endpointData.put(LogConstants.API_KEY_HEADER_FIELD, LoggerUtils.getMaskedContent(authentication. - getProperty(Authentication.Property.HEADER).getValue())); - endpointData.put(LogConstants.API_KEY_VALUE_FIELD, LoggerUtils.getMaskedContent(authentication. - getProperty(Authentication.Property.VALUE).getValue())); - break; - } - return endpointData; + JSONObject propertiesData = new JSONObject(); + properties.forEach((key, value) -> propertiesData.put(key, LoggerUtils.getMaskedContent(value.toString()))); + return propertiesData; } /** @@ -210,26 +161,20 @@ private JSONObject getEndpointData(EndpointConfig endpointConfig) { endpointData.put(LogConstants.AUTHENTICATION_SCHEME_FIELD, authentication.getType()); switch (authentication.getType()) { case BASIC: - endpointData.put(LogConstants.USERNAME_FIELD, LoggerUtils.getMaskedContent( - authentication.getProperty(Authentication.Property.USERNAME) != null - ? authentication.getProperty(Authentication.Property.USERNAME).getValue() : "")); - endpointData.put(LogConstants.PASSWORD_FIELD, LoggerUtils.getMaskedContent( - authentication.getProperty(Authentication.Property.PASSWORD) != null - ? authentication.getProperty(Authentication.Property.PASSWORD).getValue() : "")); + endpointData.put(LogConstants.USERNAME_FIELD, LoggerUtils.getMaskedContent(authentication. + getProperty(Authentication.Property.USERNAME).getValue())); + endpointData.put(LogConstants.PASSWORD_FIELD, LoggerUtils.getMaskedContent(authentication. + getProperty(Authentication.Property.PASSWORD).getValue())); break; case BEARER: - endpointData.put(LogConstants.ACCESS_TOKEN_FIELD, LoggerUtils.getMaskedContent( - authentication.getProperty(Authentication.Property.ACCESS_TOKEN) != null - ? authentication.getProperty(Authentication.Property.ACCESS_TOKEN). - getValue() : "")); + endpointData.put(LogConstants.ACCESS_TOKEN_FIELD, LoggerUtils.getMaskedContent(authentication. + getProperty(Authentication.Property.ACCESS_TOKEN).getValue())); break; case API_KEY: - endpointData.put(LogConstants.API_KEY_HEADER_FIELD, LoggerUtils.getMaskedContent( - authentication.getProperty(Authentication.Property.HEADER) != null - ? authentication.getProperty(Authentication.Property.HEADER).getValue() : "")); - endpointData.put(LogConstants.API_KEY_VALUE_FIELD, LoggerUtils.getMaskedContent( - authentication.getProperty(Authentication.Property.VALUE) != null - ? authentication.getProperty(Authentication.Property.VALUE).getValue() : "")); + endpointData.put(LogConstants.API_KEY_HEADER_FIELD, LoggerUtils.getMaskedContent(authentication. + getProperty(Authentication.Property.HEADER).getValue())); + endpointData.put(LogConstants.API_KEY_VALUE_FIELD, LoggerUtils.getMaskedContent(authentication. + getProperty(Authentication.Property.VALUE).getValue())); break; } } @@ -310,6 +255,7 @@ private static class LogConstants { public static final String ACTION_DESCRIPTION_FIELD = "ActionDescription"; public static final String ACTION_STATUS_FIELD = "ActionStatus"; public static final String ENDPOINT_CONFIG_FIELD = "EndpointConfiguration"; + public static final String ACTION_PROPERTIES = "Properties"; public static final String ENDPOINT_URI_FIELD = "EndpointUri"; public static final String AUTHENTICATION_SCHEME_FIELD = "AuthenticationScheme"; public static final String USERNAME_FIELD = "Username"; diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementUtil.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementExceptionHandler.java similarity index 75% rename from components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementUtil.java rename to components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementExceptionHandler.java index 2ba8cf79da7e..87ece6d5aa6b 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementUtil.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionManagementExceptionHandler.java @@ -19,15 +19,17 @@ package org.wso2.carbon.identity.action.management.util; import org.apache.commons.lang.ArrayUtils; -import org.wso2.carbon.identity.action.management.constant.ActionMgtConstants; +import org.wso2.carbon.identity.action.management.constant.error.ErrorMessage; import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; -import org.wso2.carbon.identity.action.management.exception.ActionMgtRuntimeException; import org.wso2.carbon.identity.action.management.exception.ActionMgtServerException; /** * Utility class for Action Management. */ -public class ActionManagementUtil { +public class ActionManagementExceptionHandler { + + private ActionManagementExceptionHandler() { + } /** * Handle Action Management client exceptions. @@ -36,8 +38,7 @@ public class ActionManagementUtil { * @param data Data. * @return ActionMgtClientException. */ - public static ActionMgtClientException handleClientException( - ActionMgtConstants.ErrorMessages error, String... data) { + public static ActionMgtClientException handleClientException(ErrorMessage error, String... data) { String description = error.getDescription(); if (ArrayUtils.isNotEmpty(data)) { @@ -55,8 +56,7 @@ public static ActionMgtClientException handleClientException( * @param data Data. * @return ActionMgtServerException. */ - public static ActionMgtServerException handleServerException( - ActionMgtConstants.ErrorMessages error, Throwable e, String... data) { + public static ActionMgtServerException handleServerException(ErrorMessage error, Throwable e, String... data) { String description = error.getDescription(); if (ArrayUtils.isNotEmpty(data)) { @@ -65,15 +65,4 @@ public static ActionMgtServerException handleServerException( return new ActionMgtServerException(error.getMessage(), description, error.getCode(), e); } - - /** - * Handle Action Management runtime exceptions. - * - * @param e Throwable. - * @return ActionMgtRuntimeException. - */ - public static ActionMgtRuntimeException handleRuntimeException(String errorMessage, Throwable e) { - - return new ActionMgtRuntimeException(errorMessage, e); - } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionSecretProcessor.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionSecretProcessor.java similarity index 95% rename from components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionSecretProcessor.java rename to components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionSecretProcessor.java index 6bbb598350f7..4709faf7d0df 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/ActionSecretProcessor.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionSecretProcessor.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.identity.action.management; +package org.wso2.carbon.identity.action.management.util; import org.wso2.carbon.identity.action.management.internal.ActionMgtServiceComponentHolder; import org.wso2.carbon.identity.action.management.model.AuthProperty; @@ -36,9 +36,6 @@ */ public class ActionSecretProcessor { - public ActionSecretProcessor() { - } - public List encryptAssociatedSecrets(Authentication authentication, String actionId) throws SecretManagementException { @@ -54,15 +51,15 @@ public List encryptAssociatedSecrets(Authentication authentication return encryptedAuthProperties; } - public List decryptAssociatedSecrets(List authProperties, String authType, - String actionId) throws SecretManagementException { + public List decryptAssociatedSecrets(Authentication authentication, String actionId) + throws SecretManagementException { List decryptedAuthProperties = new ArrayList<>(); - for (AuthProperty authProperty : authProperties) { + for (AuthProperty authProperty : authentication.getProperties()) { if (!authProperty.getIsConfidential()) { decryptedAuthProperties.add(authProperty); } else { - decryptedAuthProperties.add(decryptProperty(authProperty, authType, actionId)); + decryptedAuthProperties.add(decryptProperty(authProperty, authentication.getType().name(), actionId)); } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionValidator.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionValidator.java index 9de2ed68c026..54851f654ed2 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionValidator.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/main/java/org/wso2/carbon/identity/action/management/util/ActionValidator.java @@ -20,6 +20,7 @@ import org.apache.commons.lang.StringUtils; import org.wso2.carbon.identity.action.management.constant.ActionMgtConstants; +import org.wso2.carbon.identity.action.management.constant.error.ErrorMessage; import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; import java.util.regex.Pattern; @@ -35,9 +36,9 @@ public class ActionValidator { // and should start with an alphanumeric character. private static final String HEADER_REGEX = "^[a-zA-Z0-9][a-zA-Z0-9-.]+$"; - private Pattern actionNameRegexPattern = Pattern.compile(ACTION_NAME_REGEX); - private Pattern endpointUriRegexPattern = Pattern.compile(ENDPOINT_URI_REGEX); - private Pattern headerRegexPattern = Pattern.compile(HEADER_REGEX); + private final Pattern actionNameRegexPattern = Pattern.compile(ACTION_NAME_REGEX); + private final Pattern endpointUriRegexPattern = Pattern.compile(ENDPOINT_URI_REGEX); + private final Pattern headerRegexPattern = Pattern.compile(HEADER_REGEX); /** * Validate whether required fields exist. @@ -48,8 +49,8 @@ public class ActionValidator { public void validateForBlank(String fieldName, String fieldValue) throws ActionMgtClientException { if (StringUtils.isBlank(fieldValue)) { - throw ActionManagementUtil.handleClientException(ActionMgtConstants.ErrorMessages. - ERROR_EMPTY_ACTION_REQUEST_FIELD, fieldName); + throw ActionManagementExceptionHandler.handleClientException(ErrorMessage.ERROR_EMPTY_ACTION_REQUEST_FIELD, + fieldName); } } @@ -63,8 +64,8 @@ public void validateActionName(String name) throws ActionMgtClientException { boolean isValidName = actionNameRegexPattern.matcher(name).matches(); if (!isValidName) { - throw ActionManagementUtil.handleClientException(ActionMgtConstants.ErrorMessages. - ERROR_INVALID_ACTION_REQUEST_FIELD, ActionMgtConstants.ACTION_NAME_FIELD); + throw ActionManagementExceptionHandler.handleClientException( + ErrorMessage.ERROR_INVALID_ACTION_REQUEST_FIELD, ActionMgtConstants.ACTION_NAME_FIELD); } } @@ -78,8 +79,8 @@ public void validateEndpointUri(String uri) throws ActionMgtClientException { boolean isValidUri = endpointUriRegexPattern.matcher(uri).matches(); if (!isValidUri) { - throw ActionManagementUtil.handleClientException(ActionMgtConstants.ErrorMessages. - ERROR_INVALID_ACTION_REQUEST_FIELD, ActionMgtConstants.ENDPOINT_URI_FIELD); + throw ActionManagementExceptionHandler.handleClientException( + ErrorMessage.ERROR_INVALID_ACTION_REQUEST_FIELD, ActionMgtConstants.ENDPOINT_URI_FIELD); } } @@ -93,8 +94,8 @@ public void validateHeader(String header) throws ActionMgtClientException { boolean isValidHeader = headerRegexPattern.matcher(header).matches(); if (!isValidHeader) { - throw ActionManagementUtil.handleClientException(ActionMgtConstants.ErrorMessages. - ERROR_INVALID_ACTION_REQUEST_FIELD, ActionMgtConstants.API_KEY_HEADER_FIELD); + throw ActionManagementExceptionHandler.handleClientException( + ErrorMessage.ERROR_INVALID_ACTION_REQUEST_FIELD, ActionMgtConstants.API_KEY_HEADER_FIELD); } } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImplTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImplTest.java deleted file mode 100644 index 949efc721833..000000000000 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/ActionManagementServiceImplTest.java +++ /dev/null @@ -1,369 +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.action.management; - -import org.mockito.MockedStatic; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.identity.action.management.exception.ActionMgtException; -import org.wso2.carbon.identity.action.management.internal.ActionMgtServiceComponentHolder; -import org.wso2.carbon.identity.action.management.model.Action; -import org.wso2.carbon.identity.action.management.model.AuthProperty; -import org.wso2.carbon.identity.action.management.model.Authentication; -import org.wso2.carbon.identity.action.management.model.EndpointConfig; -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.core.internal.IdentityCoreServiceDataHolder; -import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; -import org.wso2.carbon.identity.secret.mgt.core.SecretManagerImpl; -import org.wso2.carbon.identity.secret.mgt.core.exception.SecretManagementException; -import org.wso2.carbon.identity.secret.mgt.core.model.SecretType; - -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * This class is a test suite for the ActionManagementServiceImpl class. - * It contains unit tests to verify the functionality of the methods - * in the ActionManagementServiceImpl class. - */ -@WithCarbonHome -@WithH2Database(files = {"dbscripts/h2.sql"}) -@WithRealmService(injectToSingletons = {IdentityCoreServiceDataHolder.class}) -public class ActionManagementServiceImplTest { - - private MockedStatic identityDatabaseUtil; - private Action action; - private String tenantDomain; - private ActionManagementService serviceImpl; - private Map secretProperties; - private static final String ACCESS_TOKEN = "6e47f1f7-bd29-41e9-b5dc-e9dd70ac22b7"; - private static final String PRE_ISSUE_ACCESS_TOKEN = Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN.getPathParam(); - - @BeforeClass - public void setUpClass() { - - serviceImpl = ActionManagementServiceImpl.getInstance(); - tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - } - - @BeforeMethod - public void setUp() throws SecretManagementException { - - SecretManagerImpl secretManager = mock(SecretManagerImpl.class); - SecretType secretType = mock(SecretType.class); - ActionMgtServiceComponentHolder.getInstance().setSecretManager(secretManager); - when(secretType.getId()).thenReturn("secretId"); - when(secretManager.getSecretType(any())).thenReturn(secretType); - } - - @Test(priority = 1) - public void testAddAction() throws ActionMgtException, SecretManagementException { - - Action creatingAction = buildMockAction( - "PreIssueAccessToken", - "To configure PreIssueAccessToken", - "https://example.com", - buildMockBasicAuthentication("admin", "admin")); - action = serviceImpl.addAction(PRE_ISSUE_ACCESS_TOKEN, creatingAction, - tenantDomain); - Assert.assertNotNull(action.getId()); - Assert.assertEquals(creatingAction.getName(), action.getName()); - Assert.assertEquals(creatingAction.getDescription(), action.getDescription()); - Assert.assertEquals(Action.Status.ACTIVE, action.getStatus()); - Assert.assertEquals(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN.getActionType(), - action.getType().getActionType()); - Assert.assertEquals(creatingAction.getEndpoint().getUri(), action.getEndpoint().getUri()); - Assert.assertEquals(creatingAction.getEndpoint().getAuthentication().getType(), - action.getEndpoint().getAuthentication().getType()); - Assert.assertEquals(creatingAction.getEndpoint().getAuthentication().getProperties().size(), - action.getEndpoint().getAuthentication().getProperties().size()); - Assert.assertEquals(creatingAction.getEndpoint().getAuthentication().getProperties().size(), - action.getEndpoint().getAuthentication().getPropertiesWithSecretReferences(action.getId()).size()); - secretProperties = mapActionAuthPropertiesWithSecrets(action); - Assert.assertEquals( - action.getEndpoint().getAuthentication().getProperty(Authentication.Property.USERNAME).getValue(), - secretProperties.get(Authentication.Property.USERNAME.getName())); - Assert.assertEquals( - action.getEndpoint().getAuthentication().getProperty(Authentication.Property.PASSWORD).getValue(), - secretProperties.get(Authentication.Property.PASSWORD.getName())); - } - - @Test(priority = 2, expectedExceptions = ActionMgtException.class, - expectedExceptionsMessageRegExp = "Unable to create an Action.") - public void testAddActionWithInvalidData() throws ActionMgtException { - Action creatingAction = buildMockAction( - "PreIssueAccessToken_#1", - "To configure PreIssueAccessToken", - "https://example.com", - buildMockAPIKeyAuthentication("-test-header", "thisisapikey")); - Action action = serviceImpl.addAction(PRE_ISSUE_ACCESS_TOKEN, creatingAction, tenantDomain); - Assert.assertNull(action); - } - - @Test(priority = 3, expectedExceptions = ActionMgtException.class, - expectedExceptionsMessageRegExp = "Unable to create an Action.") - public void testAddActionWithEmptyData() throws ActionMgtException { - Action creatingAction = buildMockAction( - "", - "To configure PreIssueAccessToken", - "https://example.com", - buildMockBasicAuthentication(null, "admin")); - Action action = serviceImpl.addAction(PRE_ISSUE_ACCESS_TOKEN, creatingAction, tenantDomain); - Assert.assertNull(action); - } - - @Test(priority = 4, expectedExceptions = ActionMgtException.class, - expectedExceptionsMessageRegExp = "Unable to create an Action.") - public void testAddMaximumActionsPerType() throws ActionMgtException { - - Action creatingAction = buildMockAction( - "PreIssueAccessToken", - "To configure PreIssueAccessToken", - "https://example.com", - buildMockBasicAuthentication("admin", "admin")); - action = serviceImpl.addAction(PRE_ISSUE_ACCESS_TOKEN, creatingAction, - tenantDomain); - } - - @Test(priority = 5) - public void testGetActionsByActionType() throws ActionMgtException, SecretManagementException { - - List actions = serviceImpl.getActionsByActionType(PRE_ISSUE_ACCESS_TOKEN, tenantDomain); - Assert.assertEquals(1, actions.size()); - for (Action result: actions) { - Assert.assertEquals(action.getId(), result.getId()); - Assert.assertEquals(action.getName(), result.getName()); - Assert.assertEquals(action.getDescription(), result.getDescription()); - Assert.assertEquals(action.getType().getActionType(), result.getType().getActionType()); - Assert.assertEquals(action.getStatus(), result.getStatus()); - Assert.assertEquals(action.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals(action.getEndpoint().getAuthentication().getType(), - result.getEndpoint().getAuthentication().getType()); - secretProperties = mapActionAuthPropertiesWithSecrets(result); - Assert.assertEquals( - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.USERNAME).getValue(), - secretProperties.get(Authentication.Property.USERNAME.getName())); - Assert.assertEquals( - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.PASSWORD).getValue(), - secretProperties.get(Authentication.Property.PASSWORD.getName())); - } - } - - @Test(priority = 6) - public void testGetActionByActionId() throws ActionMgtException, SecretManagementException { - - Action result = serviceImpl.getActionByActionId(action.getType().getPathParam(), action.getId(), tenantDomain); - Assert.assertEquals(action.getId(), result.getId()); - Assert.assertEquals(action.getName(), result.getName()); - Assert.assertEquals(action.getDescription(), result.getDescription()); - Assert.assertEquals(action.getType(), result.getType()); - Assert.assertEquals(action.getStatus(), result.getStatus()); - Assert.assertEquals(action.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals(action.getEndpoint().getAuthentication().getType(), - result.getEndpoint().getAuthentication().getType()); - secretProperties = mapActionAuthPropertiesWithSecrets(result); - Assert.assertEquals( - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.USERNAME).getValue(), - secretProperties.get(Authentication.Property.USERNAME.getName())); - Assert.assertEquals( - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.PASSWORD).getValue(), - secretProperties.get(Authentication.Property.PASSWORD.getName())); - } - - @Test(priority = 7) - public void testGetActionsByActionTypeFromCache() throws ActionMgtException, SecretManagementException { - - // Verify that the action is retrieved from the cache based on action type. - List actions = serviceImpl.getActionsByActionType( - PRE_ISSUE_ACCESS_TOKEN, tenantDomain); - Assert.assertEquals(1, actions.size()); - Action result = actions.get(0); - Assert.assertEquals(action.getId(), result.getId()); - Assert.assertEquals(action.getName(), result.getName()); - Assert.assertEquals(action.getDescription(), result.getDescription()); - Assert.assertEquals(action.getType(), result.getType()); - Assert.assertEquals(action.getStatus(), result.getStatus()); - Assert.assertEquals(action.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals(action.getEndpoint().getAuthentication().getType(), - result.getEndpoint().getAuthentication().getType()); - secretProperties = mapActionAuthPropertiesWithSecrets(result); - Assert.assertEquals( - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.USERNAME).getValue(), - secretProperties.get(Authentication.Property.USERNAME.getName())); - Assert.assertEquals( - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.PASSWORD).getValue(), - secretProperties.get(Authentication.Property.PASSWORD.getName())); - } - - @Test(priority = 8) - public void testUpdateAction() throws ActionMgtException, SecretManagementException { - - Action updatingAction = buildMockAction( - "Pre Issue Access Token", - "To update configuration pre issue access token", - "https://sample.com", - buildMockAPIKeyAuthentication("header", "value")); - Action result = serviceImpl.updateAction(PRE_ISSUE_ACCESS_TOKEN, action.getId(), updatingAction, tenantDomain); - Assert.assertEquals(action.getId(), result.getId()); - Assert.assertEquals(updatingAction.getName(), result.getName()); - Assert.assertEquals(updatingAction.getDescription(), result.getDescription()); - Assert.assertEquals(action.getType(), result.getType()); - Assert.assertEquals(action.getStatus(), result.getStatus()); - Assert.assertEquals(updatingAction.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals( - updatingAction.getEndpoint().getAuthentication().getType(), - result.getEndpoint().getAuthentication().getType()); - Assert.assertEquals( - updatingAction.getEndpoint().getAuthentication().getProperty(Authentication.Property.HEADER).getValue(), - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.HEADER).getValue()); - secretProperties = mapActionAuthPropertiesWithSecrets(result); - Assert.assertEquals( - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.VALUE).getValue(), - secretProperties.get(Authentication.Property.VALUE.getName())); - action = result; - } - - @Test(priority = 9) - public void testDeactivateAction() throws ActionMgtException { - - Assert.assertEquals(Action.Status.ACTIVE, action.getStatus()); - Action deactivatedAction = serviceImpl.deactivateAction( - PRE_ISSUE_ACCESS_TOKEN, action.getId(), tenantDomain); - Assert.assertEquals(Action.Status.INACTIVE, deactivatedAction.getStatus()); - } - - @Test(priority = 10) - public void testActivateAction() throws ActionMgtException { - - Action result = serviceImpl.activateAction( - PRE_ISSUE_ACCESS_TOKEN, action.getId(), tenantDomain); - Assert.assertEquals(Action.Status.ACTIVE, result.getStatus()); - } - - @Test(priority = 11) - public void testGetActionsCountPerType() throws ActionMgtException { - - Map actionMap = serviceImpl.getActionsCountPerType(tenantDomain); - Assert.assertNull(actionMap.get(Action.ActionTypes.PRE_UPDATE_PASSWORD.getActionType())); - Assert.assertNull(actionMap.get(Action.ActionTypes.PRE_UPDATE_PROFILE.getActionType())); - Assert.assertNull(actionMap.get(Action.ActionTypes.PRE_REGISTRATION.getActionType())); - Assert.assertNull(actionMap.get(Action.ActionTypes.AUTHENTICATION.getActionType())); - for (Map.Entry entry: actionMap.entrySet()) { - Assert.assertEquals(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN.getActionType(), entry.getKey()); - Assert.assertEquals(1, entry.getValue().intValue()); - } - } - - @Test(priority = 12) - public void testUpdateEndpointConfigWithSameAuthenticationType() - throws ActionMgtException, SecretManagementException { - - Authentication authentication = buildMockAPIKeyAuthentication("newheader", "newvalue"); - Action result = serviceImpl.updateActionEndpointAuthentication( - PRE_ISSUE_ACCESS_TOKEN, action.getId(), authentication, tenantDomain); - Assert.assertEquals(Authentication.Type.API_KEY, result.getEndpoint().getAuthentication().getType()); - Assert.assertEquals(authentication.getProperty(Authentication.Property.HEADER).getValue(), - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.HEADER).getValue()); - secretProperties = mapActionAuthPropertiesWithSecrets(result); - Assert.assertEquals( - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.VALUE).getValue(), - secretProperties.get(Authentication.Property.VALUE.getName())); - } - - @Test(priority = 13) - public void testUpdateEndpointConfigWithDifferentAuthenticationType() - throws ActionMgtException, SecretManagementException { - - Authentication authentication = buildMockBearerAuthentication(ACCESS_TOKEN); - Action result = serviceImpl.updateActionEndpointAuthentication( - PRE_ISSUE_ACCESS_TOKEN, action.getId(), authentication, tenantDomain); - Assert.assertEquals(Authentication.Type.BEARER, result.getEndpoint().getAuthentication().getType()); - secretProperties = mapActionAuthPropertiesWithSecrets(result); - Assert.assertEquals( - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.ACCESS_TOKEN).getValue(), - secretProperties.get(Authentication.Property.ACCESS_TOKEN.getName())); - } - - @Test(priority = 14) - public void testDeleteAction() throws ActionMgtException { - - serviceImpl.deleteAction(PRE_ISSUE_ACCESS_TOKEN, action.getId(), tenantDomain); - Assert.assertNull(serviceImpl.getActionByActionId(action.getType().getPathParam(), action.getId(), - tenantDomain)); - Map actions = serviceImpl.getActionsCountPerType(tenantDomain); - Assert.assertNull(actions.get(PRE_ISSUE_ACCESS_TOKEN)); - } - - private Map mapActionAuthPropertiesWithSecrets(Action action) throws SecretManagementException { - - return action.getEndpoint().getAuthentication() - .getPropertiesWithSecretReferences(action.getId()) - .stream() - .collect(Collectors.toMap(AuthProperty::getName, AuthProperty::getValue)); - } - - private Authentication buildMockBasicAuthentication(String username, String password) { - - return new Authentication.BasicAuthBuilder(username, password).build(); - } - - private Authentication buildMockBearerAuthentication(String accessToken) { - - return new Authentication.BearerAuthBuilder(accessToken).build(); - } - - private Authentication buildMockAPIKeyAuthentication(String header, String value) { - - return new Authentication.APIKeyAuthBuilder(header, value).build(); - } - - private EndpointConfig buildMockEndpointConfig(String uri, Authentication authentication) { - - if (uri == null && authentication == null) { - return null; - } - - return new EndpointConfig.EndpointConfigBuilder() - .uri(uri) - .authentication(authentication) - .build(); - } - - private Action buildMockAction(String name, - String description, - String uri, - Authentication authentication) { - - return new Action.ActionRequestBuilder() - .name(name) - .description(description) - .endpoint(buildMockEndpointConfig(uri, authentication)) - .build(); - } -} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionDTOModelResolverFactoryTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionDTOModelResolverFactoryTest.java new file mode 100644 index 000000000000..23171e048ad2 --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionDTOModelResolverFactoryTest.java @@ -0,0 +1,70 @@ +/* + * 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.action.management.dao; + +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.testng.Assert; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; +import org.wso2.carbon.identity.action.management.dao.impl.ActionDTOModelResolverFactory; +import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.service.ActionDTOModelResolver; + +import static org.mockito.Mockito.doReturn; + +/** + * ActionDTO Model Resolver Factory Test. + */ +public class ActionDTOModelResolverFactoryTest { + + private final Action.ActionTypes actionType = Action.ActionTypes.PRE_UPDATE_PASSWORD; + @Mock + private ActionDTOModelResolver mockActionDTOModelResolver; + + @BeforeMethod + public void setUp() { + + MockitoAnnotations.openMocks(this); + doReturn(actionType).when(mockActionDTOModelResolver).getSupportedActionType(); + } + + @Test + public void testRegisterActionDTOModelResolver() { + + ActionDTOModelResolverFactory.registerActionDTOModelResolver(mockActionDTOModelResolver); + ActionDTOModelResolver registeredResult = ActionDTOModelResolverFactory.getActionDTOModelResolver(actionType); + Assert.assertEquals(registeredResult, mockActionDTOModelResolver); + } + + @Test(dependsOnMethods = {"testRegisterActionDTOModelResolver"}) + public void testUnregisterActionDTOModelResolver() { + + ActionDTOModelResolverFactory.unregisterActionDTOModelResolver(mockActionDTOModelResolver); + ActionDTOModelResolver unregisteredResult = ActionDTOModelResolverFactory.getActionDTOModelResolver(actionType); + Assert.assertNull(unregisteredResult); + } + + @Test(dependsOnMethods = {"testUnregisterActionDTOModelResolver"}) + public void testGetActionDTOModelResolverNotFound() { + + ActionDTOModelResolver result = ActionDTOModelResolverFactory.getActionDTOModelResolver(actionType); + Assert.assertNull(result); + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java new file mode 100644 index 000000000000..8aa13fc9e089 --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOFacadeTest.java @@ -0,0 +1,403 @@ +/* + * 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.action.management.dao; + +import org.apache.commons.lang.StringUtils; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.MockitoAnnotations; +import org.testng.Assert; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; +import org.wso2.carbon.identity.action.management.constant.error.ErrorMessage; +import org.wso2.carbon.identity.action.management.dao.impl.ActionDTOModelResolverFactory; +import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOFacade; +import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOImpl; +import org.wso2.carbon.identity.action.management.exception.ActionDTOModelResolverClientException; +import org.wso2.carbon.identity.action.management.exception.ActionDTOModelResolverException; +import org.wso2.carbon.identity.action.management.exception.ActionDTOModelResolverServerException; +import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; +import org.wso2.carbon.identity.action.management.exception.ActionMgtException; +import org.wso2.carbon.identity.action.management.exception.ActionMgtServerException; +import org.wso2.carbon.identity.action.management.internal.ActionMgtServiceComponentHolder; +import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.ActionDTO; +import org.wso2.carbon.identity.action.management.model.Authentication; +import org.wso2.carbon.identity.action.management.model.EndpointConfig; +import org.wso2.carbon.identity.action.management.service.ActionDTOModelResolver; +import org.wso2.carbon.identity.action.management.util.ActionDTOBuilder; +import org.wso2.carbon.identity.action.management.util.TestUtil; +import org.wso2.carbon.identity.certificate.management.model.Certificate; +import org.wso2.carbon.identity.common.testng.WithCarbonHome; +import org.wso2.carbon.identity.common.testng.WithH2Database; +import org.wso2.carbon.identity.core.util.IdentityTenantUtil; +import org.wso2.carbon.identity.secret.mgt.core.SecretManagerImpl; +import org.wso2.carbon.identity.secret.mgt.core.exception.SecretManagementException; +import org.wso2.carbon.identity.secret.mgt.core.model.SecretType; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +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.wso2.carbon.identity.action.management.util.TestUtil.CERTIFICATE_PROPERTY_NAME; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PASSWORD_SHARING_TYPE_PROPERTY_NAME; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_ISSUE_ACCESS_TOKEN_ACTION_ID; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_ISSUE_ACCESS_TOKEN_TYPE; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_UPDATE_PASSWORD_ACTION_ID; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_UPDATE_PASSWORD_TYPE; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TENANT_DOMAIN; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TENANT_ID; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACCESS_TOKEN; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_DESCRIPTION; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_DESCRIPTION_UPDATED; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_NAME; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_NAME_UPDATED; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_URI; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_URI_UPDATED; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_CERTIFICATE; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_PASSWORD; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_PASSWORD_SHARING_TYPE; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_PASSWORD_SHARING_TYPE_UPDATED; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_USERNAME; + +/** + * This class is a test suite for the ActionManagementDAOFacade class. + * It contains unit tests to verify the functionality of the methods in the ActionManagementDAOFacade class which is + * responsible for handling external services. + */ +@WithH2Database(files = {"dbscripts/h2.sql"}) +@WithCarbonHome +public class ActionManagementDAOFacadeTest { + + @Mock + private ActionDTOModelResolver mockedActionDTOModelResolver; + private TestActionDTOModelResolver testActionPropertyResolver; + private MockedStatic actionPropertyResolverFactory; + private MockedStatic identityTenantUtil; + + private ActionManagementDAOFacade daoFacade; + private ActionDTO creatingActionDTO; + private ActionDTO createdActionDTO; + + @BeforeClass + public void setUpClass() { + + daoFacade = new ActionManagementDAOFacade(new ActionManagementDAOImpl()); + creatingActionDTO = new ActionDTOBuilder() + .id(PRE_UPDATE_PASSWORD_ACTION_ID) + .type(Action.ActionTypes.PRE_UPDATE_PASSWORD) + .name(TEST_ACTION_NAME) + .description(TEST_ACTION_DESCRIPTION) + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .uri(TEST_ACTION_URI) + .authentication(TestUtil.buildMockBasicAuthentication(TEST_USERNAME, TEST_PASSWORD)) + .build()) + .property(PASSWORD_SHARING_TYPE_PROPERTY_NAME, TEST_PASSWORD_SHARING_TYPE) + .property(CERTIFICATE_PROPERTY_NAME, + new Certificate.Builder().certificateContent(TEST_CERTIFICATE).build()) + .build(); + testActionPropertyResolver = new TestActionDTOModelResolver(); + } + + @BeforeMethod + public void setUp() throws SecretManagementException { + + SecretManagerImpl secretManager = mock(SecretManagerImpl.class); + SecretType secretType = mock(SecretType.class); + ActionMgtServiceComponentHolder.getInstance().setSecretManager(secretManager); + when(secretType.getId()).thenReturn(TestUtil.TEST_SECRET_TYPE_ID); + when(secretManager.getSecretType(any())).thenReturn(secretType); + + identityTenantUtil = mockStatic(IdentityTenantUtil.class); + identityTenantUtil.when(()-> IdentityTenantUtil.getTenantDomain(anyInt())).thenReturn(TENANT_DOMAIN); + + MockitoAnnotations.openMocks(this); + actionPropertyResolverFactory = mockStatic(ActionDTOModelResolverFactory.class); + } + + @AfterMethod + public void tearDown() { + + mockedActionDTOModelResolver = null; + identityTenantUtil.close(); + actionPropertyResolverFactory.close(); + } + + @Test(priority = 1) + public void testAddActionWithActionPropertyResolverClientException() throws ActionDTOModelResolverException { + + mockActionPropertyResolver(mockedActionDTOModelResolver); + doThrow(new ActionDTOModelResolverClientException("Invalid Certificate.", "Invalid PEM format.")) + .when(mockedActionDTOModelResolver).resolveForAddOperation(any(), any()); + + try { + daoFacade.addAction(creatingActionDTO, TENANT_ID); + Assert.fail("Successful addition of the action without an exception is considered as a failure"); + } catch (ActionMgtException e) { + Assert.assertEquals(e.getClass(), ActionMgtClientException.class); + Assert.assertEquals(e.getErrorCode(), ErrorMessage.ERROR_INVALID_ACTION_PROPERTIES.getCode()); + Assert.assertEquals(e.getMessage(), "Invalid Certificate."); + Assert.assertEquals(e.getDescription(), "Invalid PEM format."); + } + } + + @Test(priority = 2) + public void testAddActionWithActionPropertyResolverServerException() throws ActionDTOModelResolverException { + + mockActionPropertyResolver(mockedActionDTOModelResolver); + doThrow(new ActionDTOModelResolverServerException("Error adding Certificate.", null, new Throwable())) + .when(mockedActionDTOModelResolver).resolveForAddOperation(any(), any()); + + try { + daoFacade.addAction(creatingActionDTO, TENANT_ID); + Assert.fail("Successful addition of the action without an exception is considered as a failure"); + } catch (ActionMgtException e) { + Assert.assertEquals(e.getClass(), ActionMgtServerException.class); + Assert.assertEquals(e.getMessage(), ErrorMessage.ERROR_WHILE_ADDING_ACTION.getMessage()); + for (Throwable cause = e.getCause(); cause != null; cause = cause.getCause()) { + if (cause instanceof ActionDTOModelResolverServerException) { + return; + } + } + Assert.fail("Expected ActionPropertyResolverServerException was not found in the exception chain"); + } + } + + @Test(priority = 3) + public void testAddAction() throws ActionMgtException { + + mockActionPropertyResolver(testActionPropertyResolver); + try { + daoFacade.addAction(creatingActionDTO, TENANT_ID); + } catch (Exception e) { + Assert.fail(); + } + + createdActionDTO = daoFacade.getActionByActionId(PRE_UPDATE_PASSWORD_TYPE, PRE_UPDATE_PASSWORD_ACTION_ID, + TENANT_ID); + Assert.assertEquals(createdActionDTO.getId(), creatingActionDTO.getId()); + Assert.assertEquals(createdActionDTO.getType(), creatingActionDTO.getType()); + Assert.assertEquals(createdActionDTO.getName(), creatingActionDTO.getName()); + Assert.assertEquals(createdActionDTO.getDescription(), creatingActionDTO.getDescription()); + Assert.assertEquals(createdActionDTO.getStatus(), Action.Status.ACTIVE); + Assert.assertEquals(createdActionDTO.getEndpoint().getUri(), creatingActionDTO.getEndpoint().getUri()); + + Authentication createdAuthentication = createdActionDTO.getEndpoint().getAuthentication(); + Assert.assertEquals(createdAuthentication.getType(), + creatingActionDTO.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(createdAuthentication.getProperties().size(), + creatingActionDTO.getEndpoint().getAuthentication().getProperties().size()); + Assert.assertEquals(createdAuthentication.getProperty(Authentication.Property.USERNAME).getValue(), + TestUtil.buildSecretName(PRE_UPDATE_PASSWORD_ACTION_ID, Authentication.Type.BASIC, + Authentication.Property.USERNAME)); + Assert.assertEquals(createdAuthentication.getProperty(Authentication.Property.PASSWORD).getValue(), + TestUtil.buildSecretName(PRE_UPDATE_PASSWORD_ACTION_ID, Authentication.Type.BASIC, + Authentication.Property.PASSWORD)); + + Assert.assertEquals(createdActionDTO.getProperties().size(), creatingActionDTO.getProperties().size()); + Assert.assertTrue(createdActionDTO.getProperties().containsKey(PASSWORD_SHARING_TYPE_PROPERTY_NAME)); + Assert.assertTrue(createdActionDTO.getProperties().containsKey(CERTIFICATE_PROPERTY_NAME)); + Assert.assertEquals(createdActionDTO.getProperty(PASSWORD_SHARING_TYPE_PROPERTY_NAME), + creatingActionDTO.getProperty(PASSWORD_SHARING_TYPE_PROPERTY_NAME)); + Assert.assertEquals(((Certificate) createdActionDTO.getProperty(CERTIFICATE_PROPERTY_NAME)) + .getCertificateContent(), TEST_CERTIFICATE); + } + + @Test(priority = 4) + public void testGetActionsByType() throws ActionMgtException { + + mockActionPropertyResolver(testActionPropertyResolver); + List actionDTOs = daoFacade.getActionsByActionType(PRE_UPDATE_PASSWORD_TYPE, TENANT_ID); + ActionDTO result = actionDTOs.get(0); + Assert.assertEquals(result.getId(), createdActionDTO.getId()); + Assert.assertEquals(result.getType(), createdActionDTO.getType()); + Assert.assertEquals(result.getName(), createdActionDTO.getName()); + Assert.assertEquals(result.getDescription(), createdActionDTO.getDescription()); + Assert.assertEquals(result.getStatus(), createdActionDTO.getStatus()); + Assert.assertEquals(result.getEndpoint().getUri(), createdActionDTO.getEndpoint().getUri()); + + Authentication resultAuthentication = result.getEndpoint().getAuthentication(); + Assert.assertEquals(resultAuthentication.getType(), + createdActionDTO.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(resultAuthentication.getProperties().size(), + createdActionDTO.getEndpoint().getAuthentication().getProperties().size()); + Assert.assertEquals(resultAuthentication.getProperty(Authentication.Property.USERNAME).getValue(), + createdActionDTO.getEndpoint().getAuthentication().getProperty(Authentication.Property.USERNAME) + .getValue()); + Assert.assertEquals(resultAuthentication.getProperty(Authentication.Property.PASSWORD).getValue(), + createdActionDTO.getEndpoint().getAuthentication().getProperty(Authentication.Property.PASSWORD) + .getValue()); + + Assert.assertEquals(result.getProperties().size(), createdActionDTO.getProperties().size()); + Assert.assertTrue(createdActionDTO.getProperties().containsKey(PASSWORD_SHARING_TYPE_PROPERTY_NAME)); + Assert.assertTrue(createdActionDTO.getProperties().containsKey(CERTIFICATE_PROPERTY_NAME)); + Assert.assertEquals(result.getProperty(PASSWORD_SHARING_TYPE_PROPERTY_NAME), + createdActionDTO.getProperty(PASSWORD_SHARING_TYPE_PROPERTY_NAME)); + Assert.assertEquals(((Certificate) result.getProperty(CERTIFICATE_PROPERTY_NAME)).getCertificateContent(), + ((Certificate) createdActionDTO.getProperty(CERTIFICATE_PROPERTY_NAME)).getCertificateContent()); + } + + @Test(priority = 5) + public void testUpdateActionPropertyResolverClientException() throws ActionDTOModelResolverException { + + mockActionPropertyResolver(mockedActionDTOModelResolver); + doThrow(new ActionDTOModelResolverClientException("Invalid Certificate.", "Invalid PEM format.")) + .when(mockedActionDTOModelResolver).resolveForUpdateOperation(any(), any(), any()); + + try { + daoFacade.updateAction(creatingActionDTO, createdActionDTO, TENANT_ID); + Assert.fail("Successful update of the actions without an exception is considered as a failure"); + } catch (ActionMgtException e) { + Assert.assertEquals(e.getClass(), ActionMgtClientException.class); + Assert.assertEquals(e.getErrorCode(), ErrorMessage.ERROR_INVALID_ACTION_PROPERTIES.getCode()); + Assert.assertEquals(e.getMessage(), "Invalid Certificate."); + Assert.assertEquals(e.getDescription(), "Invalid PEM format."); + } + } + + @Test(priority = 6) + public void testUpdateActionWithActionPropertyResolverServerException() throws ActionDTOModelResolverException { + + mockActionPropertyResolver(mockedActionDTOModelResolver); + doThrow(new ActionDTOModelResolverServerException("Error updating Certificate.", null)).when( + mockedActionDTOModelResolver) + .resolveForUpdateOperation(any(), any(), any()); + + try { + daoFacade.updateAction(creatingActionDTO, createdActionDTO, TENANT_ID); + Assert.fail("Successful update of the actions without an exception is considered as a failure"); + } catch (ActionMgtException e) { + Assert.assertEquals(e.getClass(), ActionMgtServerException.class); + Assert.assertEquals(e.getMessage(), ErrorMessage.ERROR_WHILE_UPDATING_ACTION.getMessage()); + for (Throwable cause = e.getCause(); cause != null; cause = cause.getCause()) { + if (cause instanceof ActionDTOModelResolverServerException) { + return; + } + } + Assert.fail("Expected ActionPropertyResolverServerException was not found in the exception chain"); + } + } + + @Test(priority = 7, dependsOnMethods = "testAddAction") + public void testUpdateCompleteAction() throws ActionMgtException { + + mockActionPropertyResolver(testActionPropertyResolver); + // Update action with certificate property deletion. + ActionDTO updatingAction = new ActionDTOBuilder() + .id(createdActionDTO.getId()) + .type(Action.ActionTypes.PRE_UPDATE_PASSWORD) + .name(TEST_ACTION_NAME_UPDATED) + .description(TEST_ACTION_DESCRIPTION_UPDATED) + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .uri(TEST_ACTION_URI_UPDATED) + .authentication(TestUtil.buildMockBearerAuthentication(TEST_ACCESS_TOKEN)) + .build()) + .property(PASSWORD_SHARING_TYPE_PROPERTY_NAME, TEST_PASSWORD_SHARING_TYPE_UPDATED) + .property(CERTIFICATE_PROPERTY_NAME, + new Certificate.Builder().certificateContent(StringUtils.EMPTY).build()) + .build(); + + try { + daoFacade.updateAction(updatingAction, createdActionDTO, TENANT_ID); + } catch (Exception e) { + Assert.fail(); + } + + ActionDTO result = daoFacade.getActionByActionId(PRE_UPDATE_PASSWORD_TYPE, updatingAction.getId(), TENANT_ID); + Assert.assertEquals(result.getId(), createdActionDTO.getId()); + Assert.assertEquals(result.getType(), createdActionDTO.getType()); + Assert.assertEquals(result.getName(), updatingAction.getName()); + Assert.assertEquals(result.getDescription(), updatingAction.getDescription()); + Assert.assertEquals(result.getStatus(), createdActionDTO.getStatus()); + Assert.assertEquals(result.getEndpoint().getUri(), updatingAction.getEndpoint().getUri()); + + Authentication updatedAuthentication = result.getEndpoint().getAuthentication(); + Assert.assertEquals(updatedAuthentication.getType(), + updatingAction.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(updatedAuthentication.getProperties().size(), + updatingAction.getEndpoint().getAuthentication().getProperties().size()); + Assert.assertEquals(updatedAuthentication.getProperty(Authentication.Property.ACCESS_TOKEN).getValue(), + TestUtil.buildSecretName(PRE_UPDATE_PASSWORD_ACTION_ID, Authentication.Type.BEARER, + Authentication.Property.ACCESS_TOKEN)); + + // Check whether the certificate is removed. + Assert.assertEquals(result.getProperties().size(), updatingAction.getProperties().size() - 1); + + Assert.assertTrue(updatingAction.getProperties().containsKey(PASSWORD_SHARING_TYPE_PROPERTY_NAME)); + Assert.assertTrue(updatingAction.getProperties().containsKey(CERTIFICATE_PROPERTY_NAME)); + Assert.assertEquals(result.getProperty(PASSWORD_SHARING_TYPE_PROPERTY_NAME), + updatingAction.getProperty(PASSWORD_SHARING_TYPE_PROPERTY_NAME)); + Assert.assertNull(result.getProperty(CERTIFICATE_PROPERTY_NAME)); + createdActionDTO = result; + } + + @Test(priority = 8) + public void testDeactivateAction() throws ActionMgtException { + + Assert.assertEquals(createdActionDTO.getStatus(), Action.Status.ACTIVE); + ActionDTO deactivatedActionDTO = daoFacade.deactivateAction(PRE_UPDATE_PASSWORD_TYPE, createdActionDTO.getId(), + TENANT_ID); + Assert.assertEquals(deactivatedActionDTO.getStatus(), Action.Status.INACTIVE); + } + + @Test(priority = 9) + public void testActivateAction() throws ActionMgtException { + + ActionDTO activatedActionDTO = daoFacade.activateAction(PRE_UPDATE_PASSWORD_TYPE, createdActionDTO.getId(), + TENANT_ID); + Assert.assertEquals(activatedActionDTO.getStatus(), Action.Status.ACTIVE); + } + + @Test(priority = 10) + public void testGetActionsCountPerType() throws ActionMgtException { + + Map actionMap = daoFacade.getActionsCountPerType(TENANT_ID); + Assert.assertTrue(actionMap.containsKey(PRE_UPDATE_PASSWORD_TYPE)); + Assert.assertEquals(actionMap.get(PRE_UPDATE_PASSWORD_TYPE).intValue(), 1); + } + + @Test(priority = 11) + public void testDeleteAction() throws ActionMgtException { + + mockActionPropertyResolver(testActionPropertyResolver); + try { + daoFacade.deleteAction(createdActionDTO, TENANT_ID); + } catch (Exception e) { + Assert.fail(); + } + Assert.assertNull(daoFacade.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_TYPE, PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, + TENANT_ID)); + Assert.assertEquals(daoFacade.getActionsCountPerType(TENANT_ID), Collections.emptyMap()); + } + + private void mockActionPropertyResolver(ActionDTOModelResolver actionDTOModelResolver) { + + actionPropertyResolverFactory.when( + () -> ActionDTOModelResolverFactory.getActionDTOModelResolver(Action.ActionTypes.PRE_UPDATE_PASSWORD)) + .thenReturn(actionDTOModelResolver); + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOImplTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOImplTest.java index 2c3a5237ee5a..2f40c18b674d 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOImplTest.java +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/ActionManagementDAOImplTest.java @@ -18,48 +18,42 @@ package org.wso2.carbon.identity.action.management.dao; -import org.junit.Assert; -import org.mockito.MockedStatic; -import org.testng.annotations.AfterMethod; +import org.testng.Assert; import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.wso2.carbon.identity.action.management.dao.impl.ActionManagementDAOImpl; import org.wso2.carbon.identity.action.management.exception.ActionMgtException; -import org.wso2.carbon.identity.action.management.internal.ActionMgtServiceComponentHolder; import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.ActionDTO; import org.wso2.carbon.identity.action.management.model.Authentication; import org.wso2.carbon.identity.action.management.model.EndpointConfig; +import org.wso2.carbon.identity.action.management.util.ActionDTOBuilder; +import org.wso2.carbon.identity.action.management.util.TestUtil; import org.wso2.carbon.identity.common.testng.WithCarbonHome; import org.wso2.carbon.identity.common.testng.WithH2Database; -import org.wso2.carbon.identity.core.util.IdentityTenantUtil; -import org.wso2.carbon.identity.secret.mgt.core.SecretManagerImpl; -import org.wso2.carbon.identity.secret.mgt.core.exception.SecretManagementException; -import org.wso2.carbon.identity.secret.mgt.core.model.SecretType; +import java.util.List; import java.util.Map; import java.util.UUID; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.mockStatic; -import static org.mockito.Mockito.when; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_ISSUE_ACCESS_TOKEN_ACTION_ID; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_ISSUE_ACCESS_TOKEN_TYPE; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_UPDATE_PASSWORD_ACTION_ID; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_UPDATE_PASSWORD_TYPE; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TENANT_ID; /** * This class is a test suite for the ActionManagementDAOImpl class. - * It contains unit tests to verify the functionality of the methods - * in the ActionManagementDAOImpl class. + * It contains unit tests to verify the functionality of the methods in the ActionManagementDAOImpl class. + * This test class will utilize {@link TestActionDTOModelResolver} class as the test implementation for + * ActionPropertyResolver interface. */ @WithH2Database(files = {"dbscripts/h2.sql"}) @WithCarbonHome public class ActionManagementDAOImplTest { private ActionManagementDAOImpl daoImpl; - private MockedStatic identityTenantUtil; - private static final String PRE_ISSUE_ACCESS_TOKEN = "PRE_ISSUE_ACCESS_TOKEN"; - private static final int TENANT_ID = 2; - private Action action; + private ActionDTO createdActionDTO; @BeforeClass public void setUpClass() { @@ -67,372 +61,492 @@ public void setUpClass() { daoImpl = new ActionManagementDAOImpl(); } - @BeforeMethod - public void setUp() throws SecretManagementException { - - identityTenantUtil = mockStatic(IdentityTenantUtil.class); - SecretManagerImpl secretManager = mock(SecretManagerImpl.class); - SecretType secretType = mock(SecretType.class); - ActionMgtServiceComponentHolder.getInstance().setSecretManager(secretManager); - identityTenantUtil.when(()-> IdentityTenantUtil.getTenantId(anyString())).thenReturn(TENANT_ID); - when(secretType.getId()).thenReturn("secretId"); - when(secretManager.getSecretType(any())).thenReturn(secretType); - } - - @AfterMethod - public void tearDown() { - - identityTenantUtil.close(); - } - @Test(priority = 1) public void testAddAction() throws ActionMgtException { - String id = String.valueOf(UUID.randomUUID()); - Action creatingAction = buildMockAction( - "PreIssueAccessToken", - "To configure PreIssueAccessToken", - "https://example.com", - buildMockBasicAuthentication("admin", "admin")); - action = daoImpl.addAction(PRE_ISSUE_ACCESS_TOKEN, id, creatingAction, TENANT_ID); - Assert.assertEquals(id, action.getId()); - Assert.assertEquals(creatingAction.getName(), action.getName()); - Assert.assertEquals(creatingAction.getDescription(), action.getDescription()); - Assert.assertEquals(PRE_ISSUE_ACCESS_TOKEN, action.getType().getActionType()); - Assert.assertEquals(Action.Status.ACTIVE, action.getStatus()); - Assert.assertEquals(creatingAction.getEndpoint().getUri(), action.getEndpoint().getUri()); - Assert.assertEquals(creatingAction.getEndpoint().getAuthentication().getType(), - action.getEndpoint().getAuthentication().getType()); + ActionDTO creatingActionDTO = new ActionDTOBuilder() + .id(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID) + .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) + .name(TestUtil.TEST_ACTION_NAME) + .description(TestUtil.TEST_ACTION_DESCRIPTION) + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .uri(TestUtil.TEST_ACTION_URI) + .authentication(TestUtil.buildMockBasicAuthentication(TestUtil.TEST_USERNAME_SECRET_REFERENCE, + TestUtil.TEST_PASSWORD_SECRET_REFERENCE)) + .build()) + .property(TestUtil.TEST_ACTION_PROPERTY_NAME_1, TestUtil.TEST_ACTION_PROPERTY_VALUE_1) + .property(TestUtil.TEST_ACTION_PROPERTY_NAME_2, TestUtil.TEST_ACTION_PROPERTY_VALUE_2) + .build(); + + try { + daoImpl.addAction(creatingActionDTO, TENANT_ID); + } catch (Exception e) { + Assert.fail(); + } + createdActionDTO = daoImpl.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_TYPE, PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, + TENANT_ID); + Assert.assertEquals(createdActionDTO.getId(), creatingActionDTO.getId()); + Assert.assertEquals(createdActionDTO.getType(), creatingActionDTO.getType()); + Assert.assertEquals(createdActionDTO.getName(), creatingActionDTO.getName()); + Assert.assertEquals(createdActionDTO.getDescription(), creatingActionDTO.getDescription()); + Assert.assertEquals(createdActionDTO.getStatus(), Action.Status.ACTIVE); + Assert.assertEquals(createdActionDTO.getEndpoint().getUri(), creatingActionDTO.getEndpoint().getUri()); + + Authentication createdAuthentication = createdActionDTO.getEndpoint().getAuthentication(); + Assert.assertEquals(createdAuthentication.getType(), + creatingActionDTO.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(createdAuthentication.getProperties().size(), + creatingActionDTO.getEndpoint().getAuthentication().getProperties().size()); + Assert.assertEquals(createdAuthentication.getProperty(Authentication.Property.USERNAME).getValue(), + TestUtil.TEST_USERNAME_SECRET_REFERENCE); + Assert.assertEquals(createdAuthentication.getProperty(Authentication.Property.PASSWORD).getValue(), + TestUtil.TEST_PASSWORD_SECRET_REFERENCE); + + Assert.assertEquals(createdActionDTO.getProperties().size(), creatingActionDTO.getProperties().size()); + Assert.assertEquals(createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1), + creatingActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1)); + Assert.assertEquals(createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2), + creatingActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2)); } @Test(priority = 2, expectedExceptions = ActionMgtException.class, - expectedExceptionsMessageRegExp = "Error while adding Action.") + expectedExceptionsMessageRegExp = "Error while adding Action Basic information in the system.") public void testAddActionWithoutName() throws ActionMgtException { - Action action = buildMockAction( - null, - "To configure PreIssueAccessToken", - "https://example.com", - buildMockBasicAuthentication("admin", "admin")); - this.action = daoImpl.addAction(PRE_ISSUE_ACCESS_TOKEN, action.getId(), action, TENANT_ID); + ActionDTO creatingActionDTO = new ActionDTOBuilder() + .id(String.valueOf(UUID.randomUUID())) + .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) + .name(null) + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .uri(TestUtil.TEST_ACTION_URI) + .authentication(TestUtil.buildMockBasicAuthentication(TestUtil.TEST_USERNAME_SECRET_REFERENCE, + TestUtil.TEST_PASSWORD_SECRET_REFERENCE)) + .build()) + .build(); + + daoImpl.addAction(creatingActionDTO, TENANT_ID); } @Test(priority = 3) public void testGetActionsByActionType() throws ActionMgtException { - Assert.assertEquals(1, daoImpl.getActionsByActionType(PRE_ISSUE_ACCESS_TOKEN, TENANT_ID).size()); - Action result = daoImpl.getActionsByActionType(PRE_ISSUE_ACCESS_TOKEN, TENANT_ID).get(0); - Assert.assertEquals(action.getId(), result.getId()); - Assert.assertEquals(action.getName(), result.getName()); - Assert.assertEquals(action.getDescription(), result.getDescription()); - Assert.assertEquals(action.getType(), result.getType()); - Assert.assertEquals(action.getStatus(), result.getStatus()); - Assert.assertEquals(action.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals(action.getEndpoint().getAuthentication().getType(), - result.getEndpoint().getAuthentication().getType()); + List actionDTOList = daoImpl.getActionsByActionType(PRE_ISSUE_ACCESS_TOKEN_TYPE, TENANT_ID); + Assert.assertEquals(actionDTOList.size(), 1); + ActionDTO result = actionDTOList.get(0); + Assert.assertEquals(result.getId(), createdActionDTO.getId()); + Assert.assertEquals(result.getType(), createdActionDTO.getType()); + Assert.assertEquals(result.getName(), createdActionDTO.getName()); + Assert.assertEquals(result.getDescription(), createdActionDTO.getDescription()); + Assert.assertEquals(result.getStatus(), createdActionDTO.getStatus()); + Assert.assertEquals(result.getEndpoint().getUri(), createdActionDTO.getEndpoint().getUri()); + Assert.assertEquals(result.getEndpoint().getAuthentication().getType(), + createdActionDTO.getEndpoint().getAuthentication().getType()); + + Authentication createdAuthentication = result.getEndpoint().getAuthentication(); + Assert.assertEquals(createdAuthentication.getType(), + createdActionDTO.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(createdAuthentication.getProperties().size(), + createdActionDTO.getEndpoint().getAuthentication().getProperties().size()); + Assert.assertEquals(createdAuthentication.getProperty(Authentication.Property.USERNAME).getValue(), + TestUtil.TEST_USERNAME_SECRET_REFERENCE); + Assert.assertEquals(createdAuthentication.getProperty(Authentication.Property.PASSWORD).getValue(), + TestUtil.TEST_PASSWORD_SECRET_REFERENCE); + + Assert.assertEquals(result.getProperties().size(), createdActionDTO.getProperties().size()); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1), + createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1)); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2), + createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2)); } @Test(priority = 4) - public void testGetActionByActionId() throws ActionMgtException { - - Action result = daoImpl.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN, action.getId(), TENANT_ID); - Assert.assertEquals(action.getId(), result.getId()); - Assert.assertEquals(action.getName(), result.getName()); - Assert.assertEquals(action.getDescription(), result.getDescription()); - Assert.assertEquals(action.getType(), result.getType()); - Assert.assertEquals(action.getStatus(), result.getStatus()); - Assert.assertEquals(action.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals(action.getEndpoint().getAuthentication().getType(), - result.getEndpoint().getAuthentication().getType()); - } - - @Test(priority = 5) public void testDeleteAction() throws ActionMgtException { - daoImpl.deleteAction(PRE_ISSUE_ACCESS_TOKEN, action.getId(), action, TENANT_ID); - Assert.assertNull(daoImpl.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN, action.getId(), TENANT_ID)); + try { + daoImpl.deleteAction(createdActionDTO, TENANT_ID); + } catch (Exception e) { + Assert.fail(); + } + Assert.assertNull(daoImpl.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_TYPE, PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, + TENANT_ID)); } - @Test(priority = 6) + @Test(priority = 5) public void testAddActionWithoutDescription() throws ActionMgtException { - String id = String.valueOf(UUID.randomUUID()); - Action creatingAction = buildMockAction( - "PreIssueAccessToken", - null, - "https://example.com", - buildMockBasicAuthentication("admin", "admin")); - action = daoImpl.addAction(PRE_ISSUE_ACCESS_TOKEN, id, creatingAction, TENANT_ID); - Assert.assertEquals(id, action.getId()); - Assert.assertEquals(creatingAction.getName(), action.getName()); - Assert.assertNull(null, action.getDescription()); - Assert.assertEquals(PRE_ISSUE_ACCESS_TOKEN, action.getType().getActionType()); - Assert.assertEquals(Action.Status.ACTIVE, action.getStatus()); - Assert.assertEquals(creatingAction.getEndpoint().getUri(), action.getEndpoint().getUri()); - Assert.assertEquals(creatingAction.getEndpoint().getAuthentication().getType(), - action.getEndpoint().getAuthentication().getType()); + ActionDTO creatingActionDTO = new ActionDTOBuilder() + .id(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID) + .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) + .name(TestUtil.TEST_ACTION_NAME) + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .uri(TestUtil.TEST_ACTION_URI) + .authentication(TestUtil.buildMockBasicAuthentication(TestUtil.TEST_USERNAME_SECRET_REFERENCE, + TestUtil.TEST_PASSWORD_SECRET_REFERENCE)) + .build()) + .property(TestUtil.TEST_ACTION_PROPERTY_NAME_1, TestUtil.TEST_ACTION_PROPERTY_VALUE_1) + .property(TestUtil.TEST_ACTION_PROPERTY_NAME_2, TestUtil.TEST_ACTION_PROPERTY_VALUE_2) + .build(); + try { + daoImpl.addAction(creatingActionDTO, TENANT_ID); + } catch (Exception e) { + Assert.fail(); + } + createdActionDTO = daoImpl.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_TYPE, PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, + TENANT_ID); + Assert.assertEquals(createdActionDTO.getId(), creatingActionDTO.getId()); + Assert.assertEquals(createdActionDTO.getType(), creatingActionDTO.getType()); + Assert.assertEquals(createdActionDTO.getName(), creatingActionDTO.getName()); + Assert.assertNull(createdActionDTO.getDescription()); + Assert.assertEquals(createdActionDTO.getStatus(), Action.Status.ACTIVE); + Assert.assertEquals(createdActionDTO.getEndpoint().getUri(), creatingActionDTO.getEndpoint().getUri()); + + Authentication createdAuthentication = createdActionDTO.getEndpoint().getAuthentication(); + Assert.assertEquals(createdAuthentication.getType(), + creatingActionDTO.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(createdAuthentication.getProperties().size(), + creatingActionDTO.getEndpoint().getAuthentication().getProperties().size()); + Assert.assertEquals(createdAuthentication.getProperty(Authentication.Property.USERNAME).getValue(), + TestUtil.TEST_USERNAME_SECRET_REFERENCE); + Assert.assertEquals(createdAuthentication.getProperty(Authentication.Property.PASSWORD).getValue(), + TestUtil.TEST_PASSWORD_SECRET_REFERENCE); + + Assert.assertEquals(createdActionDTO.getProperties().size(), creatingActionDTO.getProperties().size()); + Assert.assertEquals(createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1), + creatingActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1)); + Assert.assertEquals(createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2), + creatingActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2)); } @Test(priority = 7, dependsOnMethods = "testAddActionWithoutDescription") - public void testUpdateAction() throws ActionMgtException { - - Action updatingAction = buildMockAction( - "Pre Issue Access Token", - "To configure pre issue access token", - "https://sample.com", - buildMockBasicAuthentication("updatingadmin", "updatingadmin")); - Action result = daoImpl.updateAction(PRE_ISSUE_ACCESS_TOKEN, action.getId(), updatingAction, action, TENANT_ID); - Assert.assertEquals(action.getId(), result.getId()); - Assert.assertEquals(updatingAction.getName(), result.getName()); - Assert.assertEquals(updatingAction.getDescription(), result.getDescription()); - Assert.assertEquals(action.getType(), result.getType()); - Assert.assertEquals(action.getStatus(), result.getStatus()); - Assert.assertEquals(updatingAction.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals( - updatingAction.getEndpoint().getAuthentication().getType(), - result.getEndpoint().getAuthentication().getType() - ); - action = result; + public void testUpdateCompleteAction() throws ActionMgtException { + + ActionDTO updatingAction = new ActionDTOBuilder() + .id(createdActionDTO.getId()) + .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) + .name(TestUtil.TEST_ACTION_NAME_UPDATED) + .description(TestUtil.TEST_ACTION_DESCRIPTION_UPDATED) + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .uri(TestUtil.TEST_ACTION_URI_UPDATED) + .authentication(TestUtil.buildMockBearerAuthentication( + TestUtil.TEST_ACCESS_TOKEN_SECRET_REFERENCE)) + .build()) + .property(TestUtil.TEST_ACTION_PROPERTY_NAME_1, TestUtil.TEST_ACTION_PROPERTY_VALUE_1_UPDATED) + .property(TestUtil.TEST_ACTION_PROPERTY_NAME_2, TestUtil.TEST_ACTION_PROPERTY_VALUE_2_UPDATED) + .build(); + try { + daoImpl.updateAction(updatingAction, createdActionDTO, TENANT_ID); + } catch (Exception e) { + Assert.fail(); + } + ActionDTO result = daoImpl.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_TYPE, updatingAction.getId(), TENANT_ID); + Assert.assertEquals(result.getId(), createdActionDTO.getId()); + Assert.assertEquals(result.getType(), createdActionDTO.getType()); + Assert.assertEquals(result.getName(), updatingAction.getName()); + Assert.assertEquals(result.getDescription(), updatingAction.getDescription()); + Assert.assertEquals(result.getStatus(), createdActionDTO.getStatus()); + Assert.assertEquals(result.getEndpoint().getUri(), updatingAction.getEndpoint().getUri()); + + Authentication updatedAuthentication = result.getEndpoint().getAuthentication(); + Assert.assertEquals(updatedAuthentication.getType(), + updatingAction.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(updatedAuthentication.getProperties().size(), + updatingAction.getEndpoint().getAuthentication().getProperties().size()); + Assert.assertEquals(updatedAuthentication.getProperty(Authentication.Property.ACCESS_TOKEN).getValue(), + TestUtil.TEST_ACCESS_TOKEN_SECRET_REFERENCE); + + Assert.assertEquals(result.getProperties().size(), updatingAction.getProperties().size()); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1), + updatingAction.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1)); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2), + updatingAction.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2)); + createdActionDTO = result; } @Test(priority = 8) - public void testUpdateActionWithoutNameAndDescription() throws ActionMgtException { - - // TODO: 'Name' is a required attribute. Thus, DAO layer should throw an exception if name is null. - // This should be fixed in DAO layer and test case needs to be updated accordingly. - Action updatingAction = buildMockAction( - null, - null, - "https://sample.com", - buildMockBasicAuthentication("updatingadmin", "updatingadmin")); - Action result = daoImpl.updateAction(PRE_ISSUE_ACCESS_TOKEN, action.getId(), updatingAction, action, TENANT_ID); - Assert.assertEquals(action.getId(), result.getId()); - Assert.assertEquals(action.getName(), result.getName()); - Assert.assertEquals(action.getDescription(), result.getDescription()); - Assert.assertEquals(action.getType(), result.getType()); - Assert.assertEquals(action.getStatus(), result.getStatus()); - Assert.assertEquals(updatingAction.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals(updatingAction.getEndpoint().getAuthentication().getType(), - result.getEndpoint().getAuthentication().getType()); - } + public void testUpdateActionBasicInfo() throws ActionMgtException { - @Test(priority = 9) - public void testUpdateActionWithNameAndDescription() throws ActionMgtException { - - // TODO: 'Uri','AuthenticationType','AuthProperties' are required attributes. Thus, DAO layer should throw an - // exception if those attributes are null. This should be fixed in DAO layer and test case needs to be updated - // accordingly. - Action updatingAction = buildMockAction( - "Pre Issue Access Token", - "To configure pre issue access token", - null, - null); - Action result = daoImpl.updateAction(PRE_ISSUE_ACCESS_TOKEN, action.getId(), updatingAction, action, TENANT_ID); - Assert.assertEquals(action.getId(), result.getId()); - Assert.assertEquals(updatingAction.getName(), result.getName()); - Assert.assertEquals(updatingAction.getDescription(), result.getDescription()); - Assert.assertEquals(action.getType(), result.getType()); - Assert.assertEquals(action.getStatus(), result.getStatus()); - Assert.assertEquals(action.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals(action.getEndpoint().getAuthentication().getType(), - result.getEndpoint().getAuthentication().getType()); - } + ActionDTO updatingAction = new ActionDTOBuilder() + .id(createdActionDTO.getId()) + .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) + .name(TestUtil.TEST_ACTION_NAME) + .description(TestUtil.TEST_ACTION_DESCRIPTION) + .build(); - @Test(priority = 10) - public void testUpdateActionEndpointAuthSecretProperties() throws ActionMgtException { - - Authentication authentication = buildMockBasicAuthentication("newadmin", "newadmin"); - Action result = daoImpl.updateActionEndpointAuthProperties(PRE_ISSUE_ACCESS_TOKEN, action.getId(), - authentication, TENANT_ID); - Assert.assertEquals(Authentication.Type.BASIC, result.getEndpoint().getAuthentication().getType()); - Assert.assertEquals( - action.getEndpoint().getAuthentication().getProperty(Authentication.Property.USERNAME).getValue(), - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.USERNAME).getValue()); - Assert.assertEquals( - action.getEndpoint().getAuthentication().getProperty(Authentication.Property.PASSWORD).getValue(), - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.PASSWORD).getValue()); + try { + daoImpl.updateAction(updatingAction, createdActionDTO, TENANT_ID); + } catch (Exception e) { + Assert.fail(); + } + ActionDTO result = daoImpl.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_TYPE, updatingAction.getId(), TENANT_ID); + Assert.assertEquals(result.getId(), createdActionDTO.getId()); + Assert.assertEquals(result.getType(), createdActionDTO.getType()); + Assert.assertEquals(result.getName(), updatingAction.getName()); + Assert.assertEquals(result.getDescription(), updatingAction.getDescription()); + Assert.assertEquals(result.getStatus(), createdActionDTO.getStatus()); + Assert.assertEquals(result.getEndpoint().getUri(), createdActionDTO.getEndpoint().getUri()); + + Authentication resultAuthentication = result.getEndpoint().getAuthentication(); + Assert.assertEquals(resultAuthentication.getType(), + createdActionDTO.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(resultAuthentication.getProperties().size(), + createdActionDTO.getEndpoint().getAuthentication().getProperties().size()); + Assert.assertEquals(resultAuthentication.getProperty(Authentication.Property.ACCESS_TOKEN).getValue(), + TestUtil.TEST_ACCESS_TOKEN_SECRET_REFERENCE); + + Assert.assertEquals(result.getProperties().size(), createdActionDTO.getProperties().size()); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1), + createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1)); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2), + createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2)); + createdActionDTO = result; } - @Test(priority = 11) - public void testUpdateActionWithoutEndpointUri() throws ActionMgtException { - - // TODO: 'Uri' is a required attribute. Thus, DAO layer should throw an exception if Uri is null. - // This should be fixed in DAO layer and test case needs to be updated accordingly. - Action updatingAction = buildMockAction( - "Pre Issue Access Token", - "To configure pre issue access token", - null, - buildMockBasicAuthentication("updatingadmin", "updatingadmin")); - Action result = daoImpl.updateAction(PRE_ISSUE_ACCESS_TOKEN, action.getId(), updatingAction, action, TENANT_ID); - Assert.assertEquals(action.getId(), result.getId()); - Assert.assertEquals(updatingAction.getName(), result.getName()); - Assert.assertEquals(updatingAction.getDescription(), result.getDescription()); - Assert.assertEquals(action.getType(), result.getType()); - Assert.assertEquals(action.getStatus(), result.getStatus()); - Assert.assertEquals(action.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals(updatingAction.getEndpoint().getAuthentication().getType(), - result.getEndpoint().getAuthentication().getType()); - } + @Test(priority = 9) + public void testUpdateActionEndpoint() throws ActionMgtException { - @Test(priority = 12) - public void testUpdateActionWithAuthType() throws ActionMgtException { - - Action updatingAction = buildMockAction( - "Pre Issue Access Token", - "To configure pre issue access token", - "https://sample.com", - buildMockBearerAuthentication("57c7df90-cacc-4f56-9b0a-f14bfbff3076")); - Action result = daoImpl.updateAction(PRE_ISSUE_ACCESS_TOKEN, action.getId(), updatingAction, action, TENANT_ID); - Assert.assertEquals(action.getId(), result.getId()); - Assert.assertEquals(action.getName(), result.getName()); - Assert.assertEquals(action.getDescription(), result.getDescription()); - Assert.assertEquals(action.getType(), result.getType()); - Assert.assertEquals(action.getStatus(), result.getStatus()); - Assert.assertEquals(updatingAction.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals(updatingAction.getEndpoint().getAuthentication().getType(), - result.getEndpoint().getAuthentication().getType()); - action = result; - } + ActionDTO updatingAction = new ActionDTOBuilder() + .id(createdActionDTO.getId()) + .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .uri(TestUtil.TEST_ACTION_URI) + .authentication(TestUtil.buildMockAPIKeyAuthentication(TestUtil.TEST_API_KEY_HEADER, + TestUtil.TEST_API_KEY_VALUE_SECRET_REFERENCE)) + .build()) + .build(); - @Test(priority = 13) - public void testUpdateActionWithUri() throws ActionMgtException { - - // TODO: 'Name','AuthenticationType' and 'AuthProperties' are required attributes. Thus, DAO layer should throw - // an exception if those attributes are null. This should be fixed in DAO layer and test case needs to be - // updated accordingly. - Action updatingAction = buildMockAction( - null, - null, - "https://sample.com", - null); - Action result = daoImpl.updateAction(PRE_ISSUE_ACCESS_TOKEN, action.getId(), updatingAction, action, TENANT_ID); - Assert.assertEquals(action.getId(), result.getId()); - Assert.assertEquals(action.getName(), result.getName()); - Assert.assertEquals(action.getDescription(), result.getDescription()); - Assert.assertEquals(action.getType(), result.getType()); - Assert.assertEquals(action.getStatus(), result.getStatus()); - Assert.assertEquals(updatingAction.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals(action.getEndpoint().getAuthentication().getType(), - result.getEndpoint().getAuthentication().getType()); - action = result; + try { + daoImpl.updateAction(updatingAction, createdActionDTO, TENANT_ID); + } catch (Exception e) { + Assert.fail(); + } + ActionDTO result = daoImpl.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_TYPE, updatingAction.getId(), TENANT_ID); + Assert.assertEquals(result.getId(), createdActionDTO.getId()); + Assert.assertEquals(result.getType(), createdActionDTO.getType()); + Assert.assertEquals(result.getName(), createdActionDTO.getName()); + Assert.assertEquals(result.getDescription(), createdActionDTO.getDescription()); + Assert.assertEquals(result.getStatus(), createdActionDTO.getStatus()); + Assert.assertEquals(result.getEndpoint().getUri(), updatingAction.getEndpoint().getUri()); + + Authentication updatedAuthentication = result.getEndpoint().getAuthentication(); + Assert.assertEquals(updatedAuthentication.getType(), + updatingAction.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(updatedAuthentication.getProperties().size(), + updatingAction.getEndpoint().getAuthentication().getProperties().size()); + Assert.assertEquals(updatedAuthentication.getProperty(Authentication.Property.HEADER).getValue(), + TestUtil.TEST_API_KEY_HEADER); + Assert.assertEquals(updatedAuthentication.getProperty(Authentication.Property.VALUE).getValue(), + TestUtil.TEST_API_KEY_VALUE_SECRET_REFERENCE); + + Assert.assertEquals(result.getProperties().size(), createdActionDTO.getProperties().size()); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1), + createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1)); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2), + createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2)); + createdActionDTO = result; } - @Test(priority = 14) - public void testUpdateActionWithAuthTypeWithoutUri() throws ActionMgtException { - - // TODO: 'Uri' is a required attribute. Thus, DAO layer should throw an exception if uri is null. - // This should be fixed in DAO layer and test case needs to be updated accordingly. - Action updatingAction = buildMockAction( - "Pre Issue Access Token", - "To configure pre issue access token", - null, - buildMockBasicAuthentication("updatingadmin", "updatingadmin")); - Action result = daoImpl.updateAction(PRE_ISSUE_ACCESS_TOKEN, action.getId(), updatingAction, action, TENANT_ID); - Assert.assertEquals(action.getId(), result.getId()); - Assert.assertEquals(updatingAction.getName(), result.getName()); - Assert.assertEquals(updatingAction.getDescription(), result.getDescription()); - Assert.assertEquals(action.getType(), result.getType()); - Assert.assertEquals(action.getStatus(), result.getStatus()); - Assert.assertEquals(action.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals(updatingAction.getEndpoint().getAuthentication().getType(), - result.getEndpoint().getAuthentication().getType()); - } + @Test(priority = 10) + public void testUpdateActionEndpointUri() throws ActionMgtException { + + ActionDTO updatingAction = new ActionDTOBuilder() + .id(createdActionDTO.getId()) + .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .uri(TestUtil.TEST_ACTION_URI_UPDATED) + .build()) + .build(); - @Test(priority = 15) - public void testUpdateActionEndpointAuthNonSecretProperties() throws ActionMgtException { - - Action sampleAction = buildMockAction( - "Pre Issue Access Token", - "To configure pre issue access token", - "https://sample.com", - buildMockAPIKeyAuthentication("header", "value")); - Action updatingAction = daoImpl.updateAction( - PRE_ISSUE_ACCESS_TOKEN, action.getId(), sampleAction, action, TENANT_ID); - Authentication authentication = buildMockAPIKeyAuthentication("updatingheader", "updatingvalue"); - Action result = daoImpl.updateActionEndpointAuthProperties(PRE_ISSUE_ACCESS_TOKEN, updatingAction.getId(), - authentication, TENANT_ID); - Assert.assertEquals(Authentication.Type.API_KEY, result.getEndpoint().getAuthentication().getType()); - Assert.assertEquals(authentication.getProperty(Authentication.Property.HEADER).getValue(), - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.HEADER).getValue()); - Assert.assertEquals( - updatingAction.getEndpoint().getAuthentication().getProperty(Authentication.Property.VALUE).getValue(), - result.getEndpoint().getAuthentication().getProperty(Authentication.Property.VALUE).getValue()); + try { + daoImpl.updateAction(updatingAction, createdActionDTO, TENANT_ID); + } catch (Exception e) { + Assert.fail(); + } + ActionDTO result = daoImpl.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_TYPE, updatingAction.getId(), TENANT_ID); + Assert.assertEquals(result.getId(), createdActionDTO.getId()); + Assert.assertEquals(result.getType(), createdActionDTO.getType()); + Assert.assertEquals(result.getName(), createdActionDTO.getName()); + Assert.assertEquals(result.getDescription(), createdActionDTO.getDescription()); + Assert.assertEquals(result.getStatus(), createdActionDTO.getStatus()); + Assert.assertEquals(result.getEndpoint().getUri(), updatingAction.getEndpoint().getUri()); + + Authentication resultAuthentication = result.getEndpoint().getAuthentication(); + Assert.assertEquals(resultAuthentication.getType(), + createdActionDTO.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(resultAuthentication.getProperties().size(), + createdActionDTO.getEndpoint().getAuthentication().getProperties().size()); + Assert.assertEquals(resultAuthentication.getProperty(Authentication.Property.HEADER).getValue(), + TestUtil.TEST_API_KEY_HEADER); + Assert.assertEquals(resultAuthentication.getProperty(Authentication.Property.VALUE).getValue(), + TestUtil.TEST_API_KEY_VALUE_SECRET_REFERENCE); + + Assert.assertEquals(result.getProperties().size(), createdActionDTO.getProperties().size()); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1), + createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1)); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2), + createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2)); + createdActionDTO = result; } - @Test(priority = 16) - public void testDeactivateAction() throws ActionMgtException { + @Test(priority = 11) + public void testUpdateActionEndpointAuthenticationWithSameAuthType() throws ActionMgtException { + + ActionDTO updatingAction = new ActionDTOBuilder() + .id(createdActionDTO.getId()) + .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .authentication(TestUtil.buildMockAPIKeyAuthentication(TestUtil.TEST_API_KEY_HEADER_UPDATED, + TestUtil.TEST_API_KEY_VALUE_SECRET_REFERENCE)) + .build()) + .build(); - Assert.assertEquals(Action.Status.ACTIVE, action.getStatus()); - Action deactivatedAction = daoImpl.deactivateAction(PRE_ISSUE_ACCESS_TOKEN, action.getId(), TENANT_ID); - Assert.assertEquals(Action.Status.INACTIVE, deactivatedAction.getStatus()); + try { + daoImpl.updateAction(updatingAction, createdActionDTO, TENANT_ID); + } catch (Exception e) { + Assert.fail(); + } + ActionDTO result = daoImpl.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_TYPE, updatingAction.getId(), TENANT_ID); + Assert.assertEquals(result.getId(), createdActionDTO.getId()); + Assert.assertEquals(result.getType(), createdActionDTO.getType()); + Assert.assertEquals(result.getName(), createdActionDTO.getName()); + Assert.assertEquals(result.getDescription(), createdActionDTO.getDescription()); + Assert.assertEquals(result.getStatus(), createdActionDTO.getStatus()); + Assert.assertEquals(result.getEndpoint().getUri(), createdActionDTO.getEndpoint().getUri()); + + Authentication updatedAuthentication = result.getEndpoint().getAuthentication(); + Assert.assertEquals(updatedAuthentication.getType(), + updatingAction.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(updatedAuthentication.getProperties().size(), + updatingAction.getEndpoint().getAuthentication().getProperties().size()); + Assert.assertEquals(updatedAuthentication.getProperty(Authentication.Property.HEADER).getValue(), + TestUtil.TEST_API_KEY_HEADER_UPDATED); + Assert.assertEquals(updatedAuthentication.getProperty(Authentication.Property.VALUE).getValue(), + TestUtil.TEST_API_KEY_VALUE_SECRET_REFERENCE); + + Assert.assertEquals(result.getProperties().size(), createdActionDTO.getProperties().size()); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1), + createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1)); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2), + createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2)); + createdActionDTO = result; } - @Test(priority = 17) - public void testActivateAction() throws ActionMgtException { + @Test(priority = 12) + public void testUpdateActionEndpointAuthenticationWithDifferentAuthType() throws ActionMgtException { + + ActionDTO updatingAction = new ActionDTOBuilder() + .id(createdActionDTO.getId()) + .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .authentication(new Authentication.NoneAuthBuilder().build()) + .build()) + .build(); - Action result = daoImpl.activateAction(PRE_ISSUE_ACCESS_TOKEN, action.getId(), TENANT_ID); - Assert.assertEquals(Action.Status.ACTIVE, result.getStatus()); + try { + daoImpl.updateAction(updatingAction, createdActionDTO, TENANT_ID); + } catch (Exception e) { + Assert.fail(); + } + ActionDTO result = daoImpl.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_TYPE, updatingAction.getId(), TENANT_ID); + Assert.assertEquals(result.getId(), createdActionDTO.getId()); + Assert.assertEquals(result.getType(), createdActionDTO.getType()); + Assert.assertEquals(result.getName(), createdActionDTO.getName()); + Assert.assertEquals(result.getDescription(), createdActionDTO.getDescription()); + Assert.assertEquals(result.getStatus(), createdActionDTO.getStatus()); + Assert.assertEquals(result.getEndpoint().getUri(), createdActionDTO.getEndpoint().getUri()); + + Authentication updatedAuthentication = result.getEndpoint().getAuthentication(); + Assert.assertEquals(updatedAuthentication.getType(), + updatingAction.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(updatedAuthentication.getProperties().size(), + updatingAction.getEndpoint().getAuthentication().getProperties().size()); + + Assert.assertEquals(result.getProperties().size(), createdActionDTO.getProperties().size()); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1), + createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1)); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2), + createdActionDTO.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2)); + createdActionDTO = result; } - @Test(priority = 18) - public void testUpdateActionEndpoint() throws ActionMgtException { - - EndpointConfig endpointConfig = buildMockEndpointConfig("https://template.com", - buildMockBearerAuthentication("c7fce95f-3f5b-4cda-8bb1-4cb7b3990f83")); - Action result = daoImpl.updateActionEndpoint( - PRE_ISSUE_ACCESS_TOKEN, action.getId(), endpointConfig, action.getEndpoint() - .getAuthentication(), TENANT_ID); - Assert.assertNotEquals(action.getEndpoint().getUri(), result.getEndpoint().getUri()); - Assert.assertEquals(Authentication.Type.BEARER.getName(), - result.getEndpoint().getAuthentication().getType().getName()); - } + @Test(priority = 13) + public void testUpdateActionProperties() throws ActionMgtException { - @Test(priority = 19) - public void testGetActionsCountPerType() throws ActionMgtException { + ActionDTO updatingAction = new ActionDTOBuilder() + .id(createdActionDTO.getId()) + .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) + .property(TestUtil.TEST_ACTION_PROPERTY_NAME_1, TestUtil.TEST_ACTION_PROPERTY_VALUE_1) + .property(TestUtil.TEST_ACTION_PROPERTY_NAME_2, TestUtil.TEST_ACTION_PROPERTY_VALUE_2) + .build(); - Map actionMap = daoImpl.getActionsCountPerType(TENANT_ID); - for (Map.Entry entry: actionMap.entrySet()) { - Assert.assertEquals(PRE_ISSUE_ACCESS_TOKEN, entry.getKey()); - Assert.assertEquals(1, entry.getValue().intValue()); + try { + daoImpl.updateAction(updatingAction, createdActionDTO, TENANT_ID); + } catch (Exception e) { + Assert.fail(); } + ActionDTO result = daoImpl.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_TYPE, updatingAction.getId(), TENANT_ID); + Assert.assertEquals(result.getId(), createdActionDTO.getId()); + Assert.assertEquals(result.getType(), createdActionDTO.getType()); + Assert.assertEquals(result.getName(), createdActionDTO.getName()); + Assert.assertEquals(result.getDescription(), createdActionDTO.getDescription()); + Assert.assertEquals(result.getStatus(), createdActionDTO.getStatus()); + Assert.assertEquals(result.getEndpoint().getUri(), createdActionDTO.getEndpoint().getUri()); + + Authentication resultAuthentication = result.getEndpoint().getAuthentication(); + Assert.assertEquals(resultAuthentication.getType(), + createdActionDTO.getEndpoint().getAuthentication().getType()); + Assert.assertEquals(resultAuthentication.getProperties().size(), + createdActionDTO.getEndpoint().getAuthentication().getProperties().size()); + + Assert.assertEquals(result.getProperties().size(), updatingAction.getProperties().size()); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1), + updatingAction.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_1)); + Assert.assertEquals(result.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2), + updatingAction.getProperty(TestUtil.TEST_ACTION_PROPERTY_NAME_2)); + createdActionDTO = result; } - private Authentication buildMockBasicAuthentication(String username, String password) { - - return new Authentication.BasicAuthBuilder(username, password).build(); - } - private Authentication buildMockBearerAuthentication(String accessToken) { + @Test(priority = 14) + public void testDeactivateAction() throws ActionMgtException { - return new Authentication.BearerAuthBuilder(accessToken).build(); + Assert.assertEquals(createdActionDTO.getStatus(), Action.Status.ACTIVE); + ActionDTO deactivatedActionDTO = daoImpl.deactivateAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, createdActionDTO.getId(), + TENANT_ID); + Assert.assertEquals(deactivatedActionDTO.getStatus(), Action.Status.INACTIVE); } - private Authentication buildMockAPIKeyAuthentication(String header, String value) { + @Test(priority = 15) + public void testActivateAction() throws ActionMgtException { - return new Authentication.APIKeyAuthBuilder(header, value).build(); + ActionDTO activatedActionDTO = daoImpl.activateAction(PRE_ISSUE_ACCESS_TOKEN_TYPE, createdActionDTO.getId(), + TENANT_ID); + Assert.assertEquals(activatedActionDTO.getStatus(), Action.Status.ACTIVE); } - private EndpointConfig buildMockEndpointConfig(String uri, Authentication authentication) { - - if (uri == null && authentication == null) { - return null; - } + @Test(priority = 16) + public void testGetActionsCountPerType() throws ActionMgtException { - return new EndpointConfig.EndpointConfigBuilder() - .uri(uri) - .authentication(authentication) + ActionDTO creatingPreUpdatePasswordActionDTO = new ActionDTOBuilder() + .id(PRE_UPDATE_PASSWORD_ACTION_ID) + .type(Action.ActionTypes.PRE_UPDATE_PASSWORD) + .name(TestUtil.TEST_ACTION_NAME) + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .uri(TestUtil.TEST_ACTION_URI) + .authentication(new Authentication.NoneAuthBuilder().build()) + .build()) .build(); - } - private Action buildMockAction(String name, - String description, - String uri, - Authentication authentication) { + daoImpl.addAction(creatingPreUpdatePasswordActionDTO, TENANT_ID); + ActionDTO createdPreUpdatePasswordActionDTO = daoImpl.getActionByActionId(PRE_UPDATE_PASSWORD_TYPE, + PRE_UPDATE_PASSWORD_ACTION_ID, TENANT_ID); - return new Action.ActionRequestBuilder() - .name(name) - .description(description) - .endpoint(buildMockEndpointConfig(uri, authentication)) - .build(); + Map actionMap = daoImpl.getActionsCountPerType(TENANT_ID); + Assert.assertTrue(actionMap.containsKey(PRE_ISSUE_ACCESS_TOKEN_TYPE)); + Assert.assertEquals(actionMap.get(PRE_ISSUE_ACCESS_TOKEN_TYPE).intValue(), 1); + Assert.assertTrue(actionMap.containsKey(PRE_UPDATE_PASSWORD_TYPE)); + Assert.assertEquals(actionMap.get(PRE_UPDATE_PASSWORD_TYPE).intValue(), 1); + + daoImpl.deleteAction(createdPreUpdatePasswordActionDTO, TENANT_ID); + daoImpl.deleteAction(createdActionDTO, TENANT_ID); } } diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/TestActionDTOModelResolver.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/TestActionDTOModelResolver.java new file mode 100644 index 000000000000..2b5424d40672 --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/dao/TestActionDTOModelResolver.java @@ -0,0 +1,111 @@ +/* + * 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.action.management.dao; + +import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.ActionDTO; +import org.wso2.carbon.identity.action.management.service.ActionDTOModelResolver; +import org.wso2.carbon.identity.action.management.util.TestUtil; +import org.wso2.carbon.identity.certificate.management.model.Certificate; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.wso2.carbon.identity.action.management.util.TestUtil.CERTIFICATE_NAME; +import static org.wso2.carbon.identity.action.management.util.TestUtil.CERTIFICATE_PROPERTY_NAME; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PASSWORD_SHARING_TYPE_PROPERTY_NAME; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_CERTIFICATE; + +/** + * Test implementation of {@link ActionDTOModelResolver}. + */ +public class TestActionDTOModelResolver implements ActionDTOModelResolver { + + @Override + public Action.ActionTypes getSupportedActionType() { + + return Action.ActionTypes.PRE_UPDATE_PASSWORD; + } + + @Override + public ActionDTO resolveForAddOperation(ActionDTO actionDTO, String tenantDomain) { + + Map properties = new HashMap<>(); + properties.put(PASSWORD_SHARING_TYPE_PROPERTY_NAME, actionDTO.getProperty(PASSWORD_SHARING_TYPE_PROPERTY_NAME)); + properties.put(CERTIFICATE_PROPERTY_NAME, TestUtil.CERTIFICATE_ID); + + return new ActionDTO.Builder(actionDTO).properties(properties).build(); + } + + @Override + public ActionDTO resolveForGetOperation(ActionDTO actionDTO, String tenantDomain) { + + Map properties = new HashMap<>(); + properties.put(PASSWORD_SHARING_TYPE_PROPERTY_NAME, + actionDTO.getProperty(PASSWORD_SHARING_TYPE_PROPERTY_NAME)); + if (actionDTO.getProperty(CERTIFICATE_PROPERTY_NAME) != null) { + properties.put(CERTIFICATE_PROPERTY_NAME, new Certificate.Builder() + .id((String) actionDTO.getProperty(CERTIFICATE_PROPERTY_NAME)) + .name(CERTIFICATE_NAME) + .certificateContent(TEST_CERTIFICATE) + .build()); + } + + return new ActionDTO.Builder(actionDTO).properties(properties).build(); + } + + @Override + public List resolveForGetOperation(List actionDTOList, String tenantDomain) { + + List resolvedActionDTOList = new ArrayList<>(); + for (ActionDTO actionDTO : actionDTOList) { + Map properties = new HashMap<>(); + properties.put(PASSWORD_SHARING_TYPE_PROPERTY_NAME, + actionDTO.getProperty(PASSWORD_SHARING_TYPE_PROPERTY_NAME)); + properties.put(CERTIFICATE_PROPERTY_NAME, new Certificate.Builder() + .id((String) actionDTO.getProperty(CERTIFICATE_PROPERTY_NAME)) + .name(CERTIFICATE_NAME) + .certificateContent(TEST_CERTIFICATE) + .build()); + + resolvedActionDTOList.add(new ActionDTO.Builder(actionDTO).properties(properties).build()); + } + + return resolvedActionDTOList; + } + + @Override + public ActionDTO resolveForUpdateOperation(ActionDTO updatingActionDTO, ActionDTO existingActionDTO, + String tenantDomain) { + + Map properties = new HashMap<>(); + properties.put(PASSWORD_SHARING_TYPE_PROPERTY_NAME, + updatingActionDTO.getProperty(PASSWORD_SHARING_TYPE_PROPERTY_NAME)); + + return new ActionDTO.Builder(updatingActionDTO).properties(properties).build(); + } + + @Override + public void resolveForDeleteOperation(ActionDTO deletingActionDTO, String tenantDomain) { + + // No need to resolve anything for delete operation since this is a test implementation. + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/ActionConverterFactoryTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/ActionConverterFactoryTest.java new file mode 100644 index 000000000000..424926205532 --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/ActionConverterFactoryTest.java @@ -0,0 +1,69 @@ +/* + * 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.action.management.service; + +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.testng.Assert; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; +import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.service.impl.ActionConverterFactory; + +import static org.mockito.Mockito.doReturn; + +/** + * Action Converter Factory Test. + */ +public class ActionConverterFactoryTest { + + private final Action.ActionTypes actionType = Action.ActionTypes.PRE_UPDATE_PASSWORD; + @Mock + private ActionConverter mockActionConverter; + + @BeforeMethod + public void setUp() { + + MockitoAnnotations.openMocks(this); + doReturn(actionType).when(mockActionConverter).getSupportedActionType(); + } + + @Test + public void testRegisterActionConverter() { + + ActionConverterFactory.registerActionConverter(mockActionConverter); + ActionConverter registeredResult = ActionConverterFactory.getActionConverter(actionType); + Assert.assertEquals(registeredResult, mockActionConverter); + } + + @Test(dependsOnMethods = {"testRegisterActionConverter"}) + public void testUnregisterActionConverter() { + + ActionConverterFactory.unregisterActionConverter(mockActionConverter); + ActionConverter unregisteredResult = ActionConverterFactory.getActionConverter(actionType); + Assert.assertNull(unregisteredResult); + } + + @Test(dependsOnMethods = {"testUnregisterActionConverter"}) + public void testGetActionConverterNotFound() { + + ActionConverter result = ActionConverterFactory.getActionConverter(actionType); + Assert.assertNull(result); + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/ActionManagementServiceImplTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/ActionManagementServiceImplTest.java new file mode 100644 index 000000000000..1d159ec3bcde --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/ActionManagementServiceImplTest.java @@ -0,0 +1,330 @@ +/* + * 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.action.management.service; + +import org.apache.commons.lang.StringUtils; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; +import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; +import org.wso2.carbon.identity.action.management.exception.ActionMgtException; +import org.wso2.carbon.identity.action.management.internal.ActionMgtServiceComponentHolder; +import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.AuthProperty; +import org.wso2.carbon.identity.action.management.model.Authentication; +import org.wso2.carbon.identity.action.management.service.impl.ActionManagementServiceImpl; +import org.wso2.carbon.identity.action.management.util.TestUtil; +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.core.internal.IdentityCoreServiceDataHolder; +import org.wso2.carbon.identity.secret.mgt.core.SecretManagerImpl; +import org.wso2.carbon.identity.secret.mgt.core.exception.SecretManagementException; +import org.wso2.carbon.identity.secret.mgt.core.model.SecretType; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_ISSUE_ACCESS_TOKEN_PATH; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TENANT_DOMAIN; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACCESS_TOKEN; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_DESCRIPTION; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_DESCRIPTION_UPDATED; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_NAME; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_NAME_UPDATED; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_URI; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_API_KEY_HEADER; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_API_KEY_HEADER_UPDATED; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_API_KEY_VALUE; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_API_KEY_VALUE_UPDATED; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_INVALID_ACTION_NAME; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_INVALID_API_KEY_HEADER; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_PASSWORD; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_USERNAME; + +/** + * This class is a test suite for the ActionManagementServiceImpl class. + * It contains unit tests to verify the functionality of the methods + * in the ActionManagementServiceImpl class. + */ +@WithCarbonHome +@WithH2Database(files = {"dbscripts/h2.sql"}) +@WithRealmService(injectToSingletons = {IdentityCoreServiceDataHolder.class}) +public class ActionManagementServiceImplTest { + + private ActionManagementService actionManagementService; + private Action sampleAction; + + @BeforeClass + public void setUpClass() { + + actionManagementService = new ActionManagementServiceImpl(); + } + + @BeforeMethod + public void setUp() throws SecretManagementException { + + SecretManagerImpl secretManager = mock(SecretManagerImpl.class); + SecretType secretType = mock(SecretType.class); + ActionMgtServiceComponentHolder.getInstance().setSecretManager(secretManager); + when(secretType.getId()).thenReturn(TestUtil.TEST_SECRET_TYPE_ID); + when(secretManager.getSecretType(any())).thenReturn(secretType); + } + + @Test(priority = 1) + public void testAddAction() throws ActionMgtException, SecretManagementException { + + Action creatingAction = TestUtil.buildMockAction( + TEST_ACTION_NAME, + TEST_ACTION_DESCRIPTION, + TEST_ACTION_URI, + TestUtil.buildMockBasicAuthentication(TEST_USERNAME, TEST_PASSWORD)); + sampleAction = actionManagementService.addAction(PRE_ISSUE_ACCESS_TOKEN_PATH, creatingAction, TENANT_DOMAIN); + + Assert.assertNotNull(sampleAction.getId()); + Assert.assertEquals(sampleAction.getName(), creatingAction.getName()); + Assert.assertEquals(sampleAction.getDescription(), creatingAction.getDescription()); + Assert.assertEquals(sampleAction.getStatus(), Action.Status.ACTIVE); + Assert.assertEquals(sampleAction.getType(), Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN); + Assert.assertEquals(sampleAction.getEndpoint().getUri(), creatingAction.getEndpoint().getUri()); + + Authentication sampleActionAuth = sampleAction.getEndpoint().getAuthentication(); + Authentication creatingActionAuth = creatingAction.getEndpoint().getAuthentication(); + Map secretProperties = resolveAuthPropertiesMap(creatingActionAuth, sampleAction.getId()); + + Assert.assertEquals(sampleActionAuth.getType(), creatingActionAuth.getType()); + Assert.assertEquals(sampleActionAuth.getProperties().size(), creatingActionAuth.getProperties().size()); + Assert.assertEquals(sampleActionAuth.getProperty(Authentication.Property.USERNAME).getValue(), + secretProperties.get(Authentication.Property.USERNAME.getName())); + Assert.assertEquals(sampleActionAuth.getProperty(Authentication.Property.PASSWORD).getValue(), + secretProperties.get(Authentication.Property.PASSWORD.getName())); + } + + @Test(priority = 2, expectedExceptions = ActionMgtClientException.class, + expectedExceptionsMessageRegExp = "Invalid request.") + public void testAddActionWithInvalidData() throws ActionMgtException { + Action creatingAction = TestUtil.buildMockAction( + TEST_INVALID_ACTION_NAME, + TEST_ACTION_DESCRIPTION, + TEST_ACTION_URI, + TestUtil.buildMockAPIKeyAuthentication(TEST_INVALID_API_KEY_HEADER, TEST_API_KEY_VALUE)); + Action action = actionManagementService.addAction(PRE_ISSUE_ACCESS_TOKEN_PATH, creatingAction, TENANT_DOMAIN); + Assert.assertNull(action); + } + + @Test(priority = 3, expectedExceptions = ActionMgtClientException.class, + expectedExceptionsMessageRegExp = "Invalid request.") + public void testAddActionWithEmptyData() throws ActionMgtException { + Action creatingAction = TestUtil.buildMockAction( + StringUtils.EMPTY, + TEST_ACTION_DESCRIPTION, + TEST_ACTION_URI, + TestUtil.buildMockBasicAuthentication(null, TEST_PASSWORD)); + Action action = actionManagementService.addAction(PRE_ISSUE_ACCESS_TOKEN_PATH, creatingAction, TENANT_DOMAIN); + Assert.assertNull(action); + } + + @Test(priority = 4, expectedExceptions = ActionMgtException.class, + expectedExceptionsMessageRegExp = "Unable to create an Action.") + public void testAddMaximumActionsPerType() throws ActionMgtException { + + Action creatingAction = TestUtil.buildMockAction( + TEST_ACTION_NAME, + TEST_ACTION_DESCRIPTION, + TEST_ACTION_URI, + TestUtil.buildMockBasicAuthentication(TEST_USERNAME, TEST_PASSWORD)); + sampleAction = actionManagementService.addAction(PRE_ISSUE_ACCESS_TOKEN_PATH, creatingAction, + TENANT_DOMAIN); + } + + @Test(priority = 5) + public void testGetActionsByActionType() throws ActionMgtException { + + List actions = actionManagementService.getActionsByActionType(PRE_ISSUE_ACCESS_TOKEN_PATH, + TENANT_DOMAIN); + Assert.assertEquals(actions.size(), 1); + Action result = actions.get(0); + Assert.assertEquals(result.getId(), sampleAction.getId()); + Assert.assertEquals(result.getName(), sampleAction.getName()); + Assert.assertEquals(result.getDescription(), sampleAction.getDescription()); + Assert.assertEquals(result.getType().getActionType(), sampleAction.getType().getActionType()); + Assert.assertEquals(result.getStatus(), sampleAction.getStatus()); + Assert.assertEquals(result.getEndpoint().getUri(), sampleAction.getEndpoint().getUri()); + + Authentication resultActionAuth = result.getEndpoint().getAuthentication(); + Authentication sampleActionAuth = sampleAction.getEndpoint().getAuthentication(); + + Assert.assertEquals(resultActionAuth.getType(), sampleActionAuth.getType()); + Assert.assertEquals(resultActionAuth.getProperty(Authentication.Property.USERNAME).getValue(), + sampleActionAuth.getProperty(Authentication.Property.USERNAME).getValue()); + Assert.assertEquals(resultActionAuth.getProperty(Authentication.Property.PASSWORD).getValue(), + sampleActionAuth.getProperty(Authentication.Property.PASSWORD).getValue()); + } + + @Test(priority = 6) + public void testGetActionByActionId() throws ActionMgtException { + + Action result = actionManagementService.getActionByActionId(sampleAction.getType().getPathParam(), + sampleAction.getId(), TENANT_DOMAIN); + Assert.assertEquals(result.getId(), sampleAction.getId()); + Assert.assertEquals(result.getName(), sampleAction.getName()); + Assert.assertEquals(result.getDescription(), sampleAction.getDescription()); + Assert.assertEquals(result.getType(), sampleAction.getType()); + Assert.assertEquals(result.getStatus(), sampleAction.getStatus()); + Assert.assertEquals(result.getEndpoint().getUri(), sampleAction.getEndpoint().getUri()); + + Authentication resultActionAuth = result.getEndpoint().getAuthentication(); + Authentication sampleActionAuth = sampleAction.getEndpoint().getAuthentication(); + + Assert.assertEquals(resultActionAuth.getType(), sampleActionAuth.getType()); + Assert.assertEquals(resultActionAuth.getProperty(Authentication.Property.USERNAME).getValue(), + sampleActionAuth.getProperty(Authentication.Property.USERNAME).getValue()); + Assert.assertEquals(resultActionAuth.getProperty(Authentication.Property.PASSWORD).getValue(), + sampleActionAuth.getProperty(Authentication.Property.PASSWORD).getValue()); + } + + @Test(priority = 7) + public void testUpdateAction() throws ActionMgtException, SecretManagementException { + + Action updatingAction = TestUtil.buildMockAction( + TEST_ACTION_NAME_UPDATED, + TEST_ACTION_DESCRIPTION_UPDATED, + TEST_ACTION_URI, + TestUtil.buildMockAPIKeyAuthentication(TEST_API_KEY_HEADER, TEST_API_KEY_VALUE)); + Action result = actionManagementService.updateAction(PRE_ISSUE_ACCESS_TOKEN_PATH, sampleAction.getId(), + updatingAction, TENANT_DOMAIN); + + Assert.assertEquals(result.getId(), sampleAction.getId()); + Assert.assertEquals(result.getName(), updatingAction.getName()); + Assert.assertEquals(result.getDescription(), updatingAction.getDescription()); + Assert.assertEquals(result.getType(), sampleAction.getType()); + Assert.assertEquals(result.getStatus(), sampleAction.getStatus()); + Assert.assertEquals(result.getEndpoint().getUri(), updatingAction.getEndpoint().getUri()); + + Authentication resultActionAuth = result.getEndpoint().getAuthentication(); + Authentication updatingActionAuth = updatingAction.getEndpoint().getAuthentication(); + Map secretProperties = resolveAuthPropertiesMap(updatingActionAuth, sampleAction.getId()); + + Assert.assertEquals(resultActionAuth.getType(), updatingActionAuth.getType()); + Assert.assertEquals(resultActionAuth.getProperty(Authentication.Property.HEADER).getValue(), + secretProperties.get(Authentication.Property.HEADER.getName())); + Assert.assertEquals(resultActionAuth.getProperty(Authentication.Property.VALUE).getValue(), + secretProperties.get(Authentication.Property.VALUE.getName())); + sampleAction = result; + } + + @Test(priority = 8) + public void testDeactivateAction() throws ActionMgtException { + + Assert.assertEquals(sampleAction.getStatus(), Action.Status.ACTIVE); + Action deactivatedAction = actionManagementService.deactivateAction(PRE_ISSUE_ACCESS_TOKEN_PATH, + sampleAction.getId(), TENANT_DOMAIN); + Assert.assertEquals(deactivatedAction.getStatus(), Action.Status.INACTIVE); + } + + @Test(priority = 9) + public void testActivateAction() throws ActionMgtException { + + Action activatedAction = actionManagementService.activateAction(PRE_ISSUE_ACCESS_TOKEN_PATH, + sampleAction.getId(), TENANT_DOMAIN); + Assert.assertEquals(activatedAction.getStatus(), Action.Status.ACTIVE); + } + + @Test(priority = 10) + public void testGetActionsCountPerType() throws ActionMgtException { + + Map actionMap = actionManagementService.getActionsCountPerType(TENANT_DOMAIN); + Assert.assertNull(actionMap.get(Action.ActionTypes.PRE_UPDATE_PASSWORD.getActionType())); + Assert.assertNull(actionMap.get(Action.ActionTypes.PRE_UPDATE_PROFILE.getActionType())); + Assert.assertNull(actionMap.get(Action.ActionTypes.PRE_REGISTRATION.getActionType())); + Assert.assertNull(actionMap.get(Action.ActionTypes.AUTHENTICATION.getActionType())); + for (Map.Entry entry: actionMap.entrySet()) { + Assert.assertEquals(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN.getActionType(), entry.getKey()); + Assert.assertEquals(entry.getValue().intValue(), 1); + } + } + + @Test(priority = 11) + public void testUpdateEndpointConfigWithSameAuthenticationType() throws ActionMgtException, + SecretManagementException { + + Authentication updatingAuthentication = TestUtil.buildMockAPIKeyAuthentication(TEST_API_KEY_HEADER_UPDATED, + TEST_API_KEY_VALUE_UPDATED); + Action result = actionManagementService.updateActionEndpointAuthentication(PRE_ISSUE_ACCESS_TOKEN_PATH, + sampleAction.getId(), updatingAuthentication, TENANT_DOMAIN); + + Authentication resultActionAuth = result.getEndpoint().getAuthentication(); + Map secretProperties = resolveAuthPropertiesMap(updatingAuthentication, sampleAction.getId()); + + Assert.assertEquals(resultActionAuth.getType(), updatingAuthentication.getType()); + Assert.assertEquals(resultActionAuth.getProperty(Authentication.Property.HEADER).getValue(), + secretProperties.get(Authentication.Property.HEADER.getName())); + Assert.assertEquals(resultActionAuth.getProperty(Authentication.Property.VALUE).getValue(), + secretProperties.get(Authentication.Property.VALUE.getName())); + } + + @Test(priority = 12) + public void testUpdateEndpointConfigWithDifferentAuthenticationType() + throws ActionMgtException, SecretManagementException { + + Authentication updatingAuthentication = TestUtil.buildMockBearerAuthentication(TEST_ACCESS_TOKEN); + Action result = actionManagementService.updateActionEndpointAuthentication(PRE_ISSUE_ACCESS_TOKEN_PATH, + sampleAction.getId(), updatingAuthentication, TENANT_DOMAIN); + + Authentication resultActionAuth = result.getEndpoint().getAuthentication(); + Map secretProperties = resolveAuthPropertiesMap(updatingAuthentication, sampleAction.getId()); + + Assert.assertEquals(resultActionAuth.getType(), updatingAuthentication.getType()); + Assert.assertEquals(resultActionAuth.getProperty(Authentication.Property.ACCESS_TOKEN).getValue(), + secretProperties.get(Authentication.Property.ACCESS_TOKEN.getName())); + } + + @Test(priority = 13) + public void testDeleteAction() throws ActionMgtException { + + actionManagementService.deleteAction(PRE_ISSUE_ACCESS_TOKEN_PATH, sampleAction.getId(), TENANT_DOMAIN); + Assert.assertNull(actionManagementService.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_PATH, sampleAction.getId(), + TENANT_DOMAIN)); + Map actions = actionManagementService.getActionsCountPerType(TENANT_DOMAIN); + Assert.assertNull(actions.get(PRE_ISSUE_ACCESS_TOKEN_PATH)); + } + + @Test(priority = 14) + public void testDeleteNonExistingAction() { + + try { + actionManagementService.deleteAction(PRE_ISSUE_ACCESS_TOKEN_PATH, "invalid_id", TENANT_DOMAIN); + } catch (Exception e) { + Assert.fail(); + } + } + + private Map resolveAuthPropertiesMap(Authentication authentication, String actionId) + throws SecretManagementException { + + return authentication.getPropertiesWithSecretReferences(actionId) + .stream() + .collect(Collectors.toMap(AuthProperty::getName, AuthProperty::getValue)); + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/CacheBackedActionManagementServiceTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/CacheBackedActionManagementServiceTest.java new file mode 100644 index 000000000000..29fb849cac01 --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/service/CacheBackedActionManagementServiceTest.java @@ -0,0 +1,309 @@ +/* + * 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.action.management.service; + +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; +import org.wso2.carbon.identity.action.management.exception.ActionMgtException; +import org.wso2.carbon.identity.action.management.internal.ActionMgtServiceComponentHolder; +import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.Authentication; +import org.wso2.carbon.identity.action.management.service.impl.ActionManagementServiceImpl; +import org.wso2.carbon.identity.action.management.service.impl.CacheBackedActionManagementService; +import org.wso2.carbon.identity.action.management.util.TestUtil; +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.core.internal.IdentityCoreServiceDataHolder; +import org.wso2.carbon.identity.secret.mgt.core.SecretManagerImpl; +import org.wso2.carbon.identity.secret.mgt.core.model.SecretType; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_ISSUE_ACCESS_TOKEN_ACTION_ID; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_ISSUE_ACCESS_TOKEN_PATH; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TENANT_DOMAIN; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_DESCRIPTION; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_NAME; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_URI; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_PASSWORD; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_USERNAME; + +/** + * Test class for CacheBackedActionManagement. + */ +@WithCarbonHome +@WithH2Database(files = {"dbscripts/h2.sql"}) +@WithRealmService(injectToSingletons = {IdentityCoreServiceDataHolder.class}) +public class CacheBackedActionManagementServiceTest { + + private ActionManagementServiceImpl actionManagementServiceImpl; + private CacheBackedActionManagementService cacheBackedActionManagementService; + + private final List mockedActionsList = new ArrayList<>(); + private Action mockedAction; + + @BeforeClass + public void setUpClass() { + + cacheBackedActionManagementService = CacheBackedActionManagementService.getInstance(); + mockedAction = new Action.ActionResponseBuilder() + .id(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID) + .name(TEST_ACTION_NAME) + .description(TEST_ACTION_DESCRIPTION) + .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) + .status(Action.Status.ACTIVE) + .endpoint(TestUtil.buildMockEndpointConfig(TEST_ACTION_URI, + TestUtil.buildMockBasicAuthentication(TEST_USERNAME, TEST_PASSWORD))) + .build(); + mockedActionsList.add(mockedAction); + } + + @BeforeMethod + public void setUp() throws Exception { + + SecretManagerImpl secretManager = mock(SecretManagerImpl.class); + SecretType secretType = mock(SecretType.class); + ActionMgtServiceComponentHolder.getInstance().setSecretManager(secretManager); + when(secretType.getId()).thenReturn(TestUtil.TEST_SECRET_TYPE_ID); + when(secretManager.getSecretType(any())).thenReturn(secretType); + + actionManagementServiceImpl = mock(ActionManagementServiceImpl.class); + // Set ACTION_MGT_SERVICE field using reflection + setFinalField(cacheBackedActionManagementService, "ACTION_MGT_SERVICE", actionManagementServiceImpl); + } + + @Test(priority = 1) + public void testGetActionsByActionTypeFromDB() throws ActionMgtException { + + doReturn(mockedActionsList).when(actionManagementServiceImpl).getActionsByActionType(any(), any()); + + List actions = cacheBackedActionManagementService.getActionsByActionType(PRE_ISSUE_ACCESS_TOKEN_PATH, + TENANT_DOMAIN); + verify(actionManagementServiceImpl, times(1)).getActionsByActionType(any(), any()); + Assert.assertEquals(actions.size(), mockedActionsList.size()); + Action result = actions.get(0); + assertAction(result); + } + + @Test(priority = 2, dependsOnMethods = "testGetActionsByActionTypeFromDB") + public void testGetActionsByActionTypeFromCache() throws ActionMgtException { + + doReturn(null).when(actionManagementServiceImpl).getActionsByActionType(any(), any()); + + List actions = cacheBackedActionManagementService.getActionsByActionType(PRE_ISSUE_ACCESS_TOKEN_PATH, + TENANT_DOMAIN); + verify(actionManagementServiceImpl, never()).getActionsByActionType(any(), any()); + Assert.assertNotNull(actions); + Assert.assertEquals(actions.size(), mockedActionsList.size()); + Action result = actions.get(0); + assertAction(result); + } + + @Test(priority = 3, dependsOnMethods = "testGetActionsByActionTypeFromDB") + public void testGetActionsByActionIdFromCache() throws ActionMgtException { + + doReturn(null).when(actionManagementServiceImpl).getActionByActionId(any(), any(), any()); + + Action action = cacheBackedActionManagementService.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_PATH, + PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, TENANT_DOMAIN); + verify(actionManagementServiceImpl, never()).getActionByActionId(any(), any(), any()); + Assert.assertNotNull(action); + assertAction(action); + } + + @Test(priority = 4) + public void testAddAction() throws ActionMgtException { + + doReturn(mockedAction).when(actionManagementServiceImpl).addAction(any(), any(), any()); + + Action action = cacheBackedActionManagementService.addAction(PRE_ISSUE_ACCESS_TOKEN_PATH, + mockedAction, TENANT_DOMAIN); + verify(actionManagementServiceImpl, times(1)).addAction(any(), any(), any()); + Assert.assertNotNull(action); + checkCacheInvalidation(); + } + + @Test(priority = 5) + public void testGetActionsByActionIdFromDB() throws ActionMgtException { + + doReturn(mockedAction).when(actionManagementServiceImpl).getActionByActionId(any(), any(), any()); + + Action action = cacheBackedActionManagementService.getActionByActionId(PRE_ISSUE_ACCESS_TOKEN_PATH, + PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, TENANT_DOMAIN); + verify(actionManagementServiceImpl, times(1)).getActionByActionId(any(), any(), any()); + Assert.assertNotNull(action); + assertAction(action); + } + + @Test(priority = 6) + public void testUpdateAction() throws ActionMgtException { + + doReturn(mockedAction).when(actionManagementServiceImpl).updateAction(any(), any(), any(), any()); + + Action action = cacheBackedActionManagementService.updateAction(PRE_ISSUE_ACCESS_TOKEN_PATH, + PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, mockedAction, TENANT_DOMAIN); + verify(actionManagementServiceImpl, times(1)).updateAction(any(), any(), any(), any()); + Assert.assertNotNull(action); + checkCacheInvalidation(); + } + + @Test(priority = 7) + public void testDeactivateAction() throws ActionMgtException { + + // Update cache. + doReturn(mockedActionsList).when(actionManagementServiceImpl).getActionsByActionType(any(), any()); + cacheBackedActionManagementService.getActionsByActionType(PRE_ISSUE_ACCESS_TOKEN_PATH, TENANT_DOMAIN); + + cacheBackedActionManagementService.deactivateAction(PRE_ISSUE_ACCESS_TOKEN_PATH, + PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, TENANT_DOMAIN); + verify(actionManagementServiceImpl, times(1)).deactivateAction(any(), any(), any()); + checkCacheInvalidation(); + } + + @Test(priority = 8) + public void testActivateAction() throws ActionMgtException { + + // Update cache. + doReturn(mockedActionsList).when(actionManagementServiceImpl).getActionsByActionType(any(), any()); + cacheBackedActionManagementService.getActionsByActionType(PRE_ISSUE_ACCESS_TOKEN_PATH, TENANT_DOMAIN); + + cacheBackedActionManagementService.activateAction(PRE_ISSUE_ACCESS_TOKEN_PATH, + PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, TENANT_DOMAIN); + verify(actionManagementServiceImpl, times(1)).activateAction(any(), any(), any()); + checkCacheInvalidation(); + } + + @Test(priority = 9) + public void testUpdateActionEndpointAuthentication() throws ActionMgtException { + + // Update cache. + doReturn(mockedAction).when(actionManagementServiceImpl).updateActionEndpointAuthentication(any(), any(), + any(), any()); + + Action action = cacheBackedActionManagementService.updateActionEndpointAuthentication( + PRE_ISSUE_ACCESS_TOKEN_PATH, PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, + mockedAction.getEndpoint().getAuthentication(), TENANT_DOMAIN); + verify(actionManagementServiceImpl, times(1)).updateActionEndpointAuthentication(any(), + any(), any(), any()); + Assert.assertNotNull(action); + checkCacheInvalidation(); + } + + @Test(priority = 14) + public void testDeleteAction() throws ActionMgtException { + + // Update cache. + doNothing().when(actionManagementServiceImpl).deleteAction(any(), any(), any()); + + cacheBackedActionManagementService.deleteAction(PRE_ISSUE_ACCESS_TOKEN_PATH, mockedAction.getId(), + TENANT_DOMAIN); + verify(actionManagementServiceImpl, times(1)).deleteAction(any(), any(), any()); + checkCacheInvalidation(); + } + + @Test(priority = 10) + public void testGetActionsCountPerType() throws ActionMgtException { + + Map mockedActionMap = new HashMap<>(); + mockedActionMap.put(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN.getActionType(), 1); + mockedActionMap.put(Action.ActionTypes.PRE_UPDATE_PASSWORD.getActionType(), 2); + doReturn(mockedActionMap).when(actionManagementServiceImpl).getActionsCountPerType(any()); + + Map actionMap = cacheBackedActionManagementService.getActionsCountPerType(TENANT_DOMAIN); + Assert.assertNotNull(actionMap.get(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN.getActionType())); + Assert.assertNotNull(actionMap.get(Action.ActionTypes.PRE_UPDATE_PASSWORD.getActionType())); + Assert.assertNull(actionMap.get(Action.ActionTypes.PRE_UPDATE_PROFILE.getActionType())); + Assert.assertNull(actionMap.get(Action.ActionTypes.PRE_REGISTRATION.getActionType())); + Assert.assertNull(actionMap.get(Action.ActionTypes.AUTHENTICATION.getActionType())); + + Assert.assertEquals(actionMap.get(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN.getActionType()).intValue(), 1); + Assert.assertEquals(actionMap.get(Action.ActionTypes.PRE_UPDATE_PASSWORD.getActionType()).intValue(), 2); + } + + private void checkCacheInvalidation() throws ActionMgtException { + + reset(actionManagementServiceImpl); + doReturn(null).when(actionManagementServiceImpl).getActionsByActionType(any(), any()); + doReturn(null).when(actionManagementServiceImpl).getActionByActionId(any(), any(), any()); + + List actions = cacheBackedActionManagementService.getActionsByActionType( + mockedAction.getType().getPathParam(), TENANT_DOMAIN); + Assert.assertNull(actions); + verify(actionManagementServiceImpl, times(1)).getActionsByActionType(any(), any()); + + Action action = cacheBackedActionManagementService.getActionByActionId(mockedAction.getType().getPathParam(), + mockedAction.getId(), TENANT_DOMAIN); + Assert.assertNull(action); + verify(actionManagementServiceImpl, times(1)).getActionByActionId(any(), any(), any()); + } + + private void assertAction(Action action) { + + Assert.assertEquals(action.getId(), mockedAction.getId()); + Assert.assertEquals(action.getName(), mockedAction.getName()); + Assert.assertEquals(action.getDescription(), mockedAction.getDescription()); + Assert.assertEquals(action.getType(), mockedAction.getType()); + Assert.assertEquals(action.getStatus(), mockedAction.getStatus()); + Assert.assertEquals(action.getEndpoint().getUri(), mockedAction.getEndpoint().getUri()); + + Authentication actionAuth = action.getEndpoint().getAuthentication(); + Authentication mockedActionAuth = mockedAction.getEndpoint().getAuthentication(); + + Assert.assertEquals(actionAuth.getType(), mockedActionAuth.getType()); + Assert.assertEquals(actionAuth.getProperty(Authentication.Property.USERNAME).getValue(), + mockedActionAuth.getProperty(Authentication.Property.USERNAME).getValue()); + Assert.assertEquals(actionAuth.getProperty(Authentication.Property.PASSWORD).getValue(), + mockedActionAuth.getProperty(Authentication.Property.PASSWORD).getValue()); + } + + private void setFinalField(Object target, String fieldName, Object value) throws Exception { + + Field field; + try { + field = target.getClass().getDeclaredField(fieldName); + } catch (NoSuchFieldException e) { + field = target.getClass().getSuperclass().getDeclaredField(fieldName); + } + + field.setAccessible(true); + + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); + modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); + + field.set(target, value); + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/ActionManagementAuditLoggerTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/ActionManagementAuditLoggerTest.java new file mode 100644 index 000000000000..eead34bd7a05 --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/ActionManagementAuditLoggerTest.java @@ -0,0 +1,447 @@ +/* + * 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.action.management.util; + +import org.json.JSONObject; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; +import org.mockito.MockitoAnnotations; +import org.testng.Assert; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.ActionDTO; +import org.wso2.carbon.identity.action.management.model.Authentication; +import org.wso2.carbon.identity.action.management.model.EndpointConfig; +import org.wso2.carbon.identity.central.log.mgt.utils.LoggerUtils; +import org.wso2.carbon.identity.certificate.management.model.Certificate; +import org.wso2.carbon.identity.common.testng.WithCarbonHome; +import org.wso2.carbon.identity.core.util.IdentityTenantUtil; +import org.wso2.carbon.identity.core.util.IdentityUtil; +import org.wso2.carbon.utils.AuditLog; + +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.Map; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; +import static org.wso2.carbon.identity.action.management.util.TestUtil.CERTIFICATE_ID; +import static org.wso2.carbon.identity.action.management.util.TestUtil.CERTIFICATE_NAME; +import static org.wso2.carbon.identity.action.management.util.TestUtil.CERTIFICATE_PROPERTY_NAME; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PASSWORD_SHARING_TYPE_PROPERTY_NAME; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_ISSUE_ACCESS_TOKEN_ACTION_ID; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_UPDATE_PASSWORD_ACTION_ID; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACCESS_TOKEN; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_DESCRIPTION; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_DESCRIPTION_UPDATED; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_NAME; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_NAME_UPDATED; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_URI; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACTION_URI_UPDATED; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_API_KEY_HEADER; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_API_KEY_VALUE; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_CERTIFICATE; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_CERTIFICATE_UPDATED; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_PASSWORD; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_PASSWORD_SHARING_TYPE; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_PASSWORD_SHARING_TYPE_UPDATED; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_USERNAME; + +/** + * Unit test class for ActionManagementAuditLogger class. + */ +@WithCarbonHome +public class ActionManagementAuditLoggerTest { + + private ActionManagementAuditLogger auditLogger; + private ActionDTO actionDTO; + private CarbonContext carbonContext; + private MockedStatic carbonContextMockedStatic; + private MockedStatic identityUtil; + private MockedStatic identityTenantUtil; + private MockedStatic loggerUtilsMockedStatic; + + private static final String ADD_ACTION = "add-action"; + private static final String UPDATE_ACTION = "update-action"; + private static final String DELETE_ACTION = "delete-action"; + + @BeforeMethod + public void setUp() throws NoSuchFieldException, IllegalAccessException { + + MockitoAnnotations.openMocks(this); + auditLogger = new ActionManagementAuditLogger(); + identityUtil = mockStatic(IdentityUtil.class); + identityTenantUtil = mockStatic(IdentityTenantUtil.class); + + carbonContextMockedStatic = mockStatic(CarbonContext.class); + carbonContext = mock(CarbonContext.class); + carbonContextMockedStatic.when(CarbonContext::getThreadLocalCarbonContext).thenReturn(carbonContext); + when(carbonContext.getUsername()).thenReturn("testUser"); + when(carbonContext.getTenantDomain()).thenReturn("carbon.super"); + identityUtil.when(() -> IdentityUtil.getInitiatorId("testUser", "carbon.super")). + thenReturn("initiator-id-test"); + + loggerUtilsMockedStatic = mockStatic(LoggerUtils.class); + loggerUtilsMockedStatic.when(LoggerUtils::isEnableV2AuditLogs).thenReturn(true); + loggerUtilsMockedStatic.when(() -> LoggerUtils.jsonObjectToMap(any(JSONObject.class))).thenCallRealMethod(); + loggerUtilsMockedStatic.when(() -> LoggerUtils.getMaskedContent(any(String.class))).thenCallRealMethod(); + + Map actionProperties = new HashMap<>(); + actionProperties.put(PASSWORD_SHARING_TYPE_PROPERTY_NAME, TEST_PASSWORD_SHARING_TYPE); + actionProperties.put(CERTIFICATE_PROPERTY_NAME, new Certificate.Builder() + .id(CERTIFICATE_ID).name(CERTIFICATE_NAME) + .certificateContent(TEST_CERTIFICATE).build()); + + actionDTO = new ActionDTOBuilder() + .id(PRE_UPDATE_PASSWORD_ACTION_ID) + .name(TEST_ACTION_NAME) + .description(TEST_ACTION_DESCRIPTION) + .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) + .status(Action.Status.ACTIVE) + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .uri(TEST_ACTION_URI) + .authentication(new Authentication.BearerAuthBuilder(TEST_ACCESS_TOKEN).build()) + .build()) + .properties(actionProperties) + .build(); + } + + @AfterMethod + public void tearDown() { + + auditLogger = null; + actionDTO = null; + carbonContextMockedStatic.close(); + identityUtil.close(); + identityTenantUtil.close(); + loggerUtilsMockedStatic.close(); + } + + @DataProvider + public Object[][] actionDataProvider() { + + Map actionProperties = new HashMap<>(); + actionProperties.put(PASSWORD_SHARING_TYPE_PROPERTY_NAME, TEST_PASSWORD_SHARING_TYPE); + actionProperties.put(CERTIFICATE_PROPERTY_NAME, new Certificate.Builder() + .id(CERTIFICATE_ID).name(CERTIFICATE_NAME) + .certificateContent(TEST_CERTIFICATE).build()); + + Map updatedActionProperties = new HashMap<>(); + updatedActionProperties.put(PASSWORD_SHARING_TYPE_PROPERTY_NAME, TEST_PASSWORD_SHARING_TYPE_UPDATED); + updatedActionProperties.put(CERTIFICATE_PROPERTY_NAME, new Certificate.Builder() + .id(CERTIFICATE_ID).name(CERTIFICATE_NAME) + .certificateContent(TEST_CERTIFICATE_UPDATED).build()); + + return new Object[][]{ + // Create object with all the fields. + {ActionManagementAuditLogger.Operation.ADD, + new ActionDTOBuilder() + .id(PRE_UPDATE_PASSWORD_ACTION_ID) + .name(TEST_ACTION_NAME) + .description(TEST_ACTION_DESCRIPTION) + .type(Action.ActionTypes.PRE_UPDATE_PASSWORD) + .status(Action.Status.ACTIVE) + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .uri(TEST_ACTION_URI) + .authentication(new Authentication.BearerAuthBuilder(TEST_ACCESS_TOKEN).build()) + .build()) + .properties(actionProperties) + .build() + }, + // Create object without properties + {ActionManagementAuditLogger.Operation.ADD, + new ActionDTOBuilder() + .id(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID) + .name(TEST_ACTION_NAME) + .description(TEST_ACTION_DESCRIPTION) + .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) + .status(Action.Status.ACTIVE) + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .uri(TEST_ACTION_URI) + .authentication(new Authentication.BasicAuthBuilder(TEST_USERNAME, TEST_PASSWORD) + .build()) + .build()) + .build() + }, + // Update Objects + {ActionManagementAuditLogger.Operation.UPDATE, + new ActionDTOBuilder() + .id(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID) + .name(TEST_ACTION_NAME_UPDATED) + .description(TEST_ACTION_DESCRIPTION_UPDATED) + .type(Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN) + .status(Action.Status.ACTIVE) + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .uri(TEST_ACTION_URI_UPDATED) + .authentication(new Authentication.APIKeyAuthBuilder(TEST_API_KEY_HEADER, + TEST_API_KEY_VALUE).build()) + .build()) + .properties(updatedActionProperties) + .build() + }, + {ActionManagementAuditLogger.Operation.UPDATE, + new ActionDTOBuilder() + .id(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID) + .name(TEST_ACTION_NAME_UPDATED) + .build() + }, + {ActionManagementAuditLogger.Operation.UPDATE, + new ActionDTOBuilder() + .id(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID) + .description(TEST_ACTION_DESCRIPTION_UPDATED) + .build() + }, + {ActionManagementAuditLogger.Operation.UPDATE, + new ActionDTOBuilder() + .id(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID) + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .uri(TEST_ACTION_URI) + .authentication(new Authentication.NoneAuthBuilder().build()) + .build()) + .build() + }, + {ActionManagementAuditLogger.Operation.UPDATE, + new ActionDTOBuilder() + .id(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID) + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .uri(TEST_ACTION_URI) + .build()) + .build() + }, + {ActionManagementAuditLogger.Operation.UPDATE, + new ActionDTOBuilder() + .id(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID) + .endpoint(new EndpointConfig.EndpointConfigBuilder() + .authentication(new Authentication.BearerAuthBuilder(TEST_ACCESS_TOKEN).build()) + .build()) + .build() + }, + {ActionManagementAuditLogger.Operation.UPDATE, + new ActionDTOBuilder() + .id(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID) + .properties(updatedActionProperties) + .build() + } + }; + } + + @Test(dataProvider = "actionDataProvider") + public void testPrintAuditLogWithAction(ActionManagementAuditLogger.Operation operation, ActionDTO actionDTO) + throws NoSuchFieldException, IllegalAccessException { + + auditLogger.printAuditLog(operation, actionDTO); + AuditLog.AuditLogBuilder capturedArg = captureTriggerAuditLogEventArgs(); + + Assert.assertNotNull(capturedArg); + assertActionData(capturedArg, actionDTO); + assertAuditLoggerData(capturedArg, operation.getLogAction()); + } + + @Test + public void testPrintAuditLogWithActionTypeAndId() throws NoSuchFieldException, IllegalAccessException { + + ActionManagementAuditLogger.Operation operation = ActionManagementAuditLogger.Operation.DELETE; + auditLogger.printAuditLog(operation, actionDTO.getType().name(), actionDTO.getId()); + AuditLog.AuditLogBuilder capturedArg = captureTriggerAuditLogEventArgs(); + + Assert.assertNotNull(capturedArg); + Assert.assertEquals(extractMapByField("ActionId", capturedArg), actionDTO.getId()); + Assert.assertEquals(extractMapByField("ActionType", capturedArg), + Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN.getActionType()); + assertAuditLoggerData(capturedArg, DELETE_ACTION); + + } + + /** + * Capture the arguments passed to the triggerAuditLogEvent method in the {@link LoggerUtils} class. + * The captured {@code AuditLogBuilder} contains all the necessary + * information that will be logged, allowing verification of audit log data. + * + * @return The captured {@link AuditLog.AuditLogBuilder} instance containing the data to be logged. + */ + private AuditLog.AuditLogBuilder captureTriggerAuditLogEventArgs() { + + ArgumentCaptor auditLogBuilderCaptor = ArgumentCaptor. + forClass(AuditLog.AuditLogBuilder.class); + loggerUtilsMockedStatic.verify(() -> LoggerUtils.triggerAuditLogEvent(auditLogBuilderCaptor.capture())); + return auditLogBuilderCaptor.getValue(); + } + + /** + * Extract the specific field name from the provided {@link AuditLog.AuditLogBuilder} instance. + * + * @param fieldName Name of the field to be extracted. + * @param auditLogBuilder {@link AuditLog.AuditLogBuilder} instance. + * @return Value of the extracted field. + * @throws NoSuchFieldException if the provided field does not exist. + * @throws IllegalAccessException if the provided field is not accessible. + */ + private String extractMapByField(String fieldName, AuditLog.AuditLogBuilder auditLogBuilder) + throws NoSuchFieldException, IllegalAccessException { + + Field dataField = AuditLog.AuditLogBuilder.class.getDeclaredField("data"); + dataField.setAccessible(true); + Map dataMap = (Map) dataField.get(auditLogBuilder); + return (String) dataMap.get(fieldName); + } + + /** + * Extract field. + * + * @param fieldName Name of the field to be extracted. + * @param auditLogBuilder {@link AuditLog.AuditLogBuilder} instance. + * @return Value of the extracted field. + * @throws NoSuchFieldException if the provided field does not exist. + * @throws IllegalAccessException if the provided field is not accessible. + */ + private String extractField(String fieldName, AuditLog.AuditLogBuilder auditLogBuilder) + throws NoSuchFieldException, IllegalAccessException { + + Field dataField = AuditLog.AuditLogBuilder.class.getDeclaredField(fieldName); + dataField.setAccessible(true); + return (String) dataField.get(auditLogBuilder); + } + + /** + * Assert data fields related to the Action object of the captured audit logger. + * + * @param auditLogBuilder {@link AuditLog.AuditLogBuilder} instance. + * @param actionDTO {@link ActionDTO} instance. + * @throws NoSuchFieldException if the provided field does not exist. + * @throws IllegalAccessException if the provided field is not accessible. + */ + private void assertActionData(AuditLog.AuditLogBuilder auditLogBuilder, ActionDTO actionDTO) + throws NoSuchFieldException, IllegalAccessException { + + Field dataField = AuditLog.AuditLogBuilder.class.getDeclaredField("data"); + dataField.setAccessible(true); + Map dataMap = (Map) dataField.get(auditLogBuilder); + Map endpointConfigMap = (Map) dataMap.get("EndpointConfiguration"); + Map propertiesMap = (Map) dataMap.get("Properties"); + + String id = actionDTO.getId(); + String name = actionDTO.getName(); + String description = actionDTO.getDescription(); + String type = actionDTO.getType() != null ? actionDTO.getType().name() : null; + String status = actionDTO.getStatus() != null ? actionDTO.getStatus().name() : null; + String uri = actionDTO.getEndpoint() != null && actionDTO.getEndpoint().getUri() != null ? + actionDTO.getEndpoint().getUri() : null; + String authenticationScheme = actionDTO.getEndpoint() != null && + actionDTO.getEndpoint().getAuthentication() != null && + actionDTO.getEndpoint().getAuthentication().getType() != null ? + actionDTO.getEndpoint().getAuthentication().getType().getName() : null; + + assertField(id != null, dataMap, "ActionId", id); + assertField(name != null, dataMap, "ActionName", name); + assertField(description != null, dataMap, "ActionDescription", description); + assertField(type != null, dataMap, "ActionType", type); + assertField(status != null, dataMap, "ActionStatus", status); + assertField(uri != null, endpointConfigMap, "EndpointUri", uri); + assertField(authenticationScheme != null, endpointConfigMap, "AuthenticationScheme", + authenticationScheme); + + if (authenticationScheme != null) { + switch (actionDTO.getEndpoint().getAuthentication().getType()) { + case BASIC: + assertMasked(endpointConfigMap.get("Username").toString()); + assertMasked(endpointConfigMap.get("Password").toString()); + break; + case BEARER: + assertMasked(endpointConfigMap.get("AccessToken").toString()); + break; + case API_KEY: + assertMasked(endpointConfigMap.get("ApiKeyHeader").toString()); + assertMasked(endpointConfigMap.get("ApiKeyValue").toString()); + break; + case NONE: + default: + break; + } + } + + if (actionDTO.getProperties() != null && actionDTO.getProperty(PASSWORD_SHARING_TYPE_PROPERTY_NAME) != null) { + assertMasked(propertiesMap.get(PASSWORD_SHARING_TYPE_PROPERTY_NAME).toString()); + } + if (actionDTO.getProperties() != null && actionDTO.getProperty(CERTIFICATE_PROPERTY_NAME) != null) { + assertMasked(propertiesMap.get(CERTIFICATE_PROPERTY_NAME).toString()); + } + } + + /** + * Assert field. + * + * @param isFieldExist Field existence. + * @param dataMap Data map. + * @param fieldName Field name. + * @param value Value to be asserted. + */ + private void assertField(boolean isFieldExist, Map dataMap, String fieldName, String value) { + + if (isFieldExist) { + Assert.assertEquals(dataMap.get(fieldName).toString(), value); + } else { + Assert.assertTrue(dataMap == null || dataMap.get(fieldName) == null); + } + } + + /** + * Assert masked data fields. + * + * @param value Value to be asserted. + */ + private void assertMasked(String value) { + + Assert.assertTrue(value.contains("*")); + } + + /** + * Assert generic data fields in audit logger. + * + * @param auditLogBuilder {@link AuditLog.AuditLogBuilder} instance. + * @param operation Operation to be logged. + * @throws NoSuchFieldException if the provided field does not exist. + * @throws IllegalAccessException if the provided field is not accessible. + */ + private void assertAuditLoggerData(AuditLog.AuditLogBuilder auditLogBuilder, + String operation) + throws NoSuchFieldException, IllegalAccessException { + + Assert.assertEquals(extractField("initiatorId", auditLogBuilder), "initiator-id-test"); + Assert.assertEquals(extractField("targetId", auditLogBuilder), "System"); + Assert.assertEquals(extractField("targetType", auditLogBuilder), "Action"); + switch (operation) { + case ADD_ACTION: + Assert.assertEquals(extractField("action", auditLogBuilder), "add-action"); + break; + case UPDATE_ACTION: + Assert.assertEquals(extractField("action", auditLogBuilder), "update-action"); + break; + case DELETE_ACTION: + Assert.assertEquals(extractField("action", auditLogBuilder), "delete-action"); + break; + } + } +} + diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/ActionSecretProcessorTest.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/ActionSecretProcessorTest.java new file mode 100644 index 000000000000..ef38040fe208 --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/ActionSecretProcessorTest.java @@ -0,0 +1,222 @@ +/* + * 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.action.management.util; + +import org.testng.Assert; +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.action.management.internal.ActionMgtServiceComponentHolder; +import org.wso2.carbon.identity.action.management.model.AuthProperty; +import org.wso2.carbon.identity.action.management.model.Authentication; +import org.wso2.carbon.identity.secret.mgt.core.SecretManager; +import org.wso2.carbon.identity.secret.mgt.core.SecretManagerImpl; +import org.wso2.carbon.identity.secret.mgt.core.SecretResolveManager; +import org.wso2.carbon.identity.secret.mgt.core.exception.SecretManagementException; +import org.wso2.carbon.identity.secret.mgt.core.model.ResolvedSecret; +import org.wso2.carbon.identity.secret.mgt.core.model.SecretType; + +import java.util.Arrays; +import java.util.List; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.wso2.carbon.identity.action.management.util.TestUtil.PRE_ISSUE_ACCESS_TOKEN_ACTION_ID; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACCESS_TOKEN; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_ACCESS_TOKEN_UPDATED; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_API_KEY_HEADER; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_API_KEY_VALUE; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_PASSWORD; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_SECRET_TYPE_ID; +import static org.wso2.carbon.identity.action.management.util.TestUtil.TEST_USERNAME; +import static org.wso2.carbon.identity.action.management.util.TestUtil.buildMockAPIKeyAuthentication; +import static org.wso2.carbon.identity.action.management.util.TestUtil.buildMockBasicAuthentication; +import static org.wso2.carbon.identity.action.management.util.TestUtil.buildMockBearerAuthentication; +import static org.wso2.carbon.identity.action.management.util.TestUtil.buildSecretName; + +/** + * Test class for Action secrets processor. + */ +public class ActionSecretProcessorTest { + + private SecretManager secretManager; + private SecretResolveManager secretResolveManager; + private ActionSecretProcessor actionSecretProcessor; + + @BeforeClass + public void setUpClass() { + + actionSecretProcessor = new ActionSecretProcessor(); + } + + @BeforeMethod + public void setUp() throws SecretManagementException { + + secretManager = mock(SecretManagerImpl.class); + secretResolveManager = mock(SecretResolveManager.class); + ActionMgtServiceComponentHolder.getInstance().setSecretManager(secretManager); + ActionMgtServiceComponentHolder.getInstance().setSecretResolveManager(secretResolveManager); + + SecretType secretType = mock(SecretType.class); + doReturn(TEST_SECRET_TYPE_ID).when(secretType).getId(); + doReturn(secretType).when(secretManager).getSecretType(any()); + + } + + @DataProvider + public Object[] provideAuthentication() { + + return new Object[]{ + buildMockBearerAuthentication(TEST_ACCESS_TOKEN), + buildMockBasicAuthentication(TEST_USERNAME, TEST_PASSWORD), + buildMockAPIKeyAuthentication(TEST_API_KEY_HEADER, TEST_API_KEY_VALUE) + }; + } + + @Test(dataProvider = "provideAuthentication") + public void testEncryptAssociatedSecrets(Authentication authentication) throws SecretManagementException { + + doReturn(false).when(secretManager).isSecretExist(any(), any()); + doReturn(null).when(secretManager).addSecret(any(), any()); + + List encryptedProperties = actionSecretProcessor.encryptAssociatedSecrets(authentication, + PRE_ISSUE_ACCESS_TOKEN_ACTION_ID); + + Assert.assertEquals(encryptedProperties.size(), authentication.getProperties().size()); + for (AuthProperty authProperty : encryptedProperties) { + Authentication.Property property = Arrays.stream(Authentication.Property.values()) + .filter(prop -> prop.getName().equals(authProperty.getName())) + .findFirst() + .orElse(null); + AuthProperty inputAuthProperty = authentication.getProperty(property); + + Assert.assertNotNull(property); + Assert.assertEquals(authProperty.getName(), authentication.getProperty(property).getName()); + Assert.assertEquals(authProperty.getIsConfidential(), inputAuthProperty.getIsConfidential()); + if (authProperty.getIsConfidential()) { + Assert.assertEquals(authProperty.getValue(), + TestUtil.buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, authentication.getType(), property)); + } else { + Assert.assertEquals(authProperty.getValue(), inputAuthProperty.getValue()); + } + } + } + + @Test + public void testUpdateSecret() throws SecretManagementException { + + ResolvedSecret resolvedSecret = mock(ResolvedSecret.class); + doReturn(TEST_ACCESS_TOKEN).when(resolvedSecret).getResolvedSecretValue(); + doReturn(resolvedSecret).when(secretResolveManager).getResolvedSecret(any(), any()); + doReturn(true).when(secretManager).isSecretExist(any(), any()); + doReturn(null).when(secretManager).updateSecretValue(any(), any(), any()); + + Authentication authentication = buildMockBearerAuthentication(TEST_ACCESS_TOKEN_UPDATED); + List encryptedProperties = actionSecretProcessor.encryptAssociatedSecrets(authentication, + PRE_ISSUE_ACCESS_TOKEN_ACTION_ID); + + Assert.assertEquals(encryptedProperties.size(), authentication.getProperties().size()); + Assert.assertEquals(encryptedProperties.get(0).getName(), authentication.getProperties().get(0).getName()); + Assert.assertEquals(encryptedProperties.get(0).getName(), authentication.getProperties().get(0).getName()); + Assert.assertEquals(encryptedProperties.get(0).getValue(), buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, + Authentication.Type.BEARER, Authentication.Property.ACCESS_TOKEN)); + } + + @Test + public void testDecryptAssociatedSecrets() throws SecretManagementException { + + ResolvedSecret resolvedSecret = mock(ResolvedSecret.class); + doReturn(TEST_ACCESS_TOKEN).when(resolvedSecret).getResolvedSecretValue(); + doReturn(resolvedSecret).when(secretResolveManager).getResolvedSecret(any(), any()); + doReturn(true).when(secretManager).isSecretExist(any(), any()); + + Authentication authentication = buildMockBearerAuthentication(buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, + Authentication.Type.BEARER, Authentication.Property.ACCESS_TOKEN)); + + List decryptedProperties = actionSecretProcessor.decryptAssociatedSecrets(authentication, + PRE_ISSUE_ACCESS_TOKEN_ACTION_ID); + + Assert.assertEquals(decryptedProperties.size(), authentication.getProperties().size()); + Assert.assertEquals(decryptedProperties.get(0).getName(), authentication.getProperties().get(0).getName()); + Assert.assertEquals(decryptedProperties.get(0).getIsConfidential(), + authentication.getProperties().get(0).getIsConfidential()); + Assert.assertEquals(decryptedProperties.get(0).getValue(), TEST_ACCESS_TOKEN); + } + + @Test + public void testDecryptAssociatedSecretsForNonSecret() throws SecretManagementException { + + ResolvedSecret resolvedSecret = mock(ResolvedSecret.class); + doReturn(TEST_API_KEY_VALUE).when(resolvedSecret).getResolvedSecretValue(); + doReturn(resolvedSecret).when(secretResolveManager).getResolvedSecret(any(), any()); + doReturn(true).when(secretManager).isSecretExist(any(), any()); + + Authentication authentication = buildMockAPIKeyAuthentication(TEST_API_KEY_HEADER, + buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, Authentication.Type.API_KEY, + Authentication.Property.VALUE)); + + List decryptedProperties = actionSecretProcessor.decryptAssociatedSecrets(authentication, + PRE_ISSUE_ACCESS_TOKEN_ACTION_ID); + + for (AuthProperty authProperty : decryptedProperties) { + Authentication.Property property = Arrays.stream(Authentication.Property.values()) + .filter(prop -> prop.getName().equals(authProperty.getName())) + .findFirst() + .orElse(null); + AuthProperty inputAuthProperty = authentication.getProperty(property); + + Assert.assertEquals(authProperty.getName(), authentication.getProperty(property).getName()); + Assert.assertEquals(authProperty.getIsConfidential(), inputAuthProperty.getIsConfidential()); + if (authProperty.getIsConfidential()) { + Assert.assertEquals(authProperty.getValue(), TEST_API_KEY_VALUE); + } else { + Assert.assertEquals(authProperty.getValue(), TEST_API_KEY_HEADER); + } + } + } + + @Test(expectedExceptions = SecretManagementException.class) + public void testDecryptAssociatedSecretsForNonExistingSecret() throws SecretManagementException { + + doReturn(false).when(secretManager).isSecretExist(any(), any()); + Authentication authentication = buildMockBearerAuthentication(buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, + Authentication.Type.BEARER, Authentication.Property.ACCESS_TOKEN)); + + actionSecretProcessor.decryptAssociatedSecrets(authentication, PRE_ISSUE_ACCESS_TOKEN_ACTION_ID); + } + + @Test + public void testDeleteAssociatedSecrets() throws SecretManagementException { + + doReturn(true).when(secretManager).isSecretExist(any(), any()); + doNothing().when(secretManager).deleteSecret(any(), any()); + + Authentication authentication = buildMockAPIKeyAuthentication(TEST_API_KEY_HEADER, + buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, Authentication.Type.API_KEY, + Authentication.Property.VALUE)); + + actionSecretProcessor.deleteAssociatedSecrets(authentication, PRE_ISSUE_ACCESS_TOKEN_ACTION_ID); + verify(secretManager, times(1)).deleteSecret(any(), any()); + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java new file mode 100644 index 000000000000..a235877c7147 --- /dev/null +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/java/org/wso2/carbon/identity/action/management/util/TestUtil.java @@ -0,0 +1,127 @@ +/* + * 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.action.management.util; + +import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.Authentication; +import org.wso2.carbon.identity.action.management.model.EndpointConfig; + +import java.util.UUID; + +/** + * Utility class for Action Management Tests. + */ +public class TestUtil { + + public static final int TENANT_ID = 2; + public static final String TENANT_DOMAIN = "carbon.super"; + + public static final String PRE_ISSUE_ACCESS_TOKEN_TYPE = Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN.getActionType(); + public static final String PRE_UPDATE_PASSWORD_TYPE = Action.ActionTypes.PRE_UPDATE_PASSWORD.getActionType(); + + public static final String PRE_ISSUE_ACCESS_TOKEN_PATH = Action.ActionTypes.PRE_ISSUE_ACCESS_TOKEN.getPathParam(); + + public static final String PRE_ISSUE_ACCESS_TOKEN_ACTION_ID = String.valueOf(UUID.randomUUID()); + public static final String PRE_UPDATE_PASSWORD_ACTION_ID = String.valueOf(UUID.randomUUID()); + + public static final String TEST_SECRET_TYPE_ID = "fcaf81a9-0d58-4cf4-98c8-fde2f3ba8df2"; + + public static final String TEST_ACTION_NAME = "Test Action Name"; + public static final String TEST_ACTION_NAME_UPDATED = "Updated Test Action Name"; + public static final String TEST_INVALID_ACTION_NAME = "PreIssueAccessToken_#1"; + public static final String TEST_ACTION_DESCRIPTION = "Test Action description"; + public static final String TEST_ACTION_DESCRIPTION_UPDATED = "Updated Test Action description"; + public static final String TEST_ACTION_URI = "https://example.com"; + public static final String TEST_ACTION_URI_UPDATED = "https://sample.com"; + + public static final String TEST_USERNAME = "sampleUsername"; + public static final String TEST_USERNAME_SECRET_REFERENCE = buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, + Authentication.Type.BASIC, Authentication.Property.USERNAME); + public static final String TEST_PASSWORD = "samplePassword"; + public static final String TEST_PASSWORD_SECRET_REFERENCE = buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, + Authentication.Type.BASIC, Authentication.Property.PASSWORD); + public static final String TEST_ACCESS_TOKEN = "5e482c2a-e83a-3afe-bc6a-ff79e1fdaaba"; + public static final String TEST_ACCESS_TOKEN_UPDATED = "fe326c2a-e83a-41fe-bc6a-ee79e1feabba"; + public static final String TEST_ACCESS_TOKEN_SECRET_REFERENCE = buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, + Authentication.Type.BEARER, Authentication.Property.ACCESS_TOKEN); + public static final String TEST_API_KEY_HEADER = "sampleHeader"; + public static final String TEST_API_KEY_HEADER_UPDATED = "UpdatedSampleHeader"; + public static final String TEST_INVALID_API_KEY_HEADER = "-test-header"; + public static final String TEST_API_KEY_VALUE = "sampleValue"; + public static final String TEST_API_KEY_VALUE_UPDATED = "UpdatedSampleValue"; + public static final String TEST_API_KEY_VALUE_SECRET_REFERENCE = buildSecretName(PRE_ISSUE_ACCESS_TOKEN_ACTION_ID, + Authentication.Type.API_KEY, Authentication.Property.VALUE); + + public static final String TEST_ACTION_PROPERTY_NAME_1 = "samplePropertyName"; + public static final String TEST_ACTION_PROPERTY_VALUE_1 = "samplePropertyValue"; + public static final String TEST_ACTION_PROPERTY_VALUE_1_UPDATED = "UpdatedSamplePropertyValue"; + public static final String TEST_ACTION_PROPERTY_NAME_2 = "samplePropertyName2"; + public static final String TEST_ACTION_PROPERTY_VALUE_2 = "samplePropertyValue2"; + public static final String TEST_ACTION_PROPERTY_VALUE_2_UPDATED = "UpdatedSamplePropertyValue2"; + public static final String PASSWORD_SHARING_TYPE_PROPERTY_NAME = "passwordSharingType"; + public static final String TEST_PASSWORD_SHARING_TYPE = "PLAIN_TEXT"; + public static final String TEST_PASSWORD_SHARING_TYPE_UPDATED = "SHA256_HASHED"; + public static final String CERTIFICATE_PROPERTY_NAME = "certificate"; + public static final String TEST_CERTIFICATE = "sampleCertificate"; + public static final String TEST_CERTIFICATE_UPDATED = "UpdatedSampleCertificate"; + public static final String CERTIFICATE_ID = String.valueOf(UUID.randomUUID()); + public static final String CERTIFICATE_NAME = "ACTIONS:" + PRE_UPDATE_PASSWORD_ACTION_ID; + + public static Action buildMockAction(String name, String description, String uri, Authentication authentication) { + + return new Action.ActionRequestBuilder() + .name(name) + .description(description) + .endpoint(buildMockEndpointConfig(uri, authentication)) + .build(); + } + + public static String buildSecretName(String actionId, Authentication.Type authType, + Authentication.Property authProperty) { + + return TEST_SECRET_TYPE_ID + ":" + actionId + ":" + authType.getName() + ":" + authProperty.getName(); + } + + public static Authentication buildMockBasicAuthentication(String username, String password) { + + return new Authentication.BasicAuthBuilder(username, password).build(); + } + + public static Authentication buildMockBearerAuthentication(String accessToken) { + + return new Authentication.BearerAuthBuilder(accessToken).build(); + } + + public static Authentication buildMockAPIKeyAuthentication(String header, String value) { + + return new Authentication.APIKeyAuthBuilder(header, value).build(); + } + + public static EndpointConfig buildMockEndpointConfig(String uri, Authentication authentication) { + + if (uri == null && authentication == null) { + return null; + } + + return new EndpointConfig.EndpointConfigBuilder() + .uri(uri) + .authentication(authentication) + .build(); + } +} diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/dbscripts/h2.sql b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/dbscripts/h2.sql index 776921371a60..9bf8470be8e8 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/dbscripts/h2.sql +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/dbscripts/h2.sql @@ -8,7 +8,7 @@ CREATE TABLE IF NOT EXISTS IDN_ACTION ( PRIMARY KEY (UUID) ); -CREATE TABLE IF NOT EXISTS IDN_ACTION_ENDPOINT ( +CREATE TABLE IF NOT EXISTS IDN_ACTION_PROPERTIES ( ACTION_UUID CHAR(36) NOT NULL, PROPERTY_NAME VARCHAR(100) NOT NULL, PROPERTY_VALUE VARCHAR(255) NOT NULL, diff --git a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/testng.xml b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/testng.xml index 60acc4cb2749..d9b62e751a03 100644 --- a/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/testng.xml +++ b/components/action-mgt/org.wso2.carbon.identity.action.management/src/test/resources/testng.xml @@ -21,10 +21,16 @@ - - - + + + + + + + + + diff --git a/components/action-mgt/pom.xml b/components/action-mgt/pom.xml index 68368957e296..90a50fe3901e 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.10-SNAPSHOT + 7.7.63-SNAPSHOT ../../pom.xml diff --git a/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/pom.xml b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/pom.xml new file mode 100644 index 000000000000..667885425533 --- /dev/null +++ b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/pom.xml @@ -0,0 +1,211 @@ + + + + + 4.0.0 + + org.wso2.carbon.identity.framework + ai-services-mgt + 7.6.10-SNAPSHOT + ../pom.xml + + + org.wso2.carbon.ai.service.mgt + bundle + WSO2 Carbon - AI Service Management Bundle + This is a Carbon bundle that represents the AI Service Management Bundle. + http://wso2.org + + + + org.ops4j.pax.logging + pax-logging-api + + + org.wso2.carbon.identity.framework + org.wso2.carbon.identity.core + + + org.wso2.orbit.org.apache.httpcomponents + httpasyncclient + + + org.apache.httpcomponents.wso2 + httpcore + provided + + + com.fasterxml.jackson.core + jackson-databind + + + org.mockito + mockito-core + + + org.testng + testng + test + + + org.slf4j + slf4j-api + + + org.apache.logging.log4j + log4j-core + test + + + org.wiremock + wiremock + test + + + + org.ops4j.pax.logging + pax-logging-api + + + + + + + + org.apache.felix + maven-bundle-plugin + true + + + + ${project.artifactId} + + ${project.artifactId} + + org.osgi.framework; version="${osgi.framework.imp.pkg.version.range}", + org.osgi.service.component; version="${osgi.service.component.imp.pkg.version.range}", + com.google.gson;version="${com.google.code.gson.osgi.version.range}", + org.wso2.carbon.identity.core.util; version="${carbon.identity.package.import.version.range}", + org.apache.commons.lang; version="${commons-lang.wso2.osgi.version.range}", + org.apache.commons.logging; version="${import.package.version.commons.logging}", + com.fasterxml.jackson.databind.*; version="${com.fasterxml.jackson.annotation.version.range}", + org.wso2.carbon.context; version="${carbon.kernel.package.import.version.range}", + + org.apache.http; version="${httpcore.version.osgi.import.range}", + org.apache.http.client; version="${httpcomponents-httpclient.imp.pkg.version.range}", + org.apache.http.client.methods; version="${httpcomponents-httpclient.imp.pkg.version.range}", + org.apache.http.entity; version="${httpcore.version.osgi.import.range}", + org.apache.http.message; version="${httpcore.version.osgi.import.range}", + org.apache.http.protocol; version="${httpcore.version.osgi.import.range}", + org.apache.http.util; version="${httpcore.version.osgi.import.range}", + org.apache.http.impl.client; version="${httpcomponents-httpclient.imp.pkg.version.range}", + org.apache.http.impl.nio.client; version="${httpasyncclient.version.osgi.import.range}", + org.apache.http.impl.nio.reactor; version="${httpasyncclient.version.osgi.import.range}", + org.apache.http.impl.nio.conn; version="${httpasyncclient.version.osgi.import.range}", + org.apache.http.concurrent; version="${httpcore.version.osgi.import.range}", + org.apache.http.nio.reactor; version="${httpasyncclient.version.osgi.import.range}", + org.apache.http.nio.conn; version="${httpasyncclient.version.osgi.import.range}", + + + org.wso2.carbon.ai.service.mgt.*; version="${carbon.identity.package.export.version}" + + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven.surefire.plugin.version} + + + + ${argLine} + --add-opens=java.base/java.lang=ALL-UNNAMED + --add-opens=java.base/java.util=ALL-UNNAMED + --add-opens java.xml/jdk.xml.internal=ALL-UNNAMED + --add-opens=java.base/java.io=ALL-UNNAMED + --add-opens=java.base/sun.nio.fs=ALL-UNNAMED + + + src/test/resources/testng.xml + + + + + org.jacoco + jacoco-maven-plugin + ${jacoco.version} + + + default-prepare-agent + + prepare-agent + + + + default-prepare-agent-integration + + prepare-agent-integration + + + + default-report + + report + + + + default-report-integration + + report-integration + + + + default-check + + check + + + + + BUNDLE + + + COMPLEXITY + COVEREDRATIO + 0.77 + + + + + + + + + + com.github.spotbugs + spotbugs-maven-plugin + + High + + + + + + diff --git a/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/main/java/org/wso2/carbon/ai/service/mgt/constants/AIConstants.java b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/main/java/org/wso2/carbon/ai/service/mgt/constants/AIConstants.java new file mode 100644 index 000000000000..252fd02f35f6 --- /dev/null +++ b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/main/java/org/wso2/carbon/ai/service/mgt/constants/AIConstants.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2025, 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.ai.service.mgt.constants; + +/** + * Constants for the LoginFlowAI module. + */ +public class AIConstants { + + public static final String AI_SERVICE_KEY_PROPERTY_NAME = "AIServices.Key"; + public static final String AI_TOKEN_ENDPOINT_PROPERTY_NAME = "AIServices.TokenEndpoint"; + public static final String AI_TOKEN_SERVICE_MAX_RETRIES_PROPERTY_NAME = "AIServices.TokenRequestMaxRetries"; + public static final String AI_TOKEN_SERVICE_TIMEOUT_PROPERTY_NAME = "AIServices.TokenRequestTimeout"; + public static final String HTTP_CONNECTION_POOL_SIZE_PROPERTY_NAME = "AIServices.HTTPConnectionPoolSize"; + public static final String HTTP_CONNECTION_TIMEOUT_PROPERTY_NAME = "AIServices.HTTPConnectionTimeout"; + + // Http constants. + public static final String HTTP_BASIC = "Basic"; + public static final String HTTP_BEARER = "Bearer"; + public static final String CONTENT_TYPE_FORM_URLENCODED = "application/x-www-form-urlencoded"; + public static final String CONTENT_TYPE_JSON = "application/json"; + + // Access Token response constants. + public static final String ACCESS_TOKEN_KEY = "access_token"; + + public static final String TENANT_CONTEXT_PREFIX = "/t/"; + + /** + * Enums for error messages. + */ + public enum ErrorMessages { + + MAXIMUM_RETRIES_EXCEEDED("AI_10000", "Maximum retries exceeded to retrieve the access token."), + UNABLE_TO_ACCESS_AI_SERVICE_WITH_RENEW_ACCESS_TOKEN("AI_10003", "Unable to access the " + + "AI service with the renewed access token."), + REQUEST_TIMEOUT("AI_10004", "Request to the AI service timed out."), + ERROR_RETRIEVING_ACCESS_TOKEN("AI_10007", "Error occurred while retrieving the " + + "access token."), + CLIENT_ERROR_WHILE_CONNECTING_TO_AI_SERVICE("AI_10008", "Client error occurred " + + "for %s tenant while connecting to AI service."), + SERVER_ERROR_WHILE_CONNECTING_TO_AI_SERVICE("AI_10009", "Server error occurred " + + "for %s tenant while connecting to AI service."); + + + private final String code; + private final String message; + + ErrorMessages(String code, String message) { + + this.code = code; + this.message = message; + } + + public String getCode() { + + return code; + } + + public String getMessage() { + + return message; + } + + @Override + public String toString() { + + return code + ":" + message; + } + } +} diff --git a/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/main/java/org/wso2/carbon/ai/service/mgt/exceptions/AIClientException.java b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/main/java/org/wso2/carbon/ai/service/mgt/exceptions/AIClientException.java new file mode 100644 index 000000000000..3272e573177e --- /dev/null +++ b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/main/java/org/wso2/carbon/ai/service/mgt/exceptions/AIClientException.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2025, 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.ai.service.mgt.exceptions; + +import org.wso2.carbon.ai.service.mgt.util.AIHttpClientUtil; + +/** + * Client Exception class for AI service. + */ +public class AIClientException extends Exception { + + private final String errorCode; + private AIHttpClientUtil.HttpResponseWrapper loginFlowAIResponse; + + public AIClientException(String message, String errorCode) { + + super(message); + this.errorCode = errorCode; + } + + public AIClientException(AIHttpClientUtil.HttpResponseWrapper httpResponseWrapper, + String message, String errorCode) { + + super(message); + this.errorCode = errorCode; + this.loginFlowAIResponse = httpResponseWrapper; + } + + public AIClientException(String message, String errorCode, Throwable cause) { + + super(message, cause); + this.errorCode = errorCode; + } + + public String getErrorCode() { + + return errorCode; + } + + public AIHttpClientUtil.HttpResponseWrapper getLoginFlowAIResponse() { + + return loginFlowAIResponse; + } +} diff --git a/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/main/java/org/wso2/carbon/ai/service/mgt/exceptions/AIServerException.java b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/main/java/org/wso2/carbon/ai/service/mgt/exceptions/AIServerException.java new file mode 100644 index 000000000000..1bdadca5a81e --- /dev/null +++ b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/main/java/org/wso2/carbon/ai/service/mgt/exceptions/AIServerException.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2025, 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.ai.service.mgt.exceptions; + +import org.wso2.carbon.ai.service.mgt.util.AIHttpClientUtil; + +/** + * Client Exception class for AI service. + */ +public class AIServerException extends Exception { + + private String errorCode; + private AIHttpClientUtil.HttpResponseWrapper loginFlowAIResponse; + + public AIServerException(String message, String errorCode) { + + super(message); + this.errorCode = errorCode; + } + + public AIServerException(AIHttpClientUtil.HttpResponseWrapper httpResponseWrapper, + String message, String errorCode) { + + super(message); + this.errorCode = errorCode; + this.loginFlowAIResponse = httpResponseWrapper; + } + + public AIServerException(String message, Throwable cause) { + + super(message, cause); + } + + public AIServerException(String message, String errorCode, Throwable cause) { + + super(message, cause); + this.errorCode = errorCode; + } + + public String getErrorCode() { + + return errorCode; + } + + public AIHttpClientUtil.HttpResponseWrapper getBrandingAIResponse() { + + return loginFlowAIResponse; + } +} diff --git a/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/main/java/org/wso2/carbon/ai/service/mgt/token/AIAccessTokenManager.java b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/main/java/org/wso2/carbon/ai/service/mgt/token/AIAccessTokenManager.java new file mode 100644 index 000000000000..d4c06c6c8c28 --- /dev/null +++ b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/main/java/org/wso2/carbon/ai/service/mgt/token/AIAccessTokenManager.java @@ -0,0 +1,265 @@ +/* + * Copyright (c) 2025, 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.ai.service.mgt.token; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonSyntaxException; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.concurrent.FutureCallback; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; +import org.apache.http.impl.nio.client.HttpAsyncClients; +import org.apache.http.message.BasicHeader; +import org.apache.http.protocol.HTTP; +import org.apache.http.util.EntityUtils; +import org.wso2.carbon.ai.service.mgt.exceptions.AIServerException; +import org.wso2.carbon.identity.core.util.IdentityUtil; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import static org.apache.axis2.transport.http.HTTPConstants.HEADER_CONTENT_TYPE; +import static org.apache.http.HttpHeaders.AUTHORIZATION; +import static org.wso2.carbon.ai.service.mgt.constants.AIConstants.ACCESS_TOKEN_KEY; +import static org.wso2.carbon.ai.service.mgt.constants.AIConstants.AI_SERVICE_KEY_PROPERTY_NAME; +import static org.wso2.carbon.ai.service.mgt.constants.AIConstants.AI_TOKEN_ENDPOINT_PROPERTY_NAME; +import static org.wso2.carbon.ai.service.mgt.constants.AIConstants.AI_TOKEN_SERVICE_MAX_RETRIES_PROPERTY_NAME; +import static org.wso2.carbon.ai.service.mgt.constants.AIConstants.AI_TOKEN_SERVICE_TIMEOUT_PROPERTY_NAME; +import static org.wso2.carbon.ai.service.mgt.constants.AIConstants.CONTENT_TYPE_FORM_URLENCODED; +import static org.wso2.carbon.ai.service.mgt.constants.AIConstants.ErrorMessages.MAXIMUM_RETRIES_EXCEEDED; +import static org.wso2.carbon.ai.service.mgt.constants.AIConstants.HTTP_BASIC; +import static org.wso2.carbon.identity.core.util.IdentityTenantUtil.getTenantDomainFromContext; + +/** + * The purpose of this class is to retrieve an active token to access the AI service. + */ +public class AIAccessTokenManager { + + private static volatile AIAccessTokenManager instance; // Volatile for thread safety. + private static final Object lock = new Object(); // Lock for synchronization. + + private static final Log LOG = LogFactory.getLog(AIAccessTokenManager.class); + + private static final String AI_KEY = IdentityUtil.getProperty(AI_SERVICE_KEY_PROPERTY_NAME); + private static final String AI_TOKEN_ENDPOINT = IdentityUtil.getProperty(AI_TOKEN_ENDPOINT_PROPERTY_NAME); + + private AccessTokenRequestHelper accessTokenRequestHelper; + + private String accessToken; + private final String clientId; + + private AIAccessTokenManager() { + + byte[] decodedBytes = Base64.getDecoder().decode(AI_KEY); + String decodedString = new String(decodedBytes, StandardCharsets.UTF_8); + String[] parts = decodedString.split(":"); + if (parts.length == 2) { + this.clientId = parts[0]; // Extract clientId. + } else { + throw new IllegalArgumentException("Invalid AI service key."); + } + } + + /** + * Get the singleton instance of the AIAccessTokenManager. + * + * @return The singleton instance. + */ + public static AIAccessTokenManager getInstance() { + + if (instance == null) { + synchronized (lock) { + if (instance == null) { + instance = new AIAccessTokenManager(); + } + } + } + return instance; + } + + /** + * Set the access token request helper. + * + * @param helper The access token request helper. + */ + protected void setAccessTokenRequestHelper(AccessTokenRequestHelper helper) { + + this.accessTokenRequestHelper = helper; + } + + /** + * Get the access token. + * + * @param renewAccessToken Whether to renew the access token. + * @return The access token. + * @throws AIServerException If an error occurs while obtaining the access token. + */ + public String getAccessToken(boolean renewAccessToken) throws AIServerException { + + if (StringUtils.isEmpty(accessToken) || renewAccessToken) { + synchronized (AIAccessTokenManager.class) { + if (StringUtils.isEmpty(accessToken) || renewAccessToken) { + this.accessToken = accessTokenRequestHelper != null ? + accessTokenRequestHelper.requestAccessToken() : createDefaultHelper().requestAccessToken(); + } + } + } + return this.accessToken; + } + + private AccessTokenRequestHelper createDefaultHelper() { + + return new AccessTokenRequestHelper(AI_KEY, AI_TOKEN_ENDPOINT, + // Here we keep the default HTTP client to send the token request. + // We open and close it for each request. + HttpAsyncClients.createDefault()); + } + + /** + * Get the client ID. + * + * @return The client ID. + */ + public String getClientId() { + + return this.clientId; + } + + /** + * Helper class to request access token from the AI services. + */ + protected static class AccessTokenRequestHelper { + + private final CloseableHttpAsyncClient client; + private final Gson gson; + private final String key; + private final String aiServiceTokenEndpoint; + private static final int MAX_RETRIES = IdentityUtil.getProperty( + AI_TOKEN_SERVICE_MAX_RETRIES_PROPERTY_NAME) != null ? + Integer.parseInt(IdentityUtil.getProperty(AI_TOKEN_SERVICE_MAX_RETRIES_PROPERTY_NAME)) : 3; + private static final long TIMEOUT = IdentityUtil.getProperty(AI_TOKEN_SERVICE_TIMEOUT_PROPERTY_NAME) != null ? + Long.parseLong(IdentityUtil.getProperty(AI_TOKEN_SERVICE_TIMEOUT_PROPERTY_NAME)) : 3000; + + AccessTokenRequestHelper(String key, String tokenEndpoint, CloseableHttpAsyncClient client) { + + this.client = client; + this.gson = new GsonBuilder().create(); + this.key = key; + this.aiServiceTokenEndpoint = tokenEndpoint; + } + + /** + * Request access token to access the AI services. + * + * @return the JWT access token. + * @throws AIServerException If an error occurs while requesting the access token. + */ + public String requestAccessToken() throws AIServerException { + + String tenantDomain = getTenantDomainFromContext(); + LOG.info("Initiating access token request for AI services from tenant: " + tenantDomain); + try { + client.start(); + for (int attempt = 0; attempt < MAX_RETRIES; attempt++) { + HttpPost post = new HttpPost(aiServiceTokenEndpoint); + post.setHeader(AUTHORIZATION, HTTP_BASIC + " " + key); + post.setHeader(HEADER_CONTENT_TYPE, CONTENT_TYPE_FORM_URLENCODED); + + StringEntity entity = new StringEntity("grant_type=client_credentials&tokenBindingId=" + + UUID.randomUUID()); + entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, CONTENT_TYPE_FORM_URLENCODED)); + post.setEntity(entity); + + CountDownLatch latch = new CountDownLatch(1); + final String[] accessToken = new String[1]; + client.execute(post, new FutureCallback() { + @Override + public void completed(HttpResponse response) { + + try { + if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { + String responseBody = EntityUtils.toString(response.getEntity()); + Map responseMap = gson.fromJson(responseBody, Map.class); + accessToken[0] = (String) responseMap.get(ACCESS_TOKEN_KEY); + } else { + LOG.error("Token request failed with status code: " + + response.getStatusLine().getStatusCode()); + } + } catch (IOException | JsonSyntaxException e) { + LOG.warn("Error parsing token response: " + e.getMessage(), e); + } finally { + latch.countDown(); + } + } + + @Override + public void failed(Exception e) { + + LOG.warn("Token request failed: " + e.getMessage(), e); + latch.countDown(); + } + + @Override + public void cancelled() { + + LOG.warn("Token request was cancelled"); + latch.countDown(); + } + }); + + if (latch.await(TIMEOUT, TimeUnit.MILLISECONDS)) { + if (accessToken[0] != null) { + return accessToken[0]; + } + } else { + LOG.warn("Token request timed out"); + } + // Wait before retrying. + TimeUnit.MILLISECONDS.sleep(500); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new AIServerException("Token request interrupted: " + e.getMessage(), e); + } catch (UnsupportedEncodingException e) { + throw new AIServerException("Error creating token request: " + e.getMessage(), e); + } finally { + try { + client.close(); + } catch (IOException e) { + LOG.error("Failed to close HTTP client: " + e.getMessage(), e); + } + } + // If it reaches this point. + throw new AIServerException("Failed to obtain access token after " + MAX_RETRIES + + " attempts.", MAXIMUM_RETRIES_EXCEEDED.getCode()); + } + } +} diff --git a/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/main/java/org/wso2/carbon/ai/service/mgt/util/AIHttpClientUtil.java b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/main/java/org/wso2/carbon/ai/service/mgt/util/AIHttpClientUtil.java new file mode 100644 index 000000000000..f4d8aa73292d --- /dev/null +++ b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/main/java/org/wso2/carbon/ai/service/mgt/util/AIHttpClientUtil.java @@ -0,0 +1,286 @@ +/* + * Copyright (c) 2025, 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.ai.service.mgt.util; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.concurrent.FutureCallback; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; +import org.apache.http.impl.nio.client.HttpAsyncClients; +import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager; +import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; +import org.apache.http.impl.nio.reactor.IOReactorConfig; +import org.apache.http.nio.reactor.ConnectingIOReactor; +import org.apache.http.util.EntityUtils; +import org.wso2.carbon.ai.service.mgt.exceptions.AIClientException; +import org.wso2.carbon.ai.service.mgt.exceptions.AIServerException; +import org.wso2.carbon.ai.service.mgt.token.AIAccessTokenManager; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.identity.core.util.IdentityUtil; + +import java.io.IOException; +import java.io.Serializable; +import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; + +import static org.apache.axis2.transport.http.HTTPConstants.HEADER_CONTENT_TYPE; +import static org.apache.http.HttpHeaders.AUTHORIZATION; +import static org.wso2.carbon.ai.service.mgt.constants.AIConstants.CONTENT_TYPE_JSON; +import static org.wso2.carbon.ai.service.mgt.constants.AIConstants.ErrorMessages.CLIENT_ERROR_WHILE_CONNECTING_TO_AI_SERVICE; +import static org.wso2.carbon.ai.service.mgt.constants.AIConstants.ErrorMessages.ERROR_RETRIEVING_ACCESS_TOKEN; +import static org.wso2.carbon.ai.service.mgt.constants.AIConstants.ErrorMessages.SERVER_ERROR_WHILE_CONNECTING_TO_AI_SERVICE; +import static org.wso2.carbon.ai.service.mgt.constants.AIConstants.ErrorMessages.UNABLE_TO_ACCESS_AI_SERVICE_WITH_RENEW_ACCESS_TOKEN; +import static org.wso2.carbon.ai.service.mgt.constants.AIConstants.HTTP_BEARER; +import static org.wso2.carbon.ai.service.mgt.constants.AIConstants.HTTP_CONNECTION_POOL_SIZE_PROPERTY_NAME; +import static org.wso2.carbon.ai.service.mgt.constants.AIConstants.HTTP_CONNECTION_TIMEOUT_PROPERTY_NAME; +import static org.wso2.carbon.ai.service.mgt.constants.AIConstants.TENANT_CONTEXT_PREFIX; + +/** + * Utility class for AI Services to send HTTP requests. + */ +public class AIHttpClientUtil { + + private static final Log LOG = LogFactory.getLog(AIHttpClientUtil.class); + private static final ObjectMapper objectMapper = new ObjectMapper(); + + private static final int HTTP_CONNECTION_POOL_SIZE = IdentityUtil.getProperty( + HTTP_CONNECTION_POOL_SIZE_PROPERTY_NAME) != null ? Integer.parseInt(IdentityUtil.getProperty( + HTTP_CONNECTION_POOL_SIZE_PROPERTY_NAME)) : 20; + private static final int HTTP_CONNECTION_TIMEOUT = IdentityUtil.getProperty( + HTTP_CONNECTION_TIMEOUT_PROPERTY_NAME) != null ? Integer.parseInt(IdentityUtil.getProperty( + HTTP_CONNECTION_TIMEOUT_PROPERTY_NAME)) : 60000; // Making the default timeout 60 seconds. + + + // Singleton instance of CloseableHttpAsyncClient with connection pooling. + private static final CloseableHttpAsyncClient httpClient; + + static { + // Configure the IO reactor. + IOReactorConfig ioReactorConfig = IOReactorConfig.custom() + .setIoThreadCount(Runtime.getRuntime().availableProcessors()) + .setConnectTimeout(HTTP_CONNECTION_TIMEOUT) + .build(); + ConnectingIOReactor ioReactor; + try { + // Create the IO reactor. + ioReactor = new DefaultConnectingIOReactor(ioReactorConfig); + } catch (IOException e) { + throw new RuntimeException("Error initializing IO Reactor", e); + } + // Create a connection manager with the IO reactor. + PoolingNHttpClientConnectionManager connectionManager = new PoolingNHttpClientConnectionManager(ioReactor); + // Maximum total connections. + connectionManager.setMaxTotal(HTTP_CONNECTION_POOL_SIZE); + // Initialize the HttpClient with the connection manager. + httpClient = HttpAsyncClients.custom() + .setConnectionManager(connectionManager) + .build(); + // Start the HttpClient. + httpClient.start(); + // Add a shutdown hook to close the client when the application stops. + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + try { + httpClient.close(); + } catch (IOException e) { + LOG.error("Error while shutting down HTTP client: " + e.getMessage()); + } + })); + } + + + + /** + * Execute a request to the AI service. + * + * @param path The endpoint to which the request should be sent. + * @param requestType The type of the request (GET, POST). + * @param requestBody The request body(Only for POST requests). + * @param aiServiceEndpoint The endpoint of the AI service. + * @return The response from the AI service as a map. + * @throws AIServerException If a server error occurred while accessing the AI service. + * @throws AIClientException If a client error occurred while accessing the AI service. + */ + public static Map executeRequest(String aiServiceEndpoint, String path, + Class requestType, Object requestBody) + throws AIServerException, AIClientException { + + String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + + try { + String accessToken = AIAccessTokenManager.getInstance().getAccessToken(false); + String orgName = AIAccessTokenManager.getInstance().getClientId(); + + HttpUriRequest request = createRequest(aiServiceEndpoint + TENANT_CONTEXT_PREFIX + orgName + path, + requestType, accessToken, requestBody); + HttpResponseWrapper aiServiceResponse = executeRequestWithRetry(request); + + int statusCode = aiServiceResponse.getStatusCode(); + String responseBody = aiServiceResponse.getResponseBody(); + + if (statusCode >= 400) { + handleErrorResponse(statusCode, responseBody, tenantDomain); + } + return convertJsonStringToMap(responseBody); + } catch (IOException | ExecutionException e) { + throw new AIServerException("An error occurred while connecting to the AI Service.", + SERVER_ERROR_WHILE_CONNECTING_TO_AI_SERVICE.getCode(), e); + } catch (InterruptedException e) { + // Restore the interrupted status of the thread to ensure it is not swallowed + // and can be handled appropriately by other parts of the program. This is + // important for proper thread coordination and graceful shutdown in a + // multithreaded environment. + Thread.currentThread().interrupt(); + + // Wrap and rethrow the exception as a custom AIServerException to provide + // a meaningful error message and maintain the original exception for debugging. + throw new AIServerException("An error occurred while connecting to the AI Service.", + SERVER_ERROR_WHILE_CONNECTING_TO_AI_SERVICE.getCode(), e); + } + } + + private static HttpUriRequest createRequest(String url, Class requestType, + String accessToken, Object requestBody) throws IOException { + + HttpUriRequest request; + if (requestType == HttpPost.class) { + HttpPost post = new HttpPost(url); + if (requestBody != null) { + post.setEntity(new StringEntity(objectMapper.writeValueAsString(requestBody))); + } + request = post; + } else if (requestType == HttpGet.class) { + request = new HttpGet(url); + } else { + throw new IllegalArgumentException("Unsupported request type: " + requestType.getName()); + } + + request.setHeader(AUTHORIZATION, HTTP_BEARER + " " + accessToken); + request.setHeader(HEADER_CONTENT_TYPE, CONTENT_TYPE_JSON); + return request; + } + + protected static HttpResponseWrapper executeRequestWithRetry(HttpUriRequest request) + throws InterruptedException, ExecutionException, IOException, AIServerException { + + HttpResponseWrapper response = executeHttpRequest(request); + + if (response.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { + String newAccessToken = AIAccessTokenManager.getInstance().getAccessToken(true); + if (newAccessToken == null) { + throw new AIServerException("Failed to renew access token.", ERROR_RETRIEVING_ACCESS_TOKEN.getCode()); + } + request.setHeader(AUTHORIZATION, HTTP_BEARER + " " + newAccessToken); + response = executeHttpRequest(request); + } + return response; + } + + private static void handleErrorResponse(int statusCode, String responseBody, String tenantDomain) + throws AIServerException, AIClientException { + + if (statusCode == HttpStatus.SC_UNAUTHORIZED) { + throw new AIServerException("Failed to access AI service with renewed access token for " + + "the tenant domain: " + tenantDomain, + UNABLE_TO_ACCESS_AI_SERVICE_WITH_RENEW_ACCESS_TOKEN.getCode()); + } else if (statusCode >= 400 && statusCode < 500) { + throw new AIClientException(new HttpResponseWrapper(statusCode, responseBody), + "Client error occurred from tenant: " + tenantDomain + " with status code: '" + statusCode + + "' while accessing AI service.", CLIENT_ERROR_WHILE_CONNECTING_TO_AI_SERVICE.getCode()); + } else if (statusCode >= 500) { + throw new AIServerException(new HttpResponseWrapper(statusCode, responseBody), + "Server error occurred from tenant: " + tenantDomain + " with status code: '" + statusCode + + "' while accessing AI service.", SERVER_ERROR_WHILE_CONNECTING_TO_AI_SERVICE.getCode()); + } + } + + private static Map convertJsonStringToMap(String jsonString) throws AIServerException { + + try { + return objectMapper.readValue(jsonString, Map.class); + } catch (IOException e) { + throw new AIServerException("Error occurred while parsing the JSON response from the AI service.", e); + } + } + + protected static HttpResponseWrapper executeHttpRequest(HttpUriRequest httpRequest) + throws InterruptedException, ExecutionException, IOException, AIServerException { + + Future apiResponse = AIHttpClientUtil.httpClient.execute(httpRequest, + new FutureCallback() { + @Override + public void completed(HttpResponse response) { + + LOG.info("API request completed with status code: " + response.getStatusLine().getStatusCode()); + } + + @Override + public void failed(Exception e) { + + LOG.error("API request failed: " + e.getMessage(), e); + } + + @Override + public void cancelled() { + + LOG.warn("API request was cancelled"); + } + }); + if (apiResponse == null) { + throw new AIServerException("Unable to get the response from the AI service.", + SERVER_ERROR_WHILE_CONNECTING_TO_AI_SERVICE.getCode()); + } + HttpResponse httpResponse = apiResponse.get(); + int status = httpResponse.getStatusLine().getStatusCode(); + String response = EntityUtils.toString(httpResponse.getEntity()); + return new HttpResponseWrapper(status, response); + } + + /** + * Wrapper class for HTTP response. + */ + public static class HttpResponseWrapper implements Serializable { + + private final int statusCode; + private final String responseBody; + + public HttpResponseWrapper(int statusCode, String responseBody) { + + this.statusCode = statusCode; + this.responseBody = responseBody; + } + + public int getStatusCode() { + + return statusCode; + } + + public String getResponseBody() { + + return responseBody; + } + } +} diff --git a/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/test/java/org/wso2/carbon/ai/service/mgt/constants/AIConstantsTest.java b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/test/java/org/wso2/carbon/ai/service/mgt/constants/AIConstantsTest.java new file mode 100644 index 000000000000..7eaf4ce9fca0 --- /dev/null +++ b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/test/java/org/wso2/carbon/ai/service/mgt/constants/AIConstantsTest.java @@ -0,0 +1,65 @@ +/* + * 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.ai.service.mgt.constants; + +import org.testng.annotations.Test; + +import static org.testng.AssertJUnit.assertEquals; + +/** + * Test class for AIConstants. + */ +public class AIConstantsTest { + + @Test + public void testErrorMessages() { + AIConstants.ErrorMessages errorMessage = AIConstants.ErrorMessages.MAXIMUM_RETRIES_EXCEEDED; + assertEquals(errorMessage.getCode(), "AI_10000"); + assertEquals(errorMessage.getMessage(), "Maximum retries exceeded to retrieve the access token."); + assertEquals(errorMessage.toString(), "AI_10000:Maximum retries exceeded to retrieve the access token."); + + errorMessage = AIConstants.ErrorMessages.UNABLE_TO_ACCESS_AI_SERVICE_WITH_RENEW_ACCESS_TOKEN; + assertEquals(errorMessage.getCode(), "AI_10003"); + assertEquals(errorMessage.getMessage(), "Unable to access the AI service with the renewed access token."); + assertEquals(errorMessage.toString(), "AI_10003:Unable to access the AI service with " + + "the renewed access token."); + + errorMessage = AIConstants.ErrorMessages.REQUEST_TIMEOUT; + assertEquals(errorMessage.getCode(), "AI_10004"); + assertEquals(errorMessage.getMessage(), "Request to the AI service timed out."); + assertEquals(errorMessage.toString(), "AI_10004:Request to the AI service timed out."); + + errorMessage = AIConstants.ErrorMessages.ERROR_RETRIEVING_ACCESS_TOKEN; + assertEquals(errorMessage.getCode(), "AI_10007"); + assertEquals(errorMessage.getMessage(), "Error occurred while retrieving the access token."); + assertEquals(errorMessage.toString(), "AI_10007:Error occurred while retrieving the access token."); + + errorMessage = AIConstants.ErrorMessages.CLIENT_ERROR_WHILE_CONNECTING_TO_AI_SERVICE; + assertEquals(errorMessage.getCode(), "AI_10008"); + assertEquals(errorMessage.getMessage(), "Client error occurred for %s tenant while connecting to AI service."); + assertEquals(errorMessage.toString(), "AI_10008:Client error occurred for %s tenant while" + + " connecting to AI service."); + + errorMessage = AIConstants.ErrorMessages.SERVER_ERROR_WHILE_CONNECTING_TO_AI_SERVICE; + assertEquals(errorMessage.getCode(), "AI_10009"); + assertEquals(errorMessage.getMessage(), "Server error occurred for %s tenant while connecting to AI service."); + assertEquals(errorMessage.toString(), "AI_10009:Server error occurred for %s tenant while " + + "connecting to AI service."); + } +} diff --git a/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/test/java/org/wso2/carbon/ai/service/mgt/exceptions/AIClientExceptionTest.java b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/test/java/org/wso2/carbon/ai/service/mgt/exceptions/AIClientExceptionTest.java new file mode 100644 index 000000000000..1fd73f24c95b --- /dev/null +++ b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/test/java/org/wso2/carbon/ai/service/mgt/exceptions/AIClientExceptionTest.java @@ -0,0 +1,61 @@ +/* + * 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.ai.service.mgt.exceptions; + +import org.testng.annotations.Test; +import org.wso2.carbon.ai.service.mgt.util.AIHttpClientUtil; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNull; + +/** + * Test class for AIClientException. + */ +public class AIClientExceptionTest { + + @Test + public void testAIClientExceptionWithMessageAndErrorCode() { + + AIClientException exception = new AIClientException("Test message", "AI_10001"); + assertEquals("Test message", exception.getMessage()); + assertEquals("AI_10001", exception.getErrorCode()); + assertNull(exception.getLoginFlowAIResponse()); + } + + @Test + public void testAIClientExceptionWithHttpResponseWrapperMessageAndErrorCode() { + + AIHttpClientUtil.HttpResponseWrapper responseWrapper = new AIHttpClientUtil.HttpResponseWrapper( + 400, "Test response"); + AIClientException exception = new AIClientException(responseWrapper, "Test message", "AI_10002"); + assertEquals("Test message", exception.getMessage()); + assertEquals("AI_10002", exception.getErrorCode()); + assertEquals(responseWrapper, exception.getLoginFlowAIResponse()); + } + + @Test + public void testAIClientExceptionWithMessageErrorCodeAndCause() { + Throwable cause = new Throwable("Cause message"); + AIClientException exception = new AIClientException("Test message", "AI_10003", cause); + assertEquals("Test message", exception.getMessage()); + assertEquals("AI_10003", exception.getErrorCode()); + assertEquals(cause, exception.getCause()); + assertNull(exception.getLoginFlowAIResponse()); + } +} diff --git a/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/test/java/org/wso2/carbon/ai/service/mgt/exceptions/AIServerExceptionTest.java b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/test/java/org/wso2/carbon/ai/service/mgt/exceptions/AIServerExceptionTest.java new file mode 100644 index 000000000000..17a4c992b509 --- /dev/null +++ b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/test/java/org/wso2/carbon/ai/service/mgt/exceptions/AIServerExceptionTest.java @@ -0,0 +1,71 @@ +/* + * 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.ai.service.mgt.exceptions; + +import org.testng.annotations.Test; +import org.wso2.carbon.ai.service.mgt.util.AIHttpClientUtil; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNull; + +/** + * Test class for AIServerException. + */ +public class AIServerExceptionTest { + + @Test + public void testAIServerExceptionWithMessageAndErrorCode() { + + AIServerException exception = new AIServerException("Test message", "AI_20001"); + assertEquals("Test message", exception.getMessage()); + assertEquals("AI_20001", exception.getErrorCode()); + assertNull(exception.getBrandingAIResponse()); + } + + @Test + public void testAIServerExceptionWithHttpResponseWrapperMessageAndErrorCode() { + + AIHttpClientUtil.HttpResponseWrapper responseWrapper = new AIHttpClientUtil.HttpResponseWrapper( + 500, "Test response"); + AIServerException exception = new AIServerException(responseWrapper, "Test message", "AI_20002"); + assertEquals("Test message", exception.getMessage()); + assertEquals("AI_20002", exception.getErrorCode()); + assertEquals(responseWrapper, exception.getBrandingAIResponse()); + } + + @Test + public void testAIServerExceptionWithMessageAndCause() { + Throwable cause = new Throwable("Cause message"); + AIServerException exception = new AIServerException("Test message", cause); + assertEquals("Test message", exception.getMessage()); + assertEquals(cause, exception.getCause()); + assertNull(exception.getBrandingAIResponse()); + } + + @Test + public void testAIServerExceptionWithMessageErrorCodeAndCause() { + + Throwable cause = new Throwable("Cause message"); + AIServerException exception = new AIServerException("Test message", "AI_20003", cause); + assertEquals("Test message", exception.getMessage()); + assertEquals("AI_20003", exception.getErrorCode()); + assertEquals(cause, exception.getCause()); + assertNull(exception.getBrandingAIResponse()); + } +} diff --git a/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/test/java/org/wso2/carbon/ai/service/mgt/token/AIAccessTokenManagerTest.java b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/test/java/org/wso2/carbon/ai/service/mgt/token/AIAccessTokenManagerTest.java new file mode 100644 index 000000000000..3f4fad6f7332 --- /dev/null +++ b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/test/java/org/wso2/carbon/ai/service/mgt/token/AIAccessTokenManagerTest.java @@ -0,0 +1,276 @@ +/* + * 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.ai.service.mgt.token; + +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.StatusLine; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.concurrent.FutureCallback; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.testng.Assert; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; +import org.wso2.carbon.ai.service.mgt.exceptions.AIServerException; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.Base64; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Future; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * Test class for AIAccessTokenManager. + */ +public class AIAccessTokenManagerTest { + + @Mock + private CloseableHttpAsyncClient mockHttpClient; + + @Mock + private Future mockFuture; + + @Mock + private HttpResponse mockResponse; + + @Mock + private StatusLine mockStatusLine; + + private AIAccessTokenManager tokenManager; + private TestAccessTokenRequestHelper testHelper; + private AIAccessTokenManager.AccessTokenRequestHelper helper; + + @BeforeMethod + public void setUp() throws NoSuchFieldException, IllegalAccessException { + + MockitoAnnotations.openMocks(this); + testHelper = new TestAccessTokenRequestHelper(mockHttpClient); + String key = Base64.getEncoder().encodeToString("testClientId:testClientSecret".getBytes()); + assignAIKey(key); + tokenManager = AIAccessTokenManager.getInstance(); + tokenManager.setAccessTokenRequestHelper(testHelper); + + helper = new AIAccessTokenManager.AccessTokenRequestHelper(key, "endpoint", mockHttpClient); + } + + @AfterMethod + public void tearDown() { + + // Reset other mocks and state. + tokenManager = null; + testHelper = null; + } + + @Test + public void testGetInstance() { + + AIAccessTokenManager instance1 = AIAccessTokenManager.getInstance(); + AIAccessTokenManager instance2 = AIAccessTokenManager.getInstance(); + Assert.assertSame(instance1, instance2, "getInstance should always return the same instance"); + } + + @Test + public void testGetAccessToken_Success() throws Exception { + + String expectedToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbGllbnRfaWQiOiJ0ZXN0Q2xpZW50SWQifQ.signature"; + setupMockHttpResponse(HttpStatus.SC_OK, "{\"access_token\":\"" + expectedToken + "\"}"); + + String token = tokenManager.getAccessToken(true); + Assert.assertEquals(token, expectedToken); + Assert.assertEquals(tokenManager.getClientId(), "testClientId"); + } + + @Test + public void testGetAccessToken_Renewal() throws Exception { + + setupMockHttpResponse(HttpStatus.SC_OK, "{\"access_token\":\"oldToken\"}"); + String token1 = tokenManager.getAccessToken(false); + + setupMockHttpResponse(HttpStatus.SC_OK, "{\"access_token\":\"newToken\"}"); + String token2 = tokenManager.getAccessToken(true); + + Assert.assertNotEquals(token1, token2, "Tokens should be different after renewal"); + } + + @Test(expectedExceptions = AIServerException.class) + public void testGetAccessToken_HttpError() throws Exception { + + setupMockHttpResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Internal Server Error"); + tokenManager.getAccessToken(false); + } + + @Test(expectedExceptions = AIServerException.class) + public void testGetAccessToken_Timeout() throws Exception { + + when(mockHttpClient.execute(any(HttpPost.class), any(FutureCallback.class))).thenReturn(mockFuture); + when(mockFuture.get()).thenThrow(new InterruptedException("Timeout")); + tokenManager.getAccessToken(true); + } + + @Test(expectedExceptions = AIServerException.class) + public void testGetAccessToken_MaxRetriesExceeded() throws Exception { + setupMockHttpResponse(HttpStatus.SC_BAD_REQUEST, "Bad Request"); + tokenManager.getAccessToken(false); + } + + @Test(expectedExceptions = AIServerException.class) + public void testGetAccessToken_InterruptedDuringRequest() throws Exception { + when(mockHttpClient.execute(any(HttpPost.class), any(FutureCallback.class))).thenAnswer(invocation -> { + Thread.currentThread().interrupt(); + throw new InterruptedException("Request interrupted"); + }); + + try { + tokenManager.getAccessToken(false); + } finally { + Assert.assertTrue(Thread.interrupted(), "Thread interrupt flag should be cleared"); + } + } + + @Test + public void completed_InvalidJsonResponse() throws Exception { + setupMockHttpResponse(HttpStatus.SC_OK, "Invalid JSON"); + + try { + tokenManager.getAccessToken(true); + Assert.fail("Expected AIServerException to be thrown"); + } catch (AIServerException e) { + Assert.assertTrue(e.getMessage().contains("Failed to obtain access token after 3 attempts.")); + } + } + + @Test + public void testFailedScenario() throws Exception { + ArgumentCaptor> captor = ArgumentCaptor.forClass(FutureCallback.class); + doNothing().when(mockHttpClient).start(); + doAnswer(invocation -> { + FutureCallback callback = captor.getValue(); + callback.failed(new Exception("Test Exception")); + return null; + }).when(mockHttpClient).execute(any(), captor.capture()); + + try { + helper.requestAccessToken(); + } catch (AIServerException e) { + assertEquals("Failed to obtain access token after 3 attempts.", e.getMessage()); + } + + verify(mockHttpClient, times(1)).start(); + verify(mockHttpClient, times(3)).execute(any(), any(FutureCallback.class)); + } + + @Test + public void testCancelledScenario() throws Exception { + + ArgumentCaptor> captor = ArgumentCaptor.forClass(FutureCallback.class); + doNothing().when(mockHttpClient).start(); + doAnswer(invocation -> { + FutureCallback callback = captor.getValue(); + callback.cancelled(); + return null; + }).when(mockHttpClient).execute(any(), captor.capture()); + + try { + helper.requestAccessToken(); + } catch (AIServerException e) { + assertEquals("Failed to obtain access token after 3 attempts.", e.getMessage()); + } + + verify(mockHttpClient, times(1)).start(); + verify(mockHttpClient, times(3)).execute(any(), any(FutureCallback.class)); + } + + @Test(expectedExceptions = AIServerException.class) + public void testRequestAccessToken_IOException() throws Exception { + + CloseableHttpAsyncClient mockClient = mock(CloseableHttpAsyncClient.class); + doThrow(new IOException("Test IOException")).when(mockClient).close(); + + AIAccessTokenManager.AccessTokenRequestHelper helper = + new AIAccessTokenManager.AccessTokenRequestHelper("key", "endpoint", mockClient); + + helper.requestAccessToken(); + } + + private void setupMockHttpResponse(int statusCode, String responseBody) throws Exception { + + when(mockHttpClient.execute(any(HttpPost.class), any(FutureCallback.class))).thenAnswer(invocation -> { + FutureCallback callback = invocation.getArgument(1); + when(mockResponse.getStatusLine()).thenReturn(mockStatusLine); + when(mockStatusLine.getStatusCode()).thenReturn(statusCode); + when(mockResponse.getEntity()).thenReturn(new StringEntity(responseBody)); + callback.completed(mockResponse); + return mockFuture; + }); + when(mockFuture.get()).thenReturn(mockResponse); + } + + // Custom AccessTokenRequestHelper for testing. + private class TestAccessTokenRequestHelper extends AIAccessTokenManager.AccessTokenRequestHelper { + public TestAccessTokenRequestHelper(CloseableHttpAsyncClient client) { + super("testKey", "https://test.endpoint", client); + } + + @Override + public String requestAccessToken() throws AIServerException { + try { + return super.requestAccessToken(); + } catch (AIServerException e) { + // Rethrow AIServerException directly for testing purposes. + throw e; + } catch (Exception e) { + throw new AIServerException("Test exception", e); + } + } + } + + private static void assignAIKey(String key) throws NoSuchFieldException, IllegalAccessException { + + // Target class and field. + Class targetClass = AIAccessTokenManager.class; + Field aiKeyField = targetClass.getDeclaredField("AI_KEY"); + + // Make the field accessible. + aiKeyField.setAccessible(true); + + // Remove the "final" modifier. + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); + modifiersField.setInt(aiKeyField, aiKeyField.getModifiers() & ~Modifier.FINAL); + + // Set the new value. + aiKeyField.set(null, key); // null because it's a static field. + } +} diff --git a/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/test/java/org/wso2/carbon/ai/service/mgt/util/AIHttpClientUtilTest.java b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/test/java/org/wso2/carbon/ai/service/mgt/util/AIHttpClientUtilTest.java new file mode 100644 index 000000000000..f364e2a635a4 --- /dev/null +++ b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/test/java/org/wso2/carbon/ai/service/mgt/util/AIHttpClientUtilTest.java @@ -0,0 +1,494 @@ +/* + * 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.ai.service.mgt.util; + +import com.github.tomakehurst.wiremock.WireMockServer; +import com.github.tomakehurst.wiremock.http.Fault; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpUriRequest; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.testng.Assert; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; +import org.wso2.carbon.ai.service.mgt.exceptions.AIClientException; +import org.wso2.carbon.ai.service.mgt.exceptions.AIServerException; +import org.wso2.carbon.ai.service.mgt.token.AIAccessTokenManager; +import org.wso2.carbon.base.CarbonBaseConstants; +import org.wso2.carbon.context.PrivilegedCarbonContext; + +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Map; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; +import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; +import static com.github.tomakehurst.wiremock.stubbing.Scenario.STARTED; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.openMocks; +import static org.wso2.carbon.ai.service.mgt.constants.AIConstants.TENANT_CONTEXT_PREFIX; + +/** + * Test class for AIHttpClientUtil. + */ +public class AIHttpClientUtilTest { + + private WireMockServer wireMockServer; + private final String clientId = "testClientId"; + + @Mock + private AIAccessTokenManager mockTokenManager; + + private MockedStatic aiAccessTokenManagerMockedStatic; + + @BeforeMethod + public void setUp() throws Exception { + + openMocks(this); + setCarbonHome(); + setCarbonContextForTenant(); + + aiAccessTokenManagerMockedStatic = mockStatic(AIAccessTokenManager.class); + when(AIAccessTokenManager.getInstance()).thenReturn(mockTokenManager); + when(mockTokenManager.getAccessToken(false)).thenReturn("testToken"); + when(mockTokenManager.getClientId()).thenReturn(clientId); + + // Start WireMock server on a random port. + wireMockServer = new WireMockServer(wireMockConfig().dynamicPort()); + wireMockServer.start(); + + // Reset WireMock state for each test. + wireMockServer.resetAll(); + } + + @Test + public void testExecuteRequest_Success() throws Exception { + + // Arrange: Mock a successful response. + String expectedResponse = "{\"result\":\"SUCCESS\"}"; + String path = "/test-endpoint"; + String fullPath = TENANT_CONTEXT_PREFIX + clientId + path; // This is the path that AIHttpClientUtil will use. + wireMockServer.stubFor(get(urlEqualTo(fullPath)) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "application/json") + .withBody(expectedResponse))); + + // Act: Execute the HTTP request. + String baseUrl = wireMockServer.baseUrl(); + Map resultMap = AIHttpClientUtil.executeRequest( + baseUrl, + path, + HttpGet.class, + null + ); + + // Assert: Verify the response. + Assert.assertEquals(resultMap.get("result"), "SUCCESS"); + wireMockServer.verify(getRequestedFor(urlEqualTo(fullPath))); + } + + @Test + public void testExecuteRequest_PostSuccess() throws Exception { + + // Arrange: Mock a successful response. + String expectedResponse = "{\"result\":\"POST_SUCCESS\"}"; + String path = "/test-endpoint"; + String fullPath = TENANT_CONTEXT_PREFIX + clientId + path; // This is the path that AIHttpClientUtil will use. + + // Define the request body. + String requestBody = "{\"key\":\"value\"}"; + + // Stub the POST request with the expected response. + wireMockServer.stubFor(post(urlEqualTo(fullPath)) + .withHeader("Content-Type", equalTo("application/json")) + .withRequestBody(equalToJson(requestBody)) // Ensure the request body matches. + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "application/json") + .withBody(expectedResponse))); + + // Act: Execute the HTTP request. + String baseUrl = wireMockServer.baseUrl(); + Map requestBodyMap = new HashMap<>(); + requestBodyMap.put("key", "value"); + Map resultMap = AIHttpClientUtil.executeRequest( + baseUrl, + path, + HttpPost.class, + requestBodyMap // Pass the request body as a map. + ); + + // Assert: Verify the response. + Assert.assertEquals(resultMap.get("result"), "POST_SUCCESS"); + + // Verify that the POST request was made with the correct path and body. + wireMockServer.verify(postRequestedFor(urlEqualTo(fullPath)) + .withHeader("Content-Type", equalTo("application/json")) + .withRequestBody(equalToJson(requestBody))); + } + + + @Test(expectedExceptions = AIClientException.class) + public void testExecuteRequest_ClientError() throws Exception { + + // Arrange: Mock a client error response + String path = "/test-endpoint"; + String fullPath = TENANT_CONTEXT_PREFIX + clientId + path; // This is the path that AIHttpClientUtil will use. + wireMockServer.stubFor(get(urlEqualTo(fullPath)) + .willReturn(aResponse() + .withStatus(400) // Client error status. + .withHeader("Content-Type", "application/json") + .withBody("Bad Request"))); + + // Act & Assert: Expect AIClientException. + String baseUrl = wireMockServer.baseUrl(); + AIHttpClientUtil.executeRequest( + baseUrl, + path, + HttpGet.class, + null + ); + } + + @Test(expectedExceptions = AIServerException.class) + public void testExecuteRequest_ServerError() throws Exception { + + // Arrange: Mock a server error response. + String path = "/test-endpoint"; + String fullPath = TENANT_CONTEXT_PREFIX + clientId + path; // This is the path that AIHttpClientUtil will use. + wireMockServer.stubFor(get(urlEqualTo(fullPath)) + .willReturn(aResponse() + .withStatus(500) // Simulate a server error. + .withHeader("Content-Type", "text/plain") + .withBody("Internal Server Error"))); + + // Act & Assert: Execute the HTTP request and expect AIServerException. + String baseUrl = wireMockServer.baseUrl(); + AIHttpClientUtil.executeRequest( + baseUrl, + path, + HttpGet.class, + null + ); + } + + @Test + public void testExecuteRequest_TokenRenewal() throws Exception { + + // Mock the AccessTokenManager to simulate token renewal. + when(mockTokenManager.getAccessToken(true)).thenReturn("newToken"); + + // Arrange: Mock token renewal flow. + String expectedResponse = "{\"result\":\"SUCCESS\"}"; + String path = "/test-endpoint"; + String fullPath = TENANT_CONTEXT_PREFIX + clientId + path; // This is the path that AIHttpClientUtil will use. + + // First response: 401 Unauthorized. + wireMockServer.stubFor(get(urlEqualTo(fullPath)) + .inScenario("Token Renewal") + .whenScenarioStateIs(STARTED) + .willReturn(aResponse() + .withStatus(401) // Unauthorized. + .withHeader("Content-Type", "application/json") + .withBody("Unauthorized")) + .willSetStateTo("Token Renewed")); // Transition to the next state. + + // Second response: 200 OK. + wireMockServer.stubFor(get(urlEqualTo(fullPath)) + .inScenario("Token Renewal") + .whenScenarioStateIs("Token Renewed") + .willReturn(aResponse() + .withStatus(200) // Success + .withHeader("Content-Type", "application/json") + .withBody(expectedResponse))); + + // Act: Execute the HTTP request. + String baseUrl = wireMockServer.baseUrl(); + Map resultMap = AIHttpClientUtil.executeRequest( + baseUrl, + path, + HttpGet.class, + null + ); + + // Assert: Verify the response. + Assert.assertEquals(resultMap.get("result"), "SUCCESS"); + + // Verify the requests were made twice: once for 401 and once for 200. + wireMockServer.verify(2, getRequestedFor(urlEqualTo(fullPath))); + + // Verify token renewal was called once. + verify(mockTokenManager, times(1)).getAccessToken(true); + } + + @Test(expectedExceptions = AIClientException.class) + public void testExecuteRequest_TokenRenewal_ErrorAfterRenewal() throws Exception { + // Mock the AccessTokenManager to simulate token renewal. + when(mockTokenManager.getAccessToken(true)).thenReturn("newToken"); + + // Arrange: Define paths and mock token renewal flow. + String path = "/test-endpoint"; + String fullPath = TENANT_CONTEXT_PREFIX + clientId + path; // This is the path that AIHttpClientUtil will use. + + // First response: 401 Unauthorized. + wireMockServer.stubFor(get(urlEqualTo(fullPath)) + .inScenario("Token Renewal with Error") + .whenScenarioStateIs(STARTED) + .willReturn(aResponse() + .withStatus(401) // Unauthorized. + .withHeader("Content-Type", "application/json") + .withBody("Unauthorized")) + .willSetStateTo("Token Renewed")); // Transition to the next state. + + // Second response: 400 Bad Request (or you can use 500 for Internal Server Error). + wireMockServer.stubFor(get(urlEqualTo(fullPath)) + .inScenario("Token Renewal with Error") + .whenScenarioStateIs("Token Renewed") + .willReturn(aResponse() + .withStatus(400) // Client-side error. + .withHeader("Content-Type", "application/json") + .withBody("{\"error\":\"Bad Request\"}"))); // Error response body. + + // Act: Execute the HTTP request. + String baseUrl = wireMockServer.baseUrl(); + AIHttpClientUtil.executeRequest( + baseUrl, + path, + HttpGet.class, + null + ); + } + + @Test(expectedExceptions = AIServerException.class) + public void testExecuteRequest_IOException() throws Exception { + + // Arrange: Mock a server that simulates a connection reset. + String path = "/test-endpoint"; + String fullPath = TENANT_CONTEXT_PREFIX + clientId + path; // This is the path that AIHttpClientUtil will use. + + // Simulate a connection reset. + wireMockServer.stubFor(get(urlEqualTo(fullPath)) + .willReturn(aResponse() + .withFault(Fault.CONNECTION_RESET_BY_PEER))); // Simulates a connection reset. + + // Act & Assert: Expect AIServerException due to simulated IOException (connection reset). + String baseUrl = wireMockServer.baseUrl(); + AIHttpClientUtil.executeRequest( + baseUrl, + path, + HttpGet.class, + null + ); + } + + @Test(expectedExceptions = AIServerException.class) + public void testExecuteRequest_ExecutionException() throws Exception { + + // Arrange: Mock a server that simulates an unexpected response. + String path = "/test-endpoint"; + String fullPath = TENANT_CONTEXT_PREFIX + clientId + path; // This is the path that AIHttpClientUtil will use. + + // Simulate an unexpected response that triggers an ExecutionException. + wireMockServer.stubFor(get(urlEqualTo(fullPath)) + .willReturn(aResponse() + .withFault(Fault.MALFORMED_RESPONSE_CHUNK))); // Simulates a malformed response + + // Act & Assert: Expect AIServerException due to simulated ExecutionException. + String baseUrl = wireMockServer.baseUrl(); + AIHttpClientUtil.executeRequest( + baseUrl, + path, + HttpGet.class, + null + ); + } + + @Test(expectedExceptions = AIServerException.class) + public void testExecuteRequest_InterruptedException() throws Exception { + + // Arrange: Mock a server that responds but simulate thread interruption manually. + String path = "/test-endpoint"; + String fullPath = TENANT_CONTEXT_PREFIX + clientId + path; // This is the path that AIHttpClientUtil will use. + + // Simulate a valid server response to ensure interruption occurs in client code. + wireMockServer.stubFor(get(urlEqualTo(fullPath)) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "application/json") + .withBody("{\"result\":\"SUCCESS\"}"))); + + // Simulate interruption in the thread executing the HTTP request. + Thread.currentThread().interrupt(); // Mark the thread as interrupted. + + try { + // Act: Execute the HTTP request. + String baseUrl = wireMockServer.baseUrl(); + AIHttpClientUtil.executeRequest( + baseUrl, + path, + HttpGet.class, + null + ); + } finally { + // Assert: Verify that the thread is still marked as interrupted. + Assert.assertTrue(Thread.currentThread().isInterrupted(), "Thread should be marked as interrupted"); + } + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testExecuteRequest_UnsupportedRequestType() throws Exception { + + // Arrange: Define the path and base URL. + String path = "/test-endpoint"; + String baseUrl = "https://ai-service.example.com"; + + // Act & Assert: Pass an unsupported request type and expect IllegalArgumentException. + AIHttpClientUtil.executeRequest( + baseUrl, + path, + HttpUriRequest.class, // Unsupported request type. + null + ); + } + + @Test(expectedExceptions = AIServerException.class) + public void testExecuteRequest_UnauthorizedAfterTokenRenewal() throws Exception { + + // Mock the AccessTokenManager for token renewal. + when(mockTokenManager.getAccessToken(true)).thenReturn("newToken"); + + // Arrange: Define paths. + String path = "/test-endpoint"; + String fullPath = TENANT_CONTEXT_PREFIX + clientId + path; // This is the path that AIHttpClientUtil will use. + + // First response: 401 Unauthorized + wireMockServer.stubFor(get(urlEqualTo(fullPath)) + .inScenario("Token Renewal Fails") + .whenScenarioStateIs(STARTED) + .willReturn(aResponse() + .withStatus(401) // Unauthorized + .withHeader("Content-Type", "application/json") + .withBody("Unauthorized")) + .willSetStateTo("Retry")); + + // Second response: 401 Unauthorized again + wireMockServer.stubFor(get(urlEqualTo(fullPath)) + .inScenario("Token Renewal Fails") + .whenScenarioStateIs("Retry") + .willReturn(aResponse() + .withStatus(401) // Still Unauthorized + .withHeader("Content-Type", "application/json") + .withBody("Still Unauthorized"))); + + // Act: Execute the HTTP request + String baseUrl = wireMockServer.baseUrl(); + AIHttpClientUtil.executeRequest( + baseUrl, + path, + HttpGet.class, + null + ); + } + + @Test(expectedExceptions = AIServerException.class) + public void testExecuteRequest_JsonParsingError() throws Exception { + + // Arrange: Define paths. + String path = "/test-endpoint"; + String fullPath = TENANT_CONTEXT_PREFIX + clientId + path; // This is the path that AIHttpClientUtil will use. + + // Mock the server to return invalid JSON. + wireMockServer.stubFor(get(urlEqualTo(fullPath)) + .willReturn(aResponse() + .withStatus(200) // Simulate a successful response. + .withHeader("Content-Type", "application/json") + .withBody("{ invalid json }"))); // Invalid JSON. + + // Act: Execute the HTTP request, expecting AIServerException due to JSON parsing error. + String baseUrl = wireMockServer.baseUrl(); + AIHttpClientUtil.executeRequest( + baseUrl, + path, + HttpGet.class, + null + ); + } + + @Test(expectedExceptions = AIServerException.class) + public void testExecuteRequest_FailedTokenRenewal() throws Exception { + + // Mock the AccessTokenManager to simulate failed token renewal. + when(mockTokenManager.getAccessToken(false)).thenReturn("oldToken"); + when(mockTokenManager.getAccessToken(true)).thenReturn(null); // Simulate failed token renewal. + + // Arrange: Define paths. + String path = "/test-endpoint"; + String fullPath = TENANT_CONTEXT_PREFIX + clientId + path; // This is the path that AIHttpClientUtil will use. + + // Mock the server to return 401 Unauthorized. + wireMockServer.stubFor(get(urlEqualTo(fullPath)) + .willReturn(aResponse() + .withStatus(401) // Unauthorized + .withHeader("Content-Type", "application/json") + .withBody("Unauthorized"))); + + // Act: Execute the HTTP request, expecting AIServerException due to failed token renewal. + String baseUrl = wireMockServer.baseUrl(); + AIHttpClientUtil.executeRequest( + baseUrl, + path, + HttpGet.class, + null + ); + } + + private void setCarbonHome() { + + 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, "conf").toString()); + } + + private void setCarbonContextForTenant() { + + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); + } + + @AfterMethod + public void tearDown() { + + aiAccessTokenManagerMockedStatic.close(); + PrivilegedCarbonContext.endTenantFlow(); + wireMockServer.stop(); + } +} diff --git a/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/test/resources/conf/carbon.xml b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/test/resources/conf/carbon.xml new file mode 100755 index 000000000000..e2f7f02dc050 --- /dev/null +++ b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/test/resources/conf/carbon.xml @@ -0,0 +1,686 @@ + + + + + + + + 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/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/test/resources/conf/identity/identity.xml b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/test/resources/conf/identity/identity.xml new file mode 100644 index 000000000000..1bf7cb28de20 --- /dev/null +++ b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/test/resources/conf/identity/identity.xml @@ -0,0 +1,994 @@ + + + + + + + + + jdbc/WSO2IdentityDB + + + + + true + true + 0 + + true + 20160 + 1140 + + + 50000 + + + true + + + + true + + 20 + + 40 + + + + + + + 15 + 20160 + + + + + + ${carbon.home}/conf/keystores + SunX509 + SunX509 + + + + localhost + + + 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 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ${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}/api/identity/oauth2/dcr/v1.1/register + ${carbon.protocol}://${carbon.host}:${carbon.management.port}/oauth2/jwks + ${carbon.protocol}://${carbon.host}:${carbon.management.port}/oauth2/oidcdiscovery + + + 300 + + 3600 + + 3600 + + 84600 + + 0 + + true + + org.wso2.carbon.identity.oauth.tokenprocessor.PlainTextPersistenceProcessor + + false + + 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 + false + false + + + 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 + + + urn:ietf:params:oauth:grant-type:jwt-bearer + org.wso2.carbon.identity.oauth2.grant.jwt.JWTBearerGrantHandler + org.wso2.carbon.identity.oauth2.grant.jwt.JWTGrantValidator + + + + + + + authorization_code + + + implicit + + + + + + + + + + + + + + + + + + + + + + + + + false + + + + + + + + false + + + + false + org.wso2.carbon.identity.oauth2.authcontext.JWTTokenGenerator + org.wso2.carbon.identity.oauth2.authcontext.DefaultClaimsRetriever + http://wso2.org/claims + SHA256withRSA + 15 + + + + + + + FEDERATED + + + + + org.wso2.carbon.identity.openidconnect.DefaultIDTokenBuilder + SHA256withRSA + + + RSA-OAEP + + A128GCM + + + + RSA1_5 + RSA-OAEP + + + A128GCM + A192GCM + A256GCM + A128CBC-HS256 + A128CBC+HS256 + + + true + + + + + ${carbon.protocol}://${carbon.host}:${carbon.management.port}/oauth2/token + org.wso2.carbon.identity.openidconnect.SAMLAssertionClaimsCallback + 3600 + SHA256withRSA + 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 + + false + + 120 + + + + + request_param_value_builder + org.wso2.carbon.identity.openidconnect.RequestParamRequestObjectBuilder + + + + + org.wso2.carbon.identity.openidconnect.RequestObjectValidatorImpl + + + + + true + 0 + 5 + + + + + + + + gtalk + talk.google.com + 5222 + gmail.com + multifactor1@gmail.com + wso2carbon + + + + + + ${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.DefaultSAMLAssertionBuilder + 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 + http://www.w3.org/2001/04/xmlenc#aes256-cbc + http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p + true + + + + + 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 + + + + + + + + + + + + + + + + + false + + true + true + + + true + + + + + + + + + + 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/v1.0/ + /api/identity/consent-mgt/v1.0/ + /api/identity/recovery/v0.9/ + /oauth2/ + /scim2/ + /api/identity/entitlement/ + /api/identity/oauth2/dcr/v1.1/ + + + /identity/(.*) + + + + + 300 + + + + true + + 1000 + 1000 + 51200 + + + + + + http://localhost:8280/ + + 5 + + + + + + + + + + diff --git a/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/test/resources/dbscripts/identity.sql b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/test/resources/dbscripts/identity.sql new file mode 100644 index 000000000000..ff1e7a44b2d4 --- /dev/null +++ b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/test/resources/dbscripts/identity.sql @@ -0,0 +1,1241 @@ +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', + 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) +); + +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, + PRIMARY KEY (TOKEN_ID), + FOREIGN KEY (TOKEN_ID) REFERENCES IDN_OAUTH2_ACCESS_TOKEN(TOKEN_ID) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS IDN_OAUTH2_ACCESS_TOKEN_AUDIT ( + 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 +); + + +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(60), + 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), + 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), + UNIQUE (USER_CODE), + 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 (60), + 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 ( + 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) +); + +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), + 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 ( + USER_ID VARCHAR(255) NOT NULL, + SESSION_ID VARCHAR(255) NOT NULL, + CONSTRAINT USER_SESSION_STORE_CONSTRAINT UNIQUE (USER_ID, SESSION_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 SP_TRUSTED_APPS ( + ID INTEGER AUTO_INCREMENT, + SP_ID INTEGER NOT NULL, + PLATFORM_TYPE VARCHAR(255) NOT NULL, + APP_IDENTIFIER VARCHAR(255) NOT NULL, + THUMBPRINTS VARCHAR(2048), + IS_FIDO_TRUSTED BOOLEAN DEFAULT FALSE, + TENANT_ID INTEGER DEFAULT -1, + PRIMARY KEY (ID), + UNIQUE (SP_ID, PLATFORM_TYPE), + FOREIGN KEY (SP_ID) REFERENCES SP_APP(ID) ON DELETE CASCADE); + +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), + 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 (TENANT_ID, DOMAIN_NAME, USER_NAME, USER_HANDLE)); + +CREATE TABLE IF NOT EXISTS WF_REQUEST ( + UUID VARCHAR (45), + CREATED_BY VARCHAR (255), + TENANT_ID INTEGER DEFAULT -1, + OPERATION_TYPE VARCHAR (50), + CREATED_AT TIMESTAMP, + UPDATED_AT TIMESTAMP, + STATUS VARCHAR (30), + REQUEST BLOB, + PRIMARY KEY (UUID) +); + +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), + EXP_TIME TIMESTAMP NOT NULL , + TIME_CREATED TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP , + PRIMARY KEY (JWT_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 ( + 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 +); + +CREATE TABLE IF NOT EXISTS IDN_FED_AUTH_SESSION_MAPPING ( + 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, + PRIMARY KEY(IDP_SESSION_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'); + +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 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 API_RESOURCE ( + ID VARCHAR(255) 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 VARCHAR(255) NOT NULL PRIMARY KEY, + CURSOR_KEY INTEGER NOT NULL AUTO_INCREMENT, + API_ID VARCHAR(255) NOT NULL, + NAME VARCHAR(255) NOT NULL, + DISPLAY_NAME VARCHAR(255) NOT NULL, + DESCRIPTION VARCHAR(300), + TENANT_ID INT, + FOREIGN KEY (API_ID) REFERENCES API_RESOURCE(ID) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS AUTHORIZED_API( + APP_ID VARCHAR(255) NOT NULL, + API_ID VARCHAR(255) NOT NULL, + POLICY_ID VARCHAR(255) NOT NULL, + 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 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 +); + +-- --------------------------- 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); + +-- 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); + +-- 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_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); + +-- 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); diff --git a/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/test/resources/log4j.properties b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/test/resources/log4j.properties new file mode 100644 index 000000000000..5a83c3d02a16 --- /dev/null +++ b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/test/resources/log4j.properties @@ -0,0 +1,26 @@ +# +# 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. +# + +# Root logger option +log4j.rootLogger=INFO, stdout + +# Direct log messages to stdout +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement.common/src/test/resources/testng.xml b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/test/resources/testng.xml similarity index 57% rename from components/entitlement/org.wso2.carbon.identity.entitlement.common/src/test/resources/testng.xml rename to components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/test/resources/testng.xml index 65977e15934b..69d12f19d4d5 100644 --- a/components/entitlement/org.wso2.carbon.identity.entitlement.common/src/test/resources/testng.xml +++ b/components/ai-services-mgt/org.wso2.carbon.ai.service.mgt/src/test/resources/testng.xml @@ -18,9 +18,14 @@ - - + + + + + + + diff --git a/components/ai-services-mgt/pom.xml b/components/ai-services-mgt/pom.xml new file mode 100644 index 000000000000..65195c69b8b3 --- /dev/null +++ b/components/ai-services-mgt/pom.xml @@ -0,0 +1,44 @@ + + + + + 4.0.0 + + + org.wso2.carbon.identity.framework + identity-framework + 7.6.10-SNAPSHOT + ../../pom.xml + + + ai-services-mgt + pom + WSO2 Carbon - AI Management Aggregator Module + + This is a Carbon bundle that represent the AI Management Aggregator Module. + + http://wso2.org + + + org.wso2.carbon.ai.service.mgt + + + 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 f8d5de5238ad..31247b348114 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.10-SNAPSHOT + 7.7.63-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 992947c6d6b5..8c17ad730e25 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.10-SNAPSHOT + 7.7.63-SNAPSHOT ../pom.xml org.wso2.carbon.identity.api.resource.mgt diff --git a/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/src/main/java/org/wso2/carbon/identity/api/resource/mgt/constant/APIResourceManagementConstants.java b/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/src/main/java/org/wso2/carbon/identity/api/resource/mgt/constant/APIResourceManagementConstants.java index 1cae1164c087..ff39212152cb 100644 --- a/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/src/main/java/org/wso2/carbon/identity/api/resource/mgt/constant/APIResourceManagementConstants.java +++ b/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/src/main/java/org/wso2/carbon/identity/api/resource/mgt/constant/APIResourceManagementConstants.java @@ -142,7 +142,16 @@ public enum ErrorMessages { "properties.", "Error while adding API resource properties to the database."), ERROR_CODE_ERROR_WHILE_UPDATING_SCOPE_METADATA("65015", "Error while updating scope metadata.", "Error while updating scope metadata in the database."), - ; + ERROR_CODE_ERROR_WHILE_RESOLVING_ORGANIZATION_FOR_TENANT("65016", "Error while resolving organization", + "Error while resolving organization for tenant domain : %s"), + ERROR_CODE_ADDING_API_RESOURCE_NOT_SUPPORTED_FOR_ORGANIZATIONS("65017", "Unable to add API resources", + "Adding API resource is not supported for organizations."), + ERROR_CODE_DELETING_API_RESOURCE_NOT_SUPPORTED_FOR_ORGANIZATIONS("65018", "Unable to delete API resources", + "Deleting API resource is not supported for organizations."), + ERROR_CODE_ADDING_SCOPES_NOT_SUPPORTED_FOR_ORGANIZATIONS("65019", "Unable to add scopes", + "Adding scope is not supported for organizations."), + ERROR_CODE_DELETING_SCOPES_NOT_SUPPORTED_FOR_ORGANIZATIONS("65020", "Unable to add scopes", + "Deleting scope is not supported for organizations."); private final String code; private final String message; diff --git a/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/src/main/java/org/wso2/carbon/identity/api/resource/mgt/constant/SQLConstants.java b/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/src/main/java/org/wso2/carbon/identity/api/resource/mgt/constant/SQLConstants.java index 19458f21a30f..f4cce52c6213 100644 --- a/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/src/main/java/org/wso2/carbon/identity/api/resource/mgt/constant/SQLConstants.java +++ b/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/src/main/java/org/wso2/carbon/identity/api/resource/mgt/constant/SQLConstants.java @@ -65,10 +65,19 @@ public class SQLConstants { "DESCRIPTION, TENANT_ID, TYPE, REQUIRES_AUTHORIZATION FROM API_RESOURCE WHERE "; public static final String GET_API_RESOURCES_TAIL = " (TENANT_ID = %d OR TENANT_ID IS NULL) ORDER BY CURSOR_KEY %s LIMIT %d"; + public static final String GET_API_RESOURCES_TAIL_FOR_ORGANIZATIONS = + " (TENANT_ID = %d OR TENANT_ID IS NULL) AND TYPE NOT IN ('TENANT', 'SYSTEM', 'CONSOLE_FEATURE') " + + "ORDER BY CURSOR_KEY %s LIMIT %d"; public static final String GET_API_RESOURCES_TAIL_MSSQL = " (TENANT_ID = %d OR TENANT_ID IS NULL) ORDER BY CURSOR_KEY %s"; + public static final String GET_API_RESOURCES_TAIL_FOR_ORGANIZATIONS_MSSQL = + " (TENANT_ID = %d OR TENANT_ID IS NULL) AND TYPE NOT IN ('TENANT', 'SYSTEM', 'CONSOLE_FEATURE') ORDER " + + "BY CURSOR_KEY %s"; public static final String GET_API_RESOURCES_TAIL_ORACLE = " (TENANT_ID = %d OR TENANT_ID IS NULL) ORDER BY CURSOR_KEY %s FETCH FIRST %d ROWS ONLY"; + public static final String GET_API_RESOURCES_TAIL_FOR_ORGANIZATIONS_ORACLE = + " (TENANT_ID = %d OR TENANT_ID IS NULL) AND TYPE NOT IN ('TENANT', 'SYSTEM', 'CONSOLE_FEATURE') " + + "ORDER BY CURSOR_KEY %s FETCH FIRST %d ROWS ONLY"; public static final String GET_API_RESOURCES_WITH_PROPERTIES_SELECTION = "SELECT" + " AR.ID AS API_RESOURCE_ID," + " AR.CURSOR_KEY AS CURSOR_KEY," + @@ -99,6 +108,8 @@ public class SQLConstants { " LEFT JOIN API_RESOURCE_PROPERTY ARP ON AR.ID = ARP.API_ID ORDER BY CURSOR_KEY %s"; public static final String GET_API_RESOURCES_COUNT = "SELECT COUNT(DISTINCT(ID)) FROM API_RESOURCE WHERE "; public static final String GET_API_RESOURCES_COUNT_TAIL = " (TENANT_ID = ? OR TENANT_ID IS NULL)"; + public static final String GET_API_RESOURCES_COUNT_FOR_ORGANIZATIONS_TAIL = + " (TENANT_ID = ? OR TENANT_ID IS NULL) AND TYPE NOT IN ('TENANT', 'SYSTEM', 'CONSOLE_FEATURE')"; public static final String GET_API_RESOURCE_BY_ID = "SELECT" + " AR.ID AS API_RESOURCE_ID," + " AR.NAME AS API_RESOURCE_NAME," + @@ -113,6 +124,20 @@ public class SQLConstants { " S.DESCRIPTION AS SCOPE_DESCRIPTION" + " FROM API_RESOURCE AR LEFT JOIN SCOPE S ON AR.ID = S.API_ID WHERE AR.ID = ? AND (AR.TENANT_ID = ?" + " OR AR.TENANT_ID IS NULL)"; + public static final String GET_API_RESOURCE_BY_ID_FOR_ORGANIZATIONS = "SELECT" + + " AR.ID AS API_RESOURCE_ID," + + " AR.NAME AS API_RESOURCE_NAME," + + " AR.IDENTIFIER AS API_RESOURCE_IDENTIFIER," + + " AR.DESCRIPTION AS API_RESOURCE_DESCRIPTION," + + " AR.TENANT_ID AS API_RESOURCE_TENANT_ID," + + " AR.TYPE AS API_RESOURCE_TYPE," + + " AR.REQUIRES_AUTHORIZATION AS REQUIRES_AUTHORIZATION," + + " S.ID AS SCOPE_ID," + + " S.NAME AS SCOPE_QUALIFIED_NAME," + + " S.DISPLAY_NAME AS SCOPE_DISPLAY_NAME," + + " S.DESCRIPTION AS SCOPE_DESCRIPTION" + + " FROM API_RESOURCE AR LEFT JOIN SCOPE S ON AR.ID = S.API_ID WHERE AR.ID = ? AND (AR.TENANT_ID = ?" + + " OR AR.TENANT_ID IS NULL) AND AR.TYPE NOT IN ('TENANT', 'SYSTEM', 'CONSOLE_FEATURE')"; public static final String GET_SCOPES_BY_API_ID = "SELECT ID, NAME, DISPLAY_NAME, DESCRIPTION, API_ID, TENANT_ID " + "FROM SCOPE WHERE API_ID = ? AND (TENANT_ID = ? OR TENANT_ID IS NULL)"; public static final String GET_API_RESOURCE_BY_IDENTIFIER = "SELECT" + @@ -151,6 +176,12 @@ public class SQLConstants { public static final String GET_SCOPES_BY_TENANT_ID = "SELECT ID, NAME, DISPLAY_NAME, DESCRIPTION, API_ID, " + "TENANT_ID FROM SCOPE WHERE "; public static final String GET_SCOPES_BY_TENANT_ID_TAIL = " (TENANT_ID = ? OR TENANT_ID IS NULL)"; + public static final String GET_SCOPES_BY_TENANT_ID_FOR_ORGANIZATIONS = + "SELECT SC.ID, SC.NAME, SC.DISPLAY_NAME, SC.DESCRIPTION, SC.API_ID, SC.TENANT_ID FROM SCOPE SC" + + " JOIN API_RESOURCE AR ON AR.ID = SC.API_ID" + + " WHERE "; + public static final String GET_SCOPES_BY_TENANT_ID_FOR_ORGANIZATIONS_TAIL = "(AR.TENANT_ID = ? OR AR.TENANT_ID " + + "IS NULL) AND TYPE NOT IN ('TENANT', 'SYSTEM', 'CONSOLE_FEATURE')"; public static final String DELETE_SCOPE_BY_NAME = "DELETE FROM SCOPE WHERE NAME = ? AND TENANT_ID = ?"; public static final String GET_API_RESOURCE_PROPERTIES_BY_API_ID = "SELECT ID, NAME, VALUE FROM " + "API_RESOURCE_PROPERTY WHERE API_ID = ?"; diff --git a/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/src/main/java/org/wso2/carbon/identity/api/resource/mgt/dao/impl/APIResourceManagementDAOImpl.java b/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/src/main/java/org/wso2/carbon/identity/api/resource/mgt/dao/impl/APIResourceManagementDAOImpl.java index f69704d0abdd..14784f5ecde3 100644 --- a/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/src/main/java/org/wso2/carbon/identity/api/resource/mgt/dao/impl/APIResourceManagementDAOImpl.java +++ b/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/src/main/java/org/wso2/carbon/identity/api/resource/mgt/dao/impl/APIResourceManagementDAOImpl.java @@ -20,12 +20,14 @@ import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; +import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.identity.api.resource.mgt.APIResourceMgtClientException; import org.wso2.carbon.identity.api.resource.mgt.APIResourceMgtException; import org.wso2.carbon.identity.api.resource.mgt.APIResourceMgtServerException; import org.wso2.carbon.identity.api.resource.mgt.constant.APIResourceManagementConstants; import org.wso2.carbon.identity.api.resource.mgt.constant.SQLConstants; import org.wso2.carbon.identity.api.resource.mgt.dao.APIResourceManagementDAO; +import org.wso2.carbon.identity.api.resource.mgt.internal.APIResourceManagementServiceComponentHolder; import org.wso2.carbon.identity.api.resource.mgt.model.FilterQueryBuilder; import org.wso2.carbon.identity.api.resource.mgt.util.APIResourceManagementUtil; import org.wso2.carbon.identity.application.common.model.APIResource; @@ -35,6 +37,9 @@ import org.wso2.carbon.identity.core.model.ExpressionNode; import org.wso2.carbon.identity.core.util.IdentityCoreConstants; import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; +import org.wso2.carbon.identity.core.util.IdentityTenantUtil; +import org.wso2.carbon.identity.organization.management.service.exception.OrganizationManagementException; +import org.wso2.carbon.identity.organization.management.service.util.OrganizationManagementUtil; import java.sql.Connection; import java.sql.PreparedStatement; @@ -94,6 +99,17 @@ public Integer getAPIResourcesCount(Integer tenantId, List expre Map filterAttributeValue = filterQueryBuilder.getFilterAttributeValue(); String getAPIResourcesCountSqlStmtTail = SQLConstants.GET_API_RESOURCES_COUNT_TAIL; + try { + if (OrganizationManagementUtil.isOrganization(tenantId)) { + tenantId = getRootOrganizationTenantId(tenantId); + getAPIResourcesCountSqlStmtTail = SQLConstants.GET_API_RESOURCES_COUNT_FOR_ORGANIZATIONS_TAIL; + } + } catch (OrganizationManagementException e) { + throw APIResourceManagementUtil.handleServerException(APIResourceManagementConstants.ErrorMessages + .ERROR_CODE_ERROR_WHILE_RESOLVING_ORGANIZATION_FOR_TENANT, e, + IdentityTenantUtil.getTenantDomain(tenantId)); + } + String sqlStmt = SQLConstants.GET_API_RESOURCES_COUNT + filterQueryBuilder.getFilterQuery() + getAPIResourcesCountSqlStmtTail; @@ -124,6 +140,16 @@ public Integer getAPIResourcesCount(Integer tenantId, List expre @Override public APIResource addAPIResource(APIResource apiResource, Integer tenantId) throws APIResourceMgtException { + try { + if (OrganizationManagementUtil.isOrganization(tenantId)) { + throw APIResourceManagementUtil.handleClientException(APIResourceManagementConstants.ErrorMessages + .ERROR_CODE_ADDING_API_RESOURCE_NOT_SUPPORTED_FOR_ORGANIZATIONS); + } + } catch (OrganizationManagementException e) { + throw APIResourceManagementUtil.handleServerException(APIResourceManagementConstants.ErrorMessages. + ERROR_CODE_ERROR_WHILE_RESOLVING_ORGANIZATION_FOR_TENANT, e, + IdentityTenantUtil.getTenantDomain(tenantId)); + } String generatedAPIId = UUID.randomUUID().toString(); try (Connection dbConnection = IdentityDatabaseUtil.getDBConnection(true)) { try { @@ -228,8 +254,19 @@ public boolean isAPIResourceExistById(String apiId, Integer tenantId) throws API @Override public APIResource getAPIResourceById(String apiId, Integer tenantId) throws APIResourceMgtException { + String query = SQLConstants.GET_API_RESOURCE_BY_ID; + try { + if (OrganizationManagementUtil.isOrganization(tenantId)) { + tenantId = getRootOrganizationTenantId(tenantId); + query = SQLConstants.GET_API_RESOURCE_BY_ID_FOR_ORGANIZATIONS; + } + } catch (OrganizationManagementException e) { + throw APIResourceManagementUtil.handleServerException(APIResourceManagementConstants.ErrorMessages. + ERROR_CODE_ERROR_WHILE_RESOLVING_ORGANIZATION_FOR_TENANT, e, + IdentityTenantUtil.getTenantDomain(tenantId)); + } try (Connection dbConnection = IdentityDatabaseUtil.getDBConnection(false); - PreparedStatement preparedStatement = dbConnection.prepareStatement(SQLConstants.GET_API_RESOURCE_BY_ID)) { + PreparedStatement preparedStatement = dbConnection.prepareStatement(query)) { preparedStatement.setString(1, apiId); preparedStatement.setInt(2, tenantId); ResultSet resultSet = preparedStatement.executeQuery(); @@ -326,6 +363,16 @@ public void updateScopeMetadata(Scope scope, APIResource apiResource, Integer te @Override public void deleteAPIResourceById(String apiId, Integer tenantId) throws APIResourceMgtException { + try { + if (OrganizationManagementUtil.isOrganization(tenantId)) { + throw APIResourceManagementUtil.handleClientException(APIResourceManagementConstants.ErrorMessages + .ERROR_CODE_DELETING_API_RESOURCE_NOT_SUPPORTED_FOR_ORGANIZATIONS); + } + } catch (OrganizationManagementException e) { + throw APIResourceManagementUtil.handleServerException(APIResourceManagementConstants.ErrorMessages. + ERROR_CODE_ERROR_WHILE_RESOLVING_ORGANIZATION_FOR_TENANT, e, + IdentityTenantUtil.getTenantDomain(tenantId)); + } try (Connection dbConnection = IdentityDatabaseUtil.getDBConnection(true)) { try { PreparedStatement prepStmt = dbConnection.prepareStatement(SQLConstants.DELETE_SCOPES_BY_API); @@ -450,6 +497,19 @@ public List getScopesByTenantId(Integer tenantId, List ex appendFilterQuery(expressionNodes, filterQueryBuilder, true); String query = SQLConstants.GET_SCOPES_BY_TENANT_ID + filterQueryBuilder.getFilterQuery() + SQLConstants.GET_SCOPES_BY_TENANT_ID_TAIL; + try { + if (OrganizationManagementUtil.isOrganization(tenantId)) { + FilterQueryBuilder filterQueryBuilderForOrg = new FilterQueryBuilder(); + appendFilterQueryForOrganizations(expressionNodes, filterQueryBuilderForOrg, true); + tenantId = getRootOrganizationTenantId(tenantId); + query = SQLConstants.GET_SCOPES_BY_TENANT_ID_FOR_ORGANIZATIONS + filterQueryBuilderForOrg + .getFilterQuery() + SQLConstants.GET_SCOPES_BY_TENANT_ID_FOR_ORGANIZATIONS_TAIL; + } + } catch (OrganizationManagementException e) { + throw APIResourceManagementUtil.handleServerException(APIResourceManagementConstants.ErrorMessages + .ERROR_CODE_ERROR_WHILE_RESOLVING_ORGANIZATION_FOR_TENANT, e, + IdentityTenantUtil.getTenantDomain(tenantId)); + } PreparedStatement preparedStatement = dbConnection.prepareStatement(query); preparedStatement.setInt(1, tenantId); int filterAttrSize = 0; @@ -483,6 +543,17 @@ public List getScopesByTenantId(Integer tenantId, List ex @Override public void addScopes(List scopes, String apiId, Integer tenantId) throws APIResourceMgtException { + try { + if (OrganizationManagementUtil.isOrganization(tenantId)) { + throw APIResourceManagementUtil.handleClientException(APIResourceManagementConstants.ErrorMessages + .ERROR_CODE_ADDING_SCOPES_NOT_SUPPORTED_FOR_ORGANIZATIONS); + } + } catch (OrganizationManagementException e) { + throw APIResourceManagementUtil.handleServerException(APIResourceManagementConstants.ErrorMessages. + ERROR_CODE_ERROR_WHILE_RESOLVING_ORGANIZATION_FOR_TENANT, e, + IdentityTenantUtil.getTenantDomain(tenantId)); + } + try (Connection dbConnection = IdentityDatabaseUtil.getDBConnection(true)) { addScopes(dbConnection, apiId, scopes, tenantId); IdentityDatabaseUtil.commitTransaction(dbConnection); @@ -495,6 +566,17 @@ public void addScopes(List scopes, String apiId, Integer tenantId) throws @Override public void deleteAllScopes(String apiId, Integer tenantId) throws APIResourceMgtException { + try { + if (OrganizationManagementUtil.isOrganization(tenantId)) { + throw APIResourceManagementUtil.handleClientException(APIResourceManagementConstants.ErrorMessages + .ERROR_CODE_DELETING_SCOPES_NOT_SUPPORTED_FOR_ORGANIZATIONS); + } + } catch (OrganizationManagementException e) { + throw APIResourceManagementUtil.handleServerException(APIResourceManagementConstants.ErrorMessages. + ERROR_CODE_ERROR_WHILE_RESOLVING_ORGANIZATION_FOR_TENANT, e, + IdentityTenantUtil.getTenantDomain(tenantId)); + } + try (Connection dbConnection = IdentityDatabaseUtil.getDBConnection(true)) { deleteScopeByAPIId(dbConnection, apiId, tenantId); IdentityDatabaseUtil.commitTransaction(dbConnection); @@ -507,6 +589,17 @@ public void deleteAllScopes(String apiId, Integer tenantId) throws APIResourceMg @Override public void deleteScope(String apiId, String scopeName, Integer tenantId) throws APIResourceMgtException { + try { + if (OrganizationManagementUtil.isOrganization(tenantId)) { + throw APIResourceManagementUtil.handleClientException(APIResourceManagementConstants.ErrorMessages + .ERROR_CODE_DELETING_SCOPES_NOT_SUPPORTED_FOR_ORGANIZATIONS); + } + } catch (OrganizationManagementException e) { + throw APIResourceManagementUtil.handleServerException(APIResourceManagementConstants.ErrorMessages. + ERROR_CODE_ERROR_WHILE_RESOLVING_ORGANIZATION_FOR_TENANT, e, + IdentityTenantUtil.getTenantDomain(tenantId)); + } + try (Connection dbConnection = IdentityDatabaseUtil.getDBConnection(true)) { deleteScopeByName(dbConnection, scopeName, tenantId); IdentityDatabaseUtil.commitTransaction(dbConnection); @@ -783,15 +876,38 @@ private static APIResource getApiResource(ResultSet resultSet, List expressionNodes, FilterQuery attributeName = APIResourceManagementConstants.SCOPE_ATTRIBUTE_COLUMN_MAP.get(attributeValue); } - if (StringUtils.isNotBlank(attributeName) && StringUtils.isNotBlank(value) && StringUtils - .isNotBlank(operation)) { - switch (operation) { - case APIResourceManagementConstants.EQ: { - equalFilterBuilder(count, value, attributeName, filter, filterQueryBuilder); - ++count; - break; - } - case APIResourceManagementConstants.NE: { - notEqualFilterBuilder(count, value, attributeName, filter, filterQueryBuilder); - ++count; - break; - } - case APIResourceManagementConstants.SW: { - startWithFilterBuilder(count, value, attributeName, filter, filterQueryBuilder); - ++count; - break; - } - case APIResourceManagementConstants.EW: { - endWithFilterBuilder(count, value, attributeName, filter, filterQueryBuilder); - ++count; - break; - } - case APIResourceManagementConstants.CO: { - containsFilterBuilder(count, value, attributeName, filter, filterQueryBuilder); - ++count; - break; - } - case APIResourceManagementConstants.GE: { - greaterThanOrEqualFilterBuilder(count, value, attributeName, filter, filterQueryBuilder); - ++count; - break; - } - case APIResourceManagementConstants.LE: { - lessThanOrEqualFilterBuilder(count, value, attributeName, filter, filterQueryBuilder); - ++count; - break; - } - case APIResourceManagementConstants.GT: { - greaterThanFilterBuilder(count, value, attributeName, filter, filterQueryBuilder); - ++count; - break; - } - case APIResourceManagementConstants.LT: { - lessThanFilterBuilder(count, value, attributeName, filter, filterQueryBuilder); - ++count; - break; - } - default: { - break; - } - } - } else { - throw APIResourceManagementUtil.handleClientException( - APIResourceManagementConstants.ErrorMessages.ERROR_CODE_INVALID_FILTER_VALUE); + count = buildFilterBasedOnOperation(filterQueryBuilder, attributeName, value, operation, count, filter); + } + if (StringUtils.isBlank(filter.toString())) { + filterQueryBuilder.setFilterQuery(StringUtils.EMPTY); + } else { + filterQueryBuilder.setFilterQuery(filter.toString()); + } + } + } + + /** + * Append the filter query to the query builder for the organization level. + * + * @param expressionNodes List of expression nodes. + * @param filterQueryBuilder Filter query builder. + * @param isScopeFilter Whether the filter is for scopes. + * @throws APIResourceMgtClientException If an error occurs while appending the filter query. + */ + private void appendFilterQueryForOrganizations(List expressionNodes, + FilterQueryBuilder filterQueryBuilder, boolean isScopeFilter) + throws APIResourceMgtClientException { + + int count = 1; + StringBuilder filter = new StringBuilder(); + if (CollectionUtils.isEmpty(expressionNodes)) { + filterQueryBuilder.setFilterQuery(StringUtils.EMPTY); + } else { + for (ExpressionNode expressionNode : expressionNodes) { + String operation = expressionNode.getOperation(); + String value = expressionNode.getValue(); + String attributeValue = expressionNode.getAttributeValue(); + String attributeName = "AR." + APIResourceManagementConstants.ATTRIBUTE_COLUMN_MAP.get(attributeValue); + + // If the filter is for scopes, get the column name from the scope attribute map. + if (isScopeFilter) { + attributeName = "SC." + APIResourceManagementConstants.SCOPE_ATTRIBUTE_COLUMN_MAP + .get(attributeValue); } + + count = buildFilterBasedOnOperation(filterQueryBuilder, attributeName, value, operation, count, filter); } if (StringUtils.isBlank(filter.toString())) { filterQueryBuilder.setFilterQuery(StringUtils.EMPTY); @@ -1122,6 +1223,69 @@ private void appendFilterQuery(List expressionNodes, FilterQuery } } + private int buildFilterBasedOnOperation(FilterQueryBuilder filterQueryBuilder, String attributeName, + String value, String operation, int count, StringBuilder filter) + throws APIResourceMgtClientException { + + if (StringUtils.isNotBlank(attributeName) && StringUtils.isNotBlank(value) && StringUtils + .isNotBlank(operation)) { + switch (operation) { + case APIResourceManagementConstants.EQ: { + equalFilterBuilder(count, value, attributeName, filter, filterQueryBuilder); + ++count; + break; + } + case APIResourceManagementConstants.NE: { + notEqualFilterBuilder(count, value, attributeName, filter, filterQueryBuilder); + ++count; + break; + } + case APIResourceManagementConstants.SW: { + startWithFilterBuilder(count, value, attributeName, filter, filterQueryBuilder); + ++count; + break; + } + case APIResourceManagementConstants.EW: { + endWithFilterBuilder(count, value, attributeName, filter, filterQueryBuilder); + ++count; + break; + } + case APIResourceManagementConstants.CO: { + containsFilterBuilder(count, value, attributeName, filter, filterQueryBuilder); + ++count; + break; + } + case APIResourceManagementConstants.GE: { + greaterThanOrEqualFilterBuilder(count, value, attributeName, filter, filterQueryBuilder); + ++count; + break; + } + case APIResourceManagementConstants.LE: { + lessThanOrEqualFilterBuilder(count, value, attributeName, filter, filterQueryBuilder); + ++count; + break; + } + case APIResourceManagementConstants.GT: { + greaterThanFilterBuilder(count, value, attributeName, filter, filterQueryBuilder); + ++count; + break; + } + case APIResourceManagementConstants.LT: { + lessThanFilterBuilder(count, value, attributeName, filter, filterQueryBuilder); + ++count; + break; + } + default: { + break; + } + } + } else { + throw APIResourceManagementUtil.handleClientException( + APIResourceManagementConstants.ErrorMessages.ERROR_CODE_INVALID_FILTER_VALUE); + } + return count; + } + private void equalFilterBuilder(int count, String value, String attributeName, StringBuilder filter, FilterQueryBuilder filterQueryBuilder) { @@ -1193,4 +1357,16 @@ private void lessThanFilterBuilder(int count, String value, String attributeName filter.append(attributeName).append(filterString); filterQueryBuilder.setFilterAttributeValue(count, value); } + + private int getRootOrganizationTenantId(int tenantId) throws OrganizationManagementException { + + String tenantDomain = IdentityTenantUtil.getTenantDomain(tenantId); + String orgId = APIResourceManagementServiceComponentHolder.getInstance().getOrganizationManager() + .resolveOrganizationId(tenantDomain); + String rootOrganizationId = APIResourceManagementServiceComponentHolder.getInstance() + .getOrganizationManager().getPrimaryOrganizationId(orgId); + String rootTenantDomain = APIResourceManagementServiceComponentHolder.getInstance() + .getOrganizationManager().resolveTenantDomain(rootOrganizationId); + return IdentityTenantUtil.getTenantId(rootTenantDomain); + } } diff --git a/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/src/main/java/org/wso2/carbon/identity/api/resource/mgt/internal/APIResourceManagementServiceComponent.java b/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/src/main/java/org/wso2/carbon/identity/api/resource/mgt/internal/APIResourceManagementServiceComponent.java index deddfcc767a1..ac507baae419 100644 --- a/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/src/main/java/org/wso2/carbon/identity/api/resource/mgt/internal/APIResourceManagementServiceComponent.java +++ b/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/src/main/java/org/wso2/carbon/identity/api/resource/mgt/internal/APIResourceManagementServiceComponent.java @@ -97,13 +97,15 @@ protected void unsetIdentityCoreInitializedEventService(IdentityCoreInitializedE unbind = "unsetOrganizationManager" ) protected void setOrganizationManager(OrganizationManager organizationManager) { - /* reference Organization Management service to guarantee that this component will wait until organization - management service is started */ + + APIResourceManagementServiceComponentHolder.getInstance().setOrganizationManager(organizationManager); + LOG.debug("OrganizationManager set in API Resource Management bundle."); } protected void unsetOrganizationManager(OrganizationManager organizationManager) { - /* reference Organization Management service to guarantee that this component will wait until organization - management service is started */ + + APIResourceManagementServiceComponentHolder.getInstance().setOrganizationManager(null); + LOG.debug("OrganizationManager unset in API Resource Management bundle."); } @Reference( diff --git a/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/src/main/java/org/wso2/carbon/identity/api/resource/mgt/internal/APIResourceManagementServiceComponentHolder.java b/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/src/main/java/org/wso2/carbon/identity/api/resource/mgt/internal/APIResourceManagementServiceComponentHolder.java index 8a87368b08f8..75a26626d6bb 100644 --- a/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/src/main/java/org/wso2/carbon/identity/api/resource/mgt/internal/APIResourceManagementServiceComponentHolder.java +++ b/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/src/main/java/org/wso2/carbon/identity/api/resource/mgt/internal/APIResourceManagementServiceComponentHolder.java @@ -19,6 +19,7 @@ package org.wso2.carbon.identity.api.resource.mgt.internal; import org.wso2.carbon.identity.event.services.IdentityEventService; +import org.wso2.carbon.identity.organization.management.service.OrganizationManager; /** * Service component holder for the API resource management. @@ -26,6 +27,7 @@ public class APIResourceManagementServiceComponentHolder { private IdentityEventService identityEventService; + private OrganizationManager organizationManager; private static final APIResourceManagementServiceComponentHolder instance = new APIResourceManagementServiceComponentHolder(); @@ -63,4 +65,24 @@ public void setIdentityEventService(IdentityEventService identityEventService) { this.identityEventService = identityEventService; } + + /** + * Get the OrganizationManager. + * + * @return OrganizationManager instance. + */ + public OrganizationManager getOrganizationManager() { + + return organizationManager; + } + + /** + * Set the OrganizationManager. + * + * @param organizationManager OrganizationManager instance. + */ + public void setOrganizationManager(OrganizationManager organizationManager) { + + this.organizationManager = organizationManager; + } } diff --git a/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/src/test/java/org/wso2/carbon/identity/api/resource/mgt/dao/APIResourceManagementDAOImplTest.java b/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/src/test/java/org/wso2/carbon/identity/api/resource/mgt/dao/APIResourceManagementDAOImplTest.java index bb8cad66fd6b..c6a86c10c51b 100644 --- a/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/src/test/java/org/wso2/carbon/identity/api/resource/mgt/dao/APIResourceManagementDAOImplTest.java +++ b/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/src/test/java/org/wso2/carbon/identity/api/resource/mgt/dao/APIResourceManagementDAOImplTest.java @@ -27,13 +27,18 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import org.wso2.carbon.identity.api.resource.mgt.APIResourceMgtClientException; import org.wso2.carbon.identity.api.resource.mgt.constant.APIResourceManagementConstants; import org.wso2.carbon.identity.api.resource.mgt.dao.impl.APIResourceManagementDAOImpl; +import org.wso2.carbon.identity.api.resource.mgt.internal.APIResourceManagementServiceComponentHolder; import org.wso2.carbon.identity.application.common.model.APIResource; import org.wso2.carbon.identity.application.common.model.Scope; import org.wso2.carbon.identity.core.model.ExpressionNode; import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; +import org.wso2.carbon.identity.organization.management.service.OrganizationManager; +import org.wso2.carbon.identity.organization.management.service.exception.OrganizationManagementException; +import org.wso2.carbon.identity.organization.management.service.util.OrganizationManagementUtil; import java.nio.file.Paths; import java.sql.Connection; @@ -47,12 +52,17 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; public class APIResourceManagementDAOImplTest { private static final int TENANT_ID = 2; private static final int INVALID_TENANT_ID = 3; + private static final int ORGANIZATION_TENANT_ID = 1001; private static final String DB_NAME = "api_resource_mgt_dao_db"; public static final String APIRESOURCE_IDENTIFIER = "testAPIResource identifier "; public static final String TEST_SCOPE_1 = "testScope1 "; @@ -82,39 +92,62 @@ public void tearDown() throws Exception { @DataProvider public Object[][] getAPIResourcesCountData() { return new Object[][]{ - {TENANT_ID, new ArrayList<>(), 2}, - {INVALID_TENANT_ID, new ArrayList<>(), 0}, + {TENANT_ID, TENANT_ID, new ArrayList<>(), false, 2}, + {TENANT_ID, ORGANIZATION_TENANT_ID, new ArrayList<>(), true, 2}, + {INVALID_TENANT_ID, INVALID_TENANT_ID, new ArrayList<>(), false, 0}, }; } @Test(dataProvider = "getAPIResourcesCountData") - public void testGetAPIResourcesCount(Integer tenantId, List expressionNodes, int expected) + public void testGetAPIResourcesCount(Integer rootTenantId, Integer retrievingTenantId, + List expressionNodes, boolean isOrganization, int expected) throws Exception { - try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class)) { + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + MockedStatic organizationManagementUtil = + mockStatic(OrganizationManagementUtil.class); + MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class)) { + if (isOrganization) { + mockRootOrganizationExtraction(rootTenantId, identityTenantUtil); + } identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())) .thenReturn(getConnection()); - Assert.assertEquals(daoImpl.getAPIResourcesCount(tenantId, expressionNodes).intValue(), expected); + organizationManagementUtil.when(() -> OrganizationManagementUtil.isOrganization(anyInt())) + .thenReturn(isOrganization); + Assert.assertEquals(daoImpl.getAPIResourcesCount(retrievingTenantId, expressionNodes).intValue(), + expected); } } @DataProvider public Object[][] getAPIResourcesData() { return new Object[][]{ - {2, TENANT_ID, "ASC", new ArrayList<>(), 2}, - {1, TENANT_ID, "ASC", new ArrayList<>(), 1}, - {1, INVALID_TENANT_ID, "ASC", new ArrayList<>(), 0}, + {2, TENANT_ID, TENANT_ID, false, "ASC", new ArrayList<>(), 2}, + {2, TENANT_ID, ORGANIZATION_TENANT_ID, true, "ASC", new ArrayList<>(), 2}, + {1, TENANT_ID, TENANT_ID, false, "ASC", new ArrayList<>(), 1}, + {1, TENANT_ID, ORGANIZATION_TENANT_ID, true, "ASC", new ArrayList<>(), 1}, + {1, INVALID_TENANT_ID, INVALID_TENANT_ID, false, "ASC", new ArrayList<>(), 0}, }; } @Test(dataProvider = "getAPIResourcesData", priority = 1) - public void testGetAPIResources(Integer limit, Integer tenantId, String sortOrder, - List expressionNodes, int count) throws Exception { + public void testGetAPIResources(Integer limit, Integer rootTenantId, Integer retrievingTenantId, + boolean isOrganization, String sortOrder, List expressionNodes, + int count) throws Exception { - try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class)) { + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + MockedStatic organizationManagementUtil = + mockStatic(OrganizationManagementUtil.class); + MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class)) { + if (isOrganization) { + mockRootOrganizationExtraction(rootTenantId, identityTenantUtil); + } identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())) .thenReturn(getConnection()); - Assert.assertEquals(daoImpl.getAPIResources(limit, tenantId, sortOrder, expressionNodes).size(), count); + organizationManagementUtil.when(() -> OrganizationManagementUtil.isOrganization(anyInt())) + .thenReturn(isOrganization); + Assert.assertEquals(daoImpl.getAPIResources(limit, retrievingTenantId, sortOrder, expressionNodes).size(), + count); } } @@ -122,21 +155,31 @@ public void testGetAPIResources(Integer limit, Integer tenantId, String sortOrde public Object[][] addAPIResourceData() { return new Object[][]{ - {"AddAPITest-1", TENANT_ID} + {"AddAPITest-1", TENANT_ID, false}, + {"AddAPITest-1", TENANT_ID, true} }; } @Test(dataProvider = "addAPIResourceData", priority = 2) - public void testAddAPIResource(String postfix, int tenantId) throws Exception { + public void testAddAPIResource(String postfix, int tenantId, boolean isOrganization) throws Exception { - try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class)) { + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + MockedStatic organizationManagementUtil = + mockStatic(OrganizationManagementUtil.class)) { identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())) .thenReturn(getConnection()); + organizationManagementUtil.when(() -> OrganizationManagementUtil.isOrganization(anyInt())) + .thenReturn(isOrganization); APIResource apiResource = createAPIResource(postfix); - APIResource createdAPIResource = daoImpl.addAPIResource(apiResource, tenantId); - Assert.assertNotNull(createdAPIResource); - Assert.assertTrue(createdAPIResource.getName().contains(postfix)); - Assert.assertNotNull(createdAPIResource.getId()); + if (!isOrganization) { + APIResource createdAPIResource = daoImpl.addAPIResource(apiResource, tenantId); + Assert.assertNotNull(createdAPIResource); + Assert.assertTrue(createdAPIResource.getName().contains(postfix)); + Assert.assertNotNull(createdAPIResource.getId()); + } else { + Assert.expectThrows(APIResourceMgtClientException.class, () -> + daoImpl.addAPIResource(apiResource, tenantId)); + } } } @@ -144,18 +187,29 @@ public void testAddAPIResource(String postfix, int tenantId) throws Exception { public Object[][] getScopesByAPIData() { // Define your test cases here return new Object[][]{ - {"GetScopesTest", TENANT_ID, 2}, - {"GetScopesTest2", INVALID_TENANT_ID, 0} + {"GetScopesTest", TENANT_ID, TENANT_ID, false, 2}, + {"GetScopesTest2", INVALID_TENANT_ID, INVALID_TENANT_ID, false, 0}, + {"GetScopesTest3", TENANT_ID, ORGANIZATION_TENANT_ID, true, 2} }; } @Test(dataProvider = "getScopesByAPIData", priority = 3) - public void testGetScopesByAPI(String name, Integer tenantId, int expected) throws Exception { + public void testGetScopesByAPI(String name, Integer rootTenantId, Integer retrievingTenantId, + boolean isOrganization, int expected) throws Exception { - try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class)) { - String apiId = addAPIResourceToDB(name, getConnection(), tenantId, identityDatabaseUtil).getId(); + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + MockedStatic organizationManagementUtil = + mockStatic(OrganizationManagementUtil.class); + MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class)) { + if (isOrganization) { + mockRootOrganizationExtraction(rootTenantId, identityTenantUtil); + } + String apiId = addAPIResourceToDB(name, getConnection(), rootTenantId, identityDatabaseUtil, + organizationManagementUtil).getId(); identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())) .thenReturn(getConnection()); + organizationManagementUtil.when(() -> OrganizationManagementUtil.isOrganization(anyInt())) + .thenReturn(isOrganization); Assert.assertEquals(daoImpl.getScopesByAPI(apiId, TENANT_ID).size(), expected); } } @@ -164,6 +218,7 @@ public void testGetScopesByAPI(String name, Integer tenantId, int expected) thro public Object[][] isAPIResourceExistData() { return new Object[][]{ {"identifier1", TENANT_ID, true}, + {"identifier5", TENANT_ID, true}, {"identifier4", INVALID_TENANT_ID, false} }; } @@ -171,8 +226,11 @@ public Object[][] isAPIResourceExistData() { @Test(dataProvider = "isAPIResourceExistData", priority = 4) public void testIsAPIResourceExist(String identifierPostFix, Integer tenantId, boolean expected) throws Exception { - try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class)) { - addAPIResourceToDB(identifierPostFix, getConnection(), tenantId, identityDatabaseUtil); + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + MockedStatic organizationManagementUtil = + mockStatic(OrganizationManagementUtil.class)) { + addAPIResourceToDB(identifierPostFix, getConnection(), tenantId, identityDatabaseUtil, + organizationManagementUtil); identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())) .thenReturn(getConnection()); Assert.assertEquals(daoImpl.isAPIResourceExist(APIRESOURCE_IDENTIFIER + identifierPostFix, TENANT_ID), @@ -191,10 +249,13 @@ public Object[][] isAPIResourceExistByIdData() { @Test(dataProvider = "isAPIResourceExistByIdData", priority = 5) public void testIsAPIResourceExistById(Integer tenantId, boolean expected) throws Exception { - try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class)) { - + String namePostFix = "testIsAPIResourceExistById"; + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + MockedStatic organizationManagementUtil = + mockStatic(OrganizationManagementUtil.class)) { APIResource createdAPIResource = - addAPIResourceToDB("testIsAPIResourceExistById", getConnection(), tenantId, identityDatabaseUtil); + addAPIResourceToDB(namePostFix, getConnection(), tenantId, identityDatabaseUtil, + organizationManagementUtil); String apiId = createdAPIResource.getId(); identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())) .thenReturn(getConnection()); @@ -205,21 +266,32 @@ public void testIsAPIResourceExistById(Integer tenantId, boolean expected) throw @DataProvider public Object[][] getAPIResourceByIdData() { return new Object[][]{ - {TENANT_ID, true}, - {INVALID_TENANT_ID, false} + {"testGetAPIResourceById", TENANT_ID, TENANT_ID, false, true}, + {"testGetOrgAPIResourceById", TENANT_ID, ORGANIZATION_TENANT_ID, true, true}, + {"testGetAPIResourceByIdInvalidTenant", TENANT_ID, INVALID_TENANT_ID, false, false} }; } @Test(dataProvider = "getAPIResourceByIdData", priority = 6) - public void testGetAPIResourceById(Integer tenantId, boolean expected) throws Exception { + public void testGetAPIResourceById(String apiNamePostFix, Integer rootTenantId, Integer retrievingTenantId, + boolean isOrganization, boolean expected) throws Exception { - try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class)) { + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + MockedStatic organizationManagementUtil = + mockStatic(OrganizationManagementUtil.class); + MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class)) { + if (isOrganization) { + mockRootOrganizationExtraction(rootTenantId, identityTenantUtil); + } APIResource createdAPIResource = - addAPIResourceToDB("testGetAPIResourceById", getConnection(), tenantId, identityDatabaseUtil); + addAPIResourceToDB(apiNamePostFix, getConnection(), rootTenantId, identityDatabaseUtil, + organizationManagementUtil); String apiId = createdAPIResource.getId(); identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())) .thenReturn(getConnection()); - Assert.assertEquals(daoImpl.getAPIResourceById(apiId, TENANT_ID) != null, expected); + organizationManagementUtil.when(() -> OrganizationManagementUtil.isOrganization(anyInt())) + .thenReturn(isOrganization); + Assert.assertEquals(daoImpl.getAPIResourceById(apiId, retrievingTenantId) != null, expected); } } @@ -234,9 +306,11 @@ public Object[][] isScopeExistByIdData() { @Test(dataProvider = "isScopeExistByIdData", priority = 7) public void testIsScopeExistById(Integer tenantId, boolean expected) throws Exception { - try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class)) { - APIResource createdAPIResource = addAPIResourceToDB("testIsScopeExistById", getConnection(), - tenantId, identityDatabaseUtil); + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + MockedStatic organizationManagementUtil = + mockStatic(OrganizationManagementUtil.class)) { + APIResource createdAPIResource = addAPIResourceToDB("testIsScopeExistById", getConnection(), tenantId, + identityDatabaseUtil, organizationManagementUtil); String scopeId = createdAPIResource.getScopes().get(0).getId(); identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())) .thenReturn(getConnection()); @@ -248,16 +322,24 @@ public void testIsScopeExistById(Integer tenantId, boolean expected) throws Exce public Object[][] deleteAPIResourceByIdData() { return new Object[][]{ - {TENANT_ID, false} + {TENANT_ID, false, false}, + {TENANT_ID, true, false} }; } @Test(dataProvider = "deleteAPIResourceByIdData", priority = 8) - public void testDeleteAPIResourceById(Integer tenantId, boolean expected) throws Exception { + public void testDeleteAPIResourceById(Integer tenantId, boolean isOrganization, boolean expected) + throws Exception { - try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class)) { + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + MockedStatic organizationManagementUtil = + mockStatic(OrganizationManagementUtil.class); + MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class)) { + if (isOrganization) { + mockRootOrganizationExtraction(tenantId, identityTenantUtil); + } String apiId = addAPIResourceToDB("testDeleteAPIResourceById", getConnection(), tenantId, - identityDatabaseUtil).getId(); + identityDatabaseUtil, organizationManagementUtil).getId(); Connection connection = getConnection(); identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())).thenReturn(connection); @@ -266,10 +348,17 @@ public void testDeleteAPIResourceById(Integer tenantId, boolean expected) throws connection.commit(); return null; }); - daoImpl.deleteAPIResourceById(apiId, tenantId); - identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())) - .thenReturn(getConnection()); - Assert.assertEquals(daoImpl.isAPIResourceExistById(apiId, tenantId), expected); + organizationManagementUtil.when(() -> OrganizationManagementUtil.isOrganization(anyInt())) + .thenReturn(isOrganization); + if (!isOrganization) { + daoImpl.deleteAPIResourceById(apiId, tenantId); + identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())) + .thenReturn(getConnection()); + Assert.assertEquals(daoImpl.isAPIResourceExistById(apiId, tenantId), expected); + } else { + Assert.expectThrows(APIResourceMgtClientException.class, () -> + daoImpl.deleteAPIResourceById(apiId, tenantId)); + } } } @@ -282,11 +371,14 @@ public Object[][] isScopeExistByNameData() { } @Test(dataProvider = "isScopeExistByNameData", priority = 9) - public void testIsScopeExistByName(Integer tenantId, String scopeName, boolean expected) throws Exception { - - try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class)) { + public void testIsScopeExistByName(Integer tenantId, String scopeName, boolean expected) + throws Exception { - addAPIResourceToDB(scopeName, getConnection(), tenantId, identityDatabaseUtil); + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + MockedStatic organizationManagementUtil = + mockStatic(OrganizationManagementUtil.class); + MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class)) { + addAPIResourceToDB(scopeName, getConnection(), tenantId, identityDatabaseUtil, organizationManagementUtil); identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())) .thenReturn(getConnection()); @@ -296,9 +388,8 @@ public void testIsScopeExistByName(Integer tenantId, String scopeName, boolean e @DataProvider public Object[][] getScopeByNameAndTenantIdData() { - String scopeName = "testGetScopeByNameAndTenantId"; return new Object[][]{ - {TENANT_ID, scopeName, scopeName} + {TENANT_ID, "testGetScopeByNameAndTenantId", "testGetScopeByNameAndTenantId"} }; } @@ -306,9 +397,10 @@ public Object[][] getScopeByNameAndTenantIdData() { public void testGetScopeByNameAndTenantId(Integer tenantId, String scopeName, String expectedName) throws Exception { - try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class)) { - - addAPIResourceToDB(scopeName, getConnection(), tenantId, identityDatabaseUtil); + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + MockedStatic organizationManagementUtil = + mockStatic(OrganizationManagementUtil.class)) { + addAPIResourceToDB(scopeName, getConnection(), tenantId, identityDatabaseUtil, organizationManagementUtil); identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())) .thenReturn(getConnection()); Scope scope = daoImpl.getScopeByNameAndTenantId(TEST_SCOPE_1 + scopeName, tenantId); @@ -316,16 +408,27 @@ public void testGetScopeByNameAndTenantId(Integer tenantId, String scopeName, St } } - @Test(priority = 11) - public void testAddScopes() throws Exception { + @DataProvider + public Object[][] addScopes() { + return new Object[][]{ + {TENANT_ID, TENANT_ID, false, "testAddScopes", "scope1", "scope2"}, + {TENANT_ID, ORGANIZATION_TENANT_ID, true, "testAddScopesOrg", "scope1", "scope2"} + }; + } + + @Test(dataProvider = "addScopes", priority = 11) + public void testAddScopes(Integer rootTenantId, Integer addingTenantId, boolean isOrganization, + String apiNamePostFix, String scope1, String scope2) throws Exception { try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); - MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class)) { + MockedStatic organizationManagementUtil = + mockStatic(OrganizationManagementUtil.class)) { APIResource apiResource = - addAPIResourceToDB("testAddScopes", getConnection(), TENANT_ID, identityDatabaseUtil); + addAPIResourceToDB(apiNamePostFix, getConnection(), rootTenantId, identityDatabaseUtil, + organizationManagementUtil); String apiId = apiResource.getId(); - List scopes = Arrays.asList(createScope("scope1"), createScope("scope2")); + List scopes = Arrays.asList(createScope(scope1), createScope(scope2)); Connection connection = getConnection(); identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())).thenReturn(connection); @@ -334,23 +437,41 @@ public void testAddScopes() throws Exception { connection.commit(); return null; }); - daoImpl.addScopes(scopes, apiId, TENANT_ID); - - for (Scope scope : scopes) { - identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())) - .thenReturn(getConnection()); - Assert.assertTrue(daoImpl.isScopeExistByName(scope.getName(), TENANT_ID)); + organizationManagementUtil.when(() -> OrganizationManagementUtil.isOrganization(anyInt())) + .thenReturn(isOrganization); + if (!isOrganization) { + daoImpl.addScopes(scopes, apiId, addingTenantId); + for (Scope scope : scopes) { + identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())) + .thenReturn(getConnection()); + Assert.assertTrue(daoImpl.isScopeExistByName(scope.getName(), rootTenantId)); + } + } else { + Assert.expectThrows(APIResourceMgtClientException.class, () -> + daoImpl.addScopes(scopes, apiId, addingTenantId)); } } } - @Test(priority = 12) - public void testDeleteAllScopes() throws Exception { + @DataProvider + public Object[][] deleteAllScopes() { + return new Object[][]{ + {TENANT_ID, TENANT_ID, false, "testDeleteAllScopes"}, + {TENANT_ID, ORGANIZATION_TENANT_ID, true, "testDeleteAllOrgScopes"} + }; + } + + @Test(dataProvider = "deleteAllScopes", priority = 12) + public void testDeleteAllScopes(Integer rootTenantId, Integer deletingTenantId, boolean isOrganization, + String apiNamePostFix) throws Exception { - try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class)) { + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + MockedStatic organizationManagementUtil = + mockStatic(OrganizationManagementUtil.class)) { APIResource apiResource = - addAPIResourceToDB("testDeleteAllScopes", getConnection(), TENANT_ID, identityDatabaseUtil); + addAPIResourceToDB(apiNamePostFix, getConnection(), rootTenantId, identityDatabaseUtil, + organizationManagementUtil); String apiId = apiResource.getId(); Connection connection = getConnection(); identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())).thenReturn(connection); @@ -359,23 +480,41 @@ public void testDeleteAllScopes() throws Exception { connection.commit(); return null; }); - - daoImpl.deleteAllScopes(apiId, TENANT_ID); - for (Scope scope : apiResource.getScopes()) { - identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())) - .thenReturn(getConnection()); - Assert.assertFalse(daoImpl.isScopeExistById(scope.getId(), TENANT_ID)); + organizationManagementUtil.when(() -> OrganizationManagementUtil.isOrganization(anyInt())) + .thenReturn(isOrganization); + if (!isOrganization) { + daoImpl.deleteAllScopes(apiId, deletingTenantId); + for (Scope scope : apiResource.getScopes()) { + identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())) + .thenReturn(getConnection()); + Assert.assertFalse(daoImpl.isScopeExistById(scope.getId(), TENANT_ID)); + } + } else { + Assert.expectThrows(APIResourceMgtClientException.class, () -> + daoImpl.deleteAllScopes(apiId, deletingTenantId)); } } } - @Test(priority = 13) - public void testDeleteScope() throws Exception { + @DataProvider + public Object[][] deleteScope() { + return new Object[][]{ + {TENANT_ID, TENANT_ID, false, "testDeleteScope"}, + {TENANT_ID, ORGANIZATION_TENANT_ID, true, "testDeleteOrgScope"} + }; + } - try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class)) { + @Test(dataProvider = "deleteScope", priority = 13) + public void testDeleteScope(Integer rootTenantId, Integer deletingTenantId, boolean isOrganization, + String apiNamePostFix) throws Exception { + + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + MockedStatic organizationManagementUtil = + mockStatic(OrganizationManagementUtil.class)) { APIResource apiResource = - addAPIResourceToDB("testDeleteScope", getConnection(), TENANT_ID, identityDatabaseUtil); + addAPIResourceToDB(apiNamePostFix, getConnection(), rootTenantId, identityDatabaseUtil, + organizationManagementUtil); String apiId = apiResource.getId(); String scopeName = apiResource.getScopes().get(0).getName(); // Assuming there's at least one scope @@ -387,13 +526,20 @@ public void testDeleteScope() throws Exception { return null; }); - // Testing the deleteScope method with the created API resource's ID and scope ID - daoImpl.deleteScope(apiId, scopeName, TENANT_ID); + organizationManagementUtil.when(() -> OrganizationManagementUtil.isOrganization(anyInt())) + .thenReturn(isOrganization); + if (!isOrganization) { + // Testing the deleteScope method with the created API resource's ID and scope ID + daoImpl.deleteScope(apiId, scopeName, deletingTenantId); - // Checking whether the scope is deleted - identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())) - .thenReturn(getConnection()); - Assert.assertFalse(daoImpl.isScopeExistByName(scopeName, TENANT_ID)); + // Checking whether the scope is deleted + identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())) + .thenReturn(getConnection()); + Assert.assertFalse(daoImpl.isScopeExistByName(scopeName, deletingTenantId)); + } else { + Assert.expectThrows(APIResourceMgtClientException.class, () -> + daoImpl.deleteScope(apiId, scopeName, deletingTenantId)); + } } } @@ -402,45 +548,55 @@ public void testDeleteScope() throws Exception { public Object[][] updateAPIResourceScopeAddition() { return new Object[][]{ - {APIResourceManagementConstants.BUSINESS_TYPE}, - {APIResourceManagementConstants.SYSTEM_TYPE}, - {ORGANIZATION_TYPE}, - {TENANT_TYPE}, - {CONSOLE_ORG_LEVEL_TYPE} + {APIResourceManagementConstants.BUSINESS_TYPE, 2}, + {APIResourceManagementConstants.SYSTEM_TYPE, 2}, + {ORGANIZATION_TYPE, 2}, + {TENANT_TYPE, 2}, + {CONSOLE_ORG_LEVEL_TYPE, 2} }; } @Test(dataProvider = "updateAPIResourceScopeAddition", priority = 14) - public void testUpdateAPIResourceScopeAddition(String type) throws Exception { + public void testUpdateAPIResourceScopeAddition(String type, int expectedValue) + throws Exception { // Add API resource to database. String apiNamePostFix = "update-scope-addition-test"; List scopes = new ArrayList<>(); scopes.add(createScope("test_scope_1_" + apiNamePostFix)); scopes.add(createScope("test_scope_2_" + apiNamePostFix)); - APIResource apiResource = addAPIResourceToDB(apiNamePostFix, scopes, type, getConnection(), TENANT_ID); + try (MockedStatic organizationManagementUtil = + mockStatic(OrganizationManagementUtil.class)) { + // Following mocks are in action when the registered API resources are extracted from the database. This + // will not affect to the update operation since the update operation does not support in the organization + // level. + APIResource apiResource = addAPIResourceToDB(apiNamePostFix, scopes, type, getConnection(), TENANT_ID, + organizationManagementUtil); + + // Validate scopes count before update. + validateScopesCount(apiResource.getId(), expectedValue); + + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class)) { + identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())) + .thenReturn(getConnection()); - // Validate scopes count before update. - validateScopesCount(apiResource.getId(), 2); + Scope newScope = createScope("test_scope_3_" + apiNamePostFix); + apiResource.getScopes().add(newScope); - try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class)) { - identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())) - .thenReturn(getConnection()); - Scope newScope = createScope("test_scope_3_" + apiNamePostFix); - apiResource.getScopes().add(newScope); + List addedScopes = new ArrayList<>(); + addedScopes.add(newScope); - List addedScopes = new ArrayList<>(); - addedScopes.add(newScope); + // Update API resource with a new scope. + daoImpl.updateAPIResource(apiResource, addedScopes, Collections.emptyList(), TENANT_ID); + } - // Update API resource with a new scope. - daoImpl.updateAPIResource(apiResource, addedScopes, Collections.emptyList(), TENANT_ID); - } + // Validate updated scopes count. + validateScopesCount(apiResource.getId(), 3); - // Validate updated scopes count. - validateScopesCount(apiResource.getId(), 3); + // Delete API resource from database. + deleteAPIResourceFromDB(apiResource.getId(), TENANT_ID); + } - // Delete API resource from database. - deleteAPIResourceFromDB(apiResource.getId(), TENANT_ID); } /** @@ -512,8 +668,11 @@ private static APIResource createAPIResource(String postFix, List scopes, */ private APIResource addAPIResourceToDB(String namePostFix, Connection connection, int tenantId) throws Exception { - try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class)) { - return addAPIResourceToDB(namePostFix, connection, tenantId, identityDatabaseUtil); + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + MockedStatic organizationManagementUtil = + mockStatic(OrganizationManagementUtil.class)) { + return addAPIResourceToDB(namePostFix, connection, tenantId, identityDatabaseUtil, + organizationManagementUtil); } } @@ -528,7 +687,9 @@ private APIResource addAPIResourceToDB(String namePostFix, Connection connection * @throws Exception Error when adding API resource. */ private APIResource addAPIResourceToDB(String namePostFix, Connection connection, int tenantId, - MockedStatic identityDatabaseUtil) throws Exception { + MockedStatic identityDatabaseUtil, + MockedStatic organizationManagementUtil) + throws Exception { APIResource apiResource = createAPIResource(namePostFix); identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())).thenReturn(connection); @@ -537,6 +698,8 @@ private APIResource addAPIResourceToDB(String namePostFix, Connection connection connection.commit(); return null; }); + organizationManagementUtil.when(() -> OrganizationManagementUtil.isOrganization(anyInt())) + .thenReturn(false); return daoImpl.addAPIResource(apiResource, tenantId); } @@ -552,7 +715,9 @@ private APIResource addAPIResourceToDB(String namePostFix, Connection connection * @throws Exception Error when adding API resource. */ private APIResource addAPIResourceToDB(String namePostFix, List scopes, String type, Connection connection, - int tenantId) throws Exception { + int tenantId, + MockedStatic organizationManagementUtil) + throws Exception { try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class)) { APIResource apiResource = createAPIResource(namePostFix, scopes, type); @@ -562,6 +727,8 @@ private APIResource addAPIResourceToDB(String namePostFix, List scopes, S connection.commit(); return null; }); + organizationManagementUtil.when(() -> OrganizationManagementUtil.isOrganization(anyInt())) + .thenReturn(false); return daoImpl.addAPIResource(apiResource, tenantId); } @@ -663,4 +830,26 @@ private static String getFilePath() { } throw new IllegalArgumentException("DB Script file name cannot be empty."); } + + /** + * Mock the root organization extraction when the APIs need to be extracted from the organization level. + * + * @param rootTenantId Root tenant ID of the sub organization. + * @param identityTenantUtil Mocked IdentityTenantUtil to get the tenant domains. + * @throws OrganizationManagementException Error when extracting the root organization. + */ + private static void mockRootOrganizationExtraction(Integer rootTenantId, + MockedStatic identityTenantUtil) + throws OrganizationManagementException { + + identityTenantUtil.when(() -> IdentityTenantUtil.getTenantDomain(anyInt())).thenReturn("tenant1"); + OrganizationManager organizationManager = mock(OrganizationManager.class); + APIResourceManagementServiceComponentHolder.getInstance().setOrganizationManager(organizationManager); + lenient().when(organizationManager.resolveOrganizationId(anyString())).thenReturn("org-id-1234"); + lenient().when(organizationManager.getPrimaryOrganizationId("org-id-1234")) + .thenReturn("prim-org-id-1234"); + lenient().when(organizationManager.resolveTenantDomain("prim-org-id-1234")) + .thenReturn("prim-tenant"); + identityTenantUtil.when(() -> IdentityTenantUtil.getTenantId(anyString())).thenReturn(rootTenantId); + } } diff --git a/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/src/test/java/org/wso2/carbon/identity/api/resource/mgt/dao/CacheBackedAPIResourceManagementDAOTest.java b/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/src/test/java/org/wso2/carbon/identity/api/resource/mgt/dao/CacheBackedAPIResourceManagementDAOTest.java index a6ea03d36fb8..e24909888807 100644 --- a/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/src/test/java/org/wso2/carbon/identity/api/resource/mgt/dao/CacheBackedAPIResourceManagementDAOTest.java +++ b/components/api-resource-mgt/org.wso2.carbon.identity.api.resource.mgt/src/test/java/org/wso2/carbon/identity/api/resource/mgt/dao/CacheBackedAPIResourceManagementDAOTest.java @@ -35,6 +35,7 @@ import org.wso2.carbon.identity.core.model.ExpressionNode; import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; +import org.wso2.carbon.identity.organization.management.service.util.OrganizationManagementUtil; import java.nio.file.Paths; import java.sql.Connection; @@ -47,6 +48,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.mockStatic; public class CacheBackedAPIResourceManagementDAOTest { @@ -101,9 +103,13 @@ public Object[][] getAPIResourcesCountData() { public void testGetAPIResourcesCount(Integer tenantId, List expressionNodes, int expected) throws Exception { - try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class)) { + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + MockedStatic organizationManagementUtil = + mockStatic(OrganizationManagementUtil.class)) { identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())) .thenReturn(getConnection()); + organizationManagementUtil.when(() -> OrganizationManagementUtil.isOrganization(anyInt())) + .thenReturn(false); Assert.assertEquals(daoImpl.getAPIResourcesCount(tenantId, expressionNodes).intValue(), expected); } } @@ -121,9 +127,13 @@ public Object[][] getAPIResourcesData() { public void testGetAPIResources(Integer limit, Integer tenantId, String sortOrder, List expressionNodes, int count) throws Exception { - try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class)) { + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + MockedStatic organizationManagementUtil = + mockStatic(OrganizationManagementUtil.class)) { identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())) .thenReturn(getConnection()); + organizationManagementUtil.when(() -> OrganizationManagementUtil.isOrganization(anyInt())) + .thenReturn(false); Assert.assertEquals(daoImpl.getAPIResources(limit, tenantId, sortOrder, expressionNodes).size(), count); } } @@ -139,9 +149,13 @@ public Object[][] addAPIResourceData() { @Test(dataProvider = "addAPIResourceData", priority = 2) public void testAddAPIResource(String postfix, int tenantId) throws Exception { - try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class)) { + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + MockedStatic organizationManagementUtil = + mockStatic(OrganizationManagementUtil.class)) { identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())) .thenReturn(getConnection()); + organizationManagementUtil.when(() -> OrganizationManagementUtil.isOrganization(anyInt())) + .thenReturn(false); APIResource apiResource = createAPIResource(postfix); APIResource createdAPIResource = daoImpl.addAPIResource(apiResource, tenantId); Assert.assertNotNull(createdAPIResource); @@ -163,8 +177,11 @@ public Object[][] getScopesByAPIData() { public void testGetScopesByAPI(String name, Integer tenantId, int expected) throws Exception { try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); - MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class)) { - String apiId = addAPIResourceToDB(name, getConnection(), tenantId, identityDatabaseUtil).getId(); + MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); + MockedStatic organizationManagementUtil = + mockStatic(OrganizationManagementUtil.class)) { + String apiId = addAPIResourceToDB(name, getConnection(), tenantId, identityDatabaseUtil, + organizationManagementUtil).getId(); identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(true)).thenReturn(getConnection()); identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(false)).thenReturn(getConnection()); identityTenantUtil.when(() -> IdentityTenantUtil.getTenantDomain(TENANT_ID)) @@ -185,8 +202,11 @@ public Object[][] isAPIResourceExistData() { public void testIsAPIResourceExist(String identifierPostFix, Integer tenantId, boolean expected) throws Exception { try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); - MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class)) { - addAPIResourceToDB(identifierPostFix, getConnection(), tenantId, identityDatabaseUtil); + MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); + MockedStatic organizationManagementUtil = + mockStatic(OrganizationManagementUtil.class)) { + addAPIResourceToDB(identifierPostFix, getConnection(), tenantId, identityDatabaseUtil, + organizationManagementUtil); identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(true)).thenReturn(getConnection()); identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(false)).thenReturn(getConnection()); identityTenantUtil.when(() -> IdentityTenantUtil.getTenantDomain(TENANT_ID)) @@ -208,9 +228,12 @@ public Object[][] isAPIResourceExistByIdData() { public void testIsAPIResourceExistById(Integer tenantId, boolean expected) throws Exception { try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); - MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class)) { + MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); + MockedStatic organizationManagementUtil = + mockStatic(OrganizationManagementUtil.class)) { APIResource apiresource = - addAPIResourceToDB("testIsAPIResourceExistById", getConnection(), tenantId, identityDatabaseUtil); + addAPIResourceToDB("testIsAPIResourceExistById", getConnection(), tenantId, identityDatabaseUtil, + organizationManagementUtil); String apiId = apiresource.getId(); identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(true)).thenReturn(getConnection()); identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(false)).thenReturn(getConnection()); @@ -232,13 +255,15 @@ public Object[][] getAPIResourceByIdData() { public void testGetAPIResourceById(Integer tenantId, boolean expected) throws Exception { try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); - MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class)) { + MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); + MockedStatic organizationManagementUtil = + mockStatic(OrganizationManagementUtil.class)) { identityTenantUtil.when(() -> IdentityTenantUtil.getTenantDomain(tenantId)) .thenReturn(getTenantDomain(tenantId)); String apiId = addAPIResourceToDB("testGetAPIResourceById", getConnection(), tenantId, - identityDatabaseUtil).getId(); + identityDatabaseUtil, organizationManagementUtil).getId(); identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())) .thenReturn(getConnection()); @@ -260,9 +285,11 @@ public Object[][] isScopeExistByIdData() { @Test(dataProvider = "isScopeExistByIdData", priority = 7) public void testIsScopeExistById(Integer tenantId, boolean expected) throws Exception { - try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class)) { + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + MockedStatic organizationManagementUtil = + mockStatic(OrganizationManagementUtil.class)) { String scopeId = addAPIResourceToDB("testIsScopeExistById", getConnection(), tenantId, - identityDatabaseUtil).getScopes().get(0).getId(); + identityDatabaseUtil, organizationManagementUtil).getScopes().get(0).getId(); identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())) .thenReturn(getConnection()); Assert.assertEquals(daoImpl.isScopeExistById(scopeId, TENANT_ID), expected); @@ -281,13 +308,15 @@ public Object[][] deleteAPIResourceByIdData() { public void testDeleteAPIResourceById(Integer tenantId, boolean expected) throws Exception { try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); - MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class)) { + MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); + MockedStatic organizationManagementUtil = + mockStatic(OrganizationManagementUtil.class)) { identityTenantUtil.when(() -> IdentityTenantUtil.getTenantDomain(tenantId)) .thenReturn(getTenantDomain(tenantId)); String apiId = addAPIResourceToDB("testDeleteAPIResourceById", getConnection(), tenantId, - identityDatabaseUtil).getId(); + identityDatabaseUtil, organizationManagementUtil).getId(); Connection connection = getConnection(); identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(true)).thenReturn(connection); identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(false)).thenReturn(getConnection()); @@ -318,8 +347,10 @@ public Object[][] isScopeExistByNameData() { @Test(dataProvider = "isScopeExistByNameData", priority = 9) public void testIsScopeExistByName(Integer tenantId, String scopeName, boolean expected) throws Exception { - try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class)) { - addAPIResourceToDB(scopeName, getConnection(), tenantId, identityDatabaseUtil); + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + MockedStatic organizationManagementUtil = + mockStatic(OrganizationManagementUtil.class)) { + addAPIResourceToDB(scopeName, getConnection(), tenantId, identityDatabaseUtil, organizationManagementUtil); identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())) .thenReturn(getConnection()); @@ -339,8 +370,10 @@ public Object[][] getScopeByNameAndTenantIdData() { public void testGetScopeByNameAndTenantId(Integer tenantId, String scopeName, String expectedName) throws Exception { - try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class)) { - addAPIResourceToDB(scopeName, getConnection(), tenantId, identityDatabaseUtil); + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + MockedStatic organizationManagementUtil = + mockStatic(OrganizationManagementUtil.class)) { + addAPIResourceToDB(scopeName, getConnection(), tenantId, identityDatabaseUtil, organizationManagementUtil); identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())) .thenReturn(getConnection()); Scope scope = daoImpl.getScopeByNameAndTenantId(TEST_SCOPE_1 + scopeName, tenantId); @@ -352,13 +385,16 @@ public void testGetScopeByNameAndTenantId(Integer tenantId, String scopeName, St public void testAddScopes() throws Exception { try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); - MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class)) { + MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); + MockedStatic organizationManagementUtil = + mockStatic(OrganizationManagementUtil.class)) { identityTenantUtil.when(() -> IdentityTenantUtil.getTenantDomain(TENANT_ID)) .thenReturn(getTenantDomain(TENANT_ID)); APIResource apiResource = - addAPIResourceToDB("testAddScopes", getConnection(), TENANT_ID, identityDatabaseUtil); + addAPIResourceToDB("testAddScopes", getConnection(), TENANT_ID, identityDatabaseUtil, + organizationManagementUtil); String apiId = apiResource.getId(); List scopes = Arrays.asList(createScope("scope1"), createScope("scope2")); @@ -388,13 +424,16 @@ public void testAddScopes() throws Exception { public void testDeleteAllScopes() throws Exception { try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); - MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class)) { + MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); + MockedStatic organizationManagementUtil = + mockStatic(OrganizationManagementUtil.class)) { identityTenantUtil.when(() -> IdentityTenantUtil.getTenantDomain(TENANT_ID)) .thenReturn(getTenantDomain(TENANT_ID)); APIResource apiResource = - addAPIResourceToDB("testDeleteAllScopes", getConnection(), TENANT_ID, identityDatabaseUtil); + addAPIResourceToDB("testDeleteAllScopes", getConnection(), TENANT_ID, identityDatabaseUtil, + organizationManagementUtil); String apiId = apiResource.getId(); Connection connection = getConnection(); @@ -422,13 +461,16 @@ public void testDeleteAllScopes() throws Exception { public void testDeleteScope() throws Exception { try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); - MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class)) { + MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class); + MockedStatic organizationManagementUtil = + mockStatic(OrganizationManagementUtil.class)) { identityTenantUtil.when(() -> IdentityTenantUtil.getTenantDomain(TENANT_ID)) .thenReturn(getTenantDomain(TENANT_ID)); APIResource apiResource = - addAPIResourceToDB("testDeleteScope", getConnection(), TENANT_ID, identityDatabaseUtil); + addAPIResourceToDB("testDeleteScope", getConnection(), TENANT_ID, identityDatabaseUtil, + organizationManagementUtil); String apiId = apiResource.getId(); String scopeName = apiResource.getScopes().get(0).getName(); @@ -503,8 +545,11 @@ private static APIResource createAPIResource(String postFix) { */ private APIResource addAPIResourceToDB(String namePostFix, Connection connection, int tenantId) throws Exception { - try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class)) { - return addAPIResourceToDB(namePostFix, connection, tenantId, identityDatabaseUtil); + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + MockedStatic organizationManagementUtil = + mockStatic(OrganizationManagementUtil.class)) { + return addAPIResourceToDB(namePostFix, connection, tenantId, identityDatabaseUtil, + organizationManagementUtil); } } @@ -519,7 +564,9 @@ private APIResource addAPIResourceToDB(String namePostFix, Connection connection * @throws Exception Error when adding API resource. */ private APIResource addAPIResourceToDB(String namePostFix, Connection connection, int tenantId, - MockedStatic identityDatabaseUtil) throws Exception { + MockedStatic identityDatabaseUtil, + MockedStatic organizationManagementUtil) + throws Exception { APIResource apiResource = createAPIResource(namePostFix); identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())).thenReturn(connection); @@ -529,6 +576,7 @@ private APIResource addAPIResourceToDB(String namePostFix, Connection connection connection.commit(); return null; }); + organizationManagementUtil.when(() -> OrganizationManagementUtil.isOrganization(anyInt())).thenReturn(false); return daoImpl.addAPIResource(apiResource, tenantId); } diff --git a/components/api-resource-mgt/pom.xml b/components/api-resource-mgt/pom.xml index 85e6be97b205..13c6da86c713 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.10-SNAPSHOT + 7.7.63-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 0f3961d2d743..0abe0e2bfa02 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.10-SNAPSHOT + 7.7.63-SNAPSHOT ../pom.xml @@ -61,6 +61,21 @@ org.wso2.carbon.identity.framework org.wso2.carbon.identity.central.log.mgt + + org.wso2.carbon.identity.framework + org.wso2.carbon.identity.testutil + test + + + org.mockito + mockito-core + test + + + com.h2database + h2 + test + org.wso2.carbon.identity.framework org.wso2.carbon.identity.action.management @@ -90,7 +105,11 @@ org.apache.axiom.*; version="${axiom.osgi.version.range}", org.apache.commons.logging; version="${import.package.version.commons.logging}", org.apache.commons.lang; version="${commons-lang.wso2.osgi.version.range}", + org.osgi.framework; version="${osgi.framework.imp.pkg.version.range}", + org.osgi.service.component; version="${osgi.service.component.imp.pkg.version.range}", org.apache.commons.collections; version="${commons-collections.wso2.osgi.version.range}", + org.wso2.carbon.database.utils.jdbc; version="${org.wso2.carbon.database.utils.version.range}", + org.wso2.carbon.database.utils.jdbc.exceptions; version="${org.wso2.carbon.database.utils.version.range}", org.apache.axis2.*; version="${axis2.osgi.version.range}", @@ -106,6 +125,7 @@ org.wso2.carbon.identity.core.util; version="${carbon.identity.package.import.version.range}", org.wso2.carbon.identity.core.cache; version="${carbon.identity.package.import.version.range}", org.wso2.carbon.identity.central.log.mgt.*; version="${carbon.identity.package.import.version.range}", + org.wso2.carbon.identity.action.management.*;version="${carbon.identity.package.import.version.range}", com.fasterxml.jackson.annotation; version="${com.fasterxml.jackson.annotation.version.range}" diff --git a/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/ApplicationAuthenticatorService.java b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/ApplicationAuthenticatorService.java index e93a82f42b75..92674282267c 100644 --- a/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/ApplicationAuthenticatorService.java +++ b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/ApplicationAuthenticatorService.java @@ -18,23 +18,43 @@ package org.wso2.carbon.identity.application.common; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.identity.application.common.dao.AuthenticatorManagementDAO; +import org.wso2.carbon.identity.application.common.dao.impl.AuthenticatorManagementDAOImpl; +import org.wso2.carbon.identity.application.common.dao.impl.CacheBackedAuthenticatorMgtDAO; +import org.wso2.carbon.identity.application.common.exception.AuthenticatorMgtException; import org.wso2.carbon.identity.application.common.model.FederatedAuthenticatorConfig; import org.wso2.carbon.identity.application.common.model.LocalAuthenticatorConfig; import org.wso2.carbon.identity.application.common.model.RequestPathAuthenticatorConfig; +import org.wso2.carbon.identity.application.common.model.UserDefinedLocalAuthenticatorConfig; +import org.wso2.carbon.identity.application.common.util.AuthenticatorMgtExceptionBuilder.AuthenticatorMgtError; +import org.wso2.carbon.identity.application.common.util.UserDefinedLocalAuthenticatorValidator; +import org.wso2.carbon.identity.base.AuthenticatorPropertyConstants.DefinedByType; +import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import java.util.ArrayList; import java.util.List; +import static org.wso2.carbon.identity.application.common.util.AuthenticatorMgtExceptionBuilder.buildClientException; +import static org.wso2.carbon.identity.application.common.util.AuthenticatorMgtExceptionBuilder.buildRuntimeServerException; +import static org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants.Authenticator.DISPLAY_NAME; + /** * Application authenticator service. */ public class ApplicationAuthenticatorService { private static volatile ApplicationAuthenticatorService instance; + private static final Log LOG = LogFactory.getLog(ApplicationAuthenticatorService.class); + private static final AuthenticatorManagementDAO dao = + new CacheBackedAuthenticatorMgtDAO(new AuthenticatorManagementDAOImpl()); private List localAuthenticators = new ArrayList<>(); private List federatedAuthenticators = new ArrayList<>(); private List requestPathAuthenticators = new ArrayList<>(); + private UserDefinedLocalAuthenticatorValidator authenticatorValidator = + new UserDefinedLocalAuthenticatorValidator(); public static ApplicationAuthenticatorService getInstance() { if (instance == null) { @@ -51,6 +71,18 @@ public List getLocalAuthenticators() { return this.localAuthenticators; } + /** + * This returns user defined local authenticators. + * + * @param tenantDomain Tenant domain. + * @return Retrieved LocalAuthenticatorConfig. + */ + public List getAllUserDefinedLocalAuthenticators(String tenantDomain) + throws AuthenticatorMgtException { + + return dao.getAllUserDefinedLocalAuthenticators(IdentityTenantUtil.getTenantId(tenantDomain)); + } + public List getFederatedAuthenticators() { return this.federatedAuthenticators; } @@ -59,6 +91,16 @@ public List getRequestPathAuthenticators() { return this.requestPathAuthenticators; } + /** + * This returns only SYSTEM defined local authenticator by name. + * + * @param name The name of the Local Application Authenticator configuration. + * @return Retrieved LocalAuthenticatorConfig. + * + * @deprecated It is recommended to use {@link #getLocalAuthenticatorByName(String, String)}, + * which supports retrieving both USER and SYSTEM defined Local Application Authenticator configuration by name. + */ + @Deprecated public LocalAuthenticatorConfig getLocalAuthenticatorByName(String name) { for (LocalAuthenticatorConfig localAuthenticator : localAuthenticators) { if (localAuthenticator.getName().equals(name)) { @@ -68,6 +110,27 @@ public LocalAuthenticatorConfig getLocalAuthenticatorByName(String name) { return null; } + /** + * Retrieve both USER and SYSTEM defined Local Application Authenticator configuration by name. + * + * @param name The name of the Local Application Authenticator configuration. + * @param tenantDomain Tenant domain. + * @return Retrieved LocalAuthenticatorConfig. + * @throws AuthenticatorMgtException If an error occurs while retrieving the authenticator configuration by name. + */ + public LocalAuthenticatorConfig getLocalAuthenticatorByName(String name, String tenantDomain) + throws AuthenticatorMgtException { + + /* First, check whether an authenticator by the given name is in the system defined authenticators list. + If not, check in user defined authenticators. */ + for (LocalAuthenticatorConfig localAuthenticator : localAuthenticators) { + if (localAuthenticator.getName().equals(name)) { + return localAuthenticator; + } + } + return getUserDefinedLocalAuthenticator(name, tenantDomain); + } + public FederatedAuthenticatorConfig getFederatedAuthenticatorByName(String name) { for (FederatedAuthenticatorConfig federatedAuthenticator : federatedAuthenticators) { if (federatedAuthenticator.getName().equals(name)) { @@ -86,8 +149,18 @@ public RequestPathAuthenticatorConfig getRequestPathAuthenticatorByName(String n return null; } + /** + * Add a system defined Local Application Authenticator configuration. + * + * @param authenticator The Local Application Authenticator configuration. + */ public void addLocalAuthenticator(LocalAuthenticatorConfig authenticator) { + if (authenticator != null) { + if (authenticator.getDefinedByType() != DefinedByType.SYSTEM) { + throw buildRuntimeServerException( + AuthenticatorMgtError.ERROR_CODE_INVALID_DEFINED_BY_AUTH_PROVIDED, null); + } localAuthenticators.add(authenticator); } } @@ -121,4 +194,94 @@ public void removeRequestPathAuthenticator(RequestPathAuthenticatorConfig authen requestPathAuthenticators.remove(authenticator); } } + + /** + * Create a user defined Local Application Authenticator configuration. + * + * @param authenticatorConfig The Local Application Authenticator configuration. + * @param tenantDomain Tenant domain. + * @return Updated LocalAuthenticatorConfig. + * @throws AuthenticatorMgtException If an error occurs while creating the authenticator configuration. + */ + public UserDefinedLocalAuthenticatorConfig addUserDefinedLocalAuthenticator( + UserDefinedLocalAuthenticatorConfig authenticatorConfig, String tenantDomain) + throws AuthenticatorMgtException { + + LocalAuthenticatorConfig config = getLocalAuthenticatorByName(authenticatorConfig.getName(), tenantDomain); + if (config != null) { + throw buildClientException(AuthenticatorMgtError.ERROR_AUTHENTICATOR_ALREADY_EXIST, + authenticatorConfig.getName()); + } + authenticatorValidator.validateAuthenticatorName(authenticatorConfig.getName()); + authenticatorValidator.validateForBlank(DISPLAY_NAME, authenticatorConfig.getDisplayName()); + + return dao.addUserDefinedLocalAuthenticator( + authenticatorConfig, IdentityTenantUtil.getTenantId(tenantDomain)); + } + + /** + * Update a user defined Local Application Authenticator configuration. + * + * @param authenticatorConfig The Local Application Authenticator configuration. + * @param tenantDomain Tenant Domain. + * @return Updated UserDefinedLocalAuthenticatorConfig. + * @throws AuthenticatorMgtException If an error occurs while updating the authenticator configuration. + */ + public UserDefinedLocalAuthenticatorConfig updateUserDefinedLocalAuthenticator( + UserDefinedLocalAuthenticatorConfig authenticatorConfig, String tenantDomain) + throws AuthenticatorMgtException { + + UserDefinedLocalAuthenticatorConfig existingConfig = resolveExistingAuthenticator( + authenticatorConfig.getName(), tenantDomain); + if (existingConfig == null) { + throw buildClientException(AuthenticatorMgtError.ERROR_NOT_FOUND_AUTHENTICATOR, + authenticatorConfig.getName()); + } + + authenticatorValidator.validateForBlank(DISPLAY_NAME, authenticatorConfig.getDisplayName()); + + return dao.updateUserDefinedLocalAuthenticator( + existingConfig, authenticatorConfig, IdentityTenantUtil.getTenantId(tenantDomain)); + } + + /** + * Update a Local Application Authenticator configuration. + * + * @param authenticatorName Name of Local Application Authenticator configuration to be deleted. + * @param tenantDomain Tenant domain. + * @throws AuthenticatorMgtException If an error occurs while deleting the authenticator configuration. + */ + public void deleteUserDefinedLocalAuthenticator(String authenticatorName, String tenantDomain) + throws AuthenticatorMgtException { + + UserDefinedLocalAuthenticatorConfig existingConfig = resolveExistingAuthenticator( + authenticatorName, tenantDomain); + if (existingConfig == null) { + return; + } + + dao.deleteUserDefinedLocalAuthenticator(authenticatorName, existingConfig, + IdentityTenantUtil.getTenantId(tenantDomain)); + } + + /** + * Retrieve a Local Application Authenticator configuration by name. + * + * @param authenticatorName Name of Local Application Authenticator configuration to be deleted. + * @param tenantDomain Tenant domain. + * @return Retrieved UserDefinedLocalAuthenticatorConfig. + * @throws AuthenticatorMgtException If an error occurs while retrieving the authenticator configuration. + */ + public UserDefinedLocalAuthenticatorConfig getUserDefinedLocalAuthenticator(String authenticatorName, + String tenantDomain) throws AuthenticatorMgtException { + + return dao.getUserDefinedLocalAuthenticator( + authenticatorName, IdentityTenantUtil.getTenantId(tenantDomain)); + } + + private UserDefinedLocalAuthenticatorConfig resolveExistingAuthenticator(String authenticatorName, + String tenantDomain) throws AuthenticatorMgtException { + + return dao.getUserDefinedLocalAuthenticator(authenticatorName, IdentityTenantUtil.getTenantId(tenantDomain)); + } } diff --git a/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/cache/AuthenticatorCache.java b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/cache/AuthenticatorCache.java new file mode 100644 index 000000000000..b1495a2f30db --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/cache/AuthenticatorCache.java @@ -0,0 +1,47 @@ +/* + * 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.application.common.cache; + +import org.wso2.carbon.identity.core.cache.BaseCache; +import org.wso2.carbon.utils.CarbonUtils; + +/** + * Cache for the user defined local application authenticator configurations. + */ +public class AuthenticatorCache extends BaseCache { + + private static final String CACHE_NAME = "AuthenticatorCache"; + private static final AuthenticatorCache INSTANCE = new AuthenticatorCache(); + + private AuthenticatorCache() { + + super(CACHE_NAME); + } + + /** + * Get Authenticator cache by the name instance. + * + * @return Authenticator cache by name instance. + */ + public static AuthenticatorCache getInstance() { + + CarbonUtils.checkSecurity(); + return INSTANCE; + } +} diff --git a/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/cache/AuthenticatorCacheEntry.java b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/cache/AuthenticatorCacheEntry.java new file mode 100644 index 000000000000..9529cd3aba92 --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/cache/AuthenticatorCacheEntry.java @@ -0,0 +1,47 @@ +/* + * 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.application.common.cache; + +import org.wso2.carbon.identity.application.common.model.UserDefinedLocalAuthenticatorConfig; +import org.wso2.carbon.identity.core.cache.CacheEntry; + +/** + * Cache Entry for the user defined local application authenticator configurations. + */ +public class AuthenticatorCacheEntry extends CacheEntry { + + private static final long serialVersionUID = -6234723984328871924L; + + private UserDefinedLocalAuthenticatorConfig authenticatorConfig; + + public AuthenticatorCacheEntry(UserDefinedLocalAuthenticatorConfig authenticatorConfig) { + + this.authenticatorConfig = authenticatorConfig; + } + + public UserDefinedLocalAuthenticatorConfig getAuthenticatorConfig() { + + return authenticatorConfig; + } + + public void setAuthenticatorConfig(UserDefinedLocalAuthenticatorConfig authenticatorConfig) { + + this.authenticatorConfig = authenticatorConfig; + } +} diff --git a/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/cache/AuthenticatorCacheKey.java b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/cache/AuthenticatorCacheKey.java new file mode 100644 index 000000000000..645fda5227af --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/cache/AuthenticatorCacheKey.java @@ -0,0 +1,56 @@ +/* + * 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.application.common.cache; + +import org.wso2.carbon.identity.core.cache.CacheKey; + +/** + * Cache key for the user defined local application authenticator configurations. + */ +public class AuthenticatorCacheKey extends CacheKey { + + private static final long serialVersionUID = -2897123859023483921L; + + private final String authenticatorName; + + public AuthenticatorCacheKey(String authenticatorName) { + + this.authenticatorName = authenticatorName; + } + + public String getAuthenticatorName() { + + return authenticatorName; + } + + @Override + public boolean equals(Object o) { + + if (!(o instanceof AuthenticatorCacheKey)) { + return false; + } + return authenticatorName.equals(((AuthenticatorCacheKey) o).getAuthenticatorName()); + } + + @Override + public int hashCode() { + + return authenticatorName.hashCode(); + } +} diff --git a/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/constant/AuthenticatorMgtSQLConstants.java b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/constant/AuthenticatorMgtSQLConstants.java new file mode 100644 index 000000000000..6269a541810b --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/constant/AuthenticatorMgtSQLConstants.java @@ -0,0 +1,86 @@ +/* + * 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.application.common.constant; + +/** + * SQL constants for authenticator configuration management service. + */ +public class AuthenticatorMgtSQLConstants { + + private AuthenticatorMgtSQLConstants() { + + } + + /** + * Column Names. + */ + public static class Column { + + public static final String IDP_ID = "ID"; + public static final String IDP_NAME = "IDP_NAME"; + public static final String TENANT_ID = "TENANT_ID"; + public static final String NAME = "NAME"; + public static final String IS_ENABLED = "IS_ENABLED"; + public static final String DEFINED_BY = "DEFINED_BY"; + public static final String AUTHENTICATION_TYPE = "AUTHENTICATION_TYPE"; + public static final String DISPLAY_NAME = "DISPLAY_NAME"; + public static final String ID = "ID"; + public static final String AUTHENTICATOR_ID = "AUTHENTICATOR_ID"; + public static final String PROPERTY_KEY = "PROPERTY_KEY"; + public static final String PROPERTY_VALUE = "PROPERTY_VALUE"; + public static final String IS_SECRET = "IS_SECRET"; + + private Column() { + + } + } + + /** + * Queries. + */ + public static class Query { + + public static final String ADD_AUTHENTICATOR_SQL = "INSERT INTO IDP_AUTHENTICATOR " + + "(TENANT_ID, IDP_ID, NAME, IS_ENABLED, DEFINED_BY, AUTHENTICATION_TYPE, DISPLAY_NAME) VALUES" + + " (:TENANT_ID;, (SELECT ID FROM IDP WHERE IDP.NAME = :IDP_NAME; AND IDP.TENANT_ID = :TENANT_ID;), " + + ":NAME;, :IS_ENABLED;, :DEFINED_BY;, :AUTHENTICATION_TYPE;, :DISPLAY_NAME;);"; + public static final String UPDATE_AUTHENTICATOR_SQL = "UPDATE IDP_AUTHENTICATOR SET IS_ENABLED = " + + ":IS_ENABLED;, DISPLAY_NAME = :DISPLAY_NAME; WHERE NAME = :NAME; AND TENANT_ID = :TENANT_ID;"; + public static final String GET_AUTHENTICATOR_SQL = "SELECT * FROM IDP_AUTHENTICATOR " + + "WHERE DEFINED_BY = :DEFINED_BY; AND NAME = :NAME; AND TENANT_ID = :TENANT_ID;"; + public static final String GET_ALL_USER_DEFINED_AUTHENTICATOR_SQL = "SELECT * FROM IDP_AUTHENTICATOR " + + "WHERE DEFINED_BY = :DEFINED_BY; AND TENANT_ID = :TENANT_ID;"; + public static final String DELETE_AUTHENTICATOR_SQL = "DELETE FROM IDP_AUTHENTICATOR WHERE NAME = :NAME; " + + " AND TENANT_ID = :TENANT_ID;"; + public static final String GET_AUTHENTICATOR_ID_SQL = "SELECT ID FROM IDP_AUTHENTICATOR " + + "WHERE NAME = :NAME; AND TENANT_ID = :TENANT_ID;"; + public static final String ADD_AUTHENTICATOR_PROP_SQL = "INSERT INTO IDP_AUTHENTICATOR_PROPERTY " + + "(AUTHENTICATOR_ID, TENANT_ID, PROPERTY_KEY, PROPERTY_VALUE, IS_SECRET) VALUES " + + "(:AUTHENTICATOR_ID;, :TENANT_ID;, :PROPERTY_KEY;, :PROPERTY_VALUE;, :IS_SECRET;);"; + public static final String DELETE_AUTHENTICATOR_PROP_SQL = "DELETE FROM IDP_AUTHENTICATOR_PROPERTY " + + "WHERE AUTHENTICATOR_ID = :AUTHENTICATOR_ID; AND TENANT_ID = :TENANT_ID;"; + public static final String GET_AUTHENTICATOR_PROP_SQL = "SELECT PROPERTY_KEY, PROPERTY_VALUE, IS_SECRET" + + " FROM IDP_AUTHENTICATOR_PROPERTY " + + "WHERE AUTHENTICATOR_ID = :AUTHENTICATOR_ID; AND TENANT_ID = :TENANT_ID;"; + + private Query() { + + } + } +} diff --git a/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/dao/AuthenticatorManagementDAO.java b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/dao/AuthenticatorManagementDAO.java new file mode 100644 index 000000000000..292a22192948 --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/dao/AuthenticatorManagementDAO.java @@ -0,0 +1,86 @@ +/* + * 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.application.common.dao; + +import org.wso2.carbon.identity.application.common.exception.AuthenticatorMgtException; +import org.wso2.carbon.identity.application.common.model.UserDefinedLocalAuthenticatorConfig; + +import java.util.List; + +/** + * This interface performs CRUD operations for the user defined local application authenticator configurations. + */ +public interface AuthenticatorManagementDAO { + + /** + * Create a new user defined local application authenticator configuration. + * + * @param authenticatorConfig Local application authenticator configuration. + * @param tenantId Tenant Id. + * @return Created UserDefinedLocalAuthenticatorConfig. + * @throws AuthenticatorMgtException If an error occurs while adding the authenticator configuration. + */ + UserDefinedLocalAuthenticatorConfig addUserDefinedLocalAuthenticator( + UserDefinedLocalAuthenticatorConfig authenticatorConfig, int tenantId) throws AuthenticatorMgtException; + + /** + * Update a user defined local application authenticator configuration. + * + * @param existingAuthenticatorConfig Existing Local application authenticator configuration. + * @param updatedAuthenticatorConfig New local application authenticator configuration. + * @param tenantId Tenant Id. + * @return Updated UserDefinedLocalAuthenticatorConfig. + * @throws AuthenticatorMgtException If an error occurs while updating the authenticator configuration. + */ + UserDefinedLocalAuthenticatorConfig updateUserDefinedLocalAuthenticator( + UserDefinedLocalAuthenticatorConfig existingAuthenticatorConfig, + UserDefinedLocalAuthenticatorConfig updatedAuthenticatorConfig, int tenantId) + throws AuthenticatorMgtException; + + /** + * Retrieve a local user defined application authenticator configuration by name. + * + * @param authenticatorConfigName Name of the local application authenticator configuration. + * @param tenantId Tenant Id. + * @return Retrieved UserDefinedLocalAuthenticatorConfig + * @throws AuthenticatorMgtException If an error occurs while retrieving the authenticator configuration. + */ + UserDefinedLocalAuthenticatorConfig getUserDefinedLocalAuthenticator( + String authenticatorConfigName, int tenantId) throws AuthenticatorMgtException; + + /** + * Retrieve all user defined local application authenticator configurations. + * + * @param tenantId Tenant Id. + * @return Retrieved UserDefinedLocalAuthenticatorConfig + * @throws AuthenticatorMgtException If an error occurs while retrieving the authenticator configurations. + */ + List getAllUserDefinedLocalAuthenticators(int tenantId) + throws AuthenticatorMgtException; + + /** + * Create a new user defined local application authenticator configuration. + * + * @param authenticatorConfigName Name of the local application authenticator configuration. + * @param tenantId Tenant Id. + * @throws AuthenticatorMgtException If an error occurs while deleting the authenticator configuration. + */ + void deleteUserDefinedLocalAuthenticator(String authenticatorConfigName, UserDefinedLocalAuthenticatorConfig + authenticatorConfig, int tenantId) throws AuthenticatorMgtException; +} diff --git a/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/dao/impl/AuthenticatorManagementDAOImpl.java b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/dao/impl/AuthenticatorManagementDAOImpl.java new file mode 100644 index 000000000000..e04a7f860487 --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/dao/impl/AuthenticatorManagementDAOImpl.java @@ -0,0 +1,284 @@ +/* + * 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.application.common.dao.impl; + +import org.wso2.carbon.database.utils.jdbc.NamedJdbcTemplate; +import org.wso2.carbon.database.utils.jdbc.exceptions.TransactionException; +import org.wso2.carbon.identity.application.common.constant.AuthenticatorMgtSQLConstants.Column; +import org.wso2.carbon.identity.application.common.constant.AuthenticatorMgtSQLConstants.Query; +import org.wso2.carbon.identity.application.common.dao.AuthenticatorManagementDAO; +import org.wso2.carbon.identity.application.common.exception.AuthenticatorMgtException; +import org.wso2.carbon.identity.application.common.exception.AuthenticatorMgtServerException; +import org.wso2.carbon.identity.application.common.model.Property; +import org.wso2.carbon.identity.application.common.model.UserDefinedLocalAuthenticatorConfig; +import org.wso2.carbon.identity.application.common.util.AuthenticatorMgtExceptionBuilder.AuthenticatorMgtError; +import org.wso2.carbon.identity.base.AuthenticatorPropertyConstants.AuthenticationType; +import org.wso2.carbon.identity.base.AuthenticatorPropertyConstants.DefinedByType; +import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; + +import java.util.ArrayList; +import java.util.List; + +import static org.wso2.carbon.identity.application.common.util.AuthenticatorMgtExceptionBuilder.buildServerException; + +/** + * This class implements the AuthenticatorManagementDAO interface which perform CRUD operation on database. + */ +public class AuthenticatorManagementDAOImpl implements AuthenticatorManagementDAO { + + private static final String IS_TRUE_VALUE = "1"; + private static final String IS_FALSE_VALUE = "0"; + private static final String LOCAL_IDP_NAME = "LOCAL"; + + @Override + public UserDefinedLocalAuthenticatorConfig addUserDefinedLocalAuthenticator( + UserDefinedLocalAuthenticatorConfig authenticatorConfig, int tenantId) throws AuthenticatorMgtException { + + NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); + try { + int authenticatorConfigID = jdbcTemplate.withTransaction(template -> + template.executeInsert(Query.ADD_AUTHENTICATOR_SQL, + statement -> { + statement.setString(Column.NAME, authenticatorConfig.getName()); + statement.setString(Column.DISPLAY_NAME, authenticatorConfig.getDisplayName()); + statement.setString(Column.DEFINED_BY, authenticatorConfig.getDefinedByType().toString()); + statement.setString(Column.AUTHENTICATION_TYPE, authenticatorConfig.getAuthenticationType() + .toString()); + statement.setString(Column.IS_ENABLED, + authenticatorConfig.isEnabled() ? IS_TRUE_VALUE : IS_FALSE_VALUE); + statement.setString(Column.IDP_NAME, LOCAL_IDP_NAME); + statement.setInt(Column.TENANT_ID, tenantId); + }, null, true)); + + if (authenticatorConfigID == 0) { + authenticatorConfigID = getAuthenticatorEntryId(authenticatorConfig.getName(), tenantId); + } + addAuthenticatorProperty(authenticatorConfigID, authenticatorConfig.getProperties(), tenantId); + + return getUserDefinedLocalAuthenticatorByName(authenticatorConfig.getName(), tenantId); + } catch (TransactionException e) { + throw buildServerException(AuthenticatorMgtError.ERROR_WHILE_ADDING_AUTHENTICATOR, e); + } + } + + @Override + public UserDefinedLocalAuthenticatorConfig updateUserDefinedLocalAuthenticator( + UserDefinedLocalAuthenticatorConfig existingAuthenticatorConfig, + UserDefinedLocalAuthenticatorConfig updatedAuthenticatorConfig, int tenantId) + throws AuthenticatorMgtException { + + NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); + try { + jdbcTemplate.withTransaction(template -> { + template.executeUpdate(Query.UPDATE_AUTHENTICATOR_SQL, + statement -> { + statement.setString(Column.DISPLAY_NAME, updatedAuthenticatorConfig.getDisplayName()); + statement.setString(Column.IS_ENABLED, + updatedAuthenticatorConfig.isEnabled() ? IS_TRUE_VALUE : IS_FALSE_VALUE); + statement.setString(Column.NAME, existingAuthenticatorConfig.getName()); + statement.setInt(Column.TENANT_ID, tenantId); + }); + return null; + }); + + return getUserDefinedLocalAuthenticatorByName(updatedAuthenticatorConfig.getName(), tenantId); + } catch (TransactionException e) { + throw buildServerException(AuthenticatorMgtError.ERROR_WHILE_UPDATING_AUTHENTICATOR, e); + } + } + + @Override + public UserDefinedLocalAuthenticatorConfig getUserDefinedLocalAuthenticator( + String authenticatorConfigName, int tenantId) throws AuthenticatorMgtException { + + try { + return getUserDefinedLocalAuthenticatorByName(authenticatorConfigName, tenantId); + } catch (TransactionException e) { + throw buildServerException(AuthenticatorMgtError.ERROR_WHILE_RETRIEVING_AUTHENTICATOR_BY_NAME, e); + } + } + + @Override + public List getAllUserDefinedLocalAuthenticators(int tenantId) + throws AuthenticatorMgtException { + + try { + NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); + List allUserDefinedLocalConfigs = new ArrayList<>(); + List configDaoModels = jdbcTemplate.withTransaction( + template -> template.executeQuery(Query.GET_ALL_USER_DEFINED_AUTHENTICATOR_SQL, + (resultSet, rowNumber) -> { + UserDefinedLocalAuthenticatorConfig config = getLocalAuthenticatorConfigBasedOnType( + resultSet.getString(Column.AUTHENTICATION_TYPE)); + config.setName(resultSet.getString(Column.NAME)); + config.setDisplayName(resultSet.getString(Column.DISPLAY_NAME)); + config.setEnabled(resultSet.getString(Column.IS_ENABLED).equals(IS_TRUE_VALUE)); + config.setDefinedByType(DefinedByType.valueOf(resultSet.getString(Column.DEFINED_BY))); + return new AuthenticatorConfigDaoModel(resultSet.getInt(Column.ID), config); + }, + statement -> { + statement.setString(Column.DEFINED_BY, DefinedByType.USER.toString()); + statement.setInt(Column.TENANT_ID, tenantId); + })); + + for (AuthenticatorConfigDaoModel config: configDaoModels) { + UserDefinedLocalAuthenticatorConfig retrievedConfigs = config.getConfig(); + retrievedConfigs.setProperties(getAuthenticatorProperties(config.getEntryId(), tenantId)); + allUserDefinedLocalConfigs.add(retrievedConfigs); + } + return allUserDefinedLocalConfigs; + } catch (TransactionException e) { + throw buildServerException(AuthenticatorMgtError.ERROR_WHILE_RETRIEVING_AUTHENTICATOR_BY_NAME, e); + } + } + + @Override + public void deleteUserDefinedLocalAuthenticator(String authenticatorConfigName, + UserDefinedLocalAuthenticatorConfig authenticatorConfig, int tenantId) throws AuthenticatorMgtException { + + NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); + try { + jdbcTemplate.withTransaction(template -> { + template.executeUpdate(Query.DELETE_AUTHENTICATOR_SQL, + statement -> { + statement.setString(Column.NAME, authenticatorConfigName); + statement.setInt(Column.TENANT_ID, tenantId); + statement.executeUpdate(); + }); + return null; + }); + } catch (TransactionException e) { + throw buildServerException(AuthenticatorMgtError.ERROR_WHILE_DELETING_AUTHENTICATOR, e); + } + } + + private UserDefinedLocalAuthenticatorConfig getUserDefinedLocalAuthenticatorByName(String authenticatorConfigName, + int tenantId) throws TransactionException { + + NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); + AuthenticatorConfigDaoModel configDaoModel = jdbcTemplate.withTransaction(template -> + template.fetchSingleRecord(Query.GET_AUTHENTICATOR_SQL, + (resultSet, rowNumber) -> { + UserDefinedLocalAuthenticatorConfig config = getLocalAuthenticatorConfigBasedOnType( + resultSet.getString(Column.AUTHENTICATION_TYPE)); + config.setName(resultSet.getString(Column.NAME)); + config.setDisplayName(resultSet.getString(Column.DISPLAY_NAME)); + config.setEnabled(resultSet.getString(Column.IS_ENABLED).equals(IS_TRUE_VALUE)); + config.setDefinedByType(DefinedByType.USER); + return new AuthenticatorConfigDaoModel(resultSet.getInt(Column.ID), config); + }, + statement -> { + statement.setString(Column.NAME, authenticatorConfigName); + statement.setInt(Column.TENANT_ID, tenantId); + statement.setString(Column.DEFINED_BY, DefinedByType.USER.toString()); + })); + + if (configDaoModel == null) { + return null; + } + + UserDefinedLocalAuthenticatorConfig config = configDaoModel.getConfig(); + config.setProperties(getAuthenticatorProperties(configDaoModel.getEntryId(), tenantId)); + return config; + } + + private UserDefinedLocalAuthenticatorConfig getLocalAuthenticatorConfigBasedOnType(String authenticationType) { + + if (AuthenticationType.VERIFICATION.toString().equals(authenticationType)) { + return new UserDefinedLocalAuthenticatorConfig(AuthenticationType.VERIFICATION); + } + return new UserDefinedLocalAuthenticatorConfig(AuthenticationType.IDENTIFICATION); + } + + private int getAuthenticatorEntryId(String authenticatorConfigName, int tenantId) + throws AuthenticatorMgtServerException, TransactionException { + + NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); + int id = jdbcTemplate.withTransaction(template -> + template.fetchSingleRecord(Query.GET_AUTHENTICATOR_ID_SQL, + (resultSet, rowNumber) -> resultSet.getInt(Column.ID), + statement -> { + statement.setString(Column.NAME, authenticatorConfigName); + statement.setInt(Column.TENANT_ID, tenantId); + })); + + if (id != 0) { + return id; + } + throw buildServerException(AuthenticatorMgtError.ERROR_CODE_NO_AUTHENTICATOR_FOUND, + authenticatorConfigName); + } + + private void addAuthenticatorProperty(int authenticatorConfigID, Property[] properties, int tenantId) + throws TransactionException { + + Property prop = properties[0]; + NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); + jdbcTemplate.withTransaction(template -> + template.executeInsert(Query.ADD_AUTHENTICATOR_PROP_SQL, + statementProp -> { + statementProp.setInt(Column.AUTHENTICATOR_ID, authenticatorConfigID); + statementProp.setInt(Column.TENANT_ID, tenantId); + statementProp.setString(Column.PROPERTY_KEY, prop.getName()); + statementProp.setString(Column.PROPERTY_VALUE, prop.getValue()); + statementProp.setString(Column.IS_SECRET, IS_FALSE_VALUE); + }, null, false)); + } + + private Property[] getAuthenticatorProperties(int authenticatorConfigID, int tenantId) throws TransactionException { + + NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); + List properties = jdbcTemplate.withTransaction(template -> + template.executeQuery(Query.GET_AUTHENTICATOR_PROP_SQL, + (resultSet, rowNumber) -> { + Property property = new Property(); + property.setName(resultSet.getString(Column.PROPERTY_KEY)); + property.setValue(resultSet.getString(Column.PROPERTY_VALUE)); + property.setConfidential(false); + return property; + }, + statementProp -> { + statementProp.setInt(Column.AUTHENTICATOR_ID, authenticatorConfigID); + statementProp.setInt(Column.TENANT_ID, tenantId); + })); + return properties.toArray(new Property[0]); + } + + /** + * This class represents the user defined local authenticator configuration with entry id from DAO. + */ + private static class AuthenticatorConfigDaoModel { + + private final int entryId; + private final UserDefinedLocalAuthenticatorConfig config; + + private AuthenticatorConfigDaoModel(int entryId, UserDefinedLocalAuthenticatorConfig config) { + this.entryId = entryId; + this.config = config; + } + + public int getEntryId() { + return entryId; + } + + public UserDefinedLocalAuthenticatorConfig getConfig() { + return config; + } + } +} diff --git a/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/dao/impl/AuthenticatorManagementFacade.java b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/dao/impl/AuthenticatorManagementFacade.java new file mode 100644 index 000000000000..cd182863ec43 --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/dao/impl/AuthenticatorManagementFacade.java @@ -0,0 +1,219 @@ +/* + * 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.application.common.dao.impl; + +import org.apache.commons.lang.StringUtils; +import org.wso2.carbon.database.utils.jdbc.NamedJdbcTemplate; +import org.wso2.carbon.database.utils.jdbc.exceptions.TransactionException; +import org.wso2.carbon.identity.application.common.dao.AuthenticatorManagementDAO; +import org.wso2.carbon.identity.application.common.exception.AuthenticatorMgtClientException; +import org.wso2.carbon.identity.application.common.exception.AuthenticatorMgtException; +import org.wso2.carbon.identity.application.common.exception.AuthenticatorMgtServerException; +import org.wso2.carbon.identity.application.common.model.Property; +import org.wso2.carbon.identity.application.common.model.UserDefinedLocalAuthenticatorConfig; +import org.wso2.carbon.identity.application.common.util.AuthenticatorMgtExceptionBuilder; +import org.wso2.carbon.identity.application.common.util.AuthenticatorMgtExceptionBuilder.AuthenticatorMgtError; +import org.wso2.carbon.identity.application.common.util.UserDefinedAuthenticatorEndpointConfigManager; +import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; + +import java.util.List; + +import static org.wso2.carbon.identity.application.common.util.AuthenticatorMgtExceptionBuilder.buildServerException; +import static org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants.Authenticator.ACTION_ID_PROPERTY; + +/** + * This class responsible for managing authenticator endpoint configurations for the user defined local + * authenticators. + */ +public class AuthenticatorManagementFacade implements AuthenticatorManagementDAO { + + private final AuthenticatorManagementDAO dao; + private final UserDefinedAuthenticatorEndpointConfigManager endpointConfigManager = + new UserDefinedAuthenticatorEndpointConfigManager(); + + public AuthenticatorManagementFacade(AuthenticatorManagementDAO dao) { + + this.dao = dao; + } + + /** + * Invoke external service to store associated data (endpoint configuration) and create the user defined local + * authenticator to the DB. + * + * @param authenticatorConfig User defined local authenticator configuration. + * @param tenantId Tenant ID. + * @return User defined local authenticator configuration. + * @throws AuthenticatorMgtException If an error occurs while adding the user defined local authenticator. + */ + @Override + public UserDefinedLocalAuthenticatorConfig addUserDefinedLocalAuthenticator( + UserDefinedLocalAuthenticatorConfig authenticatorConfig, int tenantId) throws AuthenticatorMgtException { + + NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); + try { + return jdbcTemplate.withTransaction(template -> { + endpointConfigManager.addEndpointConfigurations(authenticatorConfig, tenantId); + validateAuthenticatorProperties(authenticatorConfig); + return endpointConfigManager.resolveEndpointConfigurations( + dao.addUserDefinedLocalAuthenticator(authenticatorConfig, tenantId), tenantId); + }); + } catch (TransactionException e) { + throw handleAuthenticatorMgtException(AuthenticatorMgtError.ERROR_WHILE_UPDATING_AUTHENTICATOR, e, + authenticatorConfig.getName()); + } + } + + /** + * Invoke external service to update associated data (endpoint configuration) and update the user defined local + * authenticator in DB. + * + * @param existingAuthenticatorConfig Existing user defined local authenticator configuration. + * @param newAuthenticatorConfig New user defined local authenticator configuration. + * @param tenantId Tenant ID. + * @return Updated user defined local authenticator configuration. + * @throws AuthenticatorMgtException If an error occurs while updating the user defined local authenticator. + */ + @Override + public UserDefinedLocalAuthenticatorConfig updateUserDefinedLocalAuthenticator(UserDefinedLocalAuthenticatorConfig + existingAuthenticatorConfig, UserDefinedLocalAuthenticatorConfig newAuthenticatorConfig, + int tenantId) throws AuthenticatorMgtException { + + NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); + try { + return jdbcTemplate.withTransaction(template -> { + endpointConfigManager.updateEndpointConfigurations(newAuthenticatorConfig, existingAuthenticatorConfig, + tenantId); + validateAuthenticatorProperties(newAuthenticatorConfig); + return endpointConfigManager.resolveEndpointConfigurations( + dao.updateUserDefinedLocalAuthenticator(existingAuthenticatorConfig, newAuthenticatorConfig, + tenantId), tenantId); + }); + } catch (TransactionException e) { + throw handleAuthenticatorMgtException(AuthenticatorMgtError.ERROR_WHILE_UPDATING_AUTHENTICATOR, e, + newAuthenticatorConfig.getName()); + } + } + + /** + * Get user defined local authenticator by name and resolving associated data (endpoint configurations) + * by invoking external service. + * + * @param authenticatorConfigName Name of the user defined local authenticator. + * @param tenantId Tenant ID. + * @return User defined local authenticator. + * @throws AuthenticatorMgtException If an error occurs while retrieving the user defined local authenticator. + */ + @Override + public UserDefinedLocalAuthenticatorConfig getUserDefinedLocalAuthenticator( + String authenticatorConfigName, int tenantId) throws AuthenticatorMgtException { + + NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); + try { + return jdbcTemplate.withTransaction(template -> + endpointConfigManager.resolveEndpointConfigurations(dao.getUserDefinedLocalAuthenticator( + authenticatorConfigName, tenantId), tenantId)); + } catch (TransactionException e) { + throw handleAuthenticatorMgtException(AuthenticatorMgtError.ERROR_WHILE_RETRIEVING_AUTHENTICATOR_BY_NAME, e, + authenticatorConfigName); + } + } + + /** + * Get all user defined local authenticators and resolving associated data (endpoint configurations) + * by invoking external service. + * + * @param tenantId Tenant ID. + * @return List of user defined local authenticators. + * @throws AuthenticatorMgtException If an error occurs while retrieving all user defined local authenticators. + */ + @Override + public List getAllUserDefinedLocalAuthenticators(int tenantId) + throws AuthenticatorMgtException { + + NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); + try { + return jdbcTemplate.withTransaction(template -> { + List configList = + dao.getAllUserDefinedLocalAuthenticators(tenantId); + // TODO: Utilize a batch operation once issue:https://github.com/wso2/product-is/issues/21783 is done. + for (UserDefinedLocalAuthenticatorConfig config : configList) { + endpointConfigManager.resolveEndpointConfigurations(config, tenantId); + } + return configList; + }); + } catch (TransactionException e) { + throw handleAuthenticatorMgtException( + AuthenticatorMgtError.ERROR_WHILE_ALL_RETRIEVING_AUTHENTICATOR, e, StringUtils.EMPTY); + } + } + + /** + * Invoke external service to delete associated data (endpoint configuration) and delete the user defined local + * authenticator in DB. + * + * @param authenticatorConfigName Name of the user defined local authenticator. + * @param authenticatorConfig User defined local authenticator configuration. + * @param tenantId Tenant ID. + * @throws AuthenticatorMgtException If an error occurs while deleting the user defined local authenticator. + */ + @Override + public void deleteUserDefinedLocalAuthenticator(String authenticatorConfigName, UserDefinedLocalAuthenticatorConfig + authenticatorConfig, int tenantId) throws AuthenticatorMgtException { + + NamedJdbcTemplate jdbcTemplate = new NamedJdbcTemplate(IdentityDatabaseUtil.getDataSource()); + try { + jdbcTemplate.withTransaction(template -> { + endpointConfigManager.deleteEndpointConfigurations(authenticatorConfig, tenantId); + dao.deleteUserDefinedLocalAuthenticator(authenticatorConfigName, authenticatorConfig, tenantId); + return null; + }); + } catch (TransactionException e) { + throw handleAuthenticatorMgtException(AuthenticatorMgtError.ERROR_WHILE_DELETING_AUTHENTICATOR, e, + StringUtils.EMPTY); + } + } + + /** + * Handle the authenticator management client exception. + * + * @param throwable Throwable object. + * @throws AuthenticatorMgtClientException If an authenticator management client exception. + */ + private static AuthenticatorMgtException handleAuthenticatorMgtException(AuthenticatorMgtError + authenticatorMgtError, Throwable throwable, String... data) throws AuthenticatorMgtException { + + if (throwable.getCause() instanceof AuthenticatorMgtClientException) { + AuthenticatorMgtClientException error = (AuthenticatorMgtClientException) throwable.getCause(); + throw new AuthenticatorMgtClientException(error.getErrorCode(), error.getMessage(), error.getDescription()); + } + + throw buildServerException(authenticatorMgtError, throwable, data); + } + + private void validateAuthenticatorProperties(UserDefinedLocalAuthenticatorConfig authenticatorConfig) + throws AuthenticatorMgtServerException { + + // User defined local authenticator should have only one property which is the action id. + Property[] properties = authenticatorConfig.getProperties(); + if (!(properties.length == 1 && ACTION_ID_PROPERTY.equals(properties[0].getName()))) { + throw buildServerException(AuthenticatorMgtExceptionBuilder.AuthenticatorMgtError + .ERROR_CODE_HAVING_MULTIPLE_PROP, authenticatorConfig.getName()); + } + } +} diff --git a/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/dao/impl/CacheBackedAuthenticatorMgtDAO.java b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/dao/impl/CacheBackedAuthenticatorMgtDAO.java new file mode 100644 index 000000000000..e4775e6583e8 --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/dao/impl/CacheBackedAuthenticatorMgtDAO.java @@ -0,0 +1,126 @@ +/* + * 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.application.common.dao.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.identity.application.common.cache.AuthenticatorCache; +import org.wso2.carbon.identity.application.common.cache.AuthenticatorCacheEntry; +import org.wso2.carbon.identity.application.common.cache.AuthenticatorCacheKey; +import org.wso2.carbon.identity.application.common.dao.AuthenticatorManagementDAO; +import org.wso2.carbon.identity.application.common.exception.AuthenticatorMgtException; +import org.wso2.carbon.identity.application.common.model.UserDefinedLocalAuthenticatorConfig; + +import java.util.List; + +/** + * Implements caching layer for the AuthenticatorManagementDAO. + */ +public class CacheBackedAuthenticatorMgtDAO implements AuthenticatorManagementDAO { + + private static final Log LOG = LogFactory.getLog(CacheBackedAuthenticatorMgtDAO.class); + private final AuthenticatorCache authenticatorCache; + private final AuthenticatorManagementFacade authenticatorMgtFacade; + + public CacheBackedAuthenticatorMgtDAO(AuthenticatorManagementDAO authenticatorManagementDAO) { + + authenticatorMgtFacade = new AuthenticatorManagementFacade(authenticatorManagementDAO); + authenticatorCache = AuthenticatorCache.getInstance(); + } + + @Override + public UserDefinedLocalAuthenticatorConfig addUserDefinedLocalAuthenticator( + UserDefinedLocalAuthenticatorConfig authenticatorConfig, int tenantId) throws AuthenticatorMgtException { + + UserDefinedLocalAuthenticatorConfig createdConfig = authenticatorMgtFacade.addUserDefinedLocalAuthenticator( + authenticatorConfig, tenantId); + + AuthenticatorCacheKey cacheKey = new AuthenticatorCacheKey(authenticatorConfig.getName()); + authenticatorCache.addToCache(cacheKey, new AuthenticatorCacheEntry(createdConfig), tenantId); + if (LOG.isDebugEnabled()) { + LOG.debug(String.format( + "Adding cache entry for newly created authenticator %s.", authenticatorConfig.getName())); + } + return createdConfig; + } + + @Override + public UserDefinedLocalAuthenticatorConfig updateUserDefinedLocalAuthenticator(UserDefinedLocalAuthenticatorConfig + existingAuthenticatorConfig, UserDefinedLocalAuthenticatorConfig newAuthenticatorConfig, + int tenantId) throws AuthenticatorMgtException { + + AuthenticatorCacheKey cacheKey = new AuthenticatorCacheKey(existingAuthenticatorConfig.getName()); + authenticatorCache.clearCacheEntry(cacheKey, tenantId); + if (LOG.isDebugEnabled()) { + LOG.debug(String.format( + "Delete cache entry of updating authenticator %s.", existingAuthenticatorConfig.getName())); + } + + return authenticatorMgtFacade.updateUserDefinedLocalAuthenticator( + existingAuthenticatorConfig, newAuthenticatorConfig, tenantId); + } + + @Override + public UserDefinedLocalAuthenticatorConfig getUserDefinedLocalAuthenticator( + String authenticatorConfigName, int tenantId) throws AuthenticatorMgtException { + + AuthenticatorCacheKey cacheKey = new AuthenticatorCacheKey(authenticatorConfigName); + AuthenticatorCacheEntry entry = authenticatorCache.getValueFromCache(cacheKey, tenantId); + + if (entry != null) { + if (LOG.isDebugEnabled()) { + LOG.debug(String.format("Cache entry found for authenticator %s.", authenticatorConfigName)); + } + return entry.getAuthenticatorConfig(); + } + + if (LOG.isDebugEnabled()) { + LOG.debug(String.format( + "Cache entry not found for authenticator %s. Fetching from DB.", authenticatorConfigName)); + } + UserDefinedLocalAuthenticatorConfig authenticatorConfig = authenticatorMgtFacade + .getUserDefinedLocalAuthenticator(authenticatorConfigName, tenantId); + + authenticatorCache.addToCache(cacheKey, new AuthenticatorCacheEntry(authenticatorConfig), tenantId); + if (LOG.isDebugEnabled()) { + LOG.debug(String.format( + "Entry fetched from DB for authenticator %s. Adding cache entry.", authenticatorConfigName)); + } + return authenticatorConfig; + } + + @Override + public List getAllUserDefinedLocalAuthenticators(int tenantId) + throws AuthenticatorMgtException { + + return authenticatorMgtFacade.getAllUserDefinedLocalAuthenticators(tenantId); + } + + @Override + public void deleteUserDefinedLocalAuthenticator(String authenticatorConfigName, + UserDefinedLocalAuthenticatorConfig authenticatorConfig, int tenantId) throws AuthenticatorMgtException { + + authenticatorCache.clearCacheEntry(new AuthenticatorCacheKey(authenticatorConfigName), tenantId); + if (LOG.isDebugEnabled()) { + LOG.debug(String.format("Delete cache entry of deleting authenticator %s.", authenticatorConfigName)); + } + authenticatorMgtFacade.deleteUserDefinedLocalAuthenticator(authenticatorConfigName, authenticatorConfig, + tenantId); + } +} diff --git a/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/exception/AuthenticatorMgtClientException.java b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/exception/AuthenticatorMgtClientException.java new file mode 100644 index 000000000000..1542f39297fc --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/exception/AuthenticatorMgtClientException.java @@ -0,0 +1,30 @@ +/* + * 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.application.common.exception; + +/** + * Authenticator configuration management client exception. + */ +public class AuthenticatorMgtClientException extends AuthenticatorMgtException { + + public AuthenticatorMgtClientException(String errorCode, String message, String description) { + + super(message, description, errorCode); + } +} diff --git a/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/exception/AuthenticatorMgtException.java b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/exception/AuthenticatorMgtException.java new file mode 100644 index 000000000000..1ba49c6214de --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/exception/AuthenticatorMgtException.java @@ -0,0 +1,52 @@ +/* + * 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.application.common.exception; + +/** + * Authenticator configuration management exception. + */ +public class AuthenticatorMgtException extends Exception { + + private final String errorCode; + private final String description; + + public AuthenticatorMgtException(String message, String description, String errorCode) { + + super(message); + this.errorCode = errorCode; + this.description = description; + } + + public AuthenticatorMgtException(String message, String description, String errorCode, Throwable cause) { + + super(message, cause); + this.errorCode = errorCode; + this.description = description; + } + + public String getErrorCode() { + + return this.errorCode; + } + + public String getDescription() { + + return this.description; + } +} diff --git a/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/exception/AuthenticatorMgtServerException.java b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/exception/AuthenticatorMgtServerException.java new file mode 100644 index 000000000000..d70c44ab7b83 --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/exception/AuthenticatorMgtServerException.java @@ -0,0 +1,36 @@ +/* + * 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.application.common.exception; + +/** + * Authenticator configuration management server exception. + */ +public class AuthenticatorMgtServerException extends AuthenticatorMgtException { + + public AuthenticatorMgtServerException(String errorCode, String message, String description) { + + super(message, errorCode, description); + } + + public AuthenticatorMgtServerException(String errorCode, String message, String description, + Throwable cause) { + + super(message, description, errorCode, cause); + } +} diff --git a/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/exception/AuthenticatorMgtServerRuntimeException.java b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/exception/AuthenticatorMgtServerRuntimeException.java new file mode 100644 index 000000000000..3c8d4070f699 --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/exception/AuthenticatorMgtServerRuntimeException.java @@ -0,0 +1,48 @@ +/* + * 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.application.common.exception; + +/** + * Authenticator configuration management server runtime exception. + */ +public class AuthenticatorMgtServerRuntimeException extends RuntimeException { + + private final String errorCode; + private final String description; + private final Throwable cause; + + public AuthenticatorMgtServerRuntimeException( + String errorCode, String message, String description, Throwable cause) { + + super(message); + this.errorCode = errorCode; + this.description = description; + this.cause = cause; + } + + public String getErrorCode() { + + return this.errorCode; + } + + public String getDescription() { + + return this.description; + } +} diff --git a/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/internal/ApplicationCommonServiceComponent.java b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/internal/ApplicationCommonServiceComponent.java new file mode 100644 index 000000000000..7277f69d2054 --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/internal/ApplicationCommonServiceComponent.java @@ -0,0 +1,67 @@ +package org.wso2.carbon.identity.application.common.internal; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.osgi.framework.BundleContext; +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.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicy; +import org.wso2.carbon.identity.action.management.service.ActionManagementService; +import org.wso2.carbon.identity.application.common.ApplicationAuthenticatorService; + +/** + * OSGI service component for the Application Common Service Component. + */ +@Component( + name = "application.common.service.component", + immediate = true +) +public class ApplicationCommonServiceComponent { + + private static final Log LOG = LogFactory.getLog(ApplicationCommonServiceComponent.class); + + @Activate + protected void activate(ComponentContext context) { + + try { + BundleContext bundleCtx = context.getBundleContext(); + bundleCtx.registerService(ApplicationAuthenticatorService.class.getName(), + ApplicationAuthenticatorService.getInstance(), + null); + LOG.debug("Application Authenticator Service is activated."); + } catch (Throwable e) { + LOG.error("Error while initializing Application Authenticator Service component.", e); + } + } + + @Reference( + name = "action.management.service", + service = ActionManagementService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetActionManagementService" + ) + protected void setActionManagementService(ActionManagementService actionManagementService) { + + if (LOG.isDebugEnabled()) { + LOG.debug( + "Registering a reference for ActionManagementService in the ApplicationCommonServiceComponent."); + } + ApplicationCommonServiceDataHolder.getInstance().setActionManagementService(actionManagementService); + } + + protected void unsetActionManagementService(ActionManagementService actionManagementService) { + + if (LOG.isDebugEnabled()) { + LOG.debug("Unregistering the reference for ActionManagementService in the " + + "ApplicationCommonServiceComponent."); + } + if (ApplicationCommonServiceDataHolder.getInstance().getActionManagementService() + .equals(actionManagementService)) { + ApplicationCommonServiceDataHolder.getInstance().setActionManagementService(null); + } + } +} diff --git a/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/internal/ApplicationCommonServiceDataHolder.java b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/internal/ApplicationCommonServiceDataHolder.java new file mode 100644 index 000000000000..238b81ebcf35 --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/internal/ApplicationCommonServiceDataHolder.java @@ -0,0 +1,65 @@ +package org.wso2.carbon.identity.application.common.internal; + +import org.wso2.carbon.identity.action.management.service.ActionManagementService; +import org.wso2.carbon.identity.application.common.ApplicationAuthenticatorService; + +/** + * The data holder for the Application Common Service Component. + */ +public class ApplicationCommonServiceDataHolder { + + private static final ApplicationCommonServiceDataHolder INSTANCE = new ApplicationCommonServiceDataHolder(); + + private ActionManagementService actionManagementService; + private ApplicationAuthenticatorService applicationAuthenticatorService; + + /** + * Get the instance of the ApplicationCommonServiceDataHolder. + * + * @return ApplicationCommonServiceDataHolder instance. + */ + public static ApplicationCommonServiceDataHolder getInstance() { + + return INSTANCE; + } + + /** + * Get the ActionManagementService. + * + * @return ActionManagementService instance. + */ + public ActionManagementService getActionManagementService() { + + return actionManagementService; + } + + /** + * Set the ActionManagementService. + * + * @param actionManagementService ActionManagementService instance. + */ + public void setActionManagementService(ActionManagementService actionManagementService) { + + this.actionManagementService = actionManagementService; + } + + /** + * Get the ApplicationAuthenticatorService. + * + * @return ApplicationAuthenticatorService instance. + */ + public ApplicationAuthenticatorService getApplicationAuthenticatorService() { + + return applicationAuthenticatorService; + } + + /** + * Set the ApplicationAuthenticatorService. + * + * @param applicationAuthenticatorService ApplicationAuthenticatorService instance. + */ + public void setApplicationAuthenticatorService(ApplicationAuthenticatorService applicationAuthenticatorService) { + + this.applicationAuthenticatorService = applicationAuthenticatorService; + } +} diff --git a/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/model/UserDefinedFederatedAuthenticatorConfig.java b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/model/UserDefinedFederatedAuthenticatorConfig.java index c7fc749a3718..f91d7d1714a6 100644 --- a/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/model/UserDefinedFederatedAuthenticatorConfig.java +++ b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/model/UserDefinedFederatedAuthenticatorConfig.java @@ -20,14 +20,14 @@ import org.wso2.carbon.identity.base.AuthenticatorPropertyConstants.DefinedByType; +import static org.wso2.carbon.identity.base.AuthenticatorPropertyConstants.TAG_CUSTOM; + /** * The user defined federated authenticator configuration model. */ public class UserDefinedFederatedAuthenticatorConfig extends FederatedAuthenticatorConfig { - private static final String TAG_CUSTOM = "CUSTOM"; - - protected UserDefinedAuthenticatorEndpointConfig endpointConfig; + private UserDefinedAuthenticatorEndpointConfig endpointConfig; public UserDefinedFederatedAuthenticatorConfig() { @@ -36,7 +36,7 @@ public UserDefinedFederatedAuthenticatorConfig() { } /** - * Get the endpoint configurations of the User defined federated authenticator config. + * Get the endpoint configurations of the user defined federated authenticator config. * * @return UserDefinedAuthenticatorEndpointConfig */ @@ -46,9 +46,9 @@ public UserDefinedAuthenticatorEndpointConfig getEndpointConfig() { } /** - * Set the endpoint configurations of the User defined federated authenticator config. + * Set the endpoint configurations of the user defined federated authenticator config. * - * @param endpointConfig The endpoint config of the User defined federated authenticator config. + * @param endpointConfig The endpoint config of the user defined federated authenticator config. */ public void setEndpointConfig(UserDefinedAuthenticatorEndpointConfig endpointConfig) { diff --git a/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/model/UserDefinedLocalAuthenticatorConfig.java b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/model/UserDefinedLocalAuthenticatorConfig.java index fab5a37a69bd..75a9a3114eda 100644 --- a/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/model/UserDefinedLocalAuthenticatorConfig.java +++ b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/model/UserDefinedLocalAuthenticatorConfig.java @@ -21,18 +21,20 @@ import org.wso2.carbon.identity.base.AuthenticatorPropertyConstants.AuthenticationType; import org.wso2.carbon.identity.base.AuthenticatorPropertyConstants.DefinedByType; +import static org.wso2.carbon.identity.base.AuthenticatorPropertyConstants.TAG_2FA; +import static org.wso2.carbon.identity.base.AuthenticatorPropertyConstants.TAG_CUSTOM; + /** * The user defined local authenticator configuration model. */ public class UserDefinedLocalAuthenticatorConfig extends LocalAuthenticatorConfig { - private static final String TAG_2FA = "2FA"; - private static final String TAG_CUSTOM = "CUSTOM"; - - protected UserDefinedAuthenticatorEndpointConfig endpointConfig; + private AuthenticationType authenticationType; + private UserDefinedAuthenticatorEndpointConfig endpointConfig; public UserDefinedLocalAuthenticatorConfig(AuthenticationType type) { + authenticationType = type; definedByType = DefinedByType.USER; if (AuthenticationType.VERIFICATION == type) { setTags(new String[]{TAG_CUSTOM, TAG_2FA}); @@ -42,7 +44,7 @@ public UserDefinedLocalAuthenticatorConfig(AuthenticationType type) { } /** - * Get the endpoint configurations of the User defined local authenticator config. + * Get the endpoint configurations of the user defined local authenticator config. * * @return UserDefinedAuthenticatorEndpointConfig */ @@ -52,12 +54,32 @@ public UserDefinedAuthenticatorEndpointConfig getEndpointConfig() { } /** - * Set the endpoint configurations of the User defined local authenticator config. + * Set the endpoint configurations of the user defined local authenticator config. * - * @param endpointConfig The endpoint config of the User defined local authenticator config. + * @param endpointConfig The endpoint config of the user defined local authenticator config. */ public void setEndpointConfig(UserDefinedAuthenticatorEndpointConfig endpointConfig) { this.endpointConfig = endpointConfig; } + + /** + * Get the authentication type of the user defined local authenticator config. + * + * @return AuthenticationType. + */ + public AuthenticationType getAuthenticationType() { + + return authenticationType; + } + + /** + * Set the authentication type of the user defined local authenticator config. + * + * @param authenticationType The authentication type of the user defined local authenticator config. + */ + public void setAuthenticationType(AuthenticationType authenticationType) { + + this.authenticationType = authenticationType; + } } diff --git a/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/util/AuthenticatorMgtExceptionBuilder.java b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/util/AuthenticatorMgtExceptionBuilder.java new file mode 100644 index 000000000000..eb32b47d8d22 --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/util/AuthenticatorMgtExceptionBuilder.java @@ -0,0 +1,148 @@ +/* + * 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.application.common.util; + +import org.apache.commons.lang.ArrayUtils; +import org.wso2.carbon.identity.application.common.exception.AuthenticatorMgtClientException; +import org.wso2.carbon.identity.application.common.exception.AuthenticatorMgtServerException; +import org.wso2.carbon.identity.application.common.exception.AuthenticatorMgtServerRuntimeException; + +/** + * Utility class for building authenticator management exceptions. + */ +public class AuthenticatorMgtExceptionBuilder { + + private AuthenticatorMgtExceptionBuilder() { + + } + + public static AuthenticatorMgtClientException buildClientException(AuthenticatorMgtError error, String... data) { + + String description = error.getDescription(); + if (ArrayUtils.isNotEmpty(data)) { + description = String.format(description, data); + } + + return new AuthenticatorMgtClientException(error.getCode(), error.getMessage(), description); + } + + public static AuthenticatorMgtServerException buildServerException(AuthenticatorMgtError error, String... data) { + + String description = error.getDescription(); + if (ArrayUtils.isNotEmpty(data)) { + description = String.format(description, data); + } + + return new AuthenticatorMgtServerException(error.getCode(), error.getMessage(), description); + } + + public static AuthenticatorMgtServerException buildServerException(AuthenticatorMgtError error, Throwable e, + String... data) { + + String description = error.getDescription(); + if (ArrayUtils.isNotEmpty(data)) { + description = String.format(description, data); + } + + return new AuthenticatorMgtServerException(error.getCode(), error.getMessage(), description, e); + } + + public static AuthenticatorMgtServerRuntimeException buildRuntimeServerException(AuthenticatorMgtError error, + Throwable e, String... data) { + + String description = error.getDescription(); + if (ArrayUtils.isNotEmpty(data)) { + description = String.format(description, data); + } + + return new AuthenticatorMgtServerRuntimeException(error.getCode(), error.getMessage(), description, e); + } + + /** + * Enum class to represent the rule metadata errors. + */ + public enum AuthenticatorMgtError { + + // Client errors. + ERROR_NOT_FOUND_AUTHENTICATOR("60001", "No Authenticator found.", + "No Authenticator found by given authenticator name: %s."), + ERROR_OPERATION_ALLOWED_FOR_SYSTEM_AUTHENTICATOR("60002", "No operations allowed on system " + + "authenticators.", "Do not allow to perform any operation on system defined authenticator: %s."), + ERROR_AUTHENTICATOR_ALREADY_EXIST("60003", "The authenticator already exists.", + "The authenticator already exists for the given name: %s."), + ERROR_INVALID_AUTHENTICATOR_NAME("60004", "Authenticator name is invalid.", + "The provided authenticator name %s is not in the expected format %s."), + ERROR_BLANK_FIELD_VALUE("60004", "Invalid empty or blank value.", + "Value for %s should not be empty or blank."), + + // Server errors. + ERROR_WHILE_ADDING_AUTHENTICATOR("65001", "Error while adding authenticator.", + "Error while persisting authenticator to the system."), + ERROR_WHILE_UPDATING_AUTHENTICATOR("65002", "Error while updating authenticator.", + "Error while updating authenticator in the system."), + ERROR_WHILE_RETRIEVING_AUTHENTICATOR_BY_NAME("65003", "Error while retrieving authenticator.", + "Error while retrieving authenticator in the system."), + ERROR_WHILE_ALL_RETRIEVING_AUTHENTICATOR("65004", "Error while all retrieving authenticator.", + "Error while retrieving all authenticators in the system."), + ERROR_WHILE_DELETING_AUTHENTICATOR("65005", "Error while deleting authenticator.", + "Error while deleting authenticator in the system."), + ERROR_CODE_INVALID_DEFINED_BY_AUTH_PROVIDED("65006", "Error while adding local authenticator.", + "Only system defined authenticators are allowed to add via this method."), + ERROR_CODE_NO_AUTHENTICATOR_FOUND("65007", "No authenticator found.", + "No authenticator found by given authenticator name: %s."), + ERROR_CODE_NO_ACTION_ID_FOUND("65008", "No action id found.", + "No action id found for the authenticator: %s."), + ERROR_CODE_ADDING_ENDPOINT_CONFIG("65009", "Error while adding endpoint configurations.", + "Error while adding endpoint configurations for the user defined local authenticator %s."), + ERROR_CODE_UPDATING_ENDPOINT_CONFIG("65010", "Error while updating endpoint configurations.", + "Error while updating endpoint configurations for the user defined local authenticator %s."), + ERROR_CODE_RETRIEVING_ENDPOINT_CONFIG("65011", "Error while resolving endpoint configurations.", + "Error while retrieving endpoint configurations for the user defined local authenticator %s."), + ERROR_CODE_DELETING_ENDPOINT_CONFIG("65012", "Error while managing endpoint configurations.", + "Error while managing endpoint configurations for the user defined local authenticator %s."), + ERROR_CODE_HAVING_MULTIPLE_PROP("65013", "Multiple properties found", "Only actionId " + + "property is allowed for authenticator: %s."); + + private final String code; + private final String message; + private final String description; + + AuthenticatorMgtError(String code, String message, String description) { + + this.code = code; + this.message = message; + this.description = description; + } + + public String getCode() { + + return code; + } + + public String getMessage() { + + return message; + } + + public String getDescription() { + + return description; + } + } +} diff --git a/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/util/IdentityApplicationConstants.java b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/util/IdentityApplicationConstants.java index 1c748599ab6c..655e4e0674c3 100644 --- a/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/util/IdentityApplicationConstants.java +++ b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/util/IdentityApplicationConstants.java @@ -166,6 +166,9 @@ private ConfigElements() { */ public static class Authenticator { + public static final String ACTION_ID_PROPERTY = "actionId"; + public static final String DISPLAY_NAME = "displayName"; + /** * OpenId authenticator constants. */ diff --git a/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/util/UserDefinedAuthenticatorEndpointConfigManager.java b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/util/UserDefinedAuthenticatorEndpointConfigManager.java new file mode 100644 index 000000000000..50d304aa53b6 --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/util/UserDefinedAuthenticatorEndpointConfigManager.java @@ -0,0 +1,206 @@ +/* + * 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.application.common.util; + +import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; +import org.wso2.carbon.identity.action.management.exception.ActionMgtException; +import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.EndpointConfig; +import org.wso2.carbon.identity.application.common.exception.AuthenticatorMgtClientException; +import org.wso2.carbon.identity.application.common.exception.AuthenticatorMgtException; +import org.wso2.carbon.identity.application.common.exception.AuthenticatorMgtServerException; +import org.wso2.carbon.identity.application.common.internal.ApplicationCommonServiceDataHolder; +import org.wso2.carbon.identity.application.common.model.Property; +import org.wso2.carbon.identity.application.common.model.UserDefinedAuthenticatorEndpointConfig; +import org.wso2.carbon.identity.application.common.model.UserDefinedLocalAuthenticatorConfig; +import org.wso2.carbon.identity.application.common.util.AuthenticatorMgtExceptionBuilder.AuthenticatorMgtError; +import org.wso2.carbon.identity.core.util.IdentityTenantUtil; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import static org.wso2.carbon.identity.application.common.util.AuthenticatorMgtExceptionBuilder.buildServerException; +import static org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants.Authenticator.ACTION_ID_PROPERTY; + +/** + * This class responsible for managing authenticator endpoint configurations for the user defined Local + * authenticators. + */ +public class UserDefinedAuthenticatorEndpointConfigManager { + + /** + * Create a new action for given endpoint configurations of the user defined authenticator. + * + * @param config The Local application authenticator configuration. + * @param tenantId The id of Tenant domain. + * @throws AuthenticatorMgtException If an error occurs while adding the action. + */ + public void addEndpointConfigurations(UserDefinedLocalAuthenticatorConfig config, int tenantId) + throws AuthenticatorMgtException { + + try { + Action action = ApplicationCommonServiceDataHolder.getInstance().getActionManagementService() + .addAction(Action.ActionTypes.AUTHENTICATION.getPathParam(), + buildActionToCreate(config.getName(), config.getEndpointConfig().getEndpointConfig()), + IdentityTenantUtil.getTenantDomain(tenantId)); + Property endpointProperty = new Property(); + endpointProperty.setName(ACTION_ID_PROPERTY); + endpointProperty.setValue(action.getId()); + config.setProperties(new Property[]{endpointProperty}); + } catch (ActionMgtException e) { + throw handleActionMgtException(AuthenticatorMgtError.ERROR_CODE_ADDING_ENDPOINT_CONFIG, + e, config.getName()); + } + } + + /** + * Updated associated action for given updated endpoint configurations of the user defined authenticator. + * + * @param newConfig The Local application authenticator configuration to be updated. + * @param oldConfig The current Local application authenticator configuration. + * @param tenantId The id of Tenant domain. + * @throws AuthenticatorMgtException If an error occurs while updating associated action. + */ + public void updateEndpointConfigurations(UserDefinedLocalAuthenticatorConfig newConfig, + UserDefinedLocalAuthenticatorConfig oldConfig, int tenantId) + throws AuthenticatorMgtException { + + String actionId = getActionIdFromProperty(oldConfig.getProperties(), oldConfig.getName()); + try { + ApplicationCommonServiceDataHolder.getInstance().getActionManagementService() + .updateAction(Action.ActionTypes.AUTHENTICATION.getPathParam(), + actionId, + buildActionToUpdate(newConfig.getEndpointConfig().getEndpointConfig()), + IdentityTenantUtil.getTenantDomain(tenantId)); + newConfig.setProperties(oldConfig.getProperties()); + } catch (ActionMgtException e) { + throw handleActionMgtException(AuthenticatorMgtError.ERROR_CODE_UPDATING_ENDPOINT_CONFIG, e, + actionId, oldConfig.getName()); + } + } + + /** + * Retrieve associated action of the user defined authenticator. + * + * @param config The Local application authenticator configuration. + * @param tenantId The id of Tenant domain. + * @return Local authenticator with endpoint configurations resolved. + * @throws AuthenticatorMgtException If an error occurs retrieving updating associated action. + */ + public UserDefinedLocalAuthenticatorConfig resolveEndpointConfigurations(UserDefinedLocalAuthenticatorConfig config, + int tenantId) throws AuthenticatorMgtException { + + if (config == null) { + return null; + } + String actionId = getActionIdFromProperty(config.getProperties(), config.getName()); + try { + Action action = ApplicationCommonServiceDataHolder.getInstance().getActionManagementService() + .getActionByActionId(Action.ActionTypes.AUTHENTICATION.getPathParam(), + actionId, + IdentityTenantUtil.getTenantDomain(tenantId)); + + config.setEndpointConfig(buildUserDefinedAuthenticatorEndpointConfig(action.getEndpoint())); + return config; + } catch (ActionMgtException e) { + throw handleActionMgtException(AuthenticatorMgtError.ERROR_CODE_RETRIEVING_ENDPOINT_CONFIG, e, + actionId, config.getName()); + } + } + + private UserDefinedAuthenticatorEndpointConfig buildUserDefinedAuthenticatorEndpointConfig( + EndpointConfig endpointConfig) { + + UserDefinedAuthenticatorEndpointConfig.UserDefinedAuthenticatorEndpointConfigBuilder endpointConfigBuilder = + new UserDefinedAuthenticatorEndpointConfig.UserDefinedAuthenticatorEndpointConfigBuilder(); + endpointConfigBuilder.uri(endpointConfig.getUri()); + endpointConfigBuilder.authenticationType(endpointConfig.getAuthentication().getType().getName()); + Map propMap = new HashMap<>(); + endpointConfig.getAuthentication().getProperties() + .forEach(prop -> propMap.put(prop.getName(), prop.getValue())); + endpointConfigBuilder.authenticationProperties(propMap); + return endpointConfigBuilder.build(); + } + + /** + * Delete associated action of the user defined authenticator. + * + * @param config The Local application authenticator configuration. + * @param tenantId The id of Tenant domain. + * @throws AuthenticatorMgtException If an error occurs while deleting associated action. + */ + public void deleteEndpointConfigurations(UserDefinedLocalAuthenticatorConfig config, int tenantId) throws + AuthenticatorMgtException { + + String actionId = getActionIdFromProperty(config.getProperties(), config.getName()); + try { + ApplicationCommonServiceDataHolder.getInstance().getActionManagementService() + .deleteAction(Action.ActionTypes.AUTHENTICATION.getPathParam(), + actionId, + IdentityTenantUtil.getTenantDomain(tenantId)); + } catch (ActionMgtException e) { + throw handleActionMgtException(AuthenticatorMgtError.ERROR_CODE_DELETING_ENDPOINT_CONFIG, e, + actionId, config.getName()); + } + } + + private Action buildActionToCreate(String authenticatorName, EndpointConfig endpointConfig) { + + Action.ActionRequestBuilder actionRequestBuilder = new Action.ActionRequestBuilder(); + actionRequestBuilder.name(authenticatorName); + actionRequestBuilder.description(String.format("This is the action associated to the user defined Local" + + "authenticator %s.", authenticatorName)); + actionRequestBuilder.endpoint(endpointConfig); + + return actionRequestBuilder.build(); + } + + private Action buildActionToUpdate(EndpointConfig endpointConfig) { + + Action.ActionRequestBuilder actionRequestBuilder = new Action.ActionRequestBuilder(); + actionRequestBuilder.endpoint(endpointConfig); + + return actionRequestBuilder.build(); + } + + private String getActionIdFromProperty(Property[] properties, String authenticatorName) + throws AuthenticatorMgtServerException { + + return Arrays.stream(properties) + .filter(property -> ACTION_ID_PROPERTY.equals(property.getName())) + .map(Property::getValue) + .findFirst() + .orElseThrow(() -> buildServerException(AuthenticatorMgtError.ERROR_CODE_NO_ACTION_ID_FOUND, + authenticatorName)); + } + + private static AuthenticatorMgtException handleActionMgtException(AuthenticatorMgtError authenticatorMgtError, + Throwable actionException, String... data) + throws AuthenticatorMgtException { + + if (actionException instanceof ActionMgtClientException) { + ActionMgtClientException error = (ActionMgtClientException) actionException; + throw new AuthenticatorMgtClientException( + authenticatorMgtError.getCode(), error.getMessage(), error.getDescription()); + } + + throw buildServerException(authenticatorMgtError, data); + } +} diff --git a/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/util/UserDefinedLocalAuthenticatorValidator.java b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/util/UserDefinedLocalAuthenticatorValidator.java new file mode 100644 index 000000000000..836607835390 --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.identity.application.common/src/main/java/org/wso2/carbon/identity/application/common/util/UserDefinedLocalAuthenticatorValidator.java @@ -0,0 +1,65 @@ +/* + * 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.application.common.util; + +import org.apache.commons.lang.StringUtils; +import org.wso2.carbon.identity.application.common.exception.AuthenticatorMgtClientException; +import org.wso2.carbon.identity.application.common.util.AuthenticatorMgtExceptionBuilder.AuthenticatorMgtError; + +import java.util.regex.Pattern; + +import static org.wso2.carbon.identity.application.common.util.AuthenticatorMgtExceptionBuilder.buildClientException; + +/** + * User Defined Local Authenticator Validator class. + */ +public class UserDefinedLocalAuthenticatorValidator { + + private static final String AUTHENTICATOR_NAME_REGEX = "^[a-zA-Z0-9][a-zA-Z0-9-_]*$"; + private final Pattern authenticatorNameRegexPattern = Pattern.compile(AUTHENTICATOR_NAME_REGEX); + + /** + * Validate whether required fields exist. + * + * @param fieldName Field name. + * @param fieldValue Field value. + * @throws AuthenticatorMgtClientException if the provided field is empty. + */ + public void validateForBlank(String fieldName, String fieldValue) throws AuthenticatorMgtClientException { + + if (StringUtils.isBlank(fieldValue)) { + throw buildClientException(AuthenticatorMgtError.ERROR_BLANK_FIELD_VALUE, fieldName); + } + } + + /** + * Validate the user defined local authenticator name. + * + * @param name The authenticator name. + * @throws AuthenticatorMgtClientException if the authenticator name is not valid. + */ + public void validateAuthenticatorName(String name) throws AuthenticatorMgtClientException { + + boolean isValidName = authenticatorNameRegexPattern.matcher(name).matches(); + if (!isValidName) { + throw buildClientException(AuthenticatorMgtError.ERROR_INVALID_AUTHENTICATOR_NAME, + name, AUTHENTICATOR_NAME_REGEX); + } + } +} diff --git a/components/application-mgt/org.wso2.carbon.identity.application.common/src/test/java/org/wso2/carbon/identity/application/common/model/test/ApplicationAuthenticatorServiceTest.java b/components/application-mgt/org.wso2.carbon.identity.application.common/src/test/java/org/wso2/carbon/identity/application/common/model/test/ApplicationAuthenticatorServiceTest.java new file mode 100644 index 000000000000..f75199d6e85e --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.identity.application.common/src/test/java/org/wso2/carbon/identity/application/common/model/test/ApplicationAuthenticatorServiceTest.java @@ -0,0 +1,384 @@ +/* + * 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.application.common.model.test; + +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; +import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; +import org.wso2.carbon.identity.action.management.exception.ActionMgtServerException; +import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.EndpointConfig; +import org.wso2.carbon.identity.action.management.service.ActionManagementService; +import org.wso2.carbon.identity.application.common.ApplicationAuthenticatorService; +import org.wso2.carbon.identity.application.common.exception.AuthenticatorMgtClientException; +import org.wso2.carbon.identity.application.common.exception.AuthenticatorMgtException; +import org.wso2.carbon.identity.application.common.exception.AuthenticatorMgtServerException; +import org.wso2.carbon.identity.application.common.exception.AuthenticatorMgtServerRuntimeException; +import org.wso2.carbon.identity.application.common.internal.ApplicationCommonServiceDataHolder; +import org.wso2.carbon.identity.application.common.model.LocalAuthenticatorConfig; +import org.wso2.carbon.identity.application.common.model.UserDefinedLocalAuthenticatorConfig; +import org.wso2.carbon.identity.application.common.model.test.util.ActionMgtTestUtil; +import org.wso2.carbon.identity.base.AuthenticatorPropertyConstants.AuthenticationType; +import org.wso2.carbon.identity.base.AuthenticatorPropertyConstants.DefinedByType; +import org.wso2.carbon.identity.common.testng.WithAxisConfiguration; +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.core.internal.IdentityCoreServiceDataHolder; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.wso2.carbon.identity.application.common.model.test.util.ActionMgtTestUtil.mockActionService; +import static org.wso2.carbon.identity.application.common.model.test.util.UserDefinedLocalAuthenticatorDataUtil.createSystemDefinedAuthenticatorConfig; +import static org.wso2.carbon.identity.application.common.model.test.util.UserDefinedLocalAuthenticatorDataUtil.createUserDefinedAuthenticatorConfig; +import static org.wso2.carbon.identity.application.common.util.AuthenticatorMgtExceptionBuilder.AuthenticatorMgtError.ERROR_CODE_INVALID_DEFINED_BY_AUTH_PROVIDED; + +/** + * This class is a test suite for the ApplicationAuthenticatorServiceTest class. + * It contains unit tests to verify the functionality of the methods + * in the ApplicationAuthenticatorServiceTest class. + */ +@WithAxisConfiguration +@WithCarbonHome +@WithH2Database(files = {"dbscripts/h2.sql"}) +@WithRegistry +@WithRealmService(injectToSingletons = {IdentityCoreServiceDataHolder.class}) +public class ApplicationAuthenticatorServiceTest { + + private String tenantDomain; + + private UserDefinedLocalAuthenticatorConfig authenticatorConfig1; + private UserDefinedLocalAuthenticatorConfig authenticatorConfig2; + private UserDefinedLocalAuthenticatorConfig authenticatorConfigForException; + private UserDefinedLocalAuthenticatorConfig nonExistAuthenticatorConfig; + private LocalAuthenticatorConfig systemAuthenticatorConfig; + + private ActionManagementService actionManagementService; + private static Action action; + private static EndpointConfig endpointConfig; + private static EndpointConfig endpointConfigToBeUpdated; + + private static final String AUTHENTICATOR1_NAME = "auth1"; + private static final String AUTHENTICATOR2_NAME = "auth2"; + private static final String AUTHENTICATOR_CONFIG_FOR_EXCEPTION_NAME = "exception_auth"; + private static final String NON_EXIST_AUTHENTICATOR_NAME = "non_exist_auth"; + private static final String SYSTEM_AUTHENTICATOR_NAME = "system_auth"; + + @BeforeClass + public void setUpClass() throws Exception { + + tenantDomain = "carbon.super"; + systemAuthenticatorConfig = createSystemDefinedAuthenticatorConfig(SYSTEM_AUTHENTICATOR_NAME); + authenticatorConfig1 = createUserDefinedAuthenticatorConfig(AUTHENTICATOR1_NAME, + AuthenticationType.IDENTIFICATION); + authenticatorConfig2 = createUserDefinedAuthenticatorConfig(AUTHENTICATOR2_NAME, + AuthenticationType.VERIFICATION); + nonExistAuthenticatorConfig = createUserDefinedAuthenticatorConfig(NON_EXIST_AUTHENTICATOR_NAME, + AuthenticationType.IDENTIFICATION); + authenticatorConfigForException = createUserDefinedAuthenticatorConfig(AUTHENTICATOR_CONFIG_FOR_EXCEPTION_NAME, + AuthenticationType.IDENTIFICATION); + + endpointConfig = ActionMgtTestUtil.createEndpointConfig("http://localhost", "admin", "admin"); + endpointConfigToBeUpdated = ActionMgtTestUtil.createEndpointConfig( + "http://localhost1", "admin1", "admin1"); + action = ActionMgtTestUtil.createAction(endpointConfig); + actionManagementService = mockActionService(action); + + ApplicationCommonServiceDataHolder.getInstance().setApplicationAuthenticatorService( + ApplicationAuthenticatorService.getInstance()); + ApplicationCommonServiceDataHolder.getInstance().setActionManagementService(actionManagementService); + } + + @AfterClass + public void tearDownClass() throws AuthenticatorMgtException { + + ApplicationCommonServiceDataHolder.getInstance().getApplicationAuthenticatorService() + .deleteUserDefinedLocalAuthenticator(AUTHENTICATOR1_NAME, tenantDomain); + ApplicationCommonServiceDataHolder.getInstance().getApplicationAuthenticatorService() + .deleteUserDefinedLocalAuthenticator(AUTHENTICATOR2_NAME, tenantDomain); + } + + @AfterMethod + public void tearDown() { + + ApplicationCommonServiceDataHolder.getInstance().setActionManagementService(actionManagementService); + } + + @DataProvider(name = "authenticatorConfigForCreation") + public Object[][] authenticatorConfigForCreation() { + + return new Object[][]{ + {authenticatorConfig1}, + {authenticatorConfig2} + }; + } + + @Test(priority = 1, dataProvider = "authenticatorConfigForCreation") + public void testCreateUserDefinedLocalAuthenticator(UserDefinedLocalAuthenticatorConfig config) + throws AuthenticatorMgtException { + + UserDefinedLocalAuthenticatorConfig createdAuthenticator = ApplicationCommonServiceDataHolder.getInstance() + .getApplicationAuthenticatorService().addUserDefinedLocalAuthenticator(config, tenantDomain); + + Assert.assertEquals(createdAuthenticator.getName(), config.getName()); + Assert.assertEquals(createdAuthenticator.getDisplayName(), config.getDisplayName()); + Assert.assertEquals(createdAuthenticator.isEnabled(), config.isEnabled()); + Assert.assertEquals(createdAuthenticator.getDefinedByType(), DefinedByType.USER); + if (AuthenticationType.VERIFICATION == config.getAuthenticationType()) { + Assert.assertTrue(Arrays.asList(createdAuthenticator.getTags()).contains("2FA"), + "Tag list does not contain 2FA tag for verification authentication type."); + } + Assert.assertEquals(createdAuthenticator.getProperties().length, config.getProperties().length); + } + + @Test(priority = 2, dataProvider = "authenticatorConfigForCreation", expectedExceptions = + AuthenticatorMgtException.class, expectedExceptionsMessageRegExp = "The authenticator already exists.") + public void testCreateUserDefinedLocalAuthenticatorWithExistingAuthenticator( + UserDefinedLocalAuthenticatorConfig config) throws AuthenticatorMgtException { + + ApplicationCommonServiceDataHolder.getInstance().getApplicationAuthenticatorService() + .addUserDefinedLocalAuthenticator(config, tenantDomain); + } + + @Test(priority = 3, expectedExceptions = AuthenticatorMgtException.class, + expectedExceptionsMessageRegExp = "Invalid empty or blank value.") + public void testCreateUserDefinedLocalAuthenticatorWithBlankDisplayName() throws AuthenticatorMgtException { + + UserDefinedLocalAuthenticatorConfig config = createUserDefinedAuthenticatorConfig("withBlankDisplayName", + AuthenticationType.IDENTIFICATION); + config.setDisplayName(""); + ApplicationCommonServiceDataHolder.getInstance().getApplicationAuthenticatorService() + .addUserDefinedLocalAuthenticator(config, tenantDomain); + } + + @Test(priority = 4, expectedExceptions = AuthenticatorMgtException.class, + expectedExceptionsMessageRegExp = "Authenticator name is invalid.") + public void testCreateUserDefinedLocalAuthenticatorWithInvalidName() throws AuthenticatorMgtException { + + ApplicationCommonServiceDataHolder.getInstance().getApplicationAuthenticatorService() + .addUserDefinedLocalAuthenticator(createUserDefinedAuthenticatorConfig("323#2@dwd", + AuthenticationType.IDENTIFICATION), tenantDomain); + } + + @Test(priority = 5) + public void testAddIdPActionServerException() throws Exception { + + ActionManagementService actionManagementServiceForException = mock(ActionManagementService.class); + when(actionManagementServiceForException.addAction(anyString(), any(), any())) + .thenThrow(ActionMgtServerException.class); + ApplicationCommonServiceDataHolder.getInstance().setActionManagementService( + actionManagementServiceForException); + + assertThrows(AuthenticatorMgtServerException.class, () -> + ApplicationCommonServiceDataHolder.getInstance().getApplicationAuthenticatorService() + .addUserDefinedLocalAuthenticator(authenticatorConfigForException, tenantDomain)); + } + + @Test(priority = 6) + public void testAddIdPActionClientException() throws Exception { + + ActionManagementService actionManagementServiceForException = mock(ActionManagementService.class); + when(actionManagementServiceForException.addAction(anyString(), any(), any())) + .thenThrow(ActionMgtClientException.class); + ApplicationCommonServiceDataHolder.getInstance().setActionManagementService( + actionManagementServiceForException); + + assertThrows(AuthenticatorMgtClientException.class, () -> + ApplicationCommonServiceDataHolder.getInstance().getApplicationAuthenticatorService() + .addUserDefinedLocalAuthenticator(authenticatorConfigForException, tenantDomain)); + } + + @Test(priority = 7) + public void testAddLocalAuthenticator() { + + ApplicationCommonServiceDataHolder.getInstance().getApplicationAuthenticatorService() + .addLocalAuthenticator(systemAuthenticatorConfig); + Assert.assertNotNull(ApplicationCommonServiceDataHolder.getInstance().getApplicationAuthenticatorService() + .getLocalAuthenticatorByName(SYSTEM_AUTHENTICATOR_NAME)); + } + + @Test(priority = 8) + public void testAddLocalAuthenticatorWithRuntimeError() { + + AuthenticatorMgtServerRuntimeException exception = assertThrows(AuthenticatorMgtServerRuntimeException.class, + () -> ApplicationCommonServiceDataHolder.getInstance().getApplicationAuthenticatorService() + .addLocalAuthenticator(authenticatorConfig1)); + Assert.assertEquals(exception.getErrorCode(), ERROR_CODE_INVALID_DEFINED_BY_AUTH_PROVIDED.getCode()); + + } + + @Test(priority = 9) + public void testGetAllUserDefinedLocalAuthenticators() throws Exception { + + List authenticatorsList = ApplicationCommonServiceDataHolder.getInstance() + .getApplicationAuthenticatorService().getAllUserDefinedLocalAuthenticators(tenantDomain); + Assert.assertEquals(authenticatorsList.size(), 2); + } + + @DataProvider(name = "authenticatorConfigToModify") + public Object[][] authenticatorConfigToModify() { + + authenticatorConfig1.setDisplayName("Updated Display Name"); + + authenticatorConfig2.setEnabled(false); + authenticatorConfig2.setDefinedByType(DefinedByType.SYSTEM); + + return new Object[][]{ + {authenticatorConfig1}, + {authenticatorConfig2} + }; + } + + @Test(priority = 10) + public void testGetUserDefinedAuthenticator() throws Exception { + + UserDefinedLocalAuthenticatorConfig authenticator = ApplicationCommonServiceDataHolder.getInstance() + .getApplicationAuthenticatorService().getUserDefinedLocalAuthenticator( + authenticatorConfig1.getName(), tenantDomain); + Assert.assertNotNull(authenticator); + } + + @Test(priority = 11) + public void testGetUserDefinedAuthenticatorWithActionException() throws Exception { + + ApplicationCommonServiceDataHolder.getInstance().getApplicationAuthenticatorService() + .addUserDefinedLocalAuthenticator(authenticatorConfigForException, tenantDomain); + ActionManagementService actionManagementServiceForException = mock(ActionManagementService.class); + when(actionManagementServiceForException.addAction(anyString(), any(), any())).thenReturn(action); + when(actionManagementServiceForException.getActionByActionId(anyString(), any(), any())) + .thenThrow(ActionMgtServerException.class); + ApplicationCommonServiceDataHolder.getInstance().setActionManagementService( + actionManagementServiceForException); + } + + @Test(priority = 12, dataProvider = "authenticatorConfigToModify") + public void testUpdateUserDefinedLocalAuthenticator(UserDefinedLocalAuthenticatorConfig config) + throws AuthenticatorMgtException { + + UserDefinedLocalAuthenticatorConfig updatedAuthenticator = ApplicationCommonServiceDataHolder.getInstance() + .getApplicationAuthenticatorService().updateUserDefinedLocalAuthenticator(config, tenantDomain); + + Assert.assertEquals(updatedAuthenticator.getName(), config.getName()); + Assert.assertEquals(updatedAuthenticator.getDisplayName(), config.getDisplayName()); + Assert.assertEquals(updatedAuthenticator.isEnabled(), config.isEnabled()); + Assert.assertEquals(updatedAuthenticator.getDefinedByType(), DefinedByType.USER); + Assert.assertEquals(updatedAuthenticator.getProperties().length, config.getProperties().length); + } + + @Test(priority = 13, expectedExceptions = AuthenticatorMgtException.class, + expectedExceptionsMessageRegExp = "No Authenticator found.") + public void testUpdateUserDefinedLocalAuthenticatorWithNonExistingAuthenticator() throws AuthenticatorMgtException { + + ApplicationCommonServiceDataHolder.getInstance().getApplicationAuthenticatorService() + .updateUserDefinedLocalAuthenticator(nonExistAuthenticatorConfig, tenantDomain); + } + + @Test(priority = 14) + public void testUpdateIdPActionException() throws Exception { + + ActionManagementService actionManagementServiceForException = mock(ActionManagementService.class); + when(actionManagementServiceForException.updateAction(any(), any(), any(), any())) + .thenThrow(ActionMgtServerException.class); + when(actionManagementServiceForException.getActionByActionId(anyString(), any(), any())).thenReturn(action); + ApplicationCommonServiceDataHolder.getInstance().setActionManagementService( + actionManagementServiceForException); + + assertThrows(AuthenticatorMgtServerException.class, () -> ApplicationCommonServiceDataHolder.getInstance() + .getApplicationAuthenticatorService().updateUserDefinedLocalAuthenticator( + authenticatorConfigForException, tenantDomain)); + } + + @DataProvider(name = "authenticatorConfigToRetrieve") + public Object[][] authenticatorConfigToRetrieve() { + + return new Object[][]{ + {authenticatorConfig1, authenticatorConfig1, AuthenticationType.IDENTIFICATION.toString()}, + {authenticatorConfig2, authenticatorConfig2, AuthenticationType.VERIFICATION.toString()}, + {nonExistAuthenticatorConfig, null, null} + }; + } + + @Test(priority = 15, dataProvider = "authenticatorConfigToRetrieve") + public void testGetUserDefinedLocalAuthenticator(UserDefinedLocalAuthenticatorConfig configToBeRetrieved, + UserDefinedLocalAuthenticatorConfig expectedConfig, String type) throws AuthenticatorMgtException { + + UserDefinedLocalAuthenticatorConfig retrievedConfig = ApplicationCommonServiceDataHolder.getInstance() + .getApplicationAuthenticatorService().getUserDefinedLocalAuthenticator( + configToBeRetrieved.getName(), tenantDomain); + Assert.assertEquals(retrievedConfig, expectedConfig); + if (expectedConfig != null) { + Assert.assertEquals(retrievedConfig.getDisplayName(), expectedConfig.getDisplayName()); + Assert.assertEquals(retrievedConfig.isEnabled(), expectedConfig.isEnabled()); + Assert.assertEquals(retrievedConfig.getDefinedByType(), DefinedByType.USER); + if (AuthenticationType.VERIFICATION.toString().equals(type)) { + Assert.assertTrue(Arrays.asList(retrievedConfig.getTags()).contains("2FA"), + "Tag list does not contain 2FA tag for verification authentication type."); + } + Assert.assertEquals(retrievedConfig.getProperties().length, expectedConfig.getProperties().length); + } + } + + @Test(priority = 16) + public void testDeleteUserDefinedLocalAuthenticatorWithActionException() throws Exception { + + ActionManagementService actionManagementServiceForException = mock(ActionManagementService.class); + doThrow(ActionMgtServerException.class) + .when(actionManagementServiceForException).deleteAction(any(), any(), any()); + when(actionManagementServiceForException.getActionByActionId(anyString(), any(), any())).thenReturn(action); + ApplicationCommonServiceDataHolder.getInstance() + .setActionManagementService(actionManagementServiceForException); + + assertThrows(AuthenticatorMgtServerException.class, () -> ApplicationCommonServiceDataHolder.getInstance(). + getApplicationAuthenticatorService().deleteUserDefinedLocalAuthenticator( + authenticatorConfigForException.getName(), tenantDomain)); + Assert.assertNotNull(ApplicationCommonServiceDataHolder.getInstance(). + getApplicationAuthenticatorService().getUserDefinedLocalAuthenticator( + authenticatorConfigForException.getName(), tenantDomain)); + } + + @Test(priority = 17, dataProvider = "authenticatorConfigToModify") + public void testDeleteUserDefinedLocalAuthenticator(UserDefinedLocalAuthenticatorConfig config) + throws AuthenticatorMgtException { + + ApplicationCommonServiceDataHolder.getInstance().getApplicationAuthenticatorService() + .deleteUserDefinedLocalAuthenticator(config.getName(), tenantDomain); + Assert.assertNull(ApplicationCommonServiceDataHolder.getInstance().getApplicationAuthenticatorService() + .getLocalAuthenticatorByName(config.getName())); + } + + @Test(priority = 18) + public void testDeleteUserDefinedLocalAuthenticatorWithNonExistingAuthenticator() throws AuthenticatorMgtException { + + // Assert that no exception is thrown when trying to delete a non-existing authenticator. + ApplicationCommonServiceDataHolder.getInstance().getApplicationAuthenticatorService() + .deleteUserDefinedLocalAuthenticator(nonExistAuthenticatorConfig.getName(), tenantDomain); + } +} diff --git a/components/application-mgt/org.wso2.carbon.identity.application.common/src/test/java/org/wso2/carbon/identity/application/common/model/test/UserDefinedAuthenticatorTest.java b/components/application-mgt/org.wso2.carbon.identity.application.common/src/test/java/org/wso2/carbon/identity/application/common/model/test/UserDefinedAuthenticatorTest.java index 61c115d3dc94..97fcc362417a 100644 --- a/components/application-mgt/org.wso2.carbon.identity.application.common/src/test/java/org/wso2/carbon/identity/application/common/model/test/UserDefinedAuthenticatorTest.java +++ b/components/application-mgt/org.wso2.carbon.identity.application.common/src/test/java/org/wso2/carbon/identity/application/common/model/test/UserDefinedAuthenticatorTest.java @@ -29,6 +29,8 @@ import java.util.HashMap; import static org.testng.Assert.assertEquals; +import static org.wso2.carbon.identity.base.AuthenticatorPropertyConstants.TAG_2FA; +import static org.wso2.carbon.identity.base.AuthenticatorPropertyConstants.TAG_CUSTOM; public class UserDefinedAuthenticatorTest { @@ -39,7 +41,7 @@ public void createUserDefinedLocalVerificationAuthenticator() { UserDefinedLocalAuthenticatorConfig config = new UserDefinedLocalAuthenticatorConfig(AuthenticatorPropertyConstants.AuthenticationType.VERIFICATION); - assertEquals(config.getTags(), new String[]{"CUSTOM", "2FA"}); + assertEquals(config.getTags(), new String[]{TAG_CUSTOM, TAG_2FA}); assertEquals(config.getDefinedByType(), AuthenticatorPropertyConstants.DefinedByType.USER); } @@ -49,7 +51,7 @@ public void createUserDefinedLocalIdentificationAuthenticator() { UserDefinedLocalAuthenticatorConfig config = new UserDefinedLocalAuthenticatorConfig( AuthenticatorPropertyConstants.AuthenticationType.IDENTIFICATION); - assertEquals(config.getTags(), new String[]{"CUSTOM"}); + assertEquals(config.getTags(), new String[]{TAG_CUSTOM}); assertEquals(config.getDefinedByType(), AuthenticatorPropertyConstants.DefinedByType.USER); } @@ -57,7 +59,7 @@ public void createUserDefinedLocalIdentificationAuthenticator() { public void createUserDefinedFederatedAuthenticator() { UserDefinedFederatedAuthenticatorConfig config = new UserDefinedFederatedAuthenticatorConfig(); - assertEquals(config.getTags(), new String[]{"CUSTOM"}); + assertEquals(config.getTags(), new String[]{TAG_CUSTOM}); assertEquals(config.getDefinedByType(), AuthenticatorPropertyConstants.DefinedByType.USER); } diff --git a/components/application-mgt/org.wso2.carbon.identity.application.common/src/test/java/org/wso2/carbon/identity/application/common/model/test/dao/AuthenticatorManagementDAOImplTest.java b/components/application-mgt/org.wso2.carbon.identity.application.common/src/test/java/org/wso2/carbon/identity/application/common/model/test/dao/AuthenticatorManagementDAOImplTest.java new file mode 100644 index 000000000000..ef4b5ba57c49 --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.identity.application.common/src/test/java/org/wso2/carbon/identity/application/common/model/test/dao/AuthenticatorManagementDAOImplTest.java @@ -0,0 +1,176 @@ +/* + * 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.application.common.model.test.dao; + +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; +import org.wso2.carbon.identity.application.common.dao.impl.AuthenticatorManagementDAOImpl; +import org.wso2.carbon.identity.application.common.exception.AuthenticatorMgtException; +import org.wso2.carbon.identity.application.common.model.Property; +import org.wso2.carbon.identity.application.common.model.UserDefinedLocalAuthenticatorConfig; +import org.wso2.carbon.identity.application.common.model.test.util.UserDefinedLocalAuthenticatorDataUtil; +import org.wso2.carbon.identity.base.AuthenticatorPropertyConstants; +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.core.internal.IdentityCoreServiceDataHolder; + +import static org.junit.Assert.assertThrows; +import static org.wso2.carbon.identity.application.common.util.AuthenticatorMgtExceptionBuilder.AuthenticatorMgtError.ERROR_WHILE_ADDING_AUTHENTICATOR; +import static org.wso2.carbon.identity.application.common.util.AuthenticatorMgtExceptionBuilder.AuthenticatorMgtError.ERROR_WHILE_UPDATING_AUTHENTICATOR; + +@WithH2Database(files = {"dbscripts/h2.sql"}) +@WithCarbonHome +@WithRealmService(injectToSingletons = {IdentityCoreServiceDataHolder.class}) +public class AuthenticatorManagementDAOImplTest { + + private final int tenantId = -1234; + + private UserDefinedLocalAuthenticatorConfig authenticatorConfig1; + private UserDefinedLocalAuthenticatorConfig authenticatorConfig2; + private UserDefinedLocalAuthenticatorConfig authenticatorConfigForException; + private UserDefinedLocalAuthenticatorConfig authenticatorForUpdate; + private UserDefinedLocalAuthenticatorConfig authenticatorForUpdateForException; + + private static final String AUTHENTICATOR1_NAME = "auth1"; + private static final String AUTHENTICATOR2_NAME = "auth2"; + private static final String AUTHENTICATOR_CONFIG_FOR_EXCEPTION_NAME = "exception_auth"; + private static final String NON_EXIST_AUTHENTICATOR_NAME = "non_exist_auth"; + + private final AuthenticatorManagementDAOImpl authenticatorManagementDAO = new AuthenticatorManagementDAOImpl(); + + @BeforeClass + public void setUpClass() { + + authenticatorConfig1 = UserDefinedLocalAuthenticatorDataUtil.createUserDefinedAuthenticatorConfig + (AUTHENTICATOR1_NAME, AuthenticatorPropertyConstants.AuthenticationType.IDENTIFICATION); + authenticatorConfig2 = UserDefinedLocalAuthenticatorDataUtil.createUserDefinedAuthenticatorConfig( + AUTHENTICATOR2_NAME, AuthenticatorPropertyConstants.AuthenticationType.VERIFICATION); + authenticatorForUpdate = UserDefinedLocalAuthenticatorDataUtil.updateUserDefinedAuthenticatorConfig( + authenticatorConfig1); + authenticatorForUpdateForException = UserDefinedLocalAuthenticatorDataUtil + .updateUserDefinedAuthenticatorConfigForSQLException(authenticatorConfig1); + authenticatorConfigForException = UserDefinedLocalAuthenticatorDataUtil + .createUserDefinedAuthenticatorConfigForSQLException( + AUTHENTICATOR_CONFIG_FOR_EXCEPTION_NAME, + AuthenticatorPropertyConstants.AuthenticationType.IDENTIFICATION); + + } + + @DataProvider(name = "authenticatorConfig") + public Object[][] authenticatorConfig() { + + return new Object[][]{ + {authenticatorConfig1}, + {authenticatorConfig2} + }; + } + + @Test(dataProvider = "authenticatorConfig", priority = 1) + public void testAddUserDefinedLocalAuthenticator(UserDefinedLocalAuthenticatorConfig config) + throws AuthenticatorMgtException { + + UserDefinedLocalAuthenticatorConfig createdAuthenticator = authenticatorManagementDAO + .addUserDefinedLocalAuthenticator(config, tenantId); + Assert.assertNotNull(createdAuthenticator); + Assert.assertEquals(createdAuthenticator.getName(), config.getName()); + Assert.assertEquals(createdAuthenticator.getDisplayName(), config.getDisplayName()); + Assert.assertEquals(createdAuthenticator.isEnabled(), config.isEnabled()); + Assert.assertEquals(createdAuthenticator.getDefinedByType(), config.getDefinedByType()); + } + + @Test(priority = 2) + public void testAddUserDefinedLocalAuthenticatorWithSQLException() { + + AuthenticatorMgtException exception = assertThrows(AuthenticatorMgtException.class, () -> + authenticatorManagementDAO.addUserDefinedLocalAuthenticator(authenticatorConfigForException, tenantId)); + Assert.assertEquals(exception.getErrorCode(), ERROR_WHILE_ADDING_AUTHENTICATOR.getCode()); + } + + @Test(priority = 3) + public void testAddUserDefinedLocalAuthenticatorWithOutActionProperty() { + + authenticatorConfigForException.setProperties(new Property[0]); + AuthenticatorMgtException exception = assertThrows(AuthenticatorMgtException.class, () -> + authenticatorManagementDAO.addUserDefinedLocalAuthenticator(authenticatorConfigForException, tenantId)); + Assert.assertEquals(exception.getErrorCode(), ERROR_WHILE_ADDING_AUTHENTICATOR.getCode()); + } + + @Test(priority = 4) + public void testUpdateUserDefinedLocalAuthenticator() throws AuthenticatorMgtException { + + UserDefinedLocalAuthenticatorConfig updatedConfig = authenticatorManagementDAO + .updateUserDefinedLocalAuthenticator(authenticatorConfig1, authenticatorForUpdate, tenantId); + Assert.assertNotNull(updatedConfig); + Assert.assertEquals(updatedConfig.getName(), authenticatorForUpdate.getName()); + Assert.assertEquals(updatedConfig.getDisplayName(), authenticatorForUpdate.getDisplayName()); + Assert.assertEquals(updatedConfig.isEnabled(), authenticatorForUpdate.isEnabled()); + Assert.assertEquals(updatedConfig.getDefinedByType(), authenticatorForUpdate.getDefinedByType()); + + authenticatorConfig1 = authenticatorForUpdate; + } + + @Test(priority = 5) + public void testUpdateUserDefinedLocalAuthenticatorForException() { + + AuthenticatorMgtException exception = assertThrows(AuthenticatorMgtException.class, () -> + authenticatorManagementDAO.updateUserDefinedLocalAuthenticator(authenticatorConfig1, + authenticatorForUpdateForException, tenantId)); + Assert.assertEquals(exception.getErrorCode(), ERROR_WHILE_UPDATING_AUTHENTICATOR.getCode()); + } + + @Test(dataProvider = "authenticatorConfig", priority = 6) + public void testGetUserDefinedLocalAuthenticator(UserDefinedLocalAuthenticatorConfig config) + throws AuthenticatorMgtException { + + UserDefinedLocalAuthenticatorConfig retrievedConfig = authenticatorManagementDAO + .getUserDefinedLocalAuthenticator(config.getName(), tenantId); + Assert.assertNotNull(retrievedConfig); + Assert.assertEquals(retrievedConfig.getName(), config.getName()); + Assert.assertEquals(retrievedConfig.getDisplayName(), config.getDisplayName()); + Assert.assertEquals(retrievedConfig.isEnabled(), config.isEnabled()); + Assert.assertEquals(retrievedConfig.getDefinedByType(), config.getDefinedByType()); + } + + @Test(priority = 7) + public void testGetNonExistingUserDefinedLocalAuthenticator() throws AuthenticatorMgtException { + + UserDefinedLocalAuthenticatorConfig config = authenticatorManagementDAO.getUserDefinedLocalAuthenticator( + AUTHENTICATOR_CONFIG_FOR_EXCEPTION_NAME, tenantId); + + Assert.assertNull(config); + } + + @Test(priority = 8) + public void testGetUserDefinedLocalAuthenticatorForNonExist() throws AuthenticatorMgtException { + + Assert.assertNull(authenticatorManagementDAO.getUserDefinedLocalAuthenticator( + NON_EXIST_AUTHENTICATOR_NAME, tenantId)); + } + + @Test(dataProvider = "authenticatorConfig", priority = 9) + public void testDeleteUserDefinedLocalAuthenticator(UserDefinedLocalAuthenticatorConfig config) + throws AuthenticatorMgtException { + + authenticatorManagementDAO.deleteUserDefinedLocalAuthenticator(config.getName(), config, tenantId); + Assert.assertNull(authenticatorManagementDAO.getUserDefinedLocalAuthenticator(config.getName(), tenantId)); + } +} diff --git a/components/application-mgt/org.wso2.carbon.identity.application.common/src/test/java/org/wso2/carbon/identity/application/common/model/test/util/ActionMgtTestUtil.java b/components/application-mgt/org.wso2.carbon.identity.application.common/src/test/java/org/wso2/carbon/identity/application/common/model/test/util/ActionMgtTestUtil.java new file mode 100644 index 000000000000..810cfd73a976 --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.identity.application.common/src/test/java/org/wso2/carbon/identity/application/common/model/test/util/ActionMgtTestUtil.java @@ -0,0 +1,69 @@ +/* + * 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.application.common.model.test.util; + +import org.wso2.carbon.identity.action.management.exception.ActionMgtException; +import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.Authentication; +import org.wso2.carbon.identity.action.management.model.EndpointConfig; +import org.wso2.carbon.identity.action.management.service.ActionManagementService; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class ActionMgtTestUtil { + + public static final String ASSOCIATED_ACTION_ID = "Dummy_Action_ID"; + + public static Action createAction(EndpointConfig endpointConfig) { + + Action.ActionResponseBuilder actionResponseBuilder = new Action.ActionResponseBuilder(); + actionResponseBuilder.id(ASSOCIATED_ACTION_ID); + actionResponseBuilder.name("SampleAssociatedAction"); + actionResponseBuilder.type(Action.ActionTypes.AUTHENTICATION); + actionResponseBuilder.description("SampleDescription"); + actionResponseBuilder.status(Action.Status.ACTIVE); + actionResponseBuilder.endpoint(endpointConfig); + return actionResponseBuilder.build(); + } + + public static EndpointConfig createEndpointConfig(String uri, String username, String password) { + + EndpointConfig.EndpointConfigBuilder endpointConfigBuilder = new EndpointConfig.EndpointConfigBuilder(); + endpointConfigBuilder.uri(uri); + endpointConfigBuilder.authentication( + new Authentication.BasicAuthBuilder(username, password).build()); + return endpointConfigBuilder.build(); + } + + public static ActionManagementService mockActionService(Action action) throws ActionMgtException { + + ActionManagementService actionManagementService = mock(ActionManagementService.class); + + when(actionManagementService.addAction(anyString(), any(), any())).thenReturn(action); + when(actionManagementService.updateAction(anyString(), any(), any(), any())).thenReturn(action); + when(actionManagementService.getActionByActionId(anyString(), any(), any())).thenReturn(action); + doNothing().when(actionManagementService).deleteAction(anyString(), any(), any()); + + return actionManagementService; + } +} diff --git a/components/application-mgt/org.wso2.carbon.identity.application.common/src/test/java/org/wso2/carbon/identity/application/common/model/test/util/UserDefinedLocalAuthenticatorDataUtil.java b/components/application-mgt/org.wso2.carbon.identity.application.common/src/test/java/org/wso2/carbon/identity/application/common/model/test/util/UserDefinedLocalAuthenticatorDataUtil.java new file mode 100644 index 000000000000..52d82d6421ba --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.identity.application.common/src/test/java/org/wso2/carbon/identity/application/common/model/test/util/UserDefinedLocalAuthenticatorDataUtil.java @@ -0,0 +1,164 @@ +/* + * 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.application.common.model.test.util; + +import com.google.gson.Gson; +import org.wso2.carbon.identity.action.management.model.Authentication; +import org.wso2.carbon.identity.application.common.model.LocalAuthenticatorConfig; +import org.wso2.carbon.identity.application.common.model.Property; +import org.wso2.carbon.identity.application.common.model.UserDefinedAuthenticatorEndpointConfig.UserDefinedAuthenticatorEndpointConfigBuilder; +import org.wso2.carbon.identity.application.common.model.UserDefinedLocalAuthenticatorConfig; +import org.wso2.carbon.identity.base.AuthenticatorPropertyConstants; + +import java.util.HashMap; + +public class UserDefinedLocalAuthenticatorDataUtil { + + private static final Gson gson = new Gson(); + + /** + * Create a user defined authenticator configuration. + * + * @param uniqueIdentifier Unique identifier for the authenticator. + * @param type Authentication type. + * @return UserDefinedLocalAuthenticatorConfig + */ + public static UserDefinedLocalAuthenticatorConfig createUserDefinedAuthenticatorConfig(String uniqueIdentifier, + AuthenticatorPropertyConstants.AuthenticationType type) { + + UserDefinedLocalAuthenticatorConfig authenticatorConfig = new + UserDefinedLocalAuthenticatorConfig(AuthenticatorPropertyConstants.AuthenticationType.IDENTIFICATION); + authenticatorConfig.setName(uniqueIdentifier); + authenticatorConfig.setDisplayName("Custom " + uniqueIdentifier); + authenticatorConfig.setEnabled(true); + authenticatorConfig.setDefinedByType(AuthenticatorPropertyConstants.DefinedByType.USER); + authenticatorConfig.setAuthenticationType(type); + authenticatorConfig.setProperties(buildAuthenticatorProperties()); + UserDefinedAuthenticatorEndpointConfigBuilder endpointConfigBuilder = buildAuthenticatorEndpointConfig(); + authenticatorConfig.setEndpointConfig(endpointConfigBuilder.build()); + + return authenticatorConfig; + } + + /** + * Create a system defined authenticator configuration. + * + * @param uniqueIdentifier Unique identifier for the authenticator. + * @return LocalAuthenticatorConfig + */ + public static LocalAuthenticatorConfig createSystemDefinedAuthenticatorConfig(String uniqueIdentifier) { + + LocalAuthenticatorConfig authenticatorConfig = new LocalAuthenticatorConfig(); + authenticatorConfig.setName(uniqueIdentifier); + authenticatorConfig.setDisplayName("Custom " + uniqueIdentifier); + authenticatorConfig.setEnabled(true); + authenticatorConfig.setDefinedByType(AuthenticatorPropertyConstants.DefinedByType.SYSTEM); + Property prop1 = new Property(); + prop1.setName("PropertyName1_" + uniqueIdentifier); + prop1.setValue("PropertyValue1_" + uniqueIdentifier); + prop1.setConfidential(false); + Property prop2 = new Property(); + prop2.setName("PropertyName2_" + uniqueIdentifier); + prop2.setValue("PropertyValue2_" + uniqueIdentifier); + prop2.setConfidential(true); + authenticatorConfig.setProperties(new Property[]{prop1, prop2}); + + return authenticatorConfig; + } + + /** + * Create a user defined authenticator configuration for an SQL exception. + * + * @param uniqueIdentifier Unique identifier for the authenticator. + * @param type Authentication type. + * @return UserDefinedLocalAuthenticatorConfig + */ + public static UserDefinedLocalAuthenticatorConfig createUserDefinedAuthenticatorConfigForSQLException( + String uniqueIdentifier, AuthenticatorPropertyConstants.AuthenticationType type) { + + UserDefinedLocalAuthenticatorConfig authenticatorConfigForException = + createUserDefinedAuthenticatorConfig(uniqueIdentifier, type); + authenticatorConfigForException.setDisplayName("Authenticator name with 254 characters".repeat(50)); + + return authenticatorConfigForException; + } + + /** + * Build the endpoint configuration for the user defined authenticator. + * + * @return UserDefinedAuthenticatorEndpointConfigBuilder + */ + public static UserDefinedAuthenticatorEndpointConfigBuilder buildAuthenticatorEndpointConfig() { + + UserDefinedAuthenticatorEndpointConfigBuilder endpointConfigBuilder = + new UserDefinedAuthenticatorEndpointConfigBuilder(); + endpointConfigBuilder.uri("https://localhost:8080/test"); + endpointConfigBuilder.authenticationType(Authentication.Type.BASIC.getName()); + HashMap authProperties = new HashMap<>(); + authProperties.put("username", "admin"); + authProperties.put("password", "admin"); + endpointConfigBuilder.authenticationProperties(authProperties); + return endpointConfigBuilder; + } + + /** + * Update the user defined authenticator configuration. + * + * @param authenticatorConfig UserDefinedLocalAuthenticatorConfig + * @return UserDefinedLocalAuthenticatorConfig + */ + public static UserDefinedLocalAuthenticatorConfig updateUserDefinedAuthenticatorConfig( + UserDefinedLocalAuthenticatorConfig authenticatorConfig) { + + UserDefinedLocalAuthenticatorConfig updatingConfig = gson.fromJson(gson.toJson(authenticatorConfig), + UserDefinedLocalAuthenticatorConfig.class); + updatingConfig.setName(authenticatorConfig.getName()); + updatingConfig.setDisplayName("UpdatedDisplayName"); + updatingConfig.setEnabled(false); + + return updatingConfig; + } + + public static UserDefinedLocalAuthenticatorConfig updateUserDefinedAuthenticatorConfigForSQLException( + UserDefinedLocalAuthenticatorConfig authenticatorConfig) { + + UserDefinedLocalAuthenticatorConfig updatingConfig = gson.fromJson(gson.toJson(authenticatorConfig), + UserDefinedLocalAuthenticatorConfig.class); + updatingConfig.setName(authenticatorConfig.getName()); + updatingConfig.setEnabled(false); + updatingConfig.setDisplayName("Authenticator name with 254 characters".repeat(50)); + + return updatingConfig; + } + + + /** + * Build the properties for the user defined authenticator. + * + * @return Property[] + */ + public static Property[] buildAuthenticatorProperties() { + + Property property = new Property(); + property.setName("actionId"); + property.setValue("actionId"); + + return new Property[]{property}; + } +} diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/resources/dbscripts/h2.sql b/components/application-mgt/org.wso2.carbon.identity.application.common/src/test/resources/dbscripts/h2.sql similarity index 91% rename from components/entitlement/org.wso2.carbon.identity.entitlement/src/test/resources/dbscripts/h2.sql rename to components/application-mgt/org.wso2.carbon.identity.application.common/src/test/resources/dbscripts/h2.sql index d533c642133a..2460775fdce3 100644 --- a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/resources/dbscripts/h2.sql +++ b/components/application-mgt/org.wso2.carbon.identity.application.common/src/test/resources/dbscripts/h2.sql @@ -498,6 +498,18 @@ CREATE TABLE SP_TEMPLATE ( PRIMARY KEY (ID), CONSTRAINT SP_TEMPLATE_CONSTRAINT UNIQUE (TENANT_ID, NAME)); +CREATE TABLE IF NOT EXISTS SP_TRUSTED_APPS ( + ID INTEGER AUTO_INCREMENT, + SP_ID INTEGER NOT NULL, + PLATFORM_TYPE VARCHAR(255) NOT NULL, + APP_IDENTIFIER VARCHAR(255) NOT NULL, + THUMBPRINTS VARCHAR(2048), + IS_FIDO_TRUSTED BOOLEAN DEFAULT FALSE, + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY (ID), + UNIQUE (SP_ID, PLATFORM_TYPE), + FOREIGN KEY (SP_ID) REFERENCES SP_APP(ID) ON DELETE CASCADE); + CREATE TABLE IF NOT EXISTS IDN_AUTH_WAIT_STATUS ( ID INTEGER AUTO_INCREMENT NOT NULL, TENANT_ID INTEGER NOT NULL, @@ -964,7 +976,8 @@ INSERT INTO IDN_CONFIG_TYPE (ID, NAME, DESCRIPTION) VALUES ('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.'); +('c385a42a-5697-4604-b49a-62456621e926', 'DCR_CONFIGURATION', 'A resource type to keep the DCR configurations.'), +('3e5b1f91-72d8-4fbc-94d1-1b9a4f8c3b07', 'IMPERSONATION_CONFIGURATION', 'A resource type to keep the tenant impersonation preferences.'); CREATE TABLE IF NOT EXISTS IDN_CONFIG_RESOURCE ( ID VARCHAR(255) NOT NULL, @@ -1114,7 +1127,8 @@ 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'); +('29d0c37d-139a-4b1e-a343-7b8d26f0a2a9', 'ANDROID_ATTESTATION_CREDENTIALS', 'Secret type to uniquely identify secrets relevant to android client attestation credentials'), +('33f0a41b-569d-4ea5-a891-6c0e78a1c3b0', 'ACTION_API_ENDPOINT_AUTH_SECRETS', 'Secret type to uniquely identify secrets relevant to action endpoint authentication properties'); CREATE TABLE IF NOT EXISTS IDN_SECRET ( ID VARCHAR(255) NOT NULL, @@ -1339,122 +1353,23 @@ CREATE TABLE IF NOT EXISTS IDN_NOTIFICATION_APP_TEMPLATE ( 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_ACTION ( + UUID CHAR(36) NOT NULL, + TYPE VARCHAR(50) NOT NULL, + NAME VARCHAR(255) NOT NULL, + DESCRIPTION VARCHAR(255), + STATUS VARCHAR(10) NOT NULL, + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY (UUID) ); -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) +CREATE TABLE IF NOT EXISTS IDN_ACTION_ENDPOINT ( + ACTION_UUID CHAR(36) NOT NULL, + PROPERTY_NAME VARCHAR(100) NOT NULL, + PROPERTY_VALUE VARCHAR(255) NOT NULL, + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY (ACTION_UUID, PROPERTY_NAME), + FOREIGN KEY (ACTION_UUID) REFERENCES IDN_ACTION(UUID) ON DELETE CASCADE ); -- --------------------------- INDEX CREATION ----------------------------- @@ -1562,11 +1477,6 @@ 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); +-- ACTIONS -- +CREATE INDEX IDX_IDN_ACTION_TY_TI ON IDN_ACTION (TYPE, TENANT_ID); +CREATE INDEX IDX_IDN_ACTION_ENDPOINT_AU_TI ON IDN_ACTION_ENDPOINT (ACTION_UUID, TENANT_ID); diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/resources/repository/conf/carbon.xml b/components/application-mgt/org.wso2.carbon.identity.application.common/src/test/resources/repository/conf/carbon.xml similarity index 100% rename from components/entitlement/org.wso2.carbon.identity.entitlement/src/test/resources/repository/conf/carbon.xml rename to components/application-mgt/org.wso2.carbon.identity.application.common/src/test/resources/repository/conf/carbon.xml diff --git a/components/entitlement/org.wso2.carbon.identity.entitlement/src/test/resources/repository/conf/identity/identity.xml b/components/application-mgt/org.wso2.carbon.identity.application.common/src/test/resources/repository/conf/identity/identity.xml similarity index 100% rename from components/entitlement/org.wso2.carbon.identity.entitlement/src/test/resources/repository/conf/identity/identity.xml rename to components/application-mgt/org.wso2.carbon.identity.application.common/src/test/resources/repository/conf/identity/identity.xml diff --git a/components/application-mgt/org.wso2.carbon.identity.application.common/src/test/resources/testng.xml b/components/application-mgt/org.wso2.carbon.identity.application.common/src/test/resources/testng.xml index 917b616e3e8a..5e099dcc02ab 100644 --- a/components/application-mgt/org.wso2.carbon.identity.application.common/src/test/resources/testng.xml +++ b/components/application-mgt/org.wso2.carbon.identity.application.common/src/test/resources/testng.xml @@ -17,11 +17,13 @@ - + + + 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 86a46edaed73..c1d768653e04 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.10-SNAPSHOT + 7.7.63-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 67a7e52e0777..77041c4c7085 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.10-SNAPSHOT + 7.7.63-SNAPSHOT ../pom.xml org.wso2.carbon.identity.application.mgt @@ -59,6 +59,18 @@ org.apache.axis2.wso2 axis2 + + org.wso2.orbit.org.apache.httpcomponents + httpclient + + + org.apache.httpcomponents.wso2 + httpcore + + + org.wso2.orbit.org.apache.httpcomponents + httpasyncclient + org.wso2.carbon org.wso2.carbon.utils @@ -133,6 +145,10 @@ org.wso2.carbon.identity.framework org.wso2.carbon.identity.claim.metadata.mgt + + org.wso2.carbon.identity.framework + org.wso2.carbon.ai.service.mgt + org.wso2.carbon.identity.framework org.wso2.carbon.identity.api.resource.mgt @@ -264,9 +280,21 @@ version="${org.wso2.carbon.identity.organization.management.core.version.range}", org.wso2.carbon.identity.api.resource.mgt.model; version="${carbon.identity.package.import.version.range}", org.wso2.carbon.identity.api.resource.mgt.util; version="${carbon.identity.package.import.version.range}", + org.wso2.carbon.ai.service.mgt.*; version="${carbon.identity.package.import.version.range}", org.wso2.carbon.identity.certificate.management.service; version="${carbon.identity.package.import.version.range}", org.wso2.carbon.identity.certificate.management.exception; version="${carbon.identity.package.import.version.range}", org.wso2.carbon.identity.certificate.management.model; version="${carbon.identity.package.import.version.range}", + + org.apache.http; version="${httpcore.version.osgi.import.range}", + org.apache.http.client; version="${httpcomponents-httpclient.imp.pkg.version.range}", + org.apache.http.client.methods; version="${httpcomponents-httpclient.imp.pkg.version.range}", + org.apache.http.entity; version="${httpcore.version.osgi.import.range}", + org.apache.http.message; version="${httpcore.version.osgi.import.range}", + org.apache.http.protocol; version="${httpcore.version.osgi.import.range}", + org.apache.http.util; version="${httpcore.version.osgi.import.range}", + org.apache.http.impl.client; version="${httpcomponents-httpclient.imp.pkg.version.range}", + org.apache.http.impl.nio.client; version="${httpasyncclient.version.osgi.import.range}", + org.apache.http.concurrent; version="${httpcore.version.osgi.import.range}", !org.wso2.carbon.identity.application.mgt.internal, diff --git a/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/ApplicationConstants.java b/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/ApplicationConstants.java index 1c08a404ab50..b120ce2f3bf2 100644 --- a/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/ApplicationConstants.java +++ b/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/ApplicationConstants.java @@ -74,6 +74,7 @@ private ApplicationConstants() { public static final String PURPOSE_GROUP_TYPE_SP = "SP"; public static final String PURPOSE_GROUP_TYPE_SYSTEM = "SYSTEM"; public static final String PURPOSE_GROUP_SHARED = "SHARED"; + public static final String IS_FRAGMENT_APP = "isFragmentApp"; public static final String TENANT_DEFAULT_SP_TEMPLATE_NAME = "default"; public static final String MY_SQL = "MySQL"; diff --git a/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/ApplicationManagementService.java b/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/ApplicationManagementService.java index cc79a3c53b0e..d1cfbf521f8e 100644 --- a/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/ApplicationManagementService.java +++ b/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/ApplicationManagementService.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014-2023, WSO2 LLC. (http://www.wso2.com). + * Copyright (c) 2014-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 @@ -563,6 +563,21 @@ public String getMainAppId(String sharedAppId) throws IdentityApplicationManagem throw new NotImplementedException(); } + /** + * Get the shared ancestor application IDs for the given child application ID of the given child organization. + * + * @param sharedAppId ID of the shared application. + * @param orgId ID of the organization which the shared app belongs to. + * @return Map containing shared ancestor application IDs and their organization IDs. + * @throws IdentityApplicationManagementException If an error occurs while retrieving the ancestor + * application IDs. + */ + public Map getAncestorAppIds(String sharedAppId, String orgId) + throws IdentityApplicationManagementException { + + throw new NotImplementedException(); + } + /** * Get tenant ID of the application. * diff --git a/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/ApplicationManagementServiceImpl.java b/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/ApplicationManagementServiceImpl.java index 15cfd3acc428..c03f5d156af4 100644 --- a/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/ApplicationManagementServiceImpl.java +++ b/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/ApplicationManagementServiceImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014-2023, WSO2 LLC. (http://www.wso2.com). + * Copyright (c) 2014-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 @@ -93,6 +93,7 @@ import org.wso2.carbon.identity.event.services.IdentityEventService; import org.wso2.carbon.identity.organization.management.service.OrganizationManager; import org.wso2.carbon.identity.organization.management.service.exception.OrganizationManagementException; +import org.wso2.carbon.identity.organization.management.service.exception.OrganizationManagementServerException; import org.wso2.carbon.identity.role.v2.mgt.core.RoleConstants; import org.wso2.carbon.identity.role.v2.mgt.core.RoleManagementService; import org.wso2.carbon.identity.role.v2.mgt.core.exception.IdentityRoleManagementException; @@ -160,6 +161,7 @@ import static org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants.PlatformType; import static org.wso2.carbon.identity.application.mgt.ApplicationConstants.APPLICATION_NAME_CONFIG_ELEMENT; import static org.wso2.carbon.identity.application.mgt.ApplicationConstants.DEFAULT_APPLICATIONS_CONFIG_ELEMENT; +import static org.wso2.carbon.identity.application.mgt.ApplicationConstants.IS_FRAGMENT_APP; import static org.wso2.carbon.identity.application.mgt.ApplicationConstants.SYSTEM_APPLICATIONS_CONFIG_ELEMENT; import static org.wso2.carbon.identity.application.mgt.ApplicationMgtUtil.buildSPData; import static org.wso2.carbon.identity.application.mgt.ApplicationMgtUtil.endTenantFlow; @@ -2908,6 +2910,50 @@ public String getMainAppId(String sharedAppId) throws IdentityApplicationManagem return ApplicationMgtSystemConfig.getInstance().getApplicationDAO().getMainAppId(sharedAppId); } + @Override + public Map getAncestorAppIds(String sharedAppId, String orgId) + throws IdentityApplicationManagementException { + + String mainAppId = getMainAppId(sharedAppId); + if (StringUtils.isBlank(mainAppId)) { + String tenantDomain; + try { + tenantDomain = getOrganizationManager().resolveTenantDomain(orgId); + } catch (OrganizationManagementException e) { + throw buildServerException("Error while resolving the tenant domain for the organization id: " + orgId); + } + // Check if the child app is a main application. + if (isMainApp(sharedAppId, tenantDomain)) { + return Collections.singletonMap(orgId, sharedAppId); + } + return Collections.emptyMap(); + } + + String ownerOrgId = ApplicationMgtSystemConfig.getInstance().getApplicationDAO().getOwnerOrgId(sharedAppId); + if (StringUtils.isBlank(ownerOrgId)) { + throw buildServerException("Owner organization id cannot be blank for the shared app with id: " + + sharedAppId + " in organization: " + orgId); + } + + Map ancestorAppIds = new HashMap<>(); + // Add main app to the map. + ancestorAppIds.put(ownerOrgId, mainAppId); + + List ancestorOrganizationIds; + try { + ancestorOrganizationIds = getOrganizationManager().getAncestorOrganizationIds(orgId); + } catch (OrganizationManagementServerException e) { + throw buildServerException("Error while getting the ancestor organization ids for the organization id: " + + orgId); + } + + if (CollectionUtils.isNotEmpty(ancestorOrganizationIds) && ancestorOrganizationIds.size() > 1) { + ancestorAppIds.putAll(ApplicationMgtSystemConfig.getInstance().getApplicationDAO() + .getSharedApplicationIds(mainAppId, ownerOrgId, ancestorOrganizationIds)); + } + return ancestorAppIds; + } + @Override public int getTenantIdByApp(String appId) throws IdentityApplicationManagementServerException { @@ -3452,4 +3498,16 @@ private static OrganizationManager getOrganizationManager() { return ApplicationManagementServiceComponentHolder.getInstance().getOrganizationManager(); } + + private boolean isMainApp(String appId, String tenantDomain) throws IdentityApplicationManagementException { + + ServiceProvider serviceProvider = getApplicationByResourceId(appId, tenantDomain); + if (serviceProvider != null) { + boolean isFragmentApp = Arrays.stream(serviceProvider.getSpProperties()) + .anyMatch(property -> IS_FRAGMENT_APP.equals(property.getName()) && + Boolean.parseBoolean(property.getValue())); + return !isFragmentApp; + } + return false; + } } diff --git a/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/ai/LoginFlowAIManager.java b/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/ai/LoginFlowAIManager.java new file mode 100644 index 000000000000..ad242539e5eb --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/ai/LoginFlowAIManager.java @@ -0,0 +1,41 @@ +/* + * 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.application.mgt.ai; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.wso2.carbon.ai.service.mgt.exceptions.AIClientException; +import org.wso2.carbon.ai.service.mgt.exceptions.AIServerException; + +import java.util.Map; + +/** + * AI Manager interface for the LoginFlowAI module. + */ +public interface LoginFlowAIManager { + + String generateAuthenticationSequence(String userQuery, JSONArray userClaims, JSONObject availableAuthenticators) + throws AIServerException, AIClientException; + + Map getAuthenticationSequenceGenerationStatus(String operationId) throws AIServerException, + AIClientException; + + Map getAuthenticationSequenceGenerationResult(String operationId) throws AIServerException, + AIClientException; +} diff --git a/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/ai/LoginFlowAIManagerImpl.java b/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/ai/LoginFlowAIManagerImpl.java new file mode 100644 index 000000000000..b446386fdfcf --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/ai/LoginFlowAIManagerImpl.java @@ -0,0 +1,132 @@ +/* + * 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.application.mgt.ai; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.JsonSyntaxException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.json.JSONArray; +import org.json.JSONObject; +import org.wso2.carbon.ai.service.mgt.exceptions.AIClientException; +import org.wso2.carbon.ai.service.mgt.exceptions.AIServerException; +import org.wso2.carbon.identity.core.util.IdentityUtil; + +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.wso2.carbon.ai.service.mgt.util.AIHttpClientUtil.executeRequest; +import static org.wso2.carbon.identity.application.mgt.ai.constant.LoginFlowAIConstants.AUTHENTICATORS_PROPERTY; +import static org.wso2.carbon.identity.application.mgt.ai.constant.LoginFlowAIConstants.ErrorMessages.SERVER_ERROR_WHILE_CONNECTING_TO_LOGINFLOW_AI_SERVICE; +import static org.wso2.carbon.identity.application.mgt.ai.constant.LoginFlowAIConstants.OPERATION_ID_PROPERTY; +import static org.wso2.carbon.identity.application.mgt.ai.constant.LoginFlowAIConstants.USER_CLAIM_PROPERTY; +import static org.wso2.carbon.identity.application.mgt.ai.constant.LoginFlowAIConstants.USER_QUERY_PROPERTY; +import static org.wso2.carbon.registry.core.RegistryConstants.PATH_SEPARATOR; + +/** + * Implementation of the LoginFlowAIManager interface to communicate with the LoginFlowAI service. + */ +public class LoginFlowAIManagerImpl implements LoginFlowAIManager { + + private static final String LOGINFLOW_AI_ENDPOINT = IdentityUtil.getProperty( + "AIServices.LoginFlowAI.LoginFlowAIEndpoint"); + private static final String LOGINFLOW_AI_GENERATE_PATH = "/api/server/v1/applications/loginflow/generate"; + private static final String LOGINFLOW_AI_STATUS_PATH = "/api/server/v1/applications/loginflow/status"; + private static final String LOGINFLOW_AI_RESULT_PATH = "/api/server/v1/applications/loginflow/result"; + + private static final Log LOG = LogFactory.getLog(LoginFlowAIManagerImpl.class); + private static final ObjectMapper objectMapper = new ObjectMapper(); + + /** + * Generates an authentication sequence using the LoginFlow AI service. + * + * @param userQuery The user query. This is a string that contain the requested authentication + * flow by the user. + * @param userClaims The user claims. This is a JSON array that contains the user claims available + * for that organization. + * @param availableAuthenticators The available authenticators of the organization. + * @return Operation ID of the generated authentication sequence. + * @throws AIServerException When an error occurs while connecting to the LoginFlow AI service. + * @throws AIClientException When an error occurs while generating the authentication sequence. + */ + @Override + public String generateAuthenticationSequence(String userQuery, JSONArray userClaims, + JSONObject availableAuthenticators) throws AIServerException, + AIClientException { + + ObjectMapper objectMapper = new ObjectMapper(); + Map requestBody = new HashMap<>(); + requestBody.put(USER_QUERY_PROPERTY, userQuery); + try { + // Convert JSONArray to List. + List userClaimsList = objectMapper.readValue(userClaims.toString(), List.class); + requestBody.put(USER_CLAIM_PROPERTY, userClaimsList); + + // Convert JSONObject to Map. + Map authenticatorsMap = objectMapper.readValue(availableAuthenticators.toString(), + Map.class); + requestBody.put(AUTHENTICATORS_PROPERTY, authenticatorsMap); + } catch (JsonSyntaxException | IOException e) { + throw new AIClientException("Error occurred while parsing the user claims or available " + + "authenticators.", SERVER_ERROR_WHILE_CONNECTING_TO_LOGINFLOW_AI_SERVICE.getCode(), e); + } + + Map stringObjectMap = executeRequest(LOGINFLOW_AI_ENDPOINT, LOGINFLOW_AI_GENERATE_PATH, + HttpPost.class, requestBody); + return (String) stringObjectMap.get(OPERATION_ID_PROPERTY); + } + + /** + * Retrieves the status of the authentication sequence generation operation. + * + * @param operationId The operation ID of the authentication sequence generation operation. + * @return A Json representation of the status' that are completed, pending, or failed. + * @throws AIServerException When an error occurs while connecting to the LoginFlow AI service. + * @throws AIClientException When an error occurs while retrieving the authentication sequence + * generation status. + */ + @Override + public Map getAuthenticationSequenceGenerationStatus(String operationId) throws AIServerException, + AIClientException { + + return executeRequest(LOGINFLOW_AI_ENDPOINT, LOGINFLOW_AI_STATUS_PATH + PATH_SEPARATOR + operationId, + HttpGet.class, null); + } + + /** + * Retrieves the result of the authentication sequence generation operation. + * + * @param operationId The operation ID of the authentication sequence generation operation. + * @return The result of the authentication sequence generation operation. + * @throws AIServerException When an error occurs while connecting to the LoginFlow AI service. + * @throws AIClientException When an error occurs while retrieving the authentication sequence + * generation result. + */ + @Override + public Map getAuthenticationSequenceGenerationResult(String operationId) throws AIServerException, + AIClientException { + + return executeRequest(LOGINFLOW_AI_ENDPOINT, LOGINFLOW_AI_RESULT_PATH + PATH_SEPARATOR + operationId, + HttpGet.class, null); + } +} diff --git a/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/ai/constant/LoginFlowAIConstants.java b/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/ai/constant/LoginFlowAIConstants.java new file mode 100644 index 000000000000..5e164d0f86fd --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/ai/constant/LoginFlowAIConstants.java @@ -0,0 +1,78 @@ +/* + * 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.application.mgt.ai.constant; + +/** + * Constants for the LoginFlowAI module. + */ +public class LoginFlowAIConstants { + + public static final String OPERATION_ID_PROPERTY = "operation_id"; + public static final String USER_CLAIM_PROPERTY = "user_claims"; + public static final String USER_QUERY_PROPERTY = "user_query"; + public static final String AUTHENTICATORS_PROPERTY = "available_authenticators"; + + + /** + * Enums for error messages. + */ + public enum ErrorMessages { + + MAXIMUM_RETRIES_EXCEEDED("AILF_10000", "Maximum retries exceeded to retrieve the access token."), + UNABLE_TO_ACCESS_AI_SERVICE_WITH_RENEW_ACCESS_TOKEN("AILF_10003", "Unable to access the " + + "AI service with the renewed access token."), + REQUEST_TIMEOUT("AILF_10004", "Request to the AI service timed out."), + ERROR_WHILE_GENERATING_AUTHENTICATION_SEQUENCE("AILF_10005", "Error occurred while " + + "generating the authentication sequence."), + ERROR_WHILE_CONNECTING_TO_LOGINFLOW_AI_SERVICE("AILF_10006", "Error occurred while" + + " connecting to the Loginflow AI service."), + ERROR_RETRIEVING_ACCESS_TOKEN("AILF_10007", "Error occurred while retrieving the " + + "access token."), + CLIENT_ERROR_WHILE_CONNECTING_TO_LOGINFLOW_AI_SERVICE("AILF_10008", "Client error occurred " + + "for %s tenant while generating authentication sequence."), + SERVER_ERROR_WHILE_CONNECTING_TO_LOGINFLOW_AI_SERVICE("AILF_10009", "Server error occurred " + + "for %s tenant while generating authentication sequence."); + + + private final String code; + private final String message; + + ErrorMessages(String code, String message) { + + this.code = code; + this.message = message; + } + + public String getCode() { + + return code; + } + + public String getMessage() { + + return message; + } + + @Override + public String toString() { + + return code + ":" + message; + } + } +} diff --git a/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/dao/ApplicationDAO.java b/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/dao/ApplicationDAO.java index e94cb5203832..3d5dbd103213 100644 --- a/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/dao/ApplicationDAO.java +++ b/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/dao/ApplicationDAO.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014-2023, WSO2 LLC. (http://www.wso2.com). + * Copyright (c) 2014-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 @@ -382,6 +382,33 @@ default String getMainAppId(String sharedAppId) throws IdentityApplicationManage throw new NotImplementedException(); } + /** + * Method that returns the id the owner organization of the main application of the given shared app. + * + * @param sharedAppId Shared application id. + * @return Owner organization id of the given shared application. + * @throws IdentityApplicationManagementServerException Error when obtaining owner organization id. + */ + default String getOwnerOrgId(String sharedAppId) throws IdentityApplicationManagementServerException { + + throw new NotImplementedException(); + } + + /** + * Method that returns the shared application ids of the main application. + * + * @param mainAppId Main application id. + * @param ownerOrgId Owner organization id. + * @param sharedOrgIds List of shared organization ids. + * @return Map containing shared application ids and their organization ids. + * @throws IdentityApplicationManagementServerException Error when obtaining shared applications. + */ + default Map getSharedApplicationIds(String mainAppId, String ownerOrgId, List sharedOrgIds) + throws IdentityApplicationManagementServerException { + + throw new NotImplementedException(); + } + /** * Method that returns the tenant id of the application. * diff --git a/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/dao/impl/ApplicationDAOImpl.java b/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/dao/impl/ApplicationDAOImpl.java index 3e662e0a557c..a9d3b9d4127f 100644 --- a/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/dao/impl/ApplicationDAOImpl.java +++ b/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/dao/impl/ApplicationDAOImpl.java @@ -187,6 +187,13 @@ import static org.wso2.carbon.identity.application.mgt.ApplicationMgtUtil.getUserTenantDomain; import static org.wso2.carbon.identity.application.mgt.dao.impl.ApplicationMgtDBQueries.ADD_APPLICATION_ASSOC_ROLES_TAIL; import static org.wso2.carbon.identity.application.mgt.dao.impl.ApplicationMgtDBQueries.ADD_APPLICATION_ASSOC_ROLES_TAIL_ORACLE; +import static org.wso2.carbon.identity.application.mgt.dao.impl.ApplicationMgtDBQueries.GET_FILTERED_SHARED_APPLICATIONS; +import static org.wso2.carbon.identity.application.mgt.dao.impl.ApplicationMgtDBQueries.SQLPlaceholders.DB_SCHEMA_COLUMN_NAME_MAIN_APP_ID; +import static org.wso2.carbon.identity.application.mgt.dao.impl.ApplicationMgtDBQueries.SQLPlaceholders.DB_SCHEMA_COLUMN_NAME_OWNER_ORG_ID; +import static org.wso2.carbon.identity.application.mgt.dao.impl.ApplicationMgtDBQueries.SQLPlaceholders.DB_SCHEMA_COLUMN_NAME_SHARED_APP_ID; +import static org.wso2.carbon.identity.application.mgt.dao.impl.ApplicationMgtDBQueries.SQLPlaceholders.DB_SCHEMA_COLUMN_NAME_SHARED_ORG_ID; +import static org.wso2.carbon.identity.application.mgt.dao.impl.ApplicationMgtDBQueries.SQLPlaceholders.SHARED_ORG_ID_LIST_PLACEHOLDER; +import static org.wso2.carbon.identity.application.mgt.dao.impl.ApplicationMgtDBQueries.SQLPlaceholders.SHARED_ORG_ID_PLACEHOLDER_PREFIX; import static org.wso2.carbon.identity.base.IdentityConstants.SKIP_CONSENT; import static org.wso2.carbon.identity.base.IdentityConstants.SKIP_CONSENT_DISPLAY_NAME; import static org.wso2.carbon.identity.base.IdentityConstants.SKIP_LOGOUT_CONSENT; @@ -3624,31 +3631,32 @@ private SpTrustedAppMetadata getSpTrustedAppMetadata(int applicationId, Connecti loadAppConfigs.setInt(2, tenantID); try (ResultSet appConfigResultSet = loadAppConfigs.executeQuery()) { - if (appConfigResultSet.isBeforeFirst()) { - spTrustedAppMetadata = new SpTrustedAppMetadata(); - + while (appConfigResultSet.next()) { + if (spTrustedAppMetadata == null) { + spTrustedAppMetadata = new SpTrustedAppMetadata(); + } // There should be maximum two entries for each service provider. One for Android and one for iOS. - while (appConfigResultSet.next()) { - PlatformType platformType = PlatformType.valueOf(appConfigResultSet.getString(1)); - if (PlatformType.ANDROID.equals(platformType)) { - spTrustedAppMetadata.setAndroidPackageName(appConfigResultSet.getString(2)); - if (appConfigResultSet.getString(3) != null) { - spTrustedAppMetadata.setAndroidThumbprints( - appConfigResultSet.getString(3).split(ATTRIBUTE_SEPARATOR)); - } else { - spTrustedAppMetadata.setAndroidThumbprints(new String[0]); - } - } else if (PlatformType.IOS.equals(platformType)) { - spTrustedAppMetadata.setAppleAppId(appConfigResultSet.getString(2)); + PlatformType platformType = PlatformType.valueOf(appConfigResultSet.getString(1)); + if (PlatformType.ANDROID.equals(platformType)) { + spTrustedAppMetadata.setAndroidPackageName(appConfigResultSet.getString(2)); + if (appConfigResultSet.getString(3) != null) { + spTrustedAppMetadata.setAndroidThumbprints( + appConfigResultSet.getString(3).split(ATTRIBUTE_SEPARATOR)); + } else { + spTrustedAppMetadata.setAndroidThumbprints(new String[0]); } - spTrustedAppMetadata.setIsFidoTrusted(appConfigResultSet.getBoolean(4)); + } else if (PlatformType.IOS.equals(platformType)) { + spTrustedAppMetadata.setAppleAppId(appConfigResultSet.getString(2)); } - + spTrustedAppMetadata.setIsFidoTrusted(appConfigResultSet.getBoolean(4)); + } + if (spTrustedAppMetadata != null) { // If consent required property is disabled, consent is always considered as granted. spTrustedAppMetadata.setIsConsentGranted(!ApplicationMgtUtil.isTrustedAppConsentRequired() || getTrustedAppConsent(spPropertyList)); } } + } catch (SQLException e) { throw new IdentityApplicationManagementException("Error while retrieving trusted app configurations.", e); } @@ -6110,6 +6118,63 @@ public String getMainAppId(String sharedAppId) throws IdentityApplicationManagem } } + @Override + public String getOwnerOrgId(String sharedAppId) throws IdentityApplicationManagementServerException { + + try (Connection connection = IdentityDatabaseUtil.getDBConnection(false); + NamedPreparedStatement namedPreparedStatement = new NamedPreparedStatement(connection, + ApplicationMgtDBQueries.GET_OWNER_ORG_ID_BY_SHARED_APP_ID)) { + namedPreparedStatement.setString(DB_SCHEMA_COLUMN_NAME_SHARED_APP_ID, sharedAppId); + try (ResultSet resultSet = namedPreparedStatement.executeQuery()) { + if (resultSet.next()) { + return resultSet.getString(DB_SCHEMA_COLUMN_NAME_OWNER_ORG_ID); + } + } + return null; + } catch (SQLException e) { + throw new IdentityApplicationManagementServerException( + String.format("Error while getting owner organization id for the shared application with id: %s", + sharedAppId), e); + } + } + + @Override + public Map getSharedApplicationIds(String mainAppId, String ownerOrgId, List sharedOrgIds) + throws IdentityApplicationManagementServerException { + + if (CollectionUtils.isEmpty(sharedOrgIds)) { + return Collections.emptyMap(); + } + + Map sharedAppIds = new HashMap<>(); + + String placeholders = IntStream.range(0, sharedOrgIds.size()) + .mapToObj(i -> ":" + SHARED_ORG_ID_PLACEHOLDER_PREFIX + i + ";") + .collect(Collectors.joining(", ")); + String sqlStmt = GET_FILTERED_SHARED_APPLICATIONS.replace(SHARED_ORG_ID_LIST_PLACEHOLDER, placeholders); + + try (Connection connection = IdentityDatabaseUtil.getDBConnection(false); + NamedPreparedStatement namedPreparedStatement = new NamedPreparedStatement(connection, sqlStmt)) { + namedPreparedStatement.setString(DB_SCHEMA_COLUMN_NAME_MAIN_APP_ID, mainAppId); + namedPreparedStatement.setString(DB_SCHEMA_COLUMN_NAME_OWNER_ORG_ID, ownerOrgId); + for (int i = 0; i < sharedOrgIds.size(); i++) { + namedPreparedStatement.setString(SHARED_ORG_ID_PLACEHOLDER_PREFIX + i, sharedOrgIds.get(i)); + } + + try (ResultSet resultSet = namedPreparedStatement.executeQuery()) { + while (resultSet.next()) { + sharedAppIds.put(resultSet.getString(DB_SCHEMA_COLUMN_NAME_SHARED_ORG_ID), + resultSet.getString(DB_SCHEMA_COLUMN_NAME_SHARED_APP_ID)); + } + return sharedAppIds; + } + } catch (SQLException e) { + throw new IdentityApplicationManagementServerException( + String.format("Error while resolving shared applications for the main application with id: %s in " + + "organization: %s", mainAppId, ownerOrgId), e); + } + } + @Override public int getTenantIdByApp(String applicationId) throws IdentityApplicationManagementServerException { diff --git a/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/dao/impl/ApplicationMgtDBQueries.java b/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/dao/impl/ApplicationMgtDBQueries.java index 79a7cfc3a03e..75131ab0ba3a 100644 --- a/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/dao/impl/ApplicationMgtDBQueries.java +++ b/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/dao/impl/ApplicationMgtDBQueries.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023, WSO2 LLC. (http://www.wso2.com). + * Copyright (c) 2022-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 @@ -437,9 +437,9 @@ public class ApplicationMgtDBQueries { public static final String LOAD_DISCOVERABLE_APPS_BY_TENANT_ORACLE = "SELECT ID, APP_NAME, VERSION, " + "DESCRIPTION, UUID, IMAGE_URL, ACCESS_URL, USERNAME, USER_STORE, TENANT_ID FROM " + - "(SELECT ID, APP_NAME, DESCRIPTION, UUID, IMAGE_URL, ACCESS_URL, USERNAME, USER_STORE, TENANT_ID, rownum " + - "AS rnum FROM " + - "(SELECT ID, APP_NAME, DESCRIPTION, UUID, IMAGE_URL, ACCESS_URL, USERNAME, USER_STORE, " + + "(SELECT ID, APP_NAME, VERSION, DESCRIPTION, UUID, IMAGE_URL, ACCESS_URL, USERNAME, USER_STORE, TENANT_ID" + + ", rownum AS rnum FROM " + + "(SELECT ID, APP_NAME, VERSION, DESCRIPTION, UUID, IMAGE_URL, ACCESS_URL, USERNAME, USER_STORE, " + "TENANT_ID, IS_DISCOVERABLE FROM SP_APP ORDER BY ID DESC) WHERE TENANT_ID = :TENANT_ID; AND " + "rownum <= :END_INDEX; AND IS_DISCOVERABLE = '1') WHERE rnum > :ZERO_BASED_START_INDEX;"; @@ -511,6 +511,16 @@ public class ApplicationMgtDBQueries { public static final String GET_MAIN_APP_ID = "SELECT MAIN_APP_ID FROM SP_SHARED_APP WHERE SHARED_APP_ID = ?"; + public static final String GET_OWNER_ORG_ID_BY_SHARED_APP_ID = + "SELECT OWNER_ORG_ID FROM SP_SHARED_APP WHERE SHARED_APP_ID = :" + + SQLPlaceholders.DB_SCHEMA_COLUMN_NAME_SHARED_APP_ID + ";"; + + public static final String GET_FILTERED_SHARED_APPLICATIONS = + "SELECT SHARED_ORG_ID, SHARED_APP_ID FROM SP_SHARED_APP WHERE MAIN_APP_ID = :" + + SQLPlaceholders.DB_SCHEMA_COLUMN_NAME_MAIN_APP_ID + "; AND OWNER_ORG_ID = :" + + SQLPlaceholders.DB_SCHEMA_COLUMN_NAME_OWNER_ORG_ID + "; AND SHARED_ORG_ID IN (" + + SQLPlaceholders.SHARED_ORG_ID_LIST_PLACEHOLDER + ")"; + public static final String GET_APP_TENANT_ID = "SELECT TENANT_ID FROM SP_APP WHERE UUID = ?"; // Authorized API queries. @@ -577,5 +587,13 @@ public static final class SQLPlaceholders { // Related to APP_ROLE_ASSOCIATION table. public static final String DB_SCHEMA_COLUMN_NAME_APP_ID = "APP_ID"; public static final String DB_SCHEMA_COLUMN_NAME_ROLE_ID = "ROLE_ID"; + + // Related to SP_SHARED_APP table. + public static final String DB_SCHEMA_COLUMN_NAME_MAIN_APP_ID = "MAIN_APP_ID"; + public static final String DB_SCHEMA_COLUMN_NAME_OWNER_ORG_ID = "OWNER_ORG_ID"; + public static final String DB_SCHEMA_COLUMN_NAME_SHARED_APP_ID = "SHARED_APP_ID"; + public static final String DB_SCHEMA_COLUMN_NAME_SHARED_ORG_ID = "SHARED_ORG_ID"; + public static final String SHARED_ORG_ID_LIST_PLACEHOLDER = "_SHARED_ORG_ID_LIST_"; + public static final String SHARED_ORG_ID_PLACEHOLDER_PREFIX = "SHARED_ORG_ID_"; } } diff --git a/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/internal/ApplicationManagementServiceComponent.java b/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/internal/ApplicationManagementServiceComponent.java index 986b2374dad9..f2a057ab251c 100644 --- a/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/internal/ApplicationManagementServiceComponent.java +++ b/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/internal/ApplicationManagementServiceComponent.java @@ -48,6 +48,8 @@ import org.wso2.carbon.identity.application.mgt.AuthorizedAPIManagementService; import org.wso2.carbon.identity.application.mgt.AuthorizedAPIManagementServiceImpl; import org.wso2.carbon.identity.application.mgt.DiscoverableApplicationManager; +import org.wso2.carbon.identity.application.mgt.ai.LoginFlowAIManager; +import org.wso2.carbon.identity.application.mgt.ai.LoginFlowAIManagerImpl; import org.wso2.carbon.identity.application.mgt.defaultsequence.DefaultAuthSeqMgtService; import org.wso2.carbon.identity.application.mgt.defaultsequence.DefaultAuthSeqMgtServiceImpl; import org.wso2.carbon.identity.application.mgt.inbound.protocol.ApplicationInboundAuthConfigHandler; @@ -143,6 +145,8 @@ protected void activate(ComponentContext context) { bundleContext.registerService(AuthorizedAPIManagementService.class, new AuthorizedAPIManagementServiceImpl(), null); + bundleContext.registerService(LoginFlowAIManager.class, new LoginFlowAIManagerImpl(), null); + bundleContext.registerService(RoleManagementListener.class, new DefaultRoleManagementListener(), null); bundleContext.registerService(ApplicationMgtListener.class, new DefaultRoleManagementListener(), null); diff --git a/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/listener/DefaultRoleManagementListener.java b/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/listener/DefaultRoleManagementListener.java index 58a1976827c7..cdf9a56df19e 100644 --- a/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/listener/DefaultRoleManagementListener.java +++ b/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/listener/DefaultRoleManagementListener.java @@ -24,6 +24,7 @@ import org.wso2.carbon.identity.application.common.model.ApplicationBasicInfo; import org.wso2.carbon.identity.application.common.model.AuthorizedScopes; import org.wso2.carbon.identity.application.common.model.ServiceProvider; +import org.wso2.carbon.identity.application.mgt.ApplicationConstants; import org.wso2.carbon.identity.application.mgt.ApplicationManagementService; import org.wso2.carbon.identity.application.mgt.AuthorizedAPIManagementService; import org.wso2.carbon.identity.application.mgt.AuthorizedAPIManagementServiceImpl; @@ -34,6 +35,7 @@ import org.wso2.carbon.identity.application.mgt.internal.cache.ServiceProviderByResourceIdCache; import org.wso2.carbon.identity.application.mgt.internal.cache.ServiceProviderIDCacheKey; import org.wso2.carbon.identity.application.mgt.internal.cache.ServiceProviderResourceIdCacheKey; +import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.role.v2.mgt.core.exception.IdentityRoleManagementClientException; import org.wso2.carbon.identity.role.v2.mgt.core.exception.IdentityRoleManagementException; import org.wso2.carbon.identity.role.v2.mgt.core.exception.IdentityRoleManagementServerException; @@ -65,9 +67,6 @@ */ public class DefaultRoleManagementListener extends AbstractApplicationMgtListener implements RoleManagementListener { - private static final AuthorizedAPIManagementService authorizedAPIManagementService = - new AuthorizedAPIManagementServiceImpl(); - @Override public int getExecutionOrderId() { @@ -92,7 +91,7 @@ public void preAddRole(String roleName, List userList, List grou throws IdentityRoleManagementException { if (APPLICATION.equalsIgnoreCase(audience)) { - validateApplicationRoleAudience(audienceId, tenantDomain); + validateApplicationTypeAndRoleAudience(audienceId, tenantDomain); validatePermissionsForApplication(permissions, audienceId, tenantDomain); } } @@ -513,13 +512,14 @@ public void postGetAssociatedApplicationIdsByRoleId(List associatedAppli } /** - * Validate application role audience. + * Validate application type and the role audience of the application. The application type will be set to the + * thread local properties. * * @param applicationId Application ID. * @param tenantDomain Tenant domain. * @throws IdentityRoleManagementException Error occurred while validating application role audience. */ - private void validateApplicationRoleAudience(String applicationId, String tenantDomain) + private void validateApplicationTypeAndRoleAudience(String applicationId, String tenantDomain) throws IdentityRoleManagementException { try { @@ -536,6 +536,17 @@ private void validateApplicationRoleAudience(String applicationId, String tenant throw new IdentityRoleManagementClientException(INVALID_AUDIENCE.getCode(), "Application: " + applicationId + " does not have Application role audience type"); } + + // Set thread local property to identify that the application is a fragment application. This property + // will be used in the role management component to identify the application type. + if (IdentityUtil.threadLocalProperties.get().get(ApplicationConstants.IS_FRAGMENT_APP) != null) { + IdentityUtil.threadLocalProperties.get().remove(ApplicationConstants.IS_FRAGMENT_APP); + } + if (app.getSpProperties() != null && Arrays.stream(app.getSpProperties()) + .anyMatch(property -> ApplicationConstants.IS_FRAGMENT_APP.equals(property.getName()) + && Boolean.parseBoolean(property.getValue()))) { + IdentityUtil.threadLocalProperties.get().put(ApplicationConstants.IS_FRAGMENT_APP, Boolean.TRUE); + } } catch (IdentityApplicationManagementException e) { String errorMessage = "Error while retrieving the application for the given id: " + applicationId; throw new IdentityRoleManagementServerException(UNEXPECTED_SERVER_ERROR.getCode(), errorMessage, e); @@ -579,6 +590,7 @@ private List getAuthorizedScopes(String appId, String tenantDomain) List authorizedScopesList; try { + AuthorizedAPIManagementService authorizedAPIManagementService = new AuthorizedAPIManagementServiceImpl(); authorizedScopesList = authorizedAPIManagementService.getAuthorizedScopes(appId, tenantDomain); } catch (IdentityApplicationManagementException e) { throw new IdentityRoleManagementException("Error while retrieving authorized scopes.", diff --git a/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/test/java/org/wso2/carbon/identity/application/mgt/ApplicationManagementServiceImplTest.java b/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/test/java/org/wso2/carbon/identity/application/mgt/ApplicationManagementServiceImplTest.java index 1c3be111275c..78ca8e755346 100644 --- a/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/test/java/org/wso2/carbon/identity/application/mgt/ApplicationManagementServiceImplTest.java +++ b/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/test/java/org/wso2/carbon/identity/application/mgt/ApplicationManagementServiceImplTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2021-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 @@ -21,6 +21,7 @@ import org.apache.commons.lang.StringUtils; import org.mockito.MockedStatic; import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; @@ -77,8 +78,12 @@ import org.wso2.carbon.identity.common.testng.realm.InMemoryRealmService; import org.wso2.carbon.identity.common.testng.realm.MockUserStoreManager; import org.wso2.carbon.identity.core.internal.IdentityCoreServiceDataHolder; +import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.core.util.IdentityUtil; +import org.wso2.carbon.identity.organization.management.service.OrganizationManager; +import org.wso2.carbon.identity.organization.management.service.exception.OrganizationManagementException; +import org.wso2.carbon.identity.organization.management.service.exception.OrganizationManagementServerException; import org.wso2.carbon.identity.secret.mgt.core.SecretManager; import org.wso2.carbon.identity.secret.mgt.core.SecretManagerImpl; import org.wso2.carbon.identity.secret.mgt.core.SecretResolveManager; @@ -102,9 +107,13 @@ import java.lang.reflect.Field; import java.nio.file.Paths; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; +import java.util.Map; import java.util.Optional; import static java.lang.Boolean.FALSE; @@ -120,9 +129,9 @@ import static org.mockito.Mockito.reset; import static org.mockito.Mockito.when; import static org.wso2.carbon.CarbonConstants.REGISTRY_SYSTEM_USERNAME; -import static org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants.PlatformType; import static org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants.TEMPLATE_ID_SP_PROPERTY_NAME; import static org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants.TEMPLATE_VERSION_SP_PROPERTY_NAME; +import static org.wso2.carbon.identity.application.mgt.ApplicationConstants.IS_FRAGMENT_APP; import static org.wso2.carbon.identity.application.mgt.ApplicationConstants.PORTAL_NAMES_CONFIG_ELEMENT; import static org.wso2.carbon.identity.application.mgt.ApplicationConstants.TRUSTED_APP_CONSENT_REQUIRED_PROPERTY; import static org.wso2.carbon.identity.certificate.management.constant.CertificateMgtErrors.ERROR_INVALID_CERTIFICATE_CONTENT; @@ -170,6 +179,16 @@ public class ApplicationManagementServiceImplTest { private static final String UPDATED_CERTIFICATE = "updated_dummy_application_certificate"; private static final int CERTIFICATE_ID = 1; + // B2B organization and application related constants. + private static final String B2B_APPLICATION_NAME = "B2B Test application"; + private static final String ROOT_ORG_ID = "10084a8d-113f-4211-a0d5-efe36b082211"; + private static final String ROOT_TENANT_DOMAIN = "carbon.super"; + private static final int ROOT_TENANT_ID = -1234; + private static final String L1_ORG_ID = "93d996f9-a5ba-4275-a52b-adaad9eba869"; + private static final int L1_TENANT_ID = 1; + private static final String L2_ORG_ID = "30b701c6-e309-4241-b047-0c299c45d1a0"; + private static final int L2_TENANT_ID = 2; + private IdPManagementDAO idPManagementDAO; private ApplicationManagementServiceImpl applicationManagementService; private ApplicationCertificateManagementService applicationCertificateManagementService; @@ -179,6 +198,10 @@ public class ApplicationManagementServiceImplTest { private Certificate certificate; private CertificateMgtServerException serverException; private CertificateMgtClientException clientException; + private OrganizationManager organizationManager; + private String rootAppId; + private String l1AppId; + private String l2AppId; @BeforeClass public void setup() throws RegistryException, UserStoreException, SecretManagementException { @@ -217,6 +240,9 @@ public void setup() throws RegistryException, UserStoreException, SecretManageme new Throwable()); clientException = new CertificateMgtClientException(ERROR_INVALID_CERTIFICATE_CONTENT.getMessage(), ERROR_INVALID_CERTIFICATE_CONTENT.getDescription(), ERROR_INVALID_CERTIFICATE_CONTENT.getCode()); + + organizationManager = mock(OrganizationManager.class); + ApplicationManagementServiceComponentHolder.getInstance().setOrganizationManager(organizationManager); } @DataProvider(name = "addApplicationDataProvider") @@ -1636,6 +1662,85 @@ public void testAddCertificateToExistingApplication() throws IdentityApplication SUPER_TENANT_DOMAIN_NAME, REGISTRY_SYSTEM_USERNAME); } + @Test(groups = "b2b-shared-apps", priority = 13) + public void testGetAncestorAppIdsOfChildApp() throws Exception { + + createB2BTestApp(); + mockAncestorOrganizationRetrieval(L2_ORG_ID, L1_ORG_ID, ROOT_ORG_ID); + + Map resolvedAncestorAppIds = + applicationManagementService.getAncestorAppIds(l2AppId, L2_ORG_ID); + + Assert.assertNotNull(resolvedAncestorAppIds); + Assert.assertEquals(resolvedAncestorAppIds.size(), 3); + Assert.assertEquals(resolvedAncestorAppIds.get(L2_ORG_ID), l2AppId); + Assert.assertEquals(resolvedAncestorAppIds.get(L1_ORG_ID), l1AppId); + Assert.assertEquals(resolvedAncestorAppIds.get(ROOT_ORG_ID), rootAppId); + } + + @Test(groups = "b2b-shared-apps", priority = 14, dependsOnMethods = "testGetAncestorAppIdsOfChildApp") + public void testGetAncestorAppIdsOfParentApp() throws Exception { + + mockAncestorOrganizationRetrieval(L1_ORG_ID, ROOT_ORG_ID); + + Map resolvedAncestorAppIds = + applicationManagementService.getAncestorAppIds(l1AppId, L1_ORG_ID); + + Assert.assertNotNull(resolvedAncestorAppIds); + Assert.assertEquals(resolvedAncestorAppIds.size(), 2); + Assert.assertEquals(resolvedAncestorAppIds.get(L1_ORG_ID), l1AppId); + Assert.assertEquals(resolvedAncestorAppIds.get(ROOT_ORG_ID), rootAppId); + } + + @Test(groups = "b2b-shared-apps", priority = 15, dependsOnMethods = "testGetAncestorAppIdsOfChildApp") + public void testGetAncestorAppIdsOfRootApp() throws Exception { + + when(organizationManager.resolveTenantDomain(ROOT_ORG_ID)).thenReturn(ROOT_TENANT_DOMAIN); + + Map resolvedAncestorAppIds = + applicationManagementService.getAncestorAppIds(rootAppId, ROOT_ORG_ID); + + Assert.assertNotNull(resolvedAncestorAppIds); + Assert.assertEquals(resolvedAncestorAppIds.size(), 1); + Assert.assertEquals(resolvedAncestorAppIds.get(ROOT_ORG_ID), rootAppId); + } + + @Test(groups = "b2b-shared-apps", priority = 16, dependsOnMethods = "testGetAncestorAppIdsOfChildApp") + public void testGetAncestorAppIdsOfInvalidApp() throws Exception { + + when(organizationManager.resolveTenantDomain(ROOT_ORG_ID)).thenReturn(ROOT_TENANT_DOMAIN); + + Map resolvedAncestorAppIds = + applicationManagementService.getAncestorAppIds("invalid-app-id", ROOT_ORG_ID); + + Assert.assertNotNull(resolvedAncestorAppIds); + Assert.assertEquals(resolvedAncestorAppIds.size(), 0); + } + + @Test(groups = "b2b-shared-apps", priority = 17, dependsOnMethods = "testGetAncestorAppIdsOfChildApp") + public void testServerExceptionsWhileRetrievingAncestorAppIds() throws Exception { + + // Server exceptions while retrieving ancestor organization ids of level 2 organization. + when(organizationManager.getAncestorOrganizationIds(L2_ORG_ID)) + .thenThrow(OrganizationManagementServerException.class); + Assert.assertThrows(IdentityApplicationManagementException.class, () -> { + applicationManagementService.getAncestorAppIds(l2AppId, L2_ORG_ID); + }); + + // Server exceptions while retrieving ancestor organization ids of level 1 organization. + when(organizationManager.getAncestorOrganizationIds(L1_ORG_ID)) + .thenThrow(OrganizationManagementServerException.class); + Assert.assertThrows(IdentityApplicationManagementException.class, () -> { + applicationManagementService.getAncestorAppIds(l1AppId, L1_ORG_ID); + }); + + // Server exceptions while resolving tenant domain of root organization. + when(organizationManager.resolveTenantDomain(ROOT_ORG_ID)).thenThrow(OrganizationManagementException.class); + Assert.assertThrows(IdentityApplicationManagementException.class, () -> { + applicationManagementService.getAncestorAppIds(rootAppId, ROOT_ORG_ID); + }); + } + private void addApplicationConfigurations(ServiceProvider serviceProvider) { serviceProvider.setDescription("Created for testing"); @@ -1813,4 +1918,74 @@ private static void setInternalState(Class c, String field, Object value) { throw new RuntimeException("Unable to set internal state on a private field.", e); } } + + private void mockAncestorOrganizationRetrieval(String orgId, String ...ancestorOrgIds) + throws OrganizationManagementException { + + List ancestorOrganizationIds = new ArrayList<>(); + ancestorOrganizationIds.add(orgId); + if (ancestorOrgIds != null && ancestorOrgIds.length > 0) { + ancestorOrganizationIds.addAll(Arrays.asList(ancestorOrgIds)); + } + + when(organizationManager.getAncestorOrganizationIds(orgId)).thenReturn(ancestorOrganizationIds); + } + + private void createB2BTestApp() throws Exception { + + ServiceProvider serviceProvider = new ServiceProvider(); + serviceProvider.setApplicationName(B2B_APPLICATION_NAME); + addApplicationConfigurations(serviceProvider); + + // Since the app is the main app, it is not a fragment app. + ServiceProviderProperty isFragmentAppProperty = new ServiceProviderProperty(); + isFragmentAppProperty.setName(IS_FRAGMENT_APP); + isFragmentAppProperty.setValue("false"); + serviceProvider.setSpProperties(new ServiceProviderProperty[]{isFragmentAppProperty}); + + try (MockedStatic mockedIdentityTenantUtil = Mockito.mockStatic(IdentityTenantUtil.class)) { + mockedIdentityTenantUtil.when(() -> IdentityTenantUtil.getTenantId(ROOT_TENANT_DOMAIN)) + .thenReturn(ROOT_TENANT_ID); + mockedIdentityTenantUtil.when(() -> IdentityTenantUtil.getTenantId(L1_ORG_ID)).thenReturn(L1_TENANT_ID); + mockedIdentityTenantUtil.when(() -> IdentityTenantUtil.getTenantId(L2_ORG_ID)).thenReturn(L2_TENANT_ID); + mockedIdentityTenantUtil.when(IdentityTenantUtil::getRealmService) + .thenAnswer(InvocationOnMock::callRealMethod); + + rootAppId = applicationManagementService.createApplication(serviceProvider, ROOT_TENANT_DOMAIN, + REGISTRY_SYSTEM_USERNAME); + l1AppId = shareApplication(rootAppId, ROOT_ORG_ID, L1_ORG_ID); + l2AppId = shareApplication(rootAppId, ROOT_ORG_ID, L2_ORG_ID); + } + } + + private String shareApplication(String mainAppId, String ownerOrgId, String sharedOrgId) + throws Exception { + + ServiceProvider serviceProvider = new ServiceProvider(); + serviceProvider.setApplicationName(B2B_APPLICATION_NAME); + addApplicationConfigurations(serviceProvider); + + // Since the app is shared, it is a fragment app. + ServiceProviderProperty isFragmentAppProperty = new ServiceProviderProperty(); + isFragmentAppProperty.setName(IS_FRAGMENT_APP); + isFragmentAppProperty.setValue("true"); + serviceProvider.setSpProperties(new ServiceProviderProperty[]{isFragmentAppProperty}); + + String sharedAppId = applicationManagementService.createApplication(serviceProvider, sharedOrgId, + REGISTRY_SYSTEM_USERNAME); + + String query = "INSERT INTO SP_SHARED_APP (MAIN_APP_ID, OWNER_ORG_ID, SHARED_APP_ID, SHARED_ORG_ID) " + + "VALUES (?, ?, ?, ?)"; + try (Connection connection = IdentityDatabaseUtil.getDBConnection(false)) { + try (PreparedStatement preparedStatement = connection.prepareStatement(query)) { + preparedStatement.setString(1, mainAppId); + preparedStatement.setString(2, ownerOrgId); + preparedStatement.setString(3, sharedAppId); + preparedStatement.setString(4, sharedOrgId); + preparedStatement.executeUpdate(); + } + } + + return sharedAppId; + } } diff --git a/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/test/java/org/wso2/carbon/identity/application/mgt/DefaultRoleManagementListenerTest.java b/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/test/java/org/wso2/carbon/identity/application/mgt/DefaultRoleManagementListenerTest.java new file mode 100644 index 000000000000..3160d5a9b3ea --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/test/java/org/wso2/carbon/identity/application/mgt/DefaultRoleManagementListenerTest.java @@ -0,0 +1,268 @@ +/* + * 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.application.mgt; + +import org.mockito.MockedStatic; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; +import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException; +import org.wso2.carbon.identity.application.common.model.ServiceProvider; +import org.wso2.carbon.identity.application.common.model.ServiceProviderProperty; +import org.wso2.carbon.identity.application.mgt.listener.DefaultRoleManagementListener; +import org.wso2.carbon.identity.core.util.IdentityUtil; +import org.wso2.carbon.identity.role.v2.mgt.core.exception.IdentityRoleManagementClientException; +import org.wso2.carbon.identity.role.v2.mgt.core.exception.IdentityRoleManagementServerException; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; + +/** + * Contains the unit tests for the default role management listener. + */ +public class DefaultRoleManagementListenerTest { + + private DefaultRoleManagementListener defaultRoleManagementListener; + private static final String ROLE_NAME = "test_role"; + private static final String APPLICATION_NAME = "app_name"; + private static final String APPLICATION_RES_ID = "app_id"; + private static final String IS_FRAGMENT_APP = "isFragmentApp"; + private static final String APPLICATION_AUD = "APPLICATION"; + private static final String ORGANIZATION_AUD = "ORGANIZATION"; + private static final String TENANT_DOMAIN = "wso2.com"; + + @BeforeClass + public void setUp() { + + defaultRoleManagementListener = spy(new DefaultRoleManagementListener()); + } + + @DataProvider(name = "fragmentAppPropertyProvider") + public Object[][] fragmentAppPropertyProvider() { + + // Creating main application object. + ServiceProvider mainApplication = createServiceProvider(); + mainApplication.setSpProperties(null); + + // Creating shared application object. + ServiceProvider fragmentApplication = createServiceProvider(); + ServiceProviderProperty isFragmentAppSpProp = buildServiceProviderProperty(IS_FRAGMENT_APP, + Boolean.TRUE.toString()); + fragmentApplication.setSpProperties(new ServiceProviderProperty[]{isFragmentAppSpProp}); + + return new Object[][] { + {false, mainApplication}, + {true, fragmentApplication} + }; + } + + @Test(priority = 1, dataProvider = "fragmentAppPropertyProvider") + public void testPreAddRoleForFragmentApp(boolean isFragmentApp, ServiceProvider application) throws Exception { + + try (MockedStatic applicationManagementServiceMockedStatic = + mockStatic(ApplicationManagementService.class)) { + + ApplicationManagementService applicationManagementService = mock(ApplicationManagementService.class); + applicationManagementServiceMockedStatic.when(ApplicationManagementService::getInstance). + thenReturn(applicationManagementService); + when(applicationManagementService.getApplicationByResourceId(anyString(), anyString())). + thenReturn(application); + when(applicationManagementService.getAllowedAudienceForRoleAssociation(anyString(), anyString())). + thenReturn(APPLICATION_AUD); + + // Calling the preAddRole method. + defaultRoleManagementListener.preAddRole(ROLE_NAME, new ArrayList<>(), new ArrayList<>(), + new ArrayList<>(), APPLICATION_AUD, APPLICATION_RES_ID, TENANT_DOMAIN); + + Map threadLocalProps = IdentityUtil.threadLocalProperties.get(); + if (!isFragmentApp) { + assertFalse(threadLocalProps.containsKey(IS_FRAGMENT_APP)); + } else { + // If the application is a fragment app, then we add the IS_FRAGMENT_APP property to the thread local. + assertTrue(threadLocalProps.containsKey(IS_FRAGMENT_APP)); + } + // Clearing the thread local properties. + IdentityUtil.threadLocalProperties.set(new HashMap<>()); + } + } + + @Test(priority = 2, dataProvider = "fragmentAppPropertyProvider") + public void testPreAddRoleWhenPreviousFragmentPropertyNotCleared(boolean isFragmentApp, + ServiceProvider application) throws Exception { + + try (MockedStatic applicationManagementServiceMockedStatic = + mockStatic(ApplicationManagementService.class)) { + + ApplicationManagementService applicationManagementService = mock(ApplicationManagementService.class); + applicationManagementServiceMockedStatic.when(ApplicationManagementService::getInstance). + thenReturn(applicationManagementService); + when(applicationManagementService.getApplicationByResourceId(anyString(), anyString())). + thenReturn(application); + when(applicationManagementService.getAllowedAudienceForRoleAssociation(anyString(), anyString())). + thenReturn(APPLICATION_AUD); + + // Mimicking the scenario where the previous fragment property is not cleared in the thread local. + Map threadLocalProps = new HashMap<>(); + threadLocalProps.put(IS_FRAGMENT_APP, Boolean.TRUE); + IdentityUtil.threadLocalProperties.set(threadLocalProps); + + // Calling the preAddRole method. + defaultRoleManagementListener.preAddRole(ROLE_NAME, new ArrayList<>(), new ArrayList<>(), + new ArrayList<>(), APPLICATION_AUD, APPLICATION_RES_ID, TENANT_DOMAIN); + + if (!isFragmentApp) { + assertFalse(threadLocalProps.containsKey(IS_FRAGMENT_APP)); + } else { + // If the application is a fragment app, then we add the IS_FRAGMENT_APP property to the thread local. + assertTrue(threadLocalProps.containsKey(IS_FRAGMENT_APP)); + } + // Clearing the thread local properties. + IdentityUtil.threadLocalProperties.set(new HashMap<>()); + } + } + + @Test(priority = 3) + public void testPreAddRoleWithOtherSPProperties() throws Exception { + + try (MockedStatic applicationManagementServiceMockedStatic = + mockStatic(ApplicationManagementService.class)) { + + // Creating service provider object. + ServiceProvider serviceProvider = createServiceProvider(); + + // Creating service provider property object. + ServiceProviderProperty isFragmentAppSpProp = buildServiceProviderProperty("test-prop-name", + "test-prop-value"); + serviceProvider.setSpProperties(new ServiceProviderProperty[]{isFragmentAppSpProp}); + + ApplicationManagementService applicationManagementService = mock(ApplicationManagementService.class); + applicationManagementServiceMockedStatic.when(ApplicationManagementService::getInstance). + thenReturn(applicationManagementService); + when(applicationManagementService.getApplicationByResourceId(anyString(), anyString())). + thenReturn(serviceProvider); + when(applicationManagementService.getAllowedAudienceForRoleAssociation(anyString(), anyString())). + thenReturn(APPLICATION_AUD); + + // Calling the preAddRole method. + defaultRoleManagementListener.preAddRole(ROLE_NAME, new ArrayList<>(), new ArrayList<>(), + new ArrayList<>(), APPLICATION_AUD, APPLICATION_RES_ID, TENANT_DOMAIN); + + assertFalse(IdentityUtil.threadLocalProperties.get().containsKey(IS_FRAGMENT_APP)); + } + } + + @Test(priority = 4) + public void testPreAddRoleForOrgAudience() throws Exception { + + defaultRoleManagementListener.preAddRole(ROLE_NAME, new ArrayList<>(), new ArrayList<>(), + new ArrayList<>(), ORGANIZATION_AUD, "org-id", TENANT_DOMAIN); + // If the audience is not application, then in the preAddRole method, it will return without going to the + // other methods. So the thread local properties will not be set. + Map threadLocalProps = IdentityUtil.threadLocalProperties.get(); + assertFalse(threadLocalProps.containsKey(IS_FRAGMENT_APP)); + } + + @Test(priority = 5, expectedExceptions = {IdentityRoleManagementClientException.class}, + expectedExceptionsMessageRegExp = "Invalid audience. No application found with application id: " + + APPLICATION_RES_ID + " and tenant domain : " + TENANT_DOMAIN) + public void testPreAddRoleWithNullApplication() throws Exception { + + try (MockedStatic applicationManagementServiceMockedStatic = + mockStatic(ApplicationManagementService.class)) { + + ApplicationManagementService applicationManagementService = mock(ApplicationManagementService.class); + applicationManagementServiceMockedStatic.when(ApplicationManagementService::getInstance). + thenReturn(applicationManagementService); + when(applicationManagementService.getApplicationByResourceId(anyString(), anyString())). + thenReturn(null); + // Calling the preAddRole method. + defaultRoleManagementListener.preAddRole(ROLE_NAME, new ArrayList<>(), new ArrayList<>(), + new ArrayList<>(), APPLICATION_AUD, APPLICATION_RES_ID, TENANT_DOMAIN); + } + } + + @Test(priority = 6, expectedExceptions = {IdentityRoleManagementClientException.class}, + expectedExceptionsMessageRegExp = "Application: " + APPLICATION_RES_ID + " does not have Application " + + "role audience type") + public void testPreAddRoleWithWrongAudience() throws Exception { + + try (MockedStatic applicationManagementServiceMockedStatic = + mockStatic(ApplicationManagementService.class)) { + + // Creating service provider object. + ServiceProvider serviceProvider = createServiceProvider(); + + ApplicationManagementService applicationManagementService = mock(ApplicationManagementService.class); + applicationManagementServiceMockedStatic.when(ApplicationManagementService::getInstance). + thenReturn(applicationManagementService); + when(applicationManagementService.getApplicationByResourceId(anyString(), anyString())). + thenReturn(serviceProvider); + when(applicationManagementService.getAllowedAudienceForRoleAssociation(anyString(), anyString())). + thenReturn(ORGANIZATION_AUD); + // Calling the preAddRole method. + defaultRoleManagementListener.preAddRole(ROLE_NAME, new ArrayList<>(), new ArrayList<>(), + new ArrayList<>(), APPLICATION_AUD, APPLICATION_RES_ID, TENANT_DOMAIN); + } + } + + @Test(priority = 7, expectedExceptions = {IdentityRoleManagementServerException.class}, + expectedExceptionsMessageRegExp = "Error while retrieving the application for the given id: " + + APPLICATION_RES_ID) + public void testPreAddRoleWithApplicationRetrievingException() throws Exception { + + try (MockedStatic applicationManagementServiceMockedStatic = + mockStatic(ApplicationManagementService.class)) { + + ApplicationManagementService applicationManagementService = mock(ApplicationManagementService.class); + applicationManagementServiceMockedStatic.when(ApplicationManagementService::getInstance). + thenReturn(applicationManagementService); + when(applicationManagementService.getApplicationByResourceId(anyString(), anyString())). + thenThrow(IdentityApplicationManagementException.class); + + // Calling the preAddRole method. + defaultRoleManagementListener.preAddRole(ROLE_NAME, new ArrayList<>(), new ArrayList<>(), + new ArrayList<>(), APPLICATION_AUD, APPLICATION_RES_ID, TENANT_DOMAIN); + } + } + + private static ServiceProviderProperty buildServiceProviderProperty(String name, String value) { + + ServiceProviderProperty isFragmentAppSpProp = new ServiceProviderProperty(); + isFragmentAppSpProp.setName(name); + isFragmentAppSpProp.setValue(value); + return isFragmentAppSpProp; + } + + private static ServiceProvider createServiceProvider() { + + ServiceProvider serviceProvider = new ServiceProvider(); + serviceProvider.setApplicationName(APPLICATION_NAME); + serviceProvider.setApplicationResourceId(APPLICATION_RES_ID); + return serviceProvider; + } +} diff --git a/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/test/java/org/wso2/carbon/identity/application/mgt/ai/LoginFlowAIManagerTest.java b/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/test/java/org/wso2/carbon/identity/application/mgt/ai/LoginFlowAIManagerTest.java new file mode 100644 index 000000000000..7d3c681ca9f4 --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.identity.application.mgt/src/test/java/org/wso2/carbon/identity/application/mgt/ai/LoginFlowAIManagerTest.java @@ -0,0 +1,141 @@ +/* + * 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.application.mgt.ai; + +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.json.JSONArray; +import org.json.JSONObject; +import org.mockito.InjectMocks; +import org.mockito.MockedStatic; +import org.testng.Assert; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; +import org.wso2.carbon.ai.service.mgt.exceptions.AIClientException; +import org.wso2.carbon.ai.service.mgt.exceptions.AIServerException; +import org.wso2.carbon.ai.service.mgt.util.AIHttpClientUtil; +import org.wso2.carbon.base.CarbonBaseConstants; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.identity.common.testng.realm.InMemoryRealmService; +import org.wso2.carbon.identity.core.util.IdentityTenantUtil; +import org.wso2.carbon.user.core.UserStoreException; + +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Map; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.MockitoAnnotations.openMocks; +import static org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; +import static org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_ID; + +public class LoginFlowAIManagerTest { + + private MockedStatic aiHttpClientUtilMockedStatic; + + @InjectMocks + private LoginFlowAIManagerImpl loginFlowAIManager; + + @BeforeMethod + public void setUp() throws UserStoreException { + + openMocks(this); + setCarbonHome(); + setCarbonContextForTenant(SUPER_TENANT_DOMAIN_NAME, SUPER_TENANT_ID); + aiHttpClientUtilMockedStatic = mockStatic(AIHttpClientUtil.class); + } + + @Test + public void testGenerateAuthenticationSequence_Success() throws Exception { + + Map response = new HashMap<>(); + response.put("operation_id", "12345"); + mockSuccessfulResponse(response, HttpPost.class); + String result = loginFlowAIManager.generateAuthenticationSequence("Need username and password as " + + "the first step", new JSONArray(), new JSONObject()); + Assert.assertEquals(result, "12345"); + } + + @Test + public void testGetAuthenticationSequenceGenerationStatus_Success() throws Exception { + Map response = new HashMap<>(); + response.put("status", "COMPLETED"); + mockSuccessfulResponse(response, HttpGet.class); + Object result = loginFlowAIManager.getAuthenticationSequenceGenerationStatus("operation123"); + + Assert.assertTrue(result instanceof Map); + Map resultMap = (Map) result; + Assert.assertEquals("COMPLETED", resultMap.get("status")); + } + + @Test + public void testGetAuthenticationSequenceGenerationResult_Success() throws Exception { + + Map response = new HashMap<>(); + response.put("result", "SUCCESS"); + mockSuccessfulResponse(response, HttpGet.class); + Object result = loginFlowAIManager.getAuthenticationSequenceGenerationResult("operation123"); + + Assert.assertTrue(result instanceof Map); + Map resultMap = (Map) result; + Assert.assertEquals("SUCCESS", resultMap.get("result")); + } + + private void mockSuccessfulResponse(Map responseBody, Class requestClass) throws Exception { + + aiHttpClientUtilMockedStatic.when(() -> AIHttpClientUtil.executeRequest( + any(), any(), any(), any() + )).thenReturn(responseBody); + } + + private void mockErrorResponse(int statusCode, String responseBody) throws Exception { + + aiHttpClientUtilMockedStatic.when(() -> AIHttpClientUtil.executeRequest( + anyString(), anyString(), any(), any() + )).thenThrow(statusCode >= 500 ? new AIServerException(responseBody, "ERROR_CODE") : new AIClientException( + responseBody, "ERROR_CODE")); + } + + private void setCarbonHome() { + + String carbonHome = Paths.get(System.getProperty("user.dir"), "target", "test-classes", + "repository").toString(); + System.setProperty(CarbonBaseConstants.CARBON_HOME, carbonHome); + System.setProperty(CarbonBaseConstants.CARBON_CONFIG_DIR_PATH, Paths.get(carbonHome, "conf").toString()); + } + + private void setCarbonContextForTenant(String tenantDomain, int tenantId) throws UserStoreException { + + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId); + InMemoryRealmService testSessionRealmService = new InMemoryRealmService(tenantId); + IdentityTenantUtil.setRealmService(testSessionRealmService); + } + + @AfterMethod + public void tearDown() { + + aiHttpClientUtilMockedStatic.close(); + PrivilegedCarbonContext.endTenantFlow(); + } +} 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 @@ - - - - - - - - - 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 37ebd371e198..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.10-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 e482f37291d9..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.10-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/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 48c221fe285e..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.10-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 112fcf041f45..3130ce20cea7 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.10-SNAPSHOT + 7.7.63-SNAPSHOT ../pom.xml diff --git a/components/extension-mgt/pom.xml b/components/extension-mgt/pom.xml index 33acafc4b547..05904eac66da 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.10-SNAPSHOT + 7.7.63-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 2482b3cffe80..f3e4a6d76a43 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.10-SNAPSHOT + 7.7.63-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 636e0b4c8068..cd3ae4d5eb5d 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.10-SNAPSHOT + 7.7.63-SNAPSHOT ../pom.xml 4.0.0 diff --git a/components/functions-library-mgt/pom.xml b/components/functions-library-mgt/pom.xml index 61fae38ee92e..4b405a056ae5 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.10-SNAPSHOT + 7.7.63-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 1e8bced35402..319e2fb00625 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.10-SNAPSHOT + 7.7.63-SNAPSHOT ../pom.xml diff --git a/components/identity-core/org.wso2.carbon.identity.base/src/main/java/org/wso2/carbon/identity/base/AuthenticatorPropertyConstants.java b/components/identity-core/org.wso2.carbon.identity.base/src/main/java/org/wso2/carbon/identity/base/AuthenticatorPropertyConstants.java index a887fd052c80..4b796e87bd0a 100644 --- a/components/identity-core/org.wso2.carbon.identity.base/src/main/java/org/wso2/carbon/identity/base/AuthenticatorPropertyConstants.java +++ b/components/identity-core/org.wso2.carbon.identity.base/src/main/java/org/wso2/carbon/identity/base/AuthenticatorPropertyConstants.java @@ -20,6 +20,9 @@ public class AuthenticatorPropertyConstants { + public static final String TAG_2FA = "2FA"; + public static final String TAG_CUSTOM = "Custom"; + /** * The Defined by Types - SYSTEM: system define authenticator, USER: user defined authentication extension. */ diff --git a/components/identity-core/org.wso2.carbon.identity.base/src/main/java/org/wso2/carbon/identity/base/IdentityConstants.java b/components/identity-core/org.wso2.carbon.identity.base/src/main/java/org/wso2/carbon/identity/base/IdentityConstants.java index 15b84afeb875..f9aa69c124d8 100644 --- a/components/identity-core/org.wso2.carbon.identity.base/src/main/java/org/wso2/carbon/identity/base/IdentityConstants.java +++ b/components/identity-core/org.wso2.carbon.identity.base/src/main/java/org/wso2/carbon/identity/base/IdentityConstants.java @@ -278,6 +278,8 @@ public static class ServerConfig { //Identity Persistence Manager public static final String SKIP_DB_SCHEMA_CREATION = "JDBCPersistenceManager.SkipDBSchemaCreation"; + public static final String SKIP_CLAIM_METADATA_PERSISTENCE = "JDBCPersistenceManager." + + "SkipClaimMetadataPersistence"; //Timeout Configurations public static final String SESSION_IDLE_TIMEOUT = "TimeConfig.SessionIdleTimeout"; 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 e2bc8ecddebb..769d438f4807 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.10-SNAPSHOT + 7.7.63-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 a04a1490af26..c12b6386149e 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.10-SNAPSHOT + 7.7.63-SNAPSHOT ../pom.xml @@ -208,6 +208,7 @@ org.apache.commons.collections; version="${commons-collections.wso2.osgi.version.range}", org.apache.commons.collections4; version = "${commons-collections4.wso2.osgi.version.range}", ua_parser; version="${ua_parser.version.range}", + org.wso2.carbon.utils.security;version="${carbon.kernel.package.import.version.range}", !org.wso2.carbon.identity.core.internal, diff --git a/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/IdentityKeyStoreResolver.java b/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/IdentityKeyStoreResolver.java index 1cb9722b3050..480750f6d206 100644 --- a/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/IdentityKeyStoreResolver.java +++ b/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/IdentityKeyStoreResolver.java @@ -246,6 +246,78 @@ public Key getPrivateKey(String tenantDomain, InboundProtocol inboundProtocol) return getPrivateKey(tenantDomain); } + /** + * Retrieves the public certificate for a given tenant domain and context. + *

    + * This method fetches the public certificate associated with a specific tenant domain and context. + * If the context is blank, it delegates the call to the overloaded + * {@code getCertificate(String tenantDomain)} method. + * The method first checks if the certificate is cached; if not, it retrieves the certificate from + * the KeyStoreManager, caches it, and then returns it. + *

    + * + * @param tenantDomain the tenant domain for which the certificate is requested. + * @param context the specific context for the tenant's certificate. If blank, the default certificate for the tenant is fetched. + * @return the public certificate for the specified tenant domain and context. + * @throws IdentityKeyStoreResolverException if there is an error while retrieving the certificate. + */ + + private Certificate getCertificate(String tenantDomain, String context) throws IdentityKeyStoreResolverException { + + if (StringUtils.isBlank(context)) { + getCertificate(tenantDomain); + } + int tenantId = IdentityTenantUtil.getTenantId(tenantDomain); + + if (publicCerts.containsKey(buildTenantIdWithContext(tenantId, context))) { + return publicCerts.get(buildTenantIdWithContext(tenantId, context)); + } + + KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(tenantId); + Certificate publicCert; + String tenantKeyStoreName = IdentityKeyStoreResolverUtil.buildTenantKeyStoreName(tenantDomain, context); + try { + publicCert = keyStoreManager.getCertificate(tenantKeyStoreName, tenantDomain + + IdentityKeyStoreResolverConstants.KEY_STORE_CONTEXT_SEPARATOR + context); + + } catch (SecurityException e) { + if (e.getMessage() != null && e.getMessage().contains("Key Store with a name: " + tenantKeyStoreName + + " does not exist.")) { + + throw new IdentityKeyStoreResolverException( + ErrorMessages.ERROR_RETRIEVING_TENANT_CONTEXT_PUBLIC_CERTIFICATE_KEYSTORE_NOT_EXIST.getCode(), + String.format( + ErrorMessages.ERROR_RETRIEVING_TENANT_CONTEXT_PUBLIC_CERTIFICATE_KEYSTORE_NOT_EXIST + .getDescription(), tenantDomain), e); + } else { + throw new IdentityKeyStoreResolverException( + ErrorMessages.ERROR_CODE_ERROR_RETRIEVING_TENANT_PUBLIC_CERTIFICATE.getCode(), + String.format(ErrorMessages.ERROR_CODE_ERROR_RETRIEVING_TENANT_PUBLIC_CERTIFICATE.getDescription(), + tenantDomain), e); + } + } catch (Exception e) { + throw new IdentityKeyStoreResolverException( + ErrorMessages.ERROR_CODE_ERROR_RETRIEVING_TENANT_PUBLIC_CERTIFICATE.getCode(), + String.format(ErrorMessages.ERROR_CODE_ERROR_RETRIEVING_TENANT_PUBLIC_CERTIFICATE.getDescription(), + tenantDomain), e); + } + + publicCerts.put(buildTenantIdWithContext(tenantId, context), publicCert); + return publicCert; + } + + /** + * Concatenates tenantId and context with the separator. + * + * @param tenantId the key store name + * @param context the context + * @return a concatenated string in the format tenantDomain:context + */ + private String buildTenantIdWithContext(int tenantId, String context) { + + return tenantId + IdentityKeyStoreResolverConstants.KEY_STORE_CONTEXT_SEPARATOR + context; + } + /** * Return Public Certificate of the Primary or tenant keystore according to given tenant domain. * @@ -285,21 +357,24 @@ private Certificate getCertificate(String tenantDomain) throws IdentityKeyStoreR * * @param tenantDomain Tenant domain. * @param inboundProtocol Inbound authentication protocol of the application. + * @param context Context of the keystore. * @return Public Certificate of the Primary, tenant or custom keystore. * @throws IdentityKeyStoreResolverException the exception in the IdentityKeyStoreResolver class. */ - public Certificate getCertificate(String tenantDomain, InboundProtocol inboundProtocol) + public Certificate getCertificate(String tenantDomain, InboundProtocol inboundProtocol, String context) throws IdentityKeyStoreResolverException { + if (StringUtils.isEmpty(tenantDomain)) { throw new IdentityKeyStoreResolverException( ErrorMessages.ERROR_CODE_INVALID_ARGUMENT.getCode(), String.format(ErrorMessages.ERROR_CODE_INVALID_ARGUMENT.getDescription(), "Tenant domain")); } + if (context != null) { + return getCertificate(tenantDomain, context); + } if (inboundProtocol == null) { - throw new IdentityKeyStoreResolverException( - ErrorMessages.ERROR_CODE_INVALID_ARGUMENT.getCode(), - String.format(ErrorMessages.ERROR_CODE_INVALID_ARGUMENT.getDescription(), "Inbound protocol")); + return getCertificate(tenantDomain); } if (keyStoreMappings.containsKey(inboundProtocol)) { @@ -328,13 +403,27 @@ public Certificate getCertificate(String tenantDomain, InboundProtocol inboundPr throw new IdentityKeyStoreResolverException( ErrorMessages.ERROR_CODE_ERROR_RETRIEVING_CUSTOM_PUBLIC_CERTIFICATE.getCode(), String.format(ErrorMessages.ERROR_CODE_ERROR_RETRIEVING_CUSTOM_PUBLIC_CERTIFICATE - .getDescription(), keyStoreName), e); + .getDescription(), keyStoreName), e); } } } return getCertificate(tenantDomain); } + /** + * Return Public Certificate of the Primary, tenant or custom keystore. + * + * @param tenantDomain Tenant domain. + * @param inboundProtocol Inbound authentication protocol of the application. + * @return Public Certificate of the Primary, tenant or custom keystore. + * @throws IdentityKeyStoreResolverException the exception in the IdentityKeyStoreResolver class. + */ + public Certificate getCertificate(String tenantDomain, InboundProtocol inboundProtocol) + throws IdentityKeyStoreResolverException { + + return getCertificate(tenantDomain, inboundProtocol, null); + } + /** * Return Public Key of the Primary or tenant keystore according to given tenant domain. * diff --git a/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/SAMLSSOServiceProviderManager.java b/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/SAMLSSOServiceProviderManager.java index d9d0cde6c95d..b2b0040a84a4 100644 --- a/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/SAMLSSOServiceProviderManager.java +++ b/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/SAMLSSOServiceProviderManager.java @@ -18,14 +18,10 @@ package org.wso2.carbon.identity.core; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.wso2.carbon.identity.base.IdentityException; +import org.wso2.carbon.identity.core.dao.SAMLServiceProviderPersistenceManagerFactory; import org.wso2.carbon.identity.core.dao.SAMLSSOServiceProviderDAO; import org.wso2.carbon.identity.core.model.SAMLSSOServiceProviderDO; -import org.wso2.carbon.identity.core.util.IdentityTenantUtil; -import org.wso2.carbon.registry.api.RegistryException; -import org.wso2.carbon.registry.core.Registry; /** * This class is used for managing SAML SSO providers. Adding, retrieving and removing service @@ -33,20 +29,9 @@ */ public class SAMLSSOServiceProviderManager { - private static final Log LOG = LogFactory.getLog(SAMLSSOServiceProviderManager.class); - - /** - * Build the SAML service provider. - * - * @param tenantId Tenant ID. - * @return SAML service provider. - */ - private SAMLSSOServiceProviderDAO buildSAMLSSOProvider(int tenantId) throws RegistryException { - - Registry registry = IdentityTenantUtil.getRegistryService().getConfigSystemRegistry(tenantId); - return new SAMLSSOServiceProviderDAO(registry); - } - + SAMLServiceProviderPersistenceManagerFactory + samlSSOPersistenceManagerFactory = new SAMLServiceProviderPersistenceManagerFactory(); + SAMLSSOServiceProviderDAO serviceProviderDAO = samlSSOPersistenceManagerFactory.getSAMLServiceProviderPersistenceManager(); /** * Add a saml service provider. @@ -59,13 +44,7 @@ private SAMLSSOServiceProviderDAO buildSAMLSSOProvider(int tenantId) throws Regi public boolean addServiceProvider(SAMLSSOServiceProviderDO serviceProviderDO, int tenantId) throws IdentityException { - try { - SAMLSSOServiceProviderDAO serviceProviderDAO = buildSAMLSSOProvider(tenantId); - return serviceProviderDAO.addServiceProvider(serviceProviderDO); - } catch (RegistryException e) { - LOG.error("Error while adding service provider", e); - throw new IdentityException("Error while retrieving registry", e); - } + return serviceProviderDAO.addServiceProvider(serviceProviderDO, tenantId); } /** @@ -80,13 +59,7 @@ public boolean addServiceProvider(SAMLSSOServiceProviderDO serviceProviderDO, in public boolean updateServiceProvider(SAMLSSOServiceProviderDO serviceProviderDO, String currentIssuer, int tenantId) throws IdentityException { - try { - SAMLSSOServiceProviderDAO serviceProviderDAO = buildSAMLSSOProvider(tenantId); - return serviceProviderDAO.updateServiceProvider(serviceProviderDO, currentIssuer); - } catch (RegistryException e) { - LOG.error("Error while updating service provider", e); - throw new IdentityException("Error while retrieving registry", e); - } + return serviceProviderDAO.updateServiceProvider(serviceProviderDO, currentIssuer, tenantId); } /** @@ -96,16 +69,9 @@ public boolean updateServiceProvider(SAMLSSOServiceProviderDO serviceProviderDO, * @return Array of SAMLSSOServiceProviderDO. * @throws IdentityException Error when getting the SAML service providers. */ - public SAMLSSOServiceProviderDO[] getServiceProviders(int tenantId) - throws IdentityException { + public SAMLSSOServiceProviderDO[] getServiceProviders(int tenantId) throws IdentityException { - try { - SAMLSSOServiceProviderDAO serviceProviderDOA = buildSAMLSSOProvider(tenantId); - return serviceProviderDOA.getServiceProviders(); - } catch (RegistryException e) { - LOG.error("Error while getting service providers", e); - throw new IdentityException("Error while retrieving registry", e); - } + return serviceProviderDAO.getServiceProviders(tenantId); } /** @@ -116,17 +82,9 @@ public SAMLSSOServiceProviderDO[] getServiceProviders(int tenantId) * @return SAMLSSOServiceProviderDO * @throws IdentityException Error when getting the SAML service provider. */ - public SAMLSSOServiceProviderDO getServiceProvider(String issuer, int tenantId) - throws IdentityException { - - try { - SAMLSSOServiceProviderDAO serviceProviderDAO = buildSAMLSSOProvider(tenantId); - return serviceProviderDAO.getServiceProvider(issuer); - } catch (RegistryException e) { - LOG.error("Error while getting service provider", e); - throw new IdentityException("Error while retrieving SAML issuer " + e.getMessage()); - } + public SAMLSSOServiceProviderDO getServiceProvider(String issuer, int tenantId) throws IdentityException { + return serviceProviderDAO.getServiceProvider(issuer, tenantId); } /** @@ -140,13 +98,7 @@ public SAMLSSOServiceProviderDO getServiceProvider(String issuer, int tenantId) public boolean isServiceProviderExists(String issuer, int tenantId) throws IdentityException { - try { - SAMLSSOServiceProviderDAO serviceProviderDAO = buildSAMLSSOProvider(tenantId); - return serviceProviderDAO.isServiceProviderExists(issuer); - } catch (RegistryException e) { - LOG.error("Error while getting service provider", e); - throw new IdentityException("Error while retrieving SAML issuer " + e.getMessage()); - } + return serviceProviderDAO.isServiceProviderExists(issuer, tenantId); } /** @@ -156,16 +108,9 @@ public boolean isServiceProviderExists(String issuer, int tenantId) * @param tenantId Tenant ID. * @throws IdentityException Error when removing the SAML configuration. */ - public boolean removeServiceProvider(String issuer, int tenantId) - throws IdentityException { + public boolean removeServiceProvider(String issuer, int tenantId) throws IdentityException { - try { - SAMLSSOServiceProviderDAO serviceProviderDAO = buildSAMLSSOProvider(tenantId); - return serviceProviderDAO.removeServiceProvider(issuer); - } catch (RegistryException e) { - LOG.error("Error while removing service provider", e); - throw new IdentityException("Error while deleting SAML issuer " + e.getMessage()); - } + return serviceProviderDAO.removeServiceProvider(issuer, tenantId); } /** @@ -176,15 +121,9 @@ public boolean removeServiceProvider(String issuer, int tenantId) * @return SAML service provider information object. * @throws IdentityException Error when uploading the SAML configuration. */ - public SAMLSSOServiceProviderDO uploadServiceProvider(SAMLSSOServiceProviderDO samlssoServiceProviderDO, int tenantId) - throws IdentityException { + public SAMLSSOServiceProviderDO uploadServiceProvider(SAMLSSOServiceProviderDO samlssoServiceProviderDO, + int tenantId) throws IdentityException { - try { - SAMLSSOServiceProviderDAO serviceProviderDAO = buildSAMLSSOProvider(tenantId); - return serviceProviderDAO.uploadServiceProvider(samlssoServiceProviderDO); - } catch (RegistryException e) { - LOG.error("Error while uploading service provider", e); - throw new IdentityException("Error while uploading SAML issuer " + e.getMessage()); - } + return serviceProviderDAO.uploadServiceProvider(samlssoServiceProviderDO, tenantId); } } diff --git a/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/dao/RegistrySAMLSSOServiceProviderDAOImpl.java b/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/dao/RegistrySAMLSSOServiceProviderDAOImpl.java new file mode 100644 index 000000000000..f07d50eb03b5 --- /dev/null +++ b/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/dao/RegistrySAMLSSOServiceProviderDAOImpl.java @@ -0,0 +1,855 @@ +/* + * Copyright (c) 2023, 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.core.dao; + +import org.apache.commons.codec.binary.Base64; +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.carbon.database.utils.jdbc.exceptions.DataAccessException; +import org.wso2.carbon.identity.base.IdentityException; +import org.wso2.carbon.identity.core.CertificateRetriever; +import org.wso2.carbon.identity.core.CertificateRetrievingException; +import org.wso2.carbon.identity.core.DatabaseCertificateRetriever; +import org.wso2.carbon.identity.core.IdentityRegistryResources; +import org.wso2.carbon.identity.core.KeyStoreCertificateRetriever; +import org.wso2.carbon.identity.core.model.SAMLSSOServiceProviderDO; +import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; +import org.wso2.carbon.identity.core.util.IdentityTenantUtil; +import org.wso2.carbon.registry.core.Collection; +import org.wso2.carbon.registry.core.Registry; +import org.wso2.carbon.registry.core.Resource; +import org.wso2.carbon.registry.core.exceptions.RegistryException; +import org.wso2.carbon.registry.core.jdbc.utils.Transaction; +import org.wso2.carbon.registry.core.session.UserRegistry; +import org.wso2.carbon.user.api.Tenant; +import org.wso2.carbon.user.api.UserStoreException; + +import java.security.cert.X509Certificate; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import static org.wso2.carbon.identity.core.util.JdbcUtils.isH2DB; + +/** + * This class is used for managing SAML SSO service providers in the Registry. + */ +public class RegistrySAMLSSOServiceProviderDAOImpl extends AbstractDAO + implements SAMLSSOServiceProviderDAO { + + private static final String CERTIFICATE_PROPERTY_NAME = "CERTIFICATE"; + private static final String QUERY_TO_GET_APPLICATION_CERTIFICATE_ID = "SELECT " + + "META.VALUE FROM SP_INBOUND_AUTH INBOUND, SP_APP SP, SP_METADATA META WHERE SP.ID = INBOUND.APP_ID AND " + + "SP.ID = META.SP_ID AND META.NAME = ? AND INBOUND.INBOUND_AUTH_KEY = ? AND META.TENANT_ID = ?"; + + private static final String QUERY_TO_GET_APPLICATION_CERTIFICATE_ID_H2 = "SELECT " + + "META.`VALUE` FROM SP_INBOUND_AUTH INBOUND, SP_APP SP, SP_METADATA META WHERE SP.ID = INBOUND.APP_ID AND " + + "SP.ID = META.SP_ID AND META.NAME = ? AND INBOUND.INBOUND_AUTH_KEY = ? AND META.TENANT_ID = ?"; + + private static Log log = LogFactory.getLog(RegistrySAMLSSOServiceProviderDAOImpl.class); + + public RegistrySAMLSSOServiceProviderDAOImpl() { + } + + protected SAMLSSOServiceProviderDO resourceToObject(Resource resource) { + SAMLSSOServiceProviderDO serviceProviderDO = new SAMLSSOServiceProviderDO(); + serviceProviderDO.setIssuer(resource + .getProperty(IdentityRegistryResources.PROP_SAML_SSO_ISSUER)); + serviceProviderDO.setAssertionConsumerUrls(resource.getPropertyValues( + IdentityRegistryResources.PROP_SAML_SSO_ASSERTION_CONS_URLS)); + serviceProviderDO.setDefaultAssertionConsumerUrl(resource.getProperty( + IdentityRegistryResources.PROP_DEFAULT_SAML_SSO_ASSERTION_CONS_URL)); + serviceProviderDO.setCertAlias(resource + .getProperty(IdentityRegistryResources.PROP_SAML_SSO_ISSUER_CERT_ALIAS)); + + if (StringUtils.isNotEmpty(resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_SIGNING_ALGORITHM))) { + serviceProviderDO.setSigningAlgorithmUri(resource.getProperty(IdentityRegistryResources + .PROP_SAML_SSO_SIGNING_ALGORITHM)); + } + + if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_ASSERTION_QUERY_REQUEST_PROFILE_ENABLED) != + null) { + serviceProviderDO.setAssertionQueryRequestProfileEnabled(Boolean.valueOf(resource.getProperty( + IdentityRegistryResources.PROP_SAML_SSO_ASSERTION_QUERY_REQUEST_PROFILE_ENABLED).trim())); + } + + if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_SUPPORTED_ASSERTION_QUERY_REQUEST_TYPES) != + null) { + serviceProviderDO.setSupportedAssertionQueryRequestTypes(resource.getProperty( + IdentityRegistryResources.PROP_SAML_SSO_SUPPORTED_ASSERTION_QUERY_REQUEST_TYPES).trim()); + } + + if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_ENABLE_SAML2_ARTIFACT_BINDING) != + null) { + serviceProviderDO.setEnableSAML2ArtifactBinding(Boolean.valueOf(resource.getProperty( + IdentityRegistryResources.PROP_SAML_SSO_ENABLE_SAML2_ARTIFACT_BINDING).trim())); + } + + if (StringUtils.isNotEmpty(resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_DIGEST_ALGORITHM))) { + serviceProviderDO.setDigestAlgorithmUri(resource.getProperty(IdentityRegistryResources + .PROP_SAML_SSO_DIGEST_ALGORITHM)); + } + + if (StringUtils.isNotEmpty(resource.getProperty(IdentityRegistryResources + .PROP_SAML_SSO_ASSERTION_ENCRYPTION_ALGORITHM))) { + serviceProviderDO.setAssertionEncryptionAlgorithmUri(resource.getProperty(IdentityRegistryResources + .PROP_SAML_SSO_ASSERTION_ENCRYPTION_ALGORITHM)); + } + + if (StringUtils.isNotEmpty(resource.getProperty(IdentityRegistryResources + .PROP_SAML_SSO_KEY_ENCRYPTION_ALGORITHM))) { + serviceProviderDO.setKeyEncryptionAlgorithmUri(resource.getProperty(IdentityRegistryResources + .PROP_SAML_SSO_KEY_ENCRYPTION_ALGORITHM)); + } + + if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_DO_SINGLE_LOGOUT) != null) { + serviceProviderDO.setDoSingleLogout(Boolean.valueOf(resource.getProperty( + IdentityRegistryResources.PROP_SAML_SSO_DO_SINGLE_LOGOUT).trim())); + } + + if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_NAMEID_FORMAT) != null) { + serviceProviderDO.setNameIDFormat(resource. + getProperty(IdentityRegistryResources.PROP_SAML_SSO_NAMEID_FORMAT)); + } + + if (resource + .getProperty(IdentityRegistryResources.PROP_SAML_SSO_ENABLE_NAMEID_CLAIMURI) != null) { + if (Boolean.valueOf(resource.getProperty( + IdentityRegistryResources.PROP_SAML_SSO_ENABLE_NAMEID_CLAIMURI).trim())) { + serviceProviderDO.setNameIdClaimUri(resource. + getProperty(IdentityRegistryResources.PROP_SAML_SSO_NAMEID_CLAIMURI)); + } + } + + serviceProviderDO.setLoginPageURL(resource. + getProperty(IdentityRegistryResources.PROP_SAML_SSO_LOGIN_PAGE_URL)); + + if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_DO_SIGN_RESPONSE) != null) { + serviceProviderDO.setDoSignResponse(Boolean.valueOf(resource.getProperty( + IdentityRegistryResources.PROP_SAML_SSO_DO_SIGN_RESPONSE).trim())); + } + + if (serviceProviderDO.isDoSingleLogout()) { + serviceProviderDO.setSloResponseURL(resource.getProperty(IdentityRegistryResources + .PROP_SAML_SLO_RESPONSE_URL)); + serviceProviderDO.setSloRequestURL(resource.getProperty(IdentityRegistryResources + .PROP_SAML_SLO_REQUEST_URL)); + // Check front channel logout enable. + if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_DO_FRONT_CHANNEL_LOGOUT) != null) { + serviceProviderDO.setDoFrontChannelLogout(Boolean.valueOf(resource.getProperty( + IdentityRegistryResources.PROP_SAML_SSO_DO_FRONT_CHANNEL_LOGOUT).trim())); + if (serviceProviderDO.isDoFrontChannelLogout()) { + if (resource.getProperty(IdentityRegistryResources. + PROP_SAML_SSO_FRONT_CHANNEL_LOGOUT_BINDING) != null) { + serviceProviderDO.setFrontChannelLogoutBinding(resource.getProperty( + IdentityRegistryResources.PROP_SAML_SSO_FRONT_CHANNEL_LOGOUT_BINDING)); + } else { + // Default is redirect-binding. + serviceProviderDO.setFrontChannelLogoutBinding(IdentityRegistryResources + .DEFAULT_FRONT_CHANNEL_LOGOUT_BINDING); + } + + } + } + } + + if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_DO_SIGN_ASSERTIONS) != null) { + serviceProviderDO.setDoSignAssertions(Boolean.valueOf(resource.getProperty( + IdentityRegistryResources.PROP_SAML_SSO_DO_SIGN_ASSERTIONS).trim())); + } + + if (resource.getProperty(IdentityRegistryResources.PROP_SAML_ENABLE_ECP) != null) { + serviceProviderDO.setSamlECP(Boolean.valueOf(resource.getProperty( + IdentityRegistryResources.PROP_SAML_ENABLE_ECP).trim())); + } + + if (resource + .getProperty(IdentityRegistryResources.PROP_SAML_SSO_ATTRIB_CONSUMING_SERVICE_INDEX) != null) { + serviceProviderDO + .setAttributeConsumingServiceIndex(resource + .getProperty(IdentityRegistryResources.PROP_SAML_SSO_ATTRIB_CONSUMING_SERVICE_INDEX)); + } else { + // Specific DB's (like oracle) returns empty strings as null. + serviceProviderDO.setAttributeConsumingServiceIndex(""); + } + + if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_REQUESTED_CLAIMS) != null) { + serviceProviderDO.setRequestedClaims(resource + .getPropertyValues(IdentityRegistryResources.PROP_SAML_SSO_REQUESTED_CLAIMS)); + } + + if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_REQUESTED_AUDIENCES) != null) { + serviceProviderDO.setRequestedAudiences(resource + .getPropertyValues(IdentityRegistryResources.PROP_SAML_SSO_REQUESTED_AUDIENCES)); + } + + if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_REQUESTED_RECIPIENTS) != null) { + serviceProviderDO.setRequestedRecipients(resource + .getPropertyValues(IdentityRegistryResources.PROP_SAML_SSO_REQUESTED_RECIPIENTS)); + } + + if (resource + .getProperty(IdentityRegistryResources.PROP_SAML_SSO_ENABLE_ATTRIBUTES_BY_DEFAULT) != null) { + String enableAttrByDefault = resource + .getProperty(IdentityRegistryResources.PROP_SAML_SSO_ENABLE_ATTRIBUTES_BY_DEFAULT); + serviceProviderDO.setEnableAttributesByDefault(Boolean.valueOf(enableAttrByDefault)); + } + if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_IDP_INIT_SSO_ENABLED) != null) { + serviceProviderDO.setIdPInitSSOEnabled(Boolean.valueOf(resource.getProperty( + IdentityRegistryResources.PROP_SAML_SSO_IDP_INIT_SSO_ENABLED).trim())); + } + if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SLO_IDP_INIT_SLO_ENABLED) != null) { + serviceProviderDO.setIdPInitSLOEnabled(Boolean.valueOf(resource.getProperty( + IdentityRegistryResources.PROP_SAML_SLO_IDP_INIT_SLO_ENABLED).trim())); + if (serviceProviderDO.isIdPInitSLOEnabled() && resource.getProperty( + IdentityRegistryResources.PROP_SAML_IDP_INIT_SLO_RETURN_URLS) != null) { + serviceProviderDO.setIdpInitSLOReturnToURLs(resource.getPropertyValues( + IdentityRegistryResources.PROP_SAML_IDP_INIT_SLO_RETURN_URLS)); + } + } + if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_ENABLE_ENCRYPTED_ASSERTION) != null) { + serviceProviderDO.setDoEnableEncryptedAssertion(Boolean.valueOf(resource.getProperty( + IdentityRegistryResources.PROP_SAML_SSO_ENABLE_ENCRYPTED_ASSERTION).trim())); + } + if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_VALIDATE_SIGNATURE_IN_REQUESTS) != null) { + serviceProviderDO.setDoValidateSignatureInRequests(Boolean.valueOf(resource.getProperty( + IdentityRegistryResources.PROP_SAML_SSO_VALIDATE_SIGNATURE_IN_REQUESTS).trim())); + } + if (resource.getProperty( + IdentityRegistryResources.PROP_SAML_SSO_VALIDATE_SIGNATURE_IN_ARTIFACT_RESOLVE) != null) { + serviceProviderDO.setDoValidateSignatureInArtifactResolve(Boolean.valueOf(resource.getProperty( + IdentityRegistryResources.PROP_SAML_SSO_VALIDATE_SIGNATURE_IN_ARTIFACT_RESOLVE).trim())); + } + if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_ISSUER_QUALIFIER) != null) { + serviceProviderDO.setIssuerQualifier(resource + .getProperty(IdentityRegistryResources.PROP_SAML_SSO_ISSUER_QUALIFIER)); + } + if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_IDP_ENTITY_ID_ALIAS) != null) { + serviceProviderDO.setIdpEntityIDAlias(resource.getProperty(IdentityRegistryResources + .PROP_SAML_SSO_IDP_ENTITY_ID_ALIAS)); + } + return serviceProviderDO; + } + + @Override + public boolean addServiceProvider(SAMLSSOServiceProviderDO serviceProviderDO, int tenantId) + throws IdentityException { + + Registry registry = getRegistry(tenantId); + if (serviceProviderDO == null || serviceProviderDO.getIssuer() == null || + StringUtils.isBlank(serviceProviderDO.getIssuer())) { + throw new IdentityException("Issuer cannot be found in the provided arguments."); + } + + // If an issuer qualifier value is specified, it is appended to the end of the issuer value. + if (StringUtils.isNotBlank(serviceProviderDO.getIssuerQualifier())) { + serviceProviderDO.setIssuer(getIssuerWithQualifier(serviceProviderDO.getIssuer(), + serviceProviderDO.getIssuerQualifier())); + } + + String path = IdentityRegistryResources.SAML_SSO_SERVICE_PROVIDERS + encodePath(serviceProviderDO.getIssuer()); + + boolean isTransactionStarted = Transaction.isStarted(); + boolean isErrorOccurred = false; + try { + if (registry.resourceExists(path)) { + if (log.isDebugEnabled()) { + if (StringUtils.isNotBlank(serviceProviderDO.getIssuerQualifier())) { + log.debug("SAML2 Service Provider already exists with the same issuer name " + + getIssuerWithoutQualifier(serviceProviderDO.getIssuer()) + " and qualifier name " + + serviceProviderDO.getIssuerQualifier()); + } else { + log.debug("SAML2 Service Provider already exists with the same issuer name " + + serviceProviderDO.getIssuer()); + } + } + return false; + } + + Resource resource = createResource(serviceProviderDO, registry); + if (!isTransactionStarted) { + registry.beginTransaction(); + } + registry.put(path, resource); + if (log.isDebugEnabled()) { + if (StringUtils.isNotBlank(serviceProviderDO.getIssuerQualifier())) { + log.debug("SAML2 Service Provider " + serviceProviderDO.getIssuer() + " with issuer " + + getIssuerWithoutQualifier(serviceProviderDO.getIssuer()) + " and qualifier " + + serviceProviderDO.getIssuerQualifier() + " is added successfully."); + } else { + log.debug("SAML2 Service Provider " + serviceProviderDO.getIssuer() + " is added successfully."); + } + } + return true; + } catch (RegistryException e) { + isErrorOccurred = true; + String msg; + if (StringUtils.isNotBlank(serviceProviderDO.getIssuerQualifier())) { + msg = "Error while adding SAML2 Service Provider for issuer: " + getIssuerWithoutQualifier + (serviceProviderDO.getIssuer()) + " and qualifier name " + serviceProviderDO + .getIssuerQualifier(); + } else { + msg = "Error while adding SAML2 Service Provider for issuer: " + serviceProviderDO.getIssuer(); + } + log.error(msg, e); + throw IdentityException.error(msg, e); + } finally { + commitOrRollbackTransaction(isErrorOccurred, registry); + } + } + + private Resource createResource(SAMLSSOServiceProviderDO serviceProviderDO, Registry registry) + throws RegistryException { + + Resource resource = registry.newResource(); + resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_ISSUER, + serviceProviderDO.getIssuer()); + resource.setProperty(IdentityRegistryResources.PROP_SAML_SSO_ASSERTION_CONS_URLS, + serviceProviderDO.getAssertionConsumerUrlList()); + resource.addProperty(IdentityRegistryResources.PROP_DEFAULT_SAML_SSO_ASSERTION_CONS_URL, + serviceProviderDO.getDefaultAssertionConsumerUrl()); + resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_ISSUER_CERT_ALIAS, + serviceProviderDO.getCertAlias()); + resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_LOGIN_PAGE_URL, + serviceProviderDO.getLoginPageURL()); + resource.addProperty( + IdentityRegistryResources.PROP_SAML_SSO_NAMEID_FORMAT, + serviceProviderDO.getNameIDFormat()); + resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_SIGNING_ALGORITHM, serviceProviderDO + .getSigningAlgorithmUri()); + resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_DIGEST_ALGORITHM, serviceProviderDO + .getDigestAlgorithmUri()); + resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_ASSERTION_ENCRYPTION_ALGORITHM, serviceProviderDO + .getAssertionEncryptionAlgorithmUri()); + resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_KEY_ENCRYPTION_ALGORITHM, serviceProviderDO + .getKeyEncryptionAlgorithmUri()); + if (serviceProviderDO.getNameIdClaimUri() != null + && serviceProviderDO.getNameIdClaimUri().trim().length() > 0) { + resource.addProperty( + IdentityRegistryResources.PROP_SAML_SSO_ENABLE_NAMEID_CLAIMURI, + "true"); + resource.addProperty( + IdentityRegistryResources.PROP_SAML_SSO_NAMEID_CLAIMURI, + serviceProviderDO.getNameIdClaimUri()); + } else { + resource.addProperty( + IdentityRegistryResources.PROP_SAML_SSO_ENABLE_NAMEID_CLAIMURI, + "false"); + } + + String doSingleLogout = String.valueOf(serviceProviderDO.isDoSingleLogout()); + resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_DO_SINGLE_LOGOUT, doSingleLogout); + if (serviceProviderDO.isDoSingleLogout()) { + if (StringUtils.isNotBlank(serviceProviderDO.getSloResponseURL())) { + resource.addProperty(IdentityRegistryResources.PROP_SAML_SLO_RESPONSE_URL, + serviceProviderDO.getSloResponseURL()); + } + if (StringUtils.isNotBlank(serviceProviderDO.getSloRequestURL())) { + resource.addProperty(IdentityRegistryResources.PROP_SAML_SLO_REQUEST_URL, + serviceProviderDO.getSloRequestURL()); + } + // Create doFrontChannelLogout property in the registry. + String doFrontChannelLogout = String.valueOf(serviceProviderDO.isDoFrontChannelLogout()); + resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_DO_FRONT_CHANNEL_LOGOUT, doFrontChannelLogout); + if (serviceProviderDO.isDoFrontChannelLogout()) { + // Create frontChannelLogoutMethod property in the registry. + resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_FRONT_CHANNEL_LOGOUT_BINDING, + serviceProviderDO.getFrontChannelLogoutBinding()); + } + } + + String doSignResponse = String.valueOf(serviceProviderDO.isDoSignResponse()); + resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_DO_SIGN_RESPONSE, + doSignResponse); + String isAssertionQueryRequestProfileEnabled = String.valueOf(serviceProviderDO + .isAssertionQueryRequestProfileEnabled()); + resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_ASSERTION_QUERY_REQUEST_PROFILE_ENABLED, + isAssertionQueryRequestProfileEnabled); + String supportedAssertionQueryRequestTypes = serviceProviderDO.getSupportedAssertionQueryRequestTypes(); + resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_SUPPORTED_ASSERTION_QUERY_REQUEST_TYPES, + supportedAssertionQueryRequestTypes); + String isEnableSAML2ArtifactBinding = String.valueOf(serviceProviderDO + .isEnableSAML2ArtifactBinding()); + resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_ENABLE_SAML2_ARTIFACT_BINDING, + isEnableSAML2ArtifactBinding); + String doSignAssertions = String.valueOf(serviceProviderDO.isDoSignAssertions()); + resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_DO_SIGN_ASSERTIONS, + doSignAssertions); + String isSamlECP = String.valueOf(serviceProviderDO.isSamlECP()); + resource.addProperty(IdentityRegistryResources.PROP_SAML_ENABLE_ECP, + isSamlECP); + if (CollectionUtils.isNotEmpty(serviceProviderDO.getRequestedClaimsList())) { + resource.setProperty(IdentityRegistryResources.PROP_SAML_SSO_REQUESTED_CLAIMS, + serviceProviderDO.getRequestedClaimsList()); + } + if (serviceProviderDO.getAttributeConsumingServiceIndex() != null) { + resource.addProperty( + IdentityRegistryResources.PROP_SAML_SSO_ATTRIB_CONSUMING_SERVICE_INDEX, + serviceProviderDO.getAttributeConsumingServiceIndex()); + } + if (CollectionUtils.isNotEmpty(serviceProviderDO.getRequestedAudiencesList())) { + resource.setProperty(IdentityRegistryResources.PROP_SAML_SSO_REQUESTED_AUDIENCES, + serviceProviderDO.getRequestedAudiencesList()); + } + if (CollectionUtils.isNotEmpty(serviceProviderDO.getRequestedRecipientsList())) { + resource.setProperty(IdentityRegistryResources.PROP_SAML_SSO_REQUESTED_RECIPIENTS, + serviceProviderDO.getRequestedRecipientsList()); + } + + String enableAttributesByDefault = String.valueOf(serviceProviderDO.isEnableAttributesByDefault()); + resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_ENABLE_ATTRIBUTES_BY_DEFAULT, + enableAttributesByDefault); + String idPInitSSOEnabled = String.valueOf(serviceProviderDO.isIdPInitSSOEnabled()); + resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_IDP_INIT_SSO_ENABLED, + idPInitSSOEnabled); + String idPInitSLOEnabled = String.valueOf(serviceProviderDO.isIdPInitSLOEnabled()); + resource.addProperty(IdentityRegistryResources.PROP_SAML_SLO_IDP_INIT_SLO_ENABLED, idPInitSLOEnabled); + if (serviceProviderDO.isIdPInitSLOEnabled() && serviceProviderDO.getIdpInitSLOReturnToURLList().size() > 0) { + resource.setProperty(IdentityRegistryResources.PROP_SAML_IDP_INIT_SLO_RETURN_URLS, + serviceProviderDO.getIdpInitSLOReturnToURLList()); + } + String enableEncryptedAssertion = String.valueOf(serviceProviderDO.isDoEnableEncryptedAssertion()); + resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_ENABLE_ENCRYPTED_ASSERTION, + enableEncryptedAssertion); + + String validateSignatureInRequests = String.valueOf(serviceProviderDO.isDoValidateSignatureInRequests()); + resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_VALIDATE_SIGNATURE_IN_REQUESTS, + validateSignatureInRequests); + + String validateSignatureInArtifactResolve = + String.valueOf(serviceProviderDO.isDoValidateSignatureInArtifactResolve()); + resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_VALIDATE_SIGNATURE_IN_ARTIFACT_RESOLVE, + validateSignatureInArtifactResolve); + if (StringUtils.isNotBlank(serviceProviderDO.getIssuerQualifier())) { + resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_ISSUER_QUALIFIER, serviceProviderDO + .getIssuerQualifier()); + } + if (StringUtils.isNotBlank(serviceProviderDO.getIdpEntityIDAlias())) { + resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_IDP_ENTITY_ID_ALIAS, serviceProviderDO + .getIdpEntityIDAlias()); + } + return resource; + } + + /** + * Get the issuer value by removing the qualifier. + * + * @param issuerWithQualifier issuer value saved in the registry. + * @return issuer value given as 'issuer' when configuring SAML SP. + */ + private String getIssuerWithoutQualifier(String issuerWithQualifier) { + + String issuerWithoutQualifier = StringUtils.substringBeforeLast(issuerWithQualifier, + IdentityRegistryResources.QUALIFIER_ID); + return issuerWithoutQualifier; + } + + /** + * Get the issuer value to be added to registry by appending the qualifier. + * + * @param issuer value given as 'issuer' when configuring SAML SP. + * @return issuer value with qualifier appended. + */ + private String getIssuerWithQualifier(String issuer, String qualifier) { + + String issuerWithQualifier = issuer + IdentityRegistryResources.QUALIFIER_ID + qualifier; + return issuerWithQualifier; + } + + @Override + public boolean updateServiceProvider(SAMLSSOServiceProviderDO serviceProviderDO, String currentIssuer, int tenantId) + throws IdentityException { + + Registry registry = getRegistry(tenantId); + if (serviceProviderDO == null || serviceProviderDO.getIssuer() == null || + StringUtils.isBlank(serviceProviderDO.getIssuer())) { + throw new IdentityException("Issuer cannot be found in the provided arguments."); + } + + // If an issuer qualifier value is specified, it is appended to the end of the issuer value. + if (StringUtils.isNotBlank(serviceProviderDO.getIssuerQualifier())) { + serviceProviderDO.setIssuer(getIssuerWithQualifier(serviceProviderDO.getIssuer(), + serviceProviderDO.getIssuerQualifier())); + } + + String currentPath = IdentityRegistryResources.SAML_SSO_SERVICE_PROVIDERS + encodePath(currentIssuer); + String newPath = IdentityRegistryResources.SAML_SSO_SERVICE_PROVIDERS + encodePath(serviceProviderDO.getIssuer()); + + boolean isIssuerUpdated = !StringUtils.equals(currentPath, newPath); + boolean isTransactionStarted = Transaction.isStarted(); + boolean isErrorOccurred = false; + try { + // Check if the updated issuer value already exists. + if (isIssuerUpdated && registry.resourceExists(newPath)) { + if (log.isDebugEnabled()) { + if (StringUtils.isNotBlank(serviceProviderDO.getIssuerQualifier())) { + log.debug("SAML2 Service Provider already exists with the same issuer name " + + getIssuerWithoutQualifier(serviceProviderDO.getIssuer()) + " and qualifier name " + + serviceProviderDO.getIssuerQualifier()); + } else { + log.debug("SAML2 Service Provider already exists with the same issuer name " + + serviceProviderDO.getIssuer()); + } + } + return false; + } + + Resource resource = createResource(serviceProviderDO, registry); + if (!isTransactionStarted) { + registry.beginTransaction(); + } + // Delete the current resource if the issuer value is updated. + if (isIssuerUpdated) { + registry.delete(currentPath); + } + // Update the resource. + // If the issuer is updated, new resource will be created. + // If the issuer is not updated, existing resource will be updated. + registry.put(newPath, resource); + if (log.isDebugEnabled()) { + if (StringUtils.isNotBlank(serviceProviderDO.getIssuerQualifier())) { + log.debug("SAML2 Service Provider " + serviceProviderDO.getIssuer() + " with issuer " + + getIssuerWithoutQualifier(serviceProviderDO.getIssuer()) + " and qualifier " + + serviceProviderDO.getIssuerQualifier() + " is updated successfully."); + } else { + log.debug("SAML2 Service Provider " + serviceProviderDO.getIssuer() + " is updated successfully."); + } + } + return true; + } catch (RegistryException e) { + isErrorOccurred = true; + String msg; + if (StringUtils.isNotBlank(serviceProviderDO.getIssuerQualifier())) { + msg = "Error while updating SAML2 Service Provider for issuer: " + getIssuerWithoutQualifier + (serviceProviderDO.getIssuer()) + " and qualifier name " + serviceProviderDO + .getIssuerQualifier(); + } else { + msg = "Error while updating SAML2 Service Provider for issuer: " + serviceProviderDO.getIssuer(); + } + log.error(msg, e); + throw new IdentityException(msg, e); + } finally { + commitOrRollbackTransaction(isErrorOccurred, registry); + } + } + + @Override + public SAMLSSOServiceProviderDO[] getServiceProviders(int tenantId) throws IdentityException { + + Registry registry = getRegistry(tenantId); + List serviceProvidersList = new ArrayList<>(); + try { + if (registry.resourceExists(IdentityRegistryResources.SAML_SSO_SERVICE_PROVIDERS)) { + Resource samlSSOServiceProvidersResource = registry.get(IdentityRegistryResources + .SAML_SSO_SERVICE_PROVIDERS); + if (samlSSOServiceProvidersResource instanceof Collection) { + Collection samlSSOServiceProvidersCollection = (Collection) samlSSOServiceProvidersResource; + String[] resources = samlSSOServiceProvidersCollection.getChildren(); + for (String resource : resources) { + getChildResources(resource, serviceProvidersList, registry); + } + } + } + } catch (RegistryException e) { + log.error("Error reading Service Providers from Registry", e); + throw IdentityException.error("Error reading Service Providers from Registry", e); + } + return serviceProvidersList.toArray(new SAMLSSOServiceProviderDO[serviceProvidersList.size()]); + } + + @Override + public boolean removeServiceProvider(String issuer, int tenantId) throws IdentityException { + + Registry registry = getRegistry(tenantId); + if (issuer == null || StringUtils.isEmpty(issuer.trim())) { + throw new IllegalArgumentException("Trying to delete issuer \'" + issuer + "\'"); + } + + String path = IdentityRegistryResources.SAML_SSO_SERVICE_PROVIDERS + encodePath(issuer); + boolean isTransactionStarted = Transaction.isStarted(); + boolean isErrorOccurred = false; + try { + if (!registry.resourceExists(path)) { + if (log.isDebugEnabled()) { + log.debug("Registry resource does not exist for the path: " + path); + } + return false; + } + + // Since we are getting a global registry object, better to check whether this is a task inside already + // started transaction. + if (!isTransactionStarted) { + registry.beginTransaction(); + } + registry.delete(path); + return true; + } catch (RegistryException e) { + isErrorOccurred = true; + String msg = "Error removing the service provider from the registry with name: " + issuer; + log.error(msg, e); + throw IdentityException.error(msg, e); + } finally { + commitOrRollbackTransaction(isErrorOccurred, registry); + } + } + + @Override + public SAMLSSOServiceProviderDO getServiceProvider(String issuer, int tenantId) throws IdentityException { + + Registry registry = getRegistry(tenantId); + String path = IdentityRegistryResources.SAML_SSO_SERVICE_PROVIDERS + encodePath(issuer); + SAMLSSOServiceProviderDO serviceProviderDO = null; + + UserRegistry userRegistry = null; + String tenantDomain = null; + try { + userRegistry = (UserRegistry) registry; + tenantDomain = IdentityTenantUtil.getRealmService().getTenantManager().getDomain(userRegistry. + getTenantId()); + if (registry.resourceExists(path)) { + serviceProviderDO = resourceToObject(registry.get(path)); + + // Load the certificate stored in the database, if signature validation is enabled.. + if (serviceProviderDO.isDoValidateSignatureInRequests() || + serviceProviderDO.isDoValidateSignatureInArtifactResolve() || + serviceProviderDO.isDoEnableEncryptedAssertion()) { + Tenant tenant = new Tenant(); + tenant.setDomain(tenantDomain); + tenant.setId(userRegistry.getTenantId()); + + serviceProviderDO.setX509Certificate(getApplicationCertificate(serviceProviderDO, tenant)); + } + serviceProviderDO.setTenantDomain(tenantDomain); + } + } catch (RegistryException e) { + throw IdentityException.error("Error occurred while checking if resource path \'" + path + "\' exists in " + + "registry for tenant domain : " + tenantDomain, e); + } catch (UserStoreException e) { + throw IdentityException.error("Error occurred while getting tenant domain from tenant ID : " + + userRegistry.getTenantId(), e); + } catch (SQLException e) { + throw IdentityException.error(String.format("An error occurred while getting the " + + "application certificate id for validating the requests from the issuer '%s'", issuer), e); + } catch (CertificateRetrievingException e) { + throw IdentityException.error(String.format("An error occurred while getting the " + + "application certificate for validating the requests from the issuer '%s'", issuer), e); + } + return serviceProviderDO; + } + + /** + * Returns the {@link java.security.cert.Certificate} which should used to validate the requests + * for the given service provider. + * + * @param serviceProviderDO + * @param tenant + * @return + * @throws SQLException + * @throws CertificateRetrievingException + */ + private X509Certificate getApplicationCertificate(SAMLSSOServiceProviderDO serviceProviderDO, Tenant tenant) + throws SQLException, CertificateRetrievingException { + + // Check whether there is a certificate stored against the service provider (in the database) + int applicationCertificateId = getApplicationCertificateId(serviceProviderDO.getIssuer(), tenant.getId()); + + CertificateRetriever certificateRetriever; + String certificateIdentifier; + if (applicationCertificateId != -1) { + certificateRetriever = new DatabaseCertificateRetriever(); + certificateIdentifier = Integer.toString(applicationCertificateId); + } else { + certificateRetriever = new KeyStoreCertificateRetriever(); + certificateIdentifier = serviceProviderDO.getCertAlias(); + } + + return certificateRetriever.getCertificate(certificateIdentifier, tenant); + } + + /** + * Returns the certificate reference ID for the given issuer (Service Provider) if there is one. + * + * @param issuer + * @return + * @throws SQLException + */ + private int getApplicationCertificateId(String issuer, int tenantId) throws SQLException { + + try { + String sqlStmt = isH2DB() ? QUERY_TO_GET_APPLICATION_CERTIFICATE_ID_H2 : + QUERY_TO_GET_APPLICATION_CERTIFICATE_ID; + try (Connection connection = IdentityDatabaseUtil.getDBConnection(false); + PreparedStatement statementToGetApplicationCertificate = + connection.prepareStatement(sqlStmt)) { + statementToGetApplicationCertificate.setString(1, CERTIFICATE_PROPERTY_NAME); + statementToGetApplicationCertificate.setString(2, issuer); + statementToGetApplicationCertificate.setInt(3, tenantId); + + try (ResultSet queryResults = statementToGetApplicationCertificate.executeQuery()) { + if (queryResults.next()) { + return queryResults.getInt(1); + } + } + } + return -1; + } catch (DataAccessException e) { + String errorMsg = "Error while retrieving application certificate data for issuer: " + issuer + + " and tenant Id: " + tenantId; + throw new SQLException(errorMsg, e); + } + } + + @Override + public boolean isServiceProviderExists(String issuer, int tenantId) throws IdentityException { + + Registry registry = getRegistry(tenantId); + String path = IdentityRegistryResources.SAML_SSO_SERVICE_PROVIDERS + encodePath(issuer); + try { + return registry.resourceExists(path); + } catch (RegistryException e) { + throw IdentityException.error("Error occurred while checking if resource path \'" + path + "\' exists in " + + "registry"); + } + } + + private String encodePath(String path) { + String encodedStr = new String(Base64.encodeBase64(path.getBytes())); + return encodedStr.replace("=", ""); + } + + @Override + public SAMLSSOServiceProviderDO uploadServiceProvider(SAMLSSOServiceProviderDO serviceProviderDO, int tenantId) + throws IdentityException { + + Registry registry = getRegistry(tenantId); + if (serviceProviderDO == null || serviceProviderDO.getIssuer() == null) { + throw new IdentityException("Issuer cannot be found in the provided arguments."); + } + + if (StringUtils.isNotBlank(serviceProviderDO.getIssuerQualifier())) { + serviceProviderDO.setIssuer(getIssuerWithQualifier(serviceProviderDO.getIssuer(), + serviceProviderDO.getIssuerQualifier())); + } + + if (serviceProviderDO.getDefaultAssertionConsumerUrl() == null) { + throw new IdentityException("No default assertion consumer URL provided for service provider :" + + serviceProviderDO.getIssuer()); + } + + String path = IdentityRegistryResources.SAML_SSO_SERVICE_PROVIDERS + encodePath(serviceProviderDO.getIssuer()); + + boolean isTransactionStarted = Transaction.isStarted(); + boolean isErrorOccurred = false; + try { + if (registry.resourceExists(path)) { + if (log.isDebugEnabled()) { + if (StringUtils.isNotBlank(serviceProviderDO.getIssuerQualifier())) { + log.debug("SAML2 Service Provider already exists with the same issuer name " + + getIssuerWithoutQualifier(serviceProviderDO.getIssuer()) + " and qualifier name " + + serviceProviderDO.getIssuerQualifier()); + } else { + log.debug("SAML2 Service Provider already exists with the same issuer name " + + serviceProviderDO.getIssuer()); + } + } + throw IdentityException.error("A Service Provider already exists."); + } + + if (!isTransactionStarted) { + registry.beginTransaction(); + } + + Resource resource = createResource(serviceProviderDO, registry); + registry.put(path, resource); + if (log.isDebugEnabled()) { + if (StringUtils.isNotBlank(serviceProviderDO.getIssuerQualifier())) { + log.debug("SAML2 Service Provider " + serviceProviderDO.getIssuer() + " with issuer " + + getIssuerWithoutQualifier(serviceProviderDO.getIssuer()) + " and qualifier " + + serviceProviderDO.getIssuerQualifier() + " is added successfully."); + } else { + log.debug("SAML2 Service Provider " + serviceProviderDO.getIssuer() + " is added successfully."); + } + } + return serviceProviderDO; + } catch (RegistryException e) { + isErrorOccurred = true; + throw IdentityException.error("Error while adding Service Provider.", e); + } finally { + commitOrRollbackTransaction(isErrorOccurred, registry); + } + } + + /** + * Commit or rollback the registry operation depends on the error condition. + * @param isErrorOccurred Identifier for error transactions. + * @throws IdentityException Error while committing or running rollback on the transaction. + */ + private void commitOrRollbackTransaction(boolean isErrorOccurred, Registry registry) throws IdentityException { + + try { + // Rollback the transaction if there is an error, Otherwise try to commit. + if (isErrorOccurred) { + registry.rollbackTransaction(); + } else { + registry.commitTransaction(); + } + } catch (RegistryException ex) { + throw new IdentityException("Error occurred while trying to commit or rollback the registry operation.", ex); + } + } + + /** + * This helps to find resources in a recursive manner. + * + * @param parentResource parent resource Name. + * @param serviceProviderList child resource list. + * @throws RegistryException + */ + private void getChildResources(String parentResource, List serviceProviderList, + Registry registry) throws RegistryException { + + if (registry.resourceExists(parentResource)) { + Resource resource = registry.get(parentResource); + if (resource instanceof Collection) { + Collection collection = (Collection) resource; + String[] resources = collection.getChildren(); + for (String res : resources) { + getChildResources(res, serviceProviderList, registry); + } + } else { + serviceProviderList.add(resourceToObject(resource)); + } + } + } + + private Registry getRegistry(int tenantId) throws IdentityException { + + try { + Registry registry = IdentityTenantUtil.getRegistryService().getConfigSystemRegistry(tenantId); + return registry; + } catch (RegistryException e) { + throw new IdentityException("Error while retrieving registry", e); + } + } +} diff --git a/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/dao/SAMLSSOServiceProviderDAO.java b/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/dao/SAMLSSOServiceProviderDAO.java index 67121c02db9b..b46d705f582d 100644 --- a/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/dao/SAMLSSOServiceProviderDAO.java +++ b/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/dao/SAMLSSOServiceProviderDAO.java @@ -1,855 +1,100 @@ /* - * Copyright 2005-2007 WSO2, Inc. (http://wso2.com) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. + * Copyright (c) (2005-2023), 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. + * + * 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.core.dao; -import org.apache.commons.codec.binary.Base64; -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.carbon.database.utils.jdbc.exceptions.DataAccessException; import org.wso2.carbon.identity.base.IdentityException; -import org.wso2.carbon.identity.core.CertificateRetriever; -import org.wso2.carbon.identity.core.CertificateRetrievingException; -import org.wso2.carbon.identity.core.DatabaseCertificateRetriever; -import org.wso2.carbon.identity.core.IdentityRegistryResources; -import org.wso2.carbon.identity.core.KeyStoreCertificateRetriever; import org.wso2.carbon.identity.core.model.SAMLSSOServiceProviderDO; -import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; -import org.wso2.carbon.identity.core.util.IdentityTenantUtil; -import org.wso2.carbon.registry.core.Collection; -import org.wso2.carbon.registry.core.Registry; -import org.wso2.carbon.registry.core.Resource; -import org.wso2.carbon.registry.core.exceptions.RegistryException; -import org.wso2.carbon.registry.core.jdbc.utils.Transaction; -import org.wso2.carbon.registry.core.session.UserRegistry; -import org.wso2.carbon.user.api.Tenant; -import org.wso2.carbon.user.api.UserStoreException; -import java.security.cert.X509Certificate; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -import static org.wso2.carbon.identity.core.util.JdbcUtils.isH2DB; - -public class SAMLSSOServiceProviderDAO extends AbstractDAO { - - private static final String CERTIFICATE_PROPERTY_NAME = "CERTIFICATE"; - private static final String QUERY_TO_GET_APPLICATION_CERTIFICATE_ID = "SELECT " + - "META.VALUE FROM SP_INBOUND_AUTH INBOUND, SP_APP SP, SP_METADATA META WHERE SP.ID = INBOUND.APP_ID AND " + - "SP.ID = META.SP_ID AND META.NAME = ? AND INBOUND.INBOUND_AUTH_KEY = ? AND META.TENANT_ID = ?"; - - private static final String QUERY_TO_GET_APPLICATION_CERTIFICATE_ID_H2 = "SELECT " + - "META.`VALUE` FROM SP_INBOUND_AUTH INBOUND, SP_APP SP, SP_METADATA META WHERE SP.ID = INBOUND.APP_ID AND " + - "SP.ID = META.SP_ID AND META.NAME = ? AND INBOUND.INBOUND_AUTH_KEY = ? AND META.TENANT_ID = ?"; - - private static Log log = LogFactory.getLog(SAMLSSOServiceProviderDAO.class); - - public SAMLSSOServiceProviderDAO(Registry registry) { - this.registry = registry; - } - - protected SAMLSSOServiceProviderDO resourceToObject(Resource resource) { - SAMLSSOServiceProviderDO serviceProviderDO = new SAMLSSOServiceProviderDO(); - serviceProviderDO.setIssuer(resource - .getProperty(IdentityRegistryResources.PROP_SAML_SSO_ISSUER)); - serviceProviderDO.setAssertionConsumerUrls(resource.getPropertyValues( - IdentityRegistryResources.PROP_SAML_SSO_ASSERTION_CONS_URLS)); - serviceProviderDO.setDefaultAssertionConsumerUrl(resource.getProperty( - IdentityRegistryResources.PROP_DEFAULT_SAML_SSO_ASSERTION_CONS_URL)); - serviceProviderDO.setCertAlias(resource - .getProperty(IdentityRegistryResources.PROP_SAML_SSO_ISSUER_CERT_ALIAS)); - - if (StringUtils.isNotEmpty(resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_SIGNING_ALGORITHM))) { - serviceProviderDO.setSigningAlgorithmUri(resource.getProperty(IdentityRegistryResources - .PROP_SAML_SSO_SIGNING_ALGORITHM)); - } - - if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_ASSERTION_QUERY_REQUEST_PROFILE_ENABLED) != - null) { - serviceProviderDO.setAssertionQueryRequestProfileEnabled(Boolean.valueOf(resource.getProperty( - IdentityRegistryResources.PROP_SAML_SSO_ASSERTION_QUERY_REQUEST_PROFILE_ENABLED).trim())); - } - - if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_SUPPORTED_ASSERTION_QUERY_REQUEST_TYPES) != - null) { - serviceProviderDO.setSupportedAssertionQueryRequestTypes(resource.getProperty( - IdentityRegistryResources.PROP_SAML_SSO_SUPPORTED_ASSERTION_QUERY_REQUEST_TYPES).trim()); - } - - if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_ENABLE_SAML2_ARTIFACT_BINDING) != - null) { - serviceProviderDO.setEnableSAML2ArtifactBinding(Boolean.valueOf(resource.getProperty( - IdentityRegistryResources.PROP_SAML_SSO_ENABLE_SAML2_ARTIFACT_BINDING).trim())); - } - - if (StringUtils.isNotEmpty(resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_DIGEST_ALGORITHM))) { - serviceProviderDO.setDigestAlgorithmUri(resource.getProperty(IdentityRegistryResources - .PROP_SAML_SSO_DIGEST_ALGORITHM)); - } - - if (StringUtils.isNotEmpty(resource.getProperty(IdentityRegistryResources - .PROP_SAML_SSO_ASSERTION_ENCRYPTION_ALGORITHM))) { - serviceProviderDO.setAssertionEncryptionAlgorithmUri(resource.getProperty(IdentityRegistryResources - .PROP_SAML_SSO_ASSERTION_ENCRYPTION_ALGORITHM)); - } - - if (StringUtils.isNotEmpty(resource.getProperty(IdentityRegistryResources - .PROP_SAML_SSO_KEY_ENCRYPTION_ALGORITHM))) { - serviceProviderDO.setKeyEncryptionAlgorithmUri(resource.getProperty(IdentityRegistryResources - .PROP_SAML_SSO_KEY_ENCRYPTION_ALGORITHM)); - } - - if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_DO_SINGLE_LOGOUT) != null) { - serviceProviderDO.setDoSingleLogout(Boolean.valueOf(resource.getProperty( - IdentityRegistryResources.PROP_SAML_SSO_DO_SINGLE_LOGOUT).trim())); - } - - if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_NAMEID_FORMAT) != null) { - serviceProviderDO.setNameIDFormat(resource. - getProperty(IdentityRegistryResources.PROP_SAML_SSO_NAMEID_FORMAT)); - } - - if (resource - .getProperty(IdentityRegistryResources.PROP_SAML_SSO_ENABLE_NAMEID_CLAIMURI) != null) { - if (Boolean.valueOf(resource.getProperty( - IdentityRegistryResources.PROP_SAML_SSO_ENABLE_NAMEID_CLAIMURI).trim())) { - serviceProviderDO.setNameIdClaimUri(resource. - getProperty(IdentityRegistryResources.PROP_SAML_SSO_NAMEID_CLAIMURI)); - } - } - - serviceProviderDO.setLoginPageURL(resource. - getProperty(IdentityRegistryResources.PROP_SAML_SSO_LOGIN_PAGE_URL)); - - if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_DO_SIGN_RESPONSE) != null) { - serviceProviderDO.setDoSignResponse(Boolean.valueOf(resource.getProperty( - IdentityRegistryResources.PROP_SAML_SSO_DO_SIGN_RESPONSE).trim())); - } - - if (serviceProviderDO.isDoSingleLogout()) { - serviceProviderDO.setSloResponseURL(resource.getProperty(IdentityRegistryResources - .PROP_SAML_SLO_RESPONSE_URL)); - serviceProviderDO.setSloRequestURL(resource.getProperty(IdentityRegistryResources - .PROP_SAML_SLO_REQUEST_URL)); - // Check front channel logout enable. - if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_DO_FRONT_CHANNEL_LOGOUT) != null) { - serviceProviderDO.setDoFrontChannelLogout(Boolean.valueOf(resource.getProperty( - IdentityRegistryResources.PROP_SAML_SSO_DO_FRONT_CHANNEL_LOGOUT).trim())); - if (serviceProviderDO.isDoFrontChannelLogout()) { - if (resource.getProperty(IdentityRegistryResources. - PROP_SAML_SSO_FRONT_CHANNEL_LOGOUT_BINDING) != null) { - serviceProviderDO.setFrontChannelLogoutBinding(resource.getProperty( - IdentityRegistryResources.PROP_SAML_SSO_FRONT_CHANNEL_LOGOUT_BINDING)); - } else { - // Default is redirect-binding. - serviceProviderDO.setFrontChannelLogoutBinding(IdentityRegistryResources - .DEFAULT_FRONT_CHANNEL_LOGOUT_BINDING); - } - - } - } - } - - if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_DO_SIGN_ASSERTIONS) != null) { - serviceProviderDO.setDoSignAssertions(Boolean.valueOf(resource.getProperty( - IdentityRegistryResources.PROP_SAML_SSO_DO_SIGN_ASSERTIONS).trim())); - } - - if (resource.getProperty(IdentityRegistryResources.PROP_SAML_ENABLE_ECP) != null) { - serviceProviderDO.setSamlECP(Boolean.valueOf(resource.getProperty( - IdentityRegistryResources.PROP_SAML_ENABLE_ECP).trim())); - } - - if (resource - .getProperty(IdentityRegistryResources.PROP_SAML_SSO_ATTRIB_CONSUMING_SERVICE_INDEX) != null) { - serviceProviderDO - .setAttributeConsumingServiceIndex(resource - .getProperty(IdentityRegistryResources.PROP_SAML_SSO_ATTRIB_CONSUMING_SERVICE_INDEX)); - } else { - // Specific DB's (like oracle) returns empty strings as null. - serviceProviderDO.setAttributeConsumingServiceIndex(""); - } - - if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_REQUESTED_CLAIMS) != null) { - serviceProviderDO.setRequestedClaims(resource - .getPropertyValues(IdentityRegistryResources.PROP_SAML_SSO_REQUESTED_CLAIMS)); - } - - if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_REQUESTED_AUDIENCES) != null) { - serviceProviderDO.setRequestedAudiences(resource - .getPropertyValues(IdentityRegistryResources.PROP_SAML_SSO_REQUESTED_AUDIENCES)); - } - - if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_REQUESTED_RECIPIENTS) != null) { - serviceProviderDO.setRequestedRecipients(resource - .getPropertyValues(IdentityRegistryResources.PROP_SAML_SSO_REQUESTED_RECIPIENTS)); - } - - if (resource - .getProperty(IdentityRegistryResources.PROP_SAML_SSO_ENABLE_ATTRIBUTES_BY_DEFAULT) != null) { - String enableAttrByDefault = resource - .getProperty(IdentityRegistryResources.PROP_SAML_SSO_ENABLE_ATTRIBUTES_BY_DEFAULT); - serviceProviderDO.setEnableAttributesByDefault(Boolean.valueOf(enableAttrByDefault)); - } - if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_IDP_INIT_SSO_ENABLED) != null) { - serviceProviderDO.setIdPInitSSOEnabled(Boolean.valueOf(resource.getProperty( - IdentityRegistryResources.PROP_SAML_SSO_IDP_INIT_SSO_ENABLED).trim())); - } - if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SLO_IDP_INIT_SLO_ENABLED) != null) { - serviceProviderDO.setIdPInitSLOEnabled(Boolean.valueOf(resource.getProperty( - IdentityRegistryResources.PROP_SAML_SLO_IDP_INIT_SLO_ENABLED).trim())); - if (serviceProviderDO.isIdPInitSLOEnabled() && resource.getProperty( - IdentityRegistryResources.PROP_SAML_IDP_INIT_SLO_RETURN_URLS) != null) { - serviceProviderDO.setIdpInitSLOReturnToURLs(resource.getPropertyValues( - IdentityRegistryResources.PROP_SAML_IDP_INIT_SLO_RETURN_URLS)); - } - } - if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_ENABLE_ENCRYPTED_ASSERTION) != null) { - serviceProviderDO.setDoEnableEncryptedAssertion(Boolean.valueOf(resource.getProperty( - IdentityRegistryResources.PROP_SAML_SSO_ENABLE_ENCRYPTED_ASSERTION).trim())); - } - if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_VALIDATE_SIGNATURE_IN_REQUESTS) != null) { - serviceProviderDO.setDoValidateSignatureInRequests(Boolean.valueOf(resource.getProperty( - IdentityRegistryResources.PROP_SAML_SSO_VALIDATE_SIGNATURE_IN_REQUESTS).trim())); - } - if (resource.getProperty( - IdentityRegistryResources.PROP_SAML_SSO_VALIDATE_SIGNATURE_IN_ARTIFACT_RESOLVE) != null) { - serviceProviderDO.setDoValidateSignatureInArtifactResolve(Boolean.valueOf(resource.getProperty( - IdentityRegistryResources.PROP_SAML_SSO_VALIDATE_SIGNATURE_IN_ARTIFACT_RESOLVE).trim())); - } - if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_ISSUER_QUALIFIER) != null) { - serviceProviderDO.setIssuerQualifier(resource - .getProperty(IdentityRegistryResources.PROP_SAML_SSO_ISSUER_QUALIFIER)); - } - if (resource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_IDP_ENTITY_ID_ALIAS) != null) { - serviceProviderDO.setIdpEntityIDAlias(resource.getProperty(IdentityRegistryResources - .PROP_SAML_SSO_IDP_ENTITY_ID_ALIAS)); - } - return serviceProviderDO; - } +/** + * This interface is used to manage the SAML SSO service providers. + */ +public interface SAMLSSOServiceProviderDAO { /** * Add the service provider information to the registry. + * * @param serviceProviderDO Service provider information object. + * @param tenantId Tenant Id. * @return True if addition successful. * @throws IdentityException Error while persisting to the registry. */ - public boolean addServiceProvider(SAMLSSOServiceProviderDO serviceProviderDO) throws IdentityException { - - if (serviceProviderDO == null || serviceProviderDO.getIssuer() == null || - StringUtils.isBlank(serviceProviderDO.getIssuer())) { - throw new IdentityException("Issuer cannot be found in the provided arguments."); - } - - // If an issuer qualifier value is specified, it is appended to the end of the issuer value. - if (StringUtils.isNotBlank(serviceProviderDO.getIssuerQualifier())) { - serviceProviderDO.setIssuer(getIssuerWithQualifier(serviceProviderDO.getIssuer(), - serviceProviderDO.getIssuerQualifier())); - } - - String path = IdentityRegistryResources.SAML_SSO_SERVICE_PROVIDERS + encodePath(serviceProviderDO.getIssuer()); - - boolean isTransactionStarted = Transaction.isStarted(); - boolean isErrorOccurred = false; - try { - if (registry.resourceExists(path)) { - if (log.isDebugEnabled()) { - if (StringUtils.isNotBlank(serviceProviderDO.getIssuerQualifier())) { - log.debug("SAML2 Service Provider already exists with the same issuer name " - + getIssuerWithoutQualifier(serviceProviderDO.getIssuer()) + " and qualifier name " - + serviceProviderDO.getIssuerQualifier()); - } else { - log.debug("SAML2 Service Provider already exists with the same issuer name " - + serviceProviderDO.getIssuer()); - } - } - return false; - } - - Resource resource = createResource(serviceProviderDO); - if (!isTransactionStarted) { - registry.beginTransaction(); - } - registry.put(path, resource); - if (log.isDebugEnabled()) { - if (StringUtils.isNotBlank(serviceProviderDO.getIssuerQualifier())) { - log.debug("SAML2 Service Provider " + serviceProviderDO.getIssuer() + " with issuer " - + getIssuerWithoutQualifier(serviceProviderDO.getIssuer()) + " and qualifier " + - serviceProviderDO.getIssuerQualifier() + " is added successfully."); - } else { - log.debug("SAML2 Service Provider " + serviceProviderDO.getIssuer() + " is added successfully."); - } - } - return true; - } catch (RegistryException e) { - isErrorOccurred = true; - String msg; - if (StringUtils.isNotBlank(serviceProviderDO.getIssuerQualifier())) { - msg = "Error while adding SAML2 Service Provider for issuer: " + getIssuerWithoutQualifier - (serviceProviderDO.getIssuer()) + " and qualifier name " + serviceProviderDO - .getIssuerQualifier(); - } else { - msg = "Error while adding SAML2 Service Provider for issuer: " + serviceProviderDO.getIssuer(); - } - log.error(msg, e); - throw IdentityException.error(msg, e); - } finally { - commitOrRollbackTransaction(isErrorOccurred); - } - } - - private Resource createResource(SAMLSSOServiceProviderDO serviceProviderDO) throws RegistryException { - Resource resource; - resource = registry.newResource(); - resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_ISSUER, - serviceProviderDO.getIssuer()); - resource.setProperty(IdentityRegistryResources.PROP_SAML_SSO_ASSERTION_CONS_URLS, - serviceProviderDO.getAssertionConsumerUrlList()); - resource.addProperty(IdentityRegistryResources.PROP_DEFAULT_SAML_SSO_ASSERTION_CONS_URL, - serviceProviderDO.getDefaultAssertionConsumerUrl()); - resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_ISSUER_CERT_ALIAS, - serviceProviderDO.getCertAlias()); - resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_LOGIN_PAGE_URL, - serviceProviderDO.getLoginPageURL()); - resource.addProperty( - IdentityRegistryResources.PROP_SAML_SSO_NAMEID_FORMAT, - serviceProviderDO.getNameIDFormat()); - resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_SIGNING_ALGORITHM, serviceProviderDO - .getSigningAlgorithmUri()); - resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_DIGEST_ALGORITHM, serviceProviderDO - .getDigestAlgorithmUri()); - resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_ASSERTION_ENCRYPTION_ALGORITHM, serviceProviderDO - .getAssertionEncryptionAlgorithmUri()); - resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_KEY_ENCRYPTION_ALGORITHM, serviceProviderDO - .getKeyEncryptionAlgorithmUri()); - if (serviceProviderDO.getNameIdClaimUri() != null - && serviceProviderDO.getNameIdClaimUri().trim().length() > 0) { - resource.addProperty( - IdentityRegistryResources.PROP_SAML_SSO_ENABLE_NAMEID_CLAIMURI, - "true"); - resource.addProperty( - IdentityRegistryResources.PROP_SAML_SSO_NAMEID_CLAIMURI, - serviceProviderDO.getNameIdClaimUri()); - } else { - resource.addProperty( - IdentityRegistryResources.PROP_SAML_SSO_ENABLE_NAMEID_CLAIMURI, - "false"); - } - - String doSingleLogout = String.valueOf(serviceProviderDO.isDoSingleLogout()); - resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_DO_SINGLE_LOGOUT, doSingleLogout); - if (serviceProviderDO.isDoSingleLogout()) { - if (StringUtils.isNotBlank(serviceProviderDO.getSloResponseURL())) { - resource.addProperty(IdentityRegistryResources.PROP_SAML_SLO_RESPONSE_URL, - serviceProviderDO.getSloResponseURL()); - } - if (StringUtils.isNotBlank(serviceProviderDO.getSloRequestURL())) { - resource.addProperty(IdentityRegistryResources.PROP_SAML_SLO_REQUEST_URL, - serviceProviderDO.getSloRequestURL()); - } - // Create doFrontChannelLogout property in the registry. - String doFrontChannelLogout = String.valueOf(serviceProviderDO.isDoFrontChannelLogout()); - resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_DO_FRONT_CHANNEL_LOGOUT, doFrontChannelLogout); - if (serviceProviderDO.isDoFrontChannelLogout()) { - // Create frontChannelLogoutMethod property in the registry. - resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_FRONT_CHANNEL_LOGOUT_BINDING, - serviceProviderDO.getFrontChannelLogoutBinding()); - } - } - - String doSignResponse = String.valueOf(serviceProviderDO.isDoSignResponse()); - resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_DO_SIGN_RESPONSE, - doSignResponse); - String isAssertionQueryRequestProfileEnabled = String.valueOf(serviceProviderDO - .isAssertionQueryRequestProfileEnabled()); - resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_ASSERTION_QUERY_REQUEST_PROFILE_ENABLED, - isAssertionQueryRequestProfileEnabled); - String supportedAssertionQueryRequestTypes = serviceProviderDO.getSupportedAssertionQueryRequestTypes(); - resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_SUPPORTED_ASSERTION_QUERY_REQUEST_TYPES, - supportedAssertionQueryRequestTypes); - String isEnableSAML2ArtifactBinding = String.valueOf(serviceProviderDO - .isEnableSAML2ArtifactBinding()); - resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_ENABLE_SAML2_ARTIFACT_BINDING, - isEnableSAML2ArtifactBinding); - String doSignAssertions = String.valueOf(serviceProviderDO.isDoSignAssertions()); - resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_DO_SIGN_ASSERTIONS, - doSignAssertions); - String isSamlECP = String.valueOf(serviceProviderDO.isSamlECP()); - resource.addProperty(IdentityRegistryResources.PROP_SAML_ENABLE_ECP, - isSamlECP); - if (CollectionUtils.isNotEmpty(serviceProviderDO.getRequestedClaimsList())) { - resource.setProperty(IdentityRegistryResources.PROP_SAML_SSO_REQUESTED_CLAIMS, - serviceProviderDO.getRequestedClaimsList()); - } - if (serviceProviderDO.getAttributeConsumingServiceIndex() != null) { - resource.addProperty( - IdentityRegistryResources.PROP_SAML_SSO_ATTRIB_CONSUMING_SERVICE_INDEX, - serviceProviderDO.getAttributeConsumingServiceIndex()); - } - if (CollectionUtils.isNotEmpty(serviceProviderDO.getRequestedAudiencesList())) { - resource.setProperty(IdentityRegistryResources.PROP_SAML_SSO_REQUESTED_AUDIENCES, - serviceProviderDO.getRequestedAudiencesList()); - } - if (CollectionUtils.isNotEmpty(serviceProviderDO.getRequestedRecipientsList())) { - resource.setProperty(IdentityRegistryResources.PROP_SAML_SSO_REQUESTED_RECIPIENTS, - serviceProviderDO.getRequestedRecipientsList()); - } - - String enableAttributesByDefault = String.valueOf(serviceProviderDO.isEnableAttributesByDefault()); - resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_ENABLE_ATTRIBUTES_BY_DEFAULT, - enableAttributesByDefault); - String idPInitSSOEnabled = String.valueOf(serviceProviderDO.isIdPInitSSOEnabled()); - resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_IDP_INIT_SSO_ENABLED, - idPInitSSOEnabled); - String idPInitSLOEnabled = String.valueOf(serviceProviderDO.isIdPInitSLOEnabled()); - resource.addProperty(IdentityRegistryResources.PROP_SAML_SLO_IDP_INIT_SLO_ENABLED, idPInitSLOEnabled); - if (serviceProviderDO.isIdPInitSLOEnabled() && serviceProviderDO.getIdpInitSLOReturnToURLList().size() > 0) { - resource.setProperty(IdentityRegistryResources.PROP_SAML_IDP_INIT_SLO_RETURN_URLS, - serviceProviderDO.getIdpInitSLOReturnToURLList()); - } - String enableEncryptedAssertion = String.valueOf(serviceProviderDO.isDoEnableEncryptedAssertion()); - resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_ENABLE_ENCRYPTED_ASSERTION, - enableEncryptedAssertion); - - String validateSignatureInRequests = String.valueOf(serviceProviderDO.isDoValidateSignatureInRequests()); - resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_VALIDATE_SIGNATURE_IN_REQUESTS, - validateSignatureInRequests); - - String validateSignatureInArtifactResolve = - String.valueOf(serviceProviderDO.isDoValidateSignatureInArtifactResolve()); - resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_VALIDATE_SIGNATURE_IN_ARTIFACT_RESOLVE, - validateSignatureInArtifactResolve); - if (StringUtils.isNotBlank(serviceProviderDO.getIssuerQualifier())) { - resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_ISSUER_QUALIFIER, serviceProviderDO - .getIssuerQualifier()); - } - if (StringUtils.isNotBlank(serviceProviderDO.getIdpEntityIDAlias())) { - resource.addProperty(IdentityRegistryResources.PROP_SAML_SSO_IDP_ENTITY_ID_ALIAS, serviceProviderDO - .getIdpEntityIDAlias()); - } - return resource; - } - - /** - * Get the issuer value by removing the qualifier. - * - * @param issuerWithQualifier issuer value saved in the registry. - * @return issuer value given as 'issuer' when configuring SAML SP. - */ - private String getIssuerWithoutQualifier(String issuerWithQualifier) { - - String issuerWithoutQualifier = StringUtils.substringBeforeLast(issuerWithQualifier, - IdentityRegistryResources.QUALIFIER_ID); - return issuerWithoutQualifier; - } - - /** - * Get the issuer value to be added to registry by appending the qualifier. - * - * @param issuer value given as 'issuer' when configuring SAML SP. - * @return issuer value with qualifier appended. - */ - private String getIssuerWithQualifier(String issuer, String qualifier) { - - String issuerWithQualifier = issuer + IdentityRegistryResources.QUALIFIER_ID + qualifier; - return issuerWithQualifier; - } + boolean addServiceProvider(SAMLSSOServiceProviderDO serviceProviderDO, int tenantId) throws IdentityException; /** * Update the service provider if it exists. * - * @param serviceProviderDO Service provider to be updated. - * @param currentIssuer Issuer of the service provider before the update. + * @param serviceProviderDO Service provider to be updated. + * @param currentIssuer Issuer of the service provider before the update. + * @param tenantId Tenant Id. * @return True if the update is successful. * @throws IdentityException If an error occurs while updating the service provider. */ - public boolean updateServiceProvider(SAMLSSOServiceProviderDO serviceProviderDO, String currentIssuer) - throws IdentityException { - - if (serviceProviderDO == null || serviceProviderDO.getIssuer() == null || - StringUtils.isBlank(serviceProviderDO.getIssuer())) { - throw new IdentityException("Issuer cannot be found in the provided arguments."); - } - - // If an issuer qualifier value is specified, it is appended to the end of the issuer value. - if (StringUtils.isNotBlank(serviceProviderDO.getIssuerQualifier())) { - serviceProviderDO.setIssuer(getIssuerWithQualifier(serviceProviderDO.getIssuer(), - serviceProviderDO.getIssuerQualifier())); - } + boolean updateServiceProvider(SAMLSSOServiceProviderDO serviceProviderDO, String currentIssuer, int tenantId) + throws IdentityException; - String currentPath = IdentityRegistryResources.SAML_SSO_SERVICE_PROVIDERS + encodePath(currentIssuer); - String newPath = IdentityRegistryResources.SAML_SSO_SERVICE_PROVIDERS + encodePath(serviceProviderDO.getIssuer()); - - boolean isIssuerUpdated = !StringUtils.equals(currentPath, newPath); - boolean isTransactionStarted = Transaction.isStarted(); - boolean isErrorOccurred = false; - try { - // Check if the updated issuer value already exists. - if (isIssuerUpdated && registry.resourceExists(newPath)) { - if (log.isDebugEnabled()) { - if (StringUtils.isNotBlank(serviceProviderDO.getIssuerQualifier())) { - log.debug("SAML2 Service Provider already exists with the same issuer name " - + getIssuerWithoutQualifier(serviceProviderDO.getIssuer()) + " and qualifier name " - + serviceProviderDO.getIssuerQualifier()); - } else { - log.debug("SAML2 Service Provider already exists with the same issuer name " - + serviceProviderDO.getIssuer()); - } - } - return false; - } - - Resource resource = createResource(serviceProviderDO); - if (!isTransactionStarted) { - registry.beginTransaction(); - } - // Delete the current resource if the issuer value is updated. - if (isIssuerUpdated) { - registry.delete(currentPath); - } - // Update the resource. - // If the issuer is updated, new resource will be created. - // If the issuer is not updated, existing resource will be updated. - registry.put(newPath, resource); - if (log.isDebugEnabled()) { - if (StringUtils.isNotBlank(serviceProviderDO.getIssuerQualifier())) { - log.debug("SAML2 Service Provider " + serviceProviderDO.getIssuer() + " with issuer " - + getIssuerWithoutQualifier(serviceProviderDO.getIssuer()) + " and qualifier " + - serviceProviderDO.getIssuerQualifier() + " is updated successfully."); - } else { - log.debug("SAML2 Service Provider " + serviceProviderDO.getIssuer() + " is updated successfully."); - } - } - return true; - } catch (RegistryException e) { - isErrorOccurred = true; - String msg; - if (StringUtils.isNotBlank(serviceProviderDO.getIssuerQualifier())) { - msg = "Error while updating SAML2 Service Provider for issuer: " + getIssuerWithoutQualifier - (serviceProviderDO.getIssuer()) + " and qualifier name " + serviceProviderDO - .getIssuerQualifier(); - } else { - msg = "Error while updating SAML2 Service Provider for issuer: " + serviceProviderDO.getIssuer(); - } - log.error(msg, e); - throw new IdentityException(msg, e); - } finally { - commitOrRollbackTransaction(isErrorOccurred); - } - } - - public SAMLSSOServiceProviderDO[] getServiceProviders() throws IdentityException { - List serviceProvidersList = new ArrayList<>(); - try { - if (registry.resourceExists(IdentityRegistryResources.SAML_SSO_SERVICE_PROVIDERS)) { - Resource samlSSOServiceProvidersResource = registry.get(IdentityRegistryResources - .SAML_SSO_SERVICE_PROVIDERS); - if (samlSSOServiceProvidersResource instanceof Collection) { - Collection samlSSOServiceProvidersCollection = (Collection) samlSSOServiceProvidersResource; - String[] resources = samlSSOServiceProvidersCollection.getChildren(); - for (String resource : resources) { - getChildResources(resource, serviceProvidersList); - } - } - } - } catch (RegistryException e) { - log.error("Error reading Service Providers from Registry", e); - throw IdentityException.error("Error reading Service Providers from Registry", e); - } - return serviceProvidersList.toArray(new SAMLSSOServiceProviderDO[serviceProvidersList.size()]); - } + /** + * Get all the service providers. + * + * @param tenantId Tenant Id. + * @return Array of service providers. + * @throws IdentityException Error occurred while retrieving the service providers from registry. + */ + SAMLSSOServiceProviderDO[] getServiceProviders(int tenantId) throws IdentityException; /** * Remove the service provider with the given name. + * + * @param issuer Name of the SAML issuer. + * @param tenantId Tenant Id. * @return True if deletion success. - * @param issuer Name of the SAML issuer. * @throws IdentityException Error occurred while removing the SAML service provider from registry. */ - public boolean removeServiceProvider(String issuer) throws IdentityException { - - if (issuer == null || StringUtils.isEmpty(issuer.trim())) { - throw new IllegalArgumentException("Trying to delete issuer \'" + issuer + "\'"); - } - - String path = IdentityRegistryResources.SAML_SSO_SERVICE_PROVIDERS + encodePath(issuer); - boolean isTransactionStarted = Transaction.isStarted(); - boolean isErrorOccurred = false; - try { - if (!registry.resourceExists(path)) { - if (log.isDebugEnabled()) { - log.debug("Registry resource does not exist for the path: " + path); - } - return false; - } - - // Since we are getting a global registry object, better to check whether this is a task inside already - // started transaction. - if (!isTransactionStarted) { - registry.beginTransaction(); - } - registry.delete(path); - return true; - } catch (RegistryException e) { - isErrorOccurred = true; - String msg = "Error removing the service provider from the registry with name: " + issuer; - log.error(msg, e); - throw IdentityException.error(msg, e); - } finally { - commitOrRollbackTransaction(isErrorOccurred); - } - } + boolean removeServiceProvider(String issuer, int tenantId) throws IdentityException; /** * Get the service provider. * - * @param issuer - * @return - * @throws IdentityException + * @param issuer Name of the SAML issuer. + * @param tenantId tenant Id. + * @return Service provider information object. + * @throws IdentityException Error occurred while retrieving the SAML service provider from registry. */ - public SAMLSSOServiceProviderDO getServiceProvider(String issuer) throws IdentityException { - - String path = IdentityRegistryResources.SAML_SSO_SERVICE_PROVIDERS + encodePath(issuer); - SAMLSSOServiceProviderDO serviceProviderDO = null; - - UserRegistry userRegistry = null; - String tenantDomain = null; - try { - userRegistry = (UserRegistry) registry; - tenantDomain = IdentityTenantUtil.getRealmService().getTenantManager().getDomain(userRegistry. - getTenantId()); - if (registry.resourceExists(path)) { - serviceProviderDO = resourceToObject(registry.get(path)); - - // Load the certificate stored in the database, if signature validation is enabled.. - if (serviceProviderDO.isDoValidateSignatureInRequests() || - serviceProviderDO.isDoValidateSignatureInArtifactResolve() || - serviceProviderDO.isDoEnableEncryptedAssertion()) { - Tenant tenant = new Tenant(); - tenant.setDomain(tenantDomain); - tenant.setId(userRegistry.getTenantId()); - - serviceProviderDO.setX509Certificate(getApplicationCertificate(serviceProviderDO, tenant)); - } - serviceProviderDO.setTenantDomain(tenantDomain); - } - } catch (RegistryException e) { - throw IdentityException.error("Error occurred while checking if resource path \'" + path + "\' exists in " + - "registry for tenant domain : " + tenantDomain, e); - } catch (UserStoreException e) { - throw IdentityException.error("Error occurred while getting tenant domain from tenant ID : " + - userRegistry.getTenantId(), e); - } catch (SQLException e) { - throw IdentityException.error(String.format("An error occurred while getting the " + - "application certificate id for validating the requests from the issuer '%s'", issuer), e); - } catch (CertificateRetrievingException e) { - throw IdentityException.error(String.format("An error occurred while getting the " + - "application certificate for validating the requests from the issuer '%s'", issuer), e); - } - return serviceProviderDO; - } + SAMLSSOServiceProviderDO getServiceProvider(String issuer, int tenantId) throws IdentityException; /** - * Returns the {@link java.security.cert.Certificate} which should used to validate the requests - * for the given service provider. + * Check whether the service provider exists. * - * @param serviceProviderDO - * @param tenant - * @return - * @throws SQLException - * @throws CertificateRetrievingException + * @param issuer Name of the SAML issuer. + * @param tenantId Tenant Id. + * @return True if service provider exists. + * @throws IdentityException Error occurred while checking the existence of the SAML service provider. */ - private X509Certificate getApplicationCertificate(SAMLSSOServiceProviderDO serviceProviderDO, Tenant tenant) - throws SQLException, CertificateRetrievingException { - - // Check whether there is a certificate stored against the service provider (in the database) - int applicationCertificateId = getApplicationCertificateId(serviceProviderDO.getIssuer(), tenant.getId()); - - CertificateRetriever certificateRetriever; - String certificateIdentifier; - if (applicationCertificateId != -1) { - certificateRetriever = new DatabaseCertificateRetriever(); - certificateIdentifier = Integer.toString(applicationCertificateId); - } else { - certificateRetriever = new KeyStoreCertificateRetriever(); - certificateIdentifier = serviceProviderDO.getCertAlias(); - } - - return certificateRetriever.getCertificate(certificateIdentifier, tenant); - } + boolean isServiceProviderExists(String issuer, int tenantId) throws IdentityException; /** - * Returns the certificate reference ID for the given issuer (Service Provider) if there is one. + * Upload service Provider using metadata file. * - * @param issuer - * @return - * @throws SQLException - */ - private int getApplicationCertificateId(String issuer, int tenantId) throws SQLException { - - try { - String sqlStmt = isH2DB() ? QUERY_TO_GET_APPLICATION_CERTIFICATE_ID_H2 : - QUERY_TO_GET_APPLICATION_CERTIFICATE_ID; - try (Connection connection = IdentityDatabaseUtil.getDBConnection(false); - PreparedStatement statementToGetApplicationCertificate = - connection.prepareStatement(sqlStmt)) { - statementToGetApplicationCertificate.setString(1, CERTIFICATE_PROPERTY_NAME); - statementToGetApplicationCertificate.setString(2, issuer); - statementToGetApplicationCertificate.setInt(3, tenantId); - - try (ResultSet queryResults = statementToGetApplicationCertificate.executeQuery()) { - if (queryResults.next()) { - return queryResults.getInt(1); - } - } - } - return -1; - } catch (DataAccessException e) { - String errorMsg = "Error while retrieving application certificate data for issuer: " + issuer + - " and tenant Id: " + tenantId; - throw new SQLException(errorMsg, e); - } - } - - public boolean isServiceProviderExists(String issuer) throws IdentityException { - String path = IdentityRegistryResources.SAML_SSO_SERVICE_PROVIDERS + encodePath(issuer); - try { - return registry.resourceExists(path); - } catch (RegistryException e) { - throw IdentityException.error("Error occurred while checking if resource path \'" + path + "\' exists in " + - "registry"); - } - } - - private String encodePath(String path) { - String encodedStr = new String(Base64.encodeBase64(path.getBytes())); - return encodedStr.replace("=", ""); - } - - /** - * Upload service Provider using metadata file.. * @param serviceProviderDO Service provider information object. + * @param tenantId Tenant Id. * @return True if upload success. * @throws IdentityException Error occurred while adding the information to registry. */ - public SAMLSSOServiceProviderDO uploadServiceProvider(SAMLSSOServiceProviderDO serviceProviderDO) throws - IdentityException { - - if (serviceProviderDO == null || serviceProviderDO.getIssuer() == null) { - throw new IdentityException("Issuer cannot be found in the provided arguments."); - } - - if (StringUtils.isNotBlank(serviceProviderDO.getIssuerQualifier())) { - serviceProviderDO.setIssuer(getIssuerWithQualifier(serviceProviderDO.getIssuer(), - serviceProviderDO.getIssuerQualifier())); - } - - if (serviceProviderDO.getDefaultAssertionConsumerUrl() == null) { - throw new IdentityException("No default assertion consumer URL provided for service provider :" + - serviceProviderDO.getIssuer()); - } - - String path = IdentityRegistryResources.SAML_SSO_SERVICE_PROVIDERS + encodePath(serviceProviderDO.getIssuer()); - - boolean isTransactionStarted = Transaction.isStarted(); - boolean isErrorOccurred = false; - try { - if (registry.resourceExists(path)) { - if (log.isDebugEnabled()) { - if (StringUtils.isNotBlank(serviceProviderDO.getIssuerQualifier())) { - log.debug("SAML2 Service Provider already exists with the same issuer name " - + getIssuerWithoutQualifier(serviceProviderDO.getIssuer()) + " and qualifier name " - + serviceProviderDO.getIssuerQualifier()); - } else { - log.debug("SAML2 Service Provider already exists with the same issuer name " - + serviceProviderDO.getIssuer()); - } - } - throw IdentityException.error("A Service Provider already exists."); - } - - if (!isTransactionStarted) { - registry.beginTransaction(); - } - - Resource resource = createResource(serviceProviderDO); - registry.put(path, resource); - if (log.isDebugEnabled()) { - if (StringUtils.isNotBlank(serviceProviderDO.getIssuerQualifier())) { - log.debug("SAML2 Service Provider " + serviceProviderDO.getIssuer() + " with issuer " - + getIssuerWithoutQualifier(serviceProviderDO.getIssuer()) + " and qualifier " + - serviceProviderDO.getIssuerQualifier() + " is added successfully."); - } else { - log.debug("SAML2 Service Provider " + serviceProviderDO.getIssuer() + " is added successfully."); - } - } - return serviceProviderDO; - } catch (RegistryException e) { - isErrorOccurred = true; - throw IdentityException.error("Error while adding Service Provider.", e); - } finally { - commitOrRollbackTransaction(isErrorOccurred); - } - } - - /** - * Commit or rollback the registry operation depends on the error condition. - * @param isErrorOccurred Identifier for error transactions. - * @throws IdentityException Error while committing or running rollback on the transaction. - */ - private void commitOrRollbackTransaction(boolean isErrorOccurred) throws IdentityException { - - try { - // Rollback the transaction if there is an error, Otherwise try to commit. - if (isErrorOccurred) { - registry.rollbackTransaction(); - } else { - registry.commitTransaction(); - } - } catch (RegistryException ex) { - throw new IdentityException("Error occurred while trying to commit or rollback the registry operation.", ex); - } - } - - /** - * This helps to find resources in a recursive manner. - * - * @param parentResource parent resource Name. - * @param serviceProviderList child resource list. - * @throws RegistryException - */ - private void getChildResources(String parentResource, List - serviceProviderList) throws RegistryException { - - if (registry.resourceExists(parentResource)) { - Resource resource = registry.get(parentResource); - if (resource instanceof Collection) { - Collection collection = (Collection) resource; - String[] resources = collection.getChildren(); - for (String res : resources) { - getChildResources(res, serviceProviderList); - } - } else { - serviceProviderList.add(resourceToObject(resource)); - } - } - } + SAMLSSOServiceProviderDO uploadServiceProvider(SAMLSSOServiceProviderDO serviceProviderDO, int tenantId) + throws IdentityException; } diff --git a/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/dao/SAMLServiceProviderPersistenceManagerFactory.java b/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/dao/SAMLServiceProviderPersistenceManagerFactory.java new file mode 100644 index 000000000000..f78fd14290fe --- /dev/null +++ b/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/dao/SAMLServiceProviderPersistenceManagerFactory.java @@ -0,0 +1,58 @@ +/* + * 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.core.dao; + +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.identity.core.util.IdentityUtil; + +/** + * Factory class to create instances of SAMLSSOServiceProviderDAO based on the configured storage type. + */ +public class SAMLServiceProviderPersistenceManagerFactory { + + private static final Log LOG = LogFactory.getLog(SAMLServiceProviderPersistenceManagerFactory.class); + private static String SAML_STORAGE_TYPE = IdentityUtil.getProperty("DataStorageType.SAML"); + private static final String HYBRID = "hybrid"; + private static final String DATABASE = "database"; + + public SAMLSSOServiceProviderDAO getSAMLServiceProviderPersistenceManager() { + + SAMLSSOServiceProviderDAO samlSSOServiceProviderDAO = new RegistrySAMLSSOServiceProviderDAOImpl(); + if (StringUtils.isNotBlank(SAML_STORAGE_TYPE)) { + switch (SAML_STORAGE_TYPE) { + case HYBRID: + // Initialize hybrid SAML storage. + LOG.info("Hybrid SAML storage initialized."); + break; + case DATABASE: + // Initialize JDBC SAML storage. + LOG.info("JDBC based SAML storage initialized."); + break; + } + } + + if (LOG.isDebugEnabled()) { + LOG.debug( + "SAML SSO Service Provider DAO initialized with the type: " + samlSSOServiceProviderDAO.getClass()); + } + return samlSSOServiceProviderDAO; + } +} diff --git a/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/persistence/IdentityPersistenceManager.java b/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/persistence/IdentityPersistenceManager.java index e1d8b461b967..b5b680dd7f29 100644 --- a/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/persistence/IdentityPersistenceManager.java +++ b/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/persistence/IdentityPersistenceManager.java @@ -17,10 +17,12 @@ */ package org.wso2.carbon.identity.core.persistence; +import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.identity.base.IdentityException; import org.wso2.carbon.identity.core.dao.OpenIDAdminDAO; import org.wso2.carbon.identity.core.dao.OpenIDUserDAO; import org.wso2.carbon.identity.core.dao.ParameterDAO; +import org.wso2.carbon.identity.core.dao.SAMLServiceProviderPersistenceManagerFactory; import org.wso2.carbon.identity.core.dao.SAMLSSOServiceProviderDAO; import org.wso2.carbon.identity.core.dao.XMPPSettingsDAO; import org.wso2.carbon.identity.core.model.OpenIDAdminDO; @@ -34,6 +36,9 @@ public class IdentityPersistenceManager { private static IdentityPersistenceManager manager = new IdentityPersistenceManager(); + SAMLServiceProviderPersistenceManagerFactory + samlSSOPersistenceManagerFactory = new SAMLServiceProviderPersistenceManagerFactory(); + SAMLSSOServiceProviderDAO serviceProviderDAO = samlSSOPersistenceManagerFactory.getSAMLServiceProviderPersistenceManager(); private IdentityPersistenceManager() { } @@ -235,9 +240,11 @@ public void removeOpenIDSignUp(Registry registry, UserRealm realm, String openID */ public boolean addServiceProvider(Registry registry, SAMLSSOServiceProviderDO serviceProviderDO) throws IdentityException { - SAMLSSOServiceProviderDAO serviceProviderDAO = new SAMLSSOServiceProviderDAO(registry); - return serviceProviderDAO.addServiceProvider(serviceProviderDO); + + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + return serviceProviderDAO.addServiceProvider(serviceProviderDO, tenantId); } + /** * Upload Service Provider * @@ -246,8 +253,9 @@ public boolean addServiceProvider(Registry registry, SAMLSSOServiceProviderDO se * @throws IdentityException */ public SAMLSSOServiceProviderDO uploadServiceProvider(Registry registry, SAMLSSOServiceProviderDO samlssoServiceProviderDO) throws IdentityException { - SAMLSSOServiceProviderDAO serviceProviderDAO = new SAMLSSOServiceProviderDAO(registry); - return serviceProviderDAO.uploadServiceProvider(samlssoServiceProviderDO); + + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + return serviceProviderDAO.uploadServiceProvider(samlssoServiceProviderDO, tenantId); } /** @@ -258,24 +266,28 @@ public SAMLSSOServiceProviderDO uploadServiceProvider(Registry registry, SAMLSSO */ public SAMLSSOServiceProviderDO[] getServiceProviders(Registry registry) throws IdentityException { - SAMLSSOServiceProviderDAO serviceProviderDOA = new SAMLSSOServiceProviderDAO(registry); - return serviceProviderDOA.getServiceProviders(); + + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + return serviceProviderDAO.getServiceProviders(tenantId); } public boolean removeServiceProvider(Registry registry, String issuer) throws IdentityException { - SAMLSSOServiceProviderDAO serviceProviderDAO = new SAMLSSOServiceProviderDAO(registry); - return serviceProviderDAO.removeServiceProvider(issuer); + + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + return serviceProviderDAO.removeServiceProvider(issuer, tenantId); } public SAMLSSOServiceProviderDO getServiceProvider(Registry registry, String issuer) throws IdentityException { - SAMLSSOServiceProviderDAO serviceProviderDAO = new SAMLSSOServiceProviderDAO(registry); - return serviceProviderDAO.getServiceProvider(issuer); + + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + return serviceProviderDAO.getServiceProvider(issuer, tenantId); } public boolean isServiceProviderExists(Registry registry, String issuer) throws IdentityException { - SAMLSSOServiceProviderDAO serviceProviderDAO = new SAMLSSOServiceProviderDAO(registry); - return serviceProviderDAO.isServiceProviderExists(issuer); + + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + return serviceProviderDAO.isServiceProviderExists(issuer, tenantId); } public void createOrUpdateOpenIDAdmin(Registry registry, OpenIDAdminDO opAdmin) diff --git a/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/util/IdentityKeyStoreResolverConstants.java b/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/util/IdentityKeyStoreResolverConstants.java index def4bdd725d6..795ed078dd6a 100644 --- a/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/util/IdentityKeyStoreResolverConstants.java +++ b/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/util/IdentityKeyStoreResolverConstants.java @@ -41,6 +41,7 @@ public class IdentityKeyStoreResolverConstants { // KeyStore Constants. public static final String KEY_STORE_EXTENSION = ".jks"; + public static final String KEY_STORE_CONTEXT_SEPARATOR = "--"; // Inbound Protocols. public static final String INBOUND_PROTOCOL_OAUTH = "oauth"; @@ -119,6 +120,10 @@ public enum ErrorMessages { ERROR_CODE_ERROR_RETRIEVING_CUSTOM_KEYSTORE_CONFIGURATION( "IKSR-10009", "Error retrieving custom keystore configuration.", "Error occurred when retrieving custom keystore configuration for: %s."), + ERROR_RETRIEVING_TENANT_CONTEXT_PUBLIC_CERTIFICATE_KEYSTORE_NOT_EXIST( + "IKSR-10010", "Error retrieving context public certificate. Keystore doesn't exist.", + "Error occurred when retrieving context certificate for tenant: %s. " + + "Context Keystore doesn't exist."), // Errors occurred within the IdentityKeyStoreResolver ERROR_CODE_INVALID_ARGUMENT( diff --git a/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/util/IdentityKeyStoreResolverUtil.java b/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/util/IdentityKeyStoreResolverUtil.java index 98295af64c9b..da0b99e69bfd 100644 --- a/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/util/IdentityKeyStoreResolverUtil.java +++ b/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/util/IdentityKeyStoreResolverUtil.java @@ -21,6 +21,7 @@ import org.apache.commons.lang.StringUtils; import org.wso2.carbon.core.RegistryResources; import org.wso2.carbon.identity.core.util.IdentityKeyStoreResolverConstants.ErrorMessages; +import org.wso2.carbon.utils.security.KeystoreUtils; import javax.xml.namespace.QName; @@ -38,13 +39,41 @@ public class IdentityKeyStoreResolverUtil { */ public static String buildTenantKeyStoreName(String tenantDomain) throws IdentityKeyStoreResolverException { + return buildTenantKeyStoreName(tenantDomain, null); + } + + /** + * Builds the keystore name for a given tenant domain and context. + * The tenant domain is sanitized by replacing dots (.) with hyphens (-) to ensure compatibility + * with keystore naming conventions. If a context is provided, it is appended to the sanitized + * tenant domain with an underscore (_). The method also appends the standard keystore file + * extension as defined in {@link IdentityKeyStoreResolverConstants}. + * + * @param tenantDomain The domain name of the tenant (e.g., "example.com"). + * @param context The optional context to append to the tenant keystore name. + * @return A sanitized and formatted keystore name for the tenant. + * @throws IdentityKeyStoreResolverException If the tenant domain is null, empty, or invalid. + */ + public static String buildTenantKeyStoreName(String tenantDomain, String context) + throws IdentityKeyStoreResolverException { + + // Validate tenantDomain argument if (StringUtils.isEmpty(tenantDomain)) { throw new IdentityKeyStoreResolverException( ErrorMessages.ERROR_CODE_INVALID_ARGUMENT.getCode(), String.format(ErrorMessages.ERROR_CODE_INVALID_ARGUMENT.getDescription(), "Tenant domain")); } + + // Sanitize tenant domain: replace '.' with '-' String ksName = tenantDomain.trim().replace(".", "-"); - return ksName + IdentityKeyStoreResolverConstants.KEY_STORE_EXTENSION; + + // Append context if provided + if (StringUtils.isNotBlank(context)) { + ksName = buildDomainWithContext(ksName, context); + } + + // Add the keystore extension + return ksName + KeystoreUtils.getKeyStoreFileExtension(tenantDomain); } /** @@ -74,4 +103,16 @@ public static QName getQNameWithIdentityNameSpace(String localPart) { return new QName(IdentityCoreConstants.IDENTITY_DEFAULT_NAMESPACE, localPart); } + + /** + * Concatenates tenantDomain and context with the separator. + * + * @param tenantDomain the key store name + * @param context the context + * @return a concatenated string in the format tenantDomain:context + */ + public static String buildDomainWithContext(String tenantDomain, String context) { + + return tenantDomain + IdentityKeyStoreResolverConstants.KEY_STORE_CONTEXT_SEPARATOR + context; + } } diff --git a/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/util/IdentityUtil.java b/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/util/IdentityUtil.java index 202e7dcac6a1..bf9203020df3 100644 --- a/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/util/IdentityUtil.java +++ b/components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/util/IdentityUtil.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2005-2024, WSO2 LLC. (http://www.wso2.com). * - * WSO2 Inc. licenses this file to you under the Apache License, + * 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 @@ -11,10 +11,11 @@ * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ + package org.wso2.carbon.identity.core.util; import com.ibm.wsdl.util.xml.DOM2Writer; @@ -36,10 +37,13 @@ import org.wso2.carbon.caching.impl.CachingConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.core.util.AdminServicesUtil; +import org.wso2.carbon.core.util.KeyStoreManager; +import org.wso2.carbon.core.util.SignatureUtil; import org.wso2.carbon.core.util.Utils; import org.wso2.carbon.identity.base.IdentityConstants; import org.wso2.carbon.identity.base.IdentityException; import org.wso2.carbon.identity.base.IdentityRuntimeException; +import org.wso2.carbon.identity.core.IdentityKeyStoreResolver; import org.wso2.carbon.identity.core.internal.IdentityCoreServiceComponent; import org.wso2.carbon.identity.core.internal.IdentityCoreServiceDataHolder; import org.wso2.carbon.identity.core.model.IdentityCacheConfig; @@ -73,6 +77,8 @@ import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.PublicKey; import java.security.SecureRandom; import java.security.SignatureException; import java.security.cert.Certificate; @@ -108,6 +114,7 @@ import static org.wso2.carbon.identity.core.util.IdentityCoreConstants.ENCODED_ZERO; import static org.wso2.carbon.identity.core.util.IdentityCoreConstants.INDEXES; import static org.wso2.carbon.identity.core.util.IdentityCoreConstants.USERS_LIST_PER_ROLE_LOWER_BOUND; +import static org.wso2.carbon.identity.core.util.IdentityKeyStoreResolverConstants.ErrorMessages.ERROR_RETRIEVING_TENANT_CONTEXT_PUBLIC_CERTIFICATE_KEYSTORE_NOT_EXIST; public class IdentityUtil { @@ -1962,4 +1969,151 @@ public static boolean isSCIM2UserMaxItemsPerPageEnabled() { } return Boolean.parseBoolean(scim2UserMaxItemsPerPageEnabledProperty); } + + /** + * Validates the provided signature for the given data using the public key of a specified tenant. + * + * The method retrieves the public key for the tenant from the certificate stored in the tenant's keystore. + * If a context is provided, the method attempts to retrieve the certificate within that context. + * + * @param data The data to validate the signature against. + * @param signature The signature to be validated. + * @param tenantDomain The domain name of the tenant whose public key should be used for validation. + * @param context The optional context for retrieving the tenant's certificate (can be null or blank). + * @return True if the signature is valid; false otherwise. + * @throws SignatureException If an error occurs while validating the signature or accessing tenant data. + */ + public static boolean validateSignatureFromTenant(String data, byte[] signature, String tenantDomain, + String context) throws SignatureException { + + // Retrieve tenant ID based on the tenant domain + int tenantId = IdentityTenantUtil.getTenantId(tenantDomain); + try { + // Initialize the tenant's registry + IdentityTenantUtil.initializeRegistry(tenantId); + + // Retrieve the tenant's public key + PublicKey publicKey; + if (StringUtils.isBlank(context)) { + // Fetch certificate without context if context is null or blank + publicKey = IdentityKeyStoreResolver.getInstance() + .getCertificate(tenantDomain, null) + .getPublicKey(); + } else { + try { + // Fetch certificate within the provided context + Certificate certificate = IdentityKeyStoreResolver.getInstance() + .getCertificate(tenantDomain, null, context); + publicKey = certificate.getPublicKey(); + } catch (IdentityKeyStoreResolverException e) { + if (ERROR_RETRIEVING_TENANT_CONTEXT_PUBLIC_CERTIFICATE_KEYSTORE_NOT_EXIST.getCode() + .equals(e.getErrorCode())) { + // Context keystore not exits, hence return validation as false. + return false; + } else { + throw new SignatureException("Error while validating the signature for tenant: " + + tenantDomain, e); + } + } + } + + // Validate the signature using the retrieved public key + return SignatureUtil.validateSignature(data, signature, publicKey); + } catch (IdentityException e) { + // Log and throw an exception if an error occurs + throw new SignatureException("Error while validating the signature for tenant: " + tenantDomain, e); + } + } + + /** + * Validates the signature of the given data for the specified tenant domain. + * + * @param data The data to be verified. + * @param signature The signature to be verified. + * @param tenantDomain The tenant domain to which the data belongs. + * @return true if the signature is valid, false otherwise. + * @throws SignatureException If an error occurs during the signature validation process. + */ + public static boolean validateSignatureFromTenant(String data, byte[] signature, String tenantDomain) + throws SignatureException { + + return validateSignatureFromTenant(data, signature, tenantDomain, null); + } + + /** + * Signs the given data using the private key of the specified tenant. + * + * For super tenant domains, the default private key is used. For other tenants, the method retrieves the private + * key from the tenant's keystore. If a context is provided, it will attempt to retrieve the private key associated + * with that context. + * + * @param data The data to be signed. + * @param tenantDomain The domain name of the tenant whose private key will be used for signing. + * @param context The optional context for retrieving the tenant's private key (can be null or blank). + * @return A byte array containing the signature for the provided data. + * @throws SignatureException If an error occurs while retrieving the private key or signing the data. + */ + public static byte[] signWithTenantKey(String data, String tenantDomain, String context) throws SignatureException { + + // Get tenant ID from tenant domain + int tenantId = IdentityTenantUtil.getTenantId(tenantDomain); + KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(tenantId); + PrivateKey privateKey; + + if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { + try { + String tenantKeyStoreName = IdentityKeyStoreResolverUtil.buildTenantKeyStoreName(tenantDomain, context); + // Retrieve private key from the tenant's keystore + if (StringUtils.isBlank(context)) { + // Retrieve default private key for the super tenant + privateKey = keyStoreManager.getDefaultPrivateKey(); + } else { + privateKey = (PrivateKey) keyStoreManager.getPrivateKey(tenantKeyStoreName, + tenantDomain + + IdentityKeyStoreResolverConstants.KEY_STORE_CONTEXT_SEPARATOR + context); + } + + } catch (Exception e) { + throw new SignatureException(String.format( + IdentityKeyStoreResolverConstants.ErrorMessages.ERROR_CODE_ERROR_RETRIEVING_TENANT_PRIVATE_KEY + .getDescription(), + tenantDomain), e); + } + } else { + try { + // Build tenant keystore name + String tenantKeyStoreName = IdentityKeyStoreResolverUtil.buildTenantKeyStoreName(tenantDomain, context); + + // Initialize the tenant's registry + IdentityTenantUtil.initializeRegistry(tenantId); + + // Retrieve private key from the tenant's keystore + if (StringUtils.isBlank(context)) { + privateKey = (PrivateKey) keyStoreManager.getPrivateKey(tenantKeyStoreName, tenantDomain); + } else { + privateKey = (PrivateKey) keyStoreManager.getPrivateKey(tenantKeyStoreName, + tenantDomain + + IdentityKeyStoreResolverConstants.KEY_STORE_CONTEXT_SEPARATOR + context); + } + } catch (IdentityException e) { + throw new SignatureException("Error while retrieving the private key for tenant: " + tenantDomain, e); + } + } + + // Sign the data with the retrieved private key + return SignatureUtil.doSignature(data, privateKey); + } + + /** + * Sign the given data for the specified tenant domain. + * + * @param data The data to be signed. + * @param tenantDomain The tenant domain to which the data belongs. + * @return The signature of the data. + * @throws SignatureException If an error occurs during the signature generation process. + */ + public static byte[] signWithTenantKey(String data, String tenantDomain) throws SignatureException { + + return signWithTenantKey(data, tenantDomain, null); + } } diff --git a/components/identity-core/org.wso2.carbon.identity.core/src/test/java/org/wso2/carbon/identity/core/IdentityKeyStoreResolverTest.java b/components/identity-core/org.wso2.carbon.identity.core/src/test/java/org/wso2/carbon/identity/core/IdentityKeyStoreResolverTest.java index 52abb6a18591..4246e1eaaf14 100644 --- a/components/identity-core/org.wso2.carbon.identity.core/src/test/java/org/wso2/carbon/identity/core/IdentityKeyStoreResolverTest.java +++ b/components/identity-core/org.wso2.carbon.identity.core/src/test/java/org/wso2/carbon/identity/core/IdentityKeyStoreResolverTest.java @@ -30,6 +30,7 @@ import org.wso2.carbon.identity.core.util.IdentityConfigParser; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; +import org.wso2.carbon.utils.security.KeystoreUtils; import java.io.FileInputStream; import java.lang.reflect.Field; @@ -84,6 +85,7 @@ public class IdentityKeyStoreResolverTest extends TestCase { private MockedStatic identityConfigParser; private MockedStatic identityTenantUtil; + private MockedStatic keystoreUtils; private IdentityKeyStoreResolver identityKeyStoreResolver; @@ -143,6 +145,7 @@ public void setUp() throws Exception { when(keyStoreManager.getCertificate("CUSTOM/" + CUSTOM_KEY_STORE, null)).thenReturn(customCertificate); identityKeyStoreResolver = IdentityKeyStoreResolver.getInstance(); + keystoreUtils = mockStatic(KeystoreUtils.class); } @AfterClass @@ -150,6 +153,7 @@ public void close() { identityConfigParser.close(); identityTenantUtil.close(); + keystoreUtils.close(); } @Test @@ -210,6 +214,7 @@ public Object[][] keyStoreDataProvider() { @Test(dataProvider = "KeyStoreDataProvider") public void testGetKeyStore(String tenantDomain, InboundProtocol inboundProtocol, KeyStore expectedKeyStore) throws Exception { + keystoreUtils.when(() -> KeystoreUtils.getKeyStoreFileExtension(tenantDomain)).thenReturn(".jks"); assertEquals(expectedKeyStore, identityKeyStoreResolver.getKeyStore(tenantDomain, inboundProtocol)); } @@ -229,6 +234,7 @@ public Object[][] privateKeyDataProvider() { @Test(dataProvider = "PrivateKeyDataProvider") public void testGetPrivateKey(String tenantDomain, InboundProtocol inboundProtocol, PrivateKey expectedKey) throws Exception { + keystoreUtils.when(() -> KeystoreUtils.getKeyStoreFileExtension(tenantDomain)).thenReturn(".jks"); assertEquals(expectedKey, identityKeyStoreResolver.getPrivateKey(tenantDomain, inboundProtocol)); } @@ -248,6 +254,7 @@ public Object[][] publicCertificateDataProvider() { @Test(dataProvider = "PublicCertificateDataProvider") public void testGetCertificate(String tenantDomain, InboundProtocol inboundProtocol, X509Certificate expectedCert) throws Exception { + keystoreUtils.when(() -> KeystoreUtils.getKeyStoreFileExtension(tenantDomain)).thenReturn(".jks"); assertEquals(expectedCert, identityKeyStoreResolver.getCertificate(tenantDomain, inboundProtocol)); } diff --git a/components/identity-core/org.wso2.carbon.identity.core/src/test/java/org/wso2/carbon/identity/core/dao/SAMLSSOServiceProviderDAOTest.java b/components/identity-core/org.wso2.carbon.identity.core/src/test/java/org/wso2/carbon/identity/core/dao/SAMLSSOServiceProviderDAOTest.java index 402269e79109..6b3636f4744a 100644 --- a/components/identity-core/org.wso2.carbon.identity.core/src/test/java/org/wso2/carbon/identity/core/dao/SAMLSSOServiceProviderDAOTest.java +++ b/components/identity-core/org.wso2.carbon.identity.core/src/test/java/org/wso2/carbon/identity/core/dao/SAMLSSOServiceProviderDAOTest.java @@ -1,19 +1,19 @@ /* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) (2007-2023), WSO2 LLC. (http://www.wso2.com). * - * 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 + * 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 + * 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. + * 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.core.dao; @@ -39,6 +39,7 @@ import org.wso2.carbon.registry.core.ResourceImpl; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.jdbc.utils.Transaction; +import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.registry.core.session.UserRegistry; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.tenant.TenantManager; @@ -69,7 +70,7 @@ */ public class SAMLSSOServiceProviderDAOTest { - private SAMLSSOServiceProviderDAO objUnderTest; + private RegistrySAMLSSOServiceProviderDAOImpl objUnderTest; private boolean transactionStarted = false; private Registry mockRegistry; @@ -78,13 +79,15 @@ public class SAMLSSOServiceProviderDAOTest { private Map> dummyAdvProperties; private Map> dummyPropertiesWithAnIssuerQualifier; private MockedStatic transaction; - + private MockedStatic identityTenantUtil; + private static final int TENANT_ID = 1; @BeforeMethod public void setUp() throws Exception { transaction = mockStatic(Transaction.class); mockRegistry = mock(UserRegistry.class); + RegistryService mockRegistryService = mock(RegistryService.class); transaction.when(Transaction::isStarted).thenReturn(transactionStarted); //Mock commit transaction doAnswer(new Answer() { @@ -103,7 +106,10 @@ public Object answer(InvocationOnMock invocationOnMock) throws Throwable { } }).when(mockRegistry).beginTransaction(); - objUnderTest = new SAMLSSOServiceProviderDAO(mockRegistry); + objUnderTest = new RegistrySAMLSSOServiceProviderDAOImpl(); + identityTenantUtil = mockStatic(IdentityTenantUtil.class); + when(IdentityTenantUtil.getRegistryService()).thenReturn(mockRegistryService); + when(mockRegistryService.getConfigSystemRegistry(TENANT_ID)).thenReturn((UserRegistry) mockRegistry); when(mockRegistry.newResource()).thenReturn(new ResourceImpl()); } @@ -187,6 +193,7 @@ private void setUpResources() throws Exception { @AfterMethod public void tearDown() throws Exception { + identityTenantUtil.close(); transaction.close(); } @@ -348,7 +355,7 @@ public void testAddServiceProvider(Object paramMapObj) throws Exception { + IdentityRegistryResources.QUALIFIER_ID + dummyResource.getProperty(IdentityRegistryResources. PROP_SAML_SSO_ISSUER_QUALIFIER)); } - objUnderTest.addServiceProvider(serviceProviderDO); + objUnderTest.addServiceProvider(serviceProviderDO, TENANT_ID); verify(mockRegistry).put(captor.capture(), any(Resource.class)); assertEquals(captor.getValue(), expectedPath, "Resource is not added at correct path"); } @@ -359,7 +366,7 @@ public void testAddExistingServiceProvider() throws Exception { String existingPath = getPath("existingIssuer"); serviceProviderDO.setIssuer("existingIssuer"); when(mockRegistry.resourceExists(existingPath)).thenReturn(true); - assertFalse(objUnderTest.addServiceProvider(serviceProviderDO), "Resource should not have added."); + assertFalse(objUnderTest.addServiceProvider(serviceProviderDO, TENANT_ID), "Resource should not have added."); } @Test(expectedExceptions = {IdentityException.class}) @@ -369,7 +376,7 @@ public void testAddServiceProviderRegistryError() throws Exception { String existingPath = getPath("erringIssuer"); serviceProviderDO.setIssuer("erringIssuer"); doThrow(RegistryException.class).when(mockRegistry).put(eq(existingPath), any(Resource.class)); - objUnderTest.addServiceProvider(serviceProviderDO); + objUnderTest.addServiceProvider(serviceProviderDO, TENANT_ID); } @Test(dataProvider = "ResourceToObjectData") @@ -388,7 +395,7 @@ public void testUpdateServiceProvider(Object paramMapObj) throws Exception { } String expectedPath = getPath(existingIssuer); when(mockRegistry.resourceExists(expectedPath)).thenReturn(true); - objUnderTest.updateServiceProvider(serviceProviderDO, existingIssuer); + objUnderTest.updateServiceProvider(serviceProviderDO, existingIssuer, TENANT_ID); verify(mockRegistry).put(captor.capture(), any(Resource.class)); assertEquals(captor.getValue(), expectedPath, "Resource is not added at correct path"); } @@ -398,7 +405,7 @@ public void testUpdatingServiceProviderExistingIssuer() throws Exception { SAMLSSOServiceProviderDO serviceProviderDO = new SAMLSSOServiceProviderDO(); serviceProviderDO.setIssuer("newIssuer"); when(mockRegistry.resourceExists(getPath("newIssuer"))).thenReturn(true); - assertFalse(objUnderTest.updateServiceProvider(serviceProviderDO, "existingIssuer"), "Resource should not have updated."); + assertFalse(objUnderTest.updateServiceProvider(serviceProviderDO, "existingIssuer", TENANT_ID), "Resource should not have updated."); } @Test @@ -431,7 +438,7 @@ public void testGetServiceProviders() throws Exception { when(mockRegistry.resourceExists(paths[0])).thenReturn(true); when(mockRegistry.resourceExists(paths[1])).thenReturn(true); when(mockRegistry.resourceExists(paths[2])).thenReturn(true); - SAMLSSOServiceProviderDO[] serviceProviders = objUnderTest.getServiceProviders(); + SAMLSSOServiceProviderDO[] serviceProviders = objUnderTest.getServiceProviders(TENANT_ID); assertEquals(serviceProviders.length, 3, "Should have returned 3 service providers."); } @@ -440,7 +447,7 @@ public void testRemoveServiceProvider() throws Exception { String existingIssuer = "ExistingIssuer"; String path = getPath(existingIssuer); when(mockRegistry.resourceExists(path)).thenReturn(true); - assertTrue(objUnderTest.removeServiceProvider(existingIssuer), "SP Resource is not deleted from path"); + assertTrue(objUnderTest.removeServiceProvider(existingIssuer, TENANT_ID), "SP Resource is not deleted from path"); } @Test @@ -448,40 +455,39 @@ public void testRemoveNonExistingServiceProvider() throws Exception { String nonExistingIssuer = "NonExistingIssuer"; String path = getPath(nonExistingIssuer); when(mockRegistry.resourceExists(path)).thenReturn(false); - assertFalse(objUnderTest.removeServiceProvider(nonExistingIssuer), "SP Resource should not have existed to " + + assertFalse(objUnderTest.removeServiceProvider(nonExistingIssuer, TENANT_ID), "SP Resource should not have existed to " + "delete."); } @Test(expectedExceptions = IllegalArgumentException.class) public void testRemoveEmptyServiceProvider() throws Exception { - objUnderTest.removeServiceProvider(""); + objUnderTest.removeServiceProvider("", TENANT_ID); fail("SP Resource with empty name could not have been deleted."); } @Test public void testGetServiceProvider() throws Exception { - try (MockedStatic identityTenantUtil = mockStatic(IdentityTenantUtil.class)) { - RealmService mockRealmService = mock(RealmService.class); - TenantManager mockTenantManager = mock(TenantManager.class); - identityTenantUtil.when(IdentityTenantUtil::getRealmService).thenReturn(mockRealmService); - when(mockRealmService.getTenantManager()).thenReturn(mockTenantManager); - when(mockTenantManager.getDomain(anyInt())).thenReturn("test.com"); - - Properties dummyResourceProperties = new Properties(); - dummyResourceProperties.putAll(dummyBasicProperties); - Resource dummyResource = new ResourceImpl(); - dummyResource.setProperties(dummyResourceProperties); - - String path = getPath(dummyResource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_ISSUER)); - when(mockRegistry.resourceExists(path)).thenReturn(true); - when(mockRegistry.get(path)).thenReturn(dummyResource); - - SAMLSSOServiceProviderDO serviceProviderDO = objUnderTest.getServiceProvider(dummyResource.getProperty - (IdentityRegistryResources.PROP_SAML_SSO_ISSUER)); - assertEquals(serviceProviderDO.getTenantDomain(), "test.com", - "Retrieved resource's tenant domain mismatch"); - } + RealmService mockRealmService = mock(RealmService.class); + TenantManager mockTenantManager = mock(TenantManager.class); + identityTenantUtil.when(IdentityTenantUtil::getRealmService).thenReturn(mockRealmService); + when(mockRealmService.getTenantManager()).thenReturn(mockTenantManager); + when(mockTenantManager.getDomain(anyInt())).thenReturn("test.com"); + + Properties dummyResourceProperties = new Properties(); + dummyResourceProperties.putAll(dummyBasicProperties); + Resource dummyResource = new ResourceImpl(); + dummyResource.setProperties(dummyResourceProperties); + + String path = getPath(dummyResource.getProperty(IdentityRegistryResources.PROP_SAML_SSO_ISSUER)); + when(mockRegistry.resourceExists(path)).thenReturn(true); + when(mockRegistry.get(path)).thenReturn(dummyResource); + + SAMLSSOServiceProviderDO serviceProviderDO = objUnderTest.getServiceProvider(dummyResource.getProperty + (IdentityRegistryResources.PROP_SAML_SSO_ISSUER), TENANT_ID); + assertEquals(serviceProviderDO.getTenantDomain(), "test.com", + "Retrieved resource's tenant domain mismatch"); + } @Test @@ -489,7 +495,7 @@ public void testIsServiceProviderExists() throws Exception { String validSP = "ValidSP"; String path = getPath(validSP); when(mockRegistry.resourceExists(path)).thenReturn(true); - assertTrue(objUnderTest.isServiceProviderExists(validSP)); + assertTrue(objUnderTest.isServiceProviderExists(validSP, TENANT_ID)); } @Test @@ -497,7 +503,7 @@ public void testNonExistingSPIsServiceProviderExists() throws Exception { String invalidSP = "InvalidSP"; String path = getPath(invalidSP); when(mockRegistry.resourceExists(path)).thenReturn(false); - assertFalse(objUnderTest.isServiceProviderExists(invalidSP)); + assertFalse(objUnderTest.isServiceProviderExists(invalidSP, TENANT_ID)); } @Test @@ -511,7 +517,7 @@ public void testUploadServiceProvider() throws Exception { .getProperty(IdentityRegistryResources.PROP_SAML_SSO_ISSUER)); when(mockRegistry.resourceExists(expectedPath)).thenReturn(false); SAMLSSOServiceProviderDO serviceProviderDO = objUnderTest.resourceToObject(dummyResource); - assertEquals(objUnderTest.uploadServiceProvider(serviceProviderDO), serviceProviderDO, "Same resource should" + + assertEquals(objUnderTest.uploadServiceProvider(serviceProviderDO, TENANT_ID), serviceProviderDO, "Same resource should" + " have returned after successful upload."); } @@ -526,7 +532,7 @@ public void testUploadExistingServiceProvider() throws Exception { .getProperty(IdentityRegistryResources.PROP_SAML_SSO_ISSUER)); when(mockRegistry.resourceExists(expectedPath)).thenReturn(true); SAMLSSOServiceProviderDO serviceProviderDO = objUnderTest.resourceToObject(dummyResource); - objUnderTest.uploadServiceProvider(serviceProviderDO); + objUnderTest.uploadServiceProvider(serviceProviderDO, TENANT_ID); fail("Uploading an existing SP should have failed"); } diff --git a/components/identity-core/org.wso2.carbon.identity.core/src/test/java/org/wso2/carbon/identity/core/dao/SAMLServiceProviderPersistenceManagerFactoryTest.java b/components/identity-core/org.wso2.carbon.identity.core/src/test/java/org/wso2/carbon/identity/core/dao/SAMLServiceProviderPersistenceManagerFactoryTest.java new file mode 100644 index 000000000000..0df52c6d7ad2 --- /dev/null +++ b/components/identity-core/org.wso2.carbon.identity.core/src/test/java/org/wso2/carbon/identity/core/dao/SAMLServiceProviderPersistenceManagerFactoryTest.java @@ -0,0 +1,78 @@ +/* + * 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.core.dao; + +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.lang.reflect.Field; + +import static org.testng.Assert.assertTrue; + +public class SAMLServiceProviderPersistenceManagerFactoryTest { + + private SAMLServiceProviderPersistenceManagerFactory factory; + + @BeforeMethod + public void setUp() { + + factory = new SAMLServiceProviderPersistenceManagerFactory(); + + } + + @AfterMethod + public void tearDown() throws Exception { + + setPrivateStaticField(SAMLServiceProviderPersistenceManagerFactory.class, "SAML_STORAGE_TYPE", ""); + factory = null; + } + + @Test + public void testGetSAMLServiceProviderPersistenceManagerWithDefaultStorage() throws Exception { + + setPrivateStaticField(SAMLServiceProviderPersistenceManagerFactory.class, "SAML_STORAGE_TYPE", "database"); + SAMLSSOServiceProviderDAO samlSSOServiceProviderDAO = factory.getSAMLServiceProviderPersistenceManager(); +// assertTrue(samlSSOServiceProviderDAO instanceof JDBCSAMLSSOServiceProviderDAOImpl); + } + + @Test + public void testGetSAMLServiceProviderPersistenceManagerWithRegistryStorage() throws Exception { + + setPrivateStaticField(SAMLServiceProviderPersistenceManagerFactory.class, "SAML_STORAGE_TYPE", "registry"); + SAMLSSOServiceProviderDAO samlSSOServiceProviderDAO = factory.getSAMLServiceProviderPersistenceManager(); + assertTrue(samlSSOServiceProviderDAO instanceof RegistrySAMLSSOServiceProviderDAOImpl); + } + + @Test + public void testGetSAMLServiceProviderPersistenceManagerWithHybridStorage() throws Exception { + + setPrivateStaticField(SAMLServiceProviderPersistenceManagerFactory.class, "SAML_STORAGE_TYPE", "hybrid"); + SAMLSSOServiceProviderDAO samlSSOServiceProviderDAO = factory.getSAMLServiceProviderPersistenceManager(); +// assertTrue(samlSSOServiceProviderDAO instanceof JDBCSAMLSSOServiceProviderDAOImpl); + } + + 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/identity-core/org.wso2.carbon.identity.core/src/test/java/org/wso2/carbon/identity/core/util/IdentityKeyStoreResolverUtilTest.java b/components/identity-core/org.wso2.carbon.identity.core/src/test/java/org/wso2/carbon/identity/core/util/IdentityKeyStoreResolverUtilTest.java index 0a3d7eb3faf1..98d094f26871 100644 --- a/components/identity-core/org.wso2.carbon.identity.core/src/test/java/org/wso2/carbon/identity/core/util/IdentityKeyStoreResolverUtilTest.java +++ b/components/identity-core/org.wso2.carbon.identity.core/src/test/java/org/wso2/carbon/identity/core/util/IdentityKeyStoreResolverUtilTest.java @@ -18,9 +18,14 @@ package org.wso2.carbon.identity.core.util; +import org.mockito.MockedStatic; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import org.wso2.carbon.utils.security.KeystoreUtils; +import static org.mockito.Mockito.mockStatic; import static org.testng.Assert.assertEquals; import static org.wso2.carbon.identity.core.util.IdentityKeyStoreResolverUtil.buildCustomKeyStoreName; @@ -34,6 +39,14 @@ */ public class IdentityKeyStoreResolverUtilTest { + private MockedStatic keystoreUtils; + + @BeforeClass + public void setUp() throws Exception { + + keystoreUtils = mockStatic(KeystoreUtils.class); + } + @DataProvider(name = "CorrectTenantKeyStoreNameDataProvider") public Object[][] correctTenantKeyStoreNameDataProvider() { @@ -43,10 +56,17 @@ public Object[][] correctTenantKeyStoreNameDataProvider() { }; } + @AfterClass + public void close() { + + keystoreUtils.close(); + } + @Test(dataProvider = "CorrectTenantKeyStoreNameDataProvider") public void testCorrectBuildTenantKeyStoreName(String tenantDomain, String expectedResult) throws IdentityKeyStoreResolverException { - assertEquals(expectedResult, buildTenantKeyStoreName(tenantDomain)); + keystoreUtils.when(() -> KeystoreUtils.getKeyStoreFileExtension(tenantDomain)).thenReturn(".jks"); + assertEquals(buildTenantKeyStoreName(tenantDomain), expectedResult); } @DataProvider(name = "IncorrectTenantKeyStoreNameDataProvider") diff --git a/components/identity-core/org.wso2.carbon.identity.core/src/test/java/org/wso2/carbon/identity/core/util/IdentityUtilTest.java b/components/identity-core/org.wso2.carbon.identity.core/src/test/java/org/wso2/carbon/identity/core/util/IdentityUtilTest.java index 0b88bf78bbed..cd833299e972 100644 --- a/components/identity-core/org.wso2.carbon.identity.core/src/test/java/org/wso2/carbon/identity/core/util/IdentityUtilTest.java +++ b/components/identity-core/org.wso2.carbon.identity.core/src/test/java/org/wso2/carbon/identity/core/util/IdentityUtilTest.java @@ -34,7 +34,10 @@ import org.w3c.dom.Element; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.base.ServerConfiguration; +import org.wso2.carbon.core.util.KeyStoreManager; +import org.wso2.carbon.core.util.SignatureUtil; import org.wso2.carbon.identity.base.IdentityConstants; +import org.wso2.carbon.identity.core.IdentityKeyStoreResolver; import org.wso2.carbon.identity.core.internal.IdentityCoreServiceComponent; import org.wso2.carbon.identity.core.model.IdentityCacheConfig; import org.wso2.carbon.identity.core.model.IdentityCacheConfigKey; @@ -53,6 +56,7 @@ import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.ConfigurationContextService; import org.wso2.carbon.utils.NetworkUtils; +import org.wso2.carbon.utils.security.KeystoreUtils; import java.io.FileInputStream; import java.io.IOException; @@ -62,6 +66,8 @@ import java.nio.file.Paths; import java.security.KeyStore; import java.security.KeyStoreException; +import java.security.PrivateKey; +import java.security.PublicKey; import java.security.SignatureException; import java.security.cert.Certificate; import java.security.cert.CertificateException; @@ -91,6 +97,8 @@ import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; +import static org.wso2.carbon.identity.core.util.IdentityKeyStoreResolverConstants.ErrorMessages.ERROR_CODE_ERROR_RETRIEVING_TENANT_PUBLIC_CERTIFICATE; +import static org.wso2.carbon.identity.core.util.IdentityKeyStoreResolverConstants.ErrorMessages.ERROR_RETRIEVING_TENANT_CONTEXT_PUBLIC_CERTIFICATE_KEYSTORE_NOT_EXIST; @Listeners(MockitoTestNGListener.class) public class IdentityUtilTest { @@ -121,6 +129,18 @@ public class IdentityUtilTest { private RealmConfiguration mockRealmConfiguration; @Mock private HttpServletRequest mockRequest; + @Mock + private IdentityKeyStoreResolver mockIdentityKeyStoreResolver; + @Mock + private PrivateKey mockPrivateKey; + @Mock + private PublicKey mockPublicKey; + @Mock + private KeyStoreManager mockKeyStoreManager; + @Mock + private Certificate mockCertificate; + + private KeyStore primaryKeyStore; @@ -130,6 +150,11 @@ public class IdentityUtilTest { MockedStatic identityCoreServiceComponent; MockedStatic identityConfigParser; MockedStatic identityTenantUtil; + MockedStatic signatureUtil; + MockedStatic identityKeyStoreResolver; + MockedStatic keyStoreManager; + private MockedStatic keystoreUtils; + @BeforeMethod public void setUp() throws Exception { @@ -140,6 +165,10 @@ public void setUp() throws Exception { identityCoreServiceComponent = mockStatic(IdentityCoreServiceComponent.class); identityConfigParser = mockStatic(IdentityConfigParser.class); identityTenantUtil = mockStatic(IdentityTenantUtil.class); + signatureUtil = mockStatic(SignatureUtil.class); + identityKeyStoreResolver = mockStatic(IdentityKeyStoreResolver.class); + keyStoreManager = mockStatic(KeyStoreManager.class); + keystoreUtils = mockStatic(KeystoreUtils.class); serverConfiguration.when(ServerConfiguration::getInstance).thenReturn(mockServerConfiguration); identityCoreServiceComponent.when( @@ -176,6 +205,10 @@ public void tearDown() throws Exception { identityCoreServiceComponent.close(); identityConfigParser.close(); identityTenantUtil.close(); + signatureUtil.close(); + identityKeyStoreResolver.close(); + keyStoreManager.close(); + keystoreUtils.close(); } @Test(description = "Test converting a certificate to PEM format") @@ -1067,4 +1100,105 @@ private KeyStore getKeyStoreFromFile(String keystoreName, String password) throw return keystore; } + @Test + public void testValidateSignatureFromTenant() throws Exception { + + String data = "testData"; + byte[] signature = new byte[]{1, 2, 3}; + String tenantDomain = "carbon.super"; + + when(mockCertificate.getPublicKey()).thenReturn(mockPublicKey); + identityKeyStoreResolver.when(IdentityKeyStoreResolver::getInstance).thenReturn(mockIdentityKeyStoreResolver); + when(mockIdentityKeyStoreResolver.getCertificate(tenantDomain, null)).thenReturn(mockCertificate); + signatureUtil.when(() -> SignatureUtil.validateSignature(data, signature, mockPublicKey)).thenReturn(true); + + boolean result = IdentityUtil.validateSignatureFromTenant(data, signature, tenantDomain); + assertTrue(result); + } + + @Test + public void testValidateSignatureFromContextKeystore() throws Exception { + + String data = "testData"; + byte[] signature = new byte[]{1, 2, 3}; + String tenantDomain = "carbon.super"; + String context = "cookie"; + + when(mockCertificate.getPublicKey()).thenReturn(mockPublicKey); + identityKeyStoreResolver.when(IdentityKeyStoreResolver::getInstance).thenReturn(mockIdentityKeyStoreResolver); + when(mockIdentityKeyStoreResolver.getCertificate(tenantDomain, null, context)).thenReturn(mockCertificate); + signatureUtil.when(() -> SignatureUtil.validateSignature(data, signature, mockPublicKey)).thenReturn(true); + + boolean result = IdentityUtil.validateSignatureFromTenant(data, signature, tenantDomain, context); + assertTrue(result); + } + + @Test(description = "Validate signature when the context keystore does not exist. " + + "Expect the method to return false without throwing an exception.") + public void testValidateSignatureFromContextKeystoreIfNotExists() throws Exception { + + String data = "testData"; + byte[] signature = new byte[]{1, 2, 3}; + String tenantDomain = "carbon.super"; + String context = "cookie"; + + identityKeyStoreResolver.when(IdentityKeyStoreResolver::getInstance).thenReturn(mockIdentityKeyStoreResolver); + when(mockIdentityKeyStoreResolver.getCertificate(tenantDomain, null, context)) + .thenThrow(new IdentityKeyStoreResolverException + (ERROR_RETRIEVING_TENANT_CONTEXT_PUBLIC_CERTIFICATE_KEYSTORE_NOT_EXIST.getCode(), + ERROR_RETRIEVING_TENANT_CONTEXT_PUBLIC_CERTIFICATE_KEYSTORE_NOT_EXIST.getDescription())); + signatureUtil.when(() -> SignatureUtil.validateSignature(data, signature, mockPublicKey)).thenReturn(true); + + boolean result = IdentityUtil.validateSignatureFromTenant(data, signature, tenantDomain, context); + assertFalse(result); + } + + @Test(description = "Validate signature when an unexpected exception occurs while retrieving the " + + "tenant's public certificate. Expect a SignatureException to be thrown.", + expectedExceptions = SignatureException.class) + public void testValidateSignatureFromContextKeystoreNegative() throws Exception { + + String data = "testData"; + byte[] signature = new byte[]{1, 2, 3}; + String tenantDomain = "carbon.super"; + String context = "cookie"; + + identityKeyStoreResolver.when(IdentityKeyStoreResolver::getInstance).thenReturn(mockIdentityKeyStoreResolver); + when(mockIdentityKeyStoreResolver.getCertificate(tenantDomain, null, context)) + .thenThrow(new IdentityKeyStoreResolverException + (ERROR_CODE_ERROR_RETRIEVING_TENANT_PUBLIC_CERTIFICATE.getCode(), + ERROR_CODE_ERROR_RETRIEVING_TENANT_PUBLIC_CERTIFICATE.getDescription())); + + IdentityUtil.validateSignatureFromTenant(data, signature, tenantDomain, context); + } + + @Test + public void testSignWithTenantKey() throws Exception { + + String data = "testData"; + String superTenantDomain = "carbon.super"; + keyStoreManager.when(() -> KeyStoreManager.getInstance(anyInt())).thenReturn(mockKeyStoreManager); + keystoreUtils.when(() -> KeystoreUtils.getKeyStoreFileExtension(superTenantDomain)).thenReturn(".jks"); + when(mockKeyStoreManager.getDefaultPrivateKey()).thenReturn(mockPrivateKey); + when(mockKeyStoreManager.getPrivateKey(anyString(), anyString())).thenReturn(mockPrivateKey); + + byte[] expectedSignature = new byte[]{1, 2, 3}; + signatureUtil.when(() -> SignatureUtil.doSignature(data, mockPrivateKey)).thenReturn(expectedSignature); + + byte[] result = IdentityUtil.signWithTenantKey(data, "wso2.com"); + assertEquals(result, expectedSignature); + + // Test sign with super tenant key. + result = IdentityUtil.signWithTenantKey(data, superTenantDomain); + assertEquals(result, expectedSignature); + + // Sign with super tenant causing an exception. + when(mockKeyStoreManager.getDefaultPrivateKey()).thenThrow(new Exception()); + try { + IdentityUtil.signWithTenantKey(data, superTenantDomain); + } catch (Exception e) { + assertEquals(e.getMessage(), String.format(IdentityKeyStoreResolverConstants.ErrorMessages + .ERROR_CODE_ERROR_RETRIEVING_TENANT_PRIVATE_KEY.getDescription(), superTenantDomain)); + } + } } 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/org.wso2.carbon.identity.core/src/test/resources/testng.xml b/components/identity-core/org.wso2.carbon.identity.core/src/test/resources/testng.xml index 043fa43d7ae7..086c07b39dae 100644 --- a/components/identity-core/org.wso2.carbon.identity.core/src/test/resources/testng.xml +++ b/components/identity-core/org.wso2.carbon.identity.core/src/test/resources/testng.xml @@ -25,6 +25,7 @@ + diff --git a/components/identity-core/pom.xml b/components/identity-core/pom.xml index 210f01268c0e..3213c399e677 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.10-SNAPSHOT + 7.7.63-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 2158b5e5cd62..91c789a8dba9 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.10-SNAPSHOT + 7.7.63-SNAPSHOT ../pom.xml diff --git a/components/identity-event/org.wso2.carbon.identity.event/src/main/java/org/wso2/carbon/identity/event/IdentityEventConstants.java b/components/identity-event/org.wso2.carbon.identity.event/src/main/java/org/wso2/carbon/identity/event/IdentityEventConstants.java index 600b4076acb0..dcda266bcc26 100644 --- a/components/identity-event/org.wso2.carbon.identity.event/src/main/java/org/wso2/carbon/identity/event/IdentityEventConstants.java +++ b/components/identity-event/org.wso2.carbon.identity.event/src/main/java/org/wso2/carbon/identity/event/IdentityEventConstants.java @@ -234,6 +234,8 @@ private Event(){} public static final String POST_GET_ROLES_V2_EVENT = "POST_GET_ROLES_V2_EVENT"; public static final String PRE_GET_ROLES_V2_COUNT_EVENT = "PRE_GET_ROLES_V2_COUNT_EVENT"; public static final String POST_GET_ROLES_V2_COUNT_EVENT = "POST_GET_ROLES_V2_COUNT_EVENT"; + public static final String PRE_GET_ROLES_V2_FILTERED_COUNT_EVENT = "PRE_GET_ROLES_V2_COUNT_EVENT"; + public static final String POST_GET_ROLES_V2_FILTERED_COUNT_EVENT = "POST_GET_ROLES_V2_COUNT_EVENT"; public static final String PRE_GET_ROLE_V2_EVENT = "PRE_GET_ROLE_V2_EVENT"; public static final String POST_GET_ROLE_V2_EVENT = "POST_GET_ROLE_V2_EVENT"; public static final String PRE_UPDATE_ROLE_V2_NAME_EVENT = "PRE_UPDATE_ROLE_V2_NAME_EVENT"; @@ -393,6 +395,7 @@ private EventProperty(){} public static final String SORT_ORDER = "SORT_ORDER"; public static final String USER = "USER"; public static final String FILTER = "FILTER"; + public static final String SEARCH_FILTER = "SEARCH_FILTER"; public static final String USER_CLAIM_SEARCH_ENTRIES = "USER_CLAIM_SEARCH_ENTRIES"; public static final String LOGIN_IDENTIFIERS = "LOGIN_IDENTIFIERS"; public static final String CONTEXT = "context"; diff --git a/components/identity-event/pom.xml b/components/identity-event/pom.xml index fe5c193bd540..9233c2b0b63c 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.10-SNAPSHOT + 7.7.63-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 f0a31989ef35..eb845a9cea6a 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.10-SNAPSHOT + 7.7.63-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 8941dc550dd9..f9ff0521ccf4 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.10-SNAPSHOT + 7.7.63-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 f22a5faf79d1..667d308539f4 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.10-SNAPSHOT + 7.7.63-SNAPSHOT ../pom.xml diff --git a/components/identity-mgt/org.wso2.carbon.identity.mgt/src/main/java/org/wso2/carbon/identity/mgt/constants/PasswordPolicyStatusCodes.java b/components/identity-mgt/org.wso2.carbon.identity.mgt/src/main/java/org/wso2/carbon/identity/mgt/constants/PasswordPolicyStatusCodes.java new file mode 100644 index 000000000000..a68421f12914 --- /dev/null +++ b/components/identity-mgt/org.wso2.carbon.identity.mgt/src/main/java/org/wso2/carbon/identity/mgt/constants/PasswordPolicyStatusCodes.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) 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.mgt.constants; + +/** + * Password policy violation related constants. + */ +public class PasswordPolicyStatusCodes { + + public static final String ERROR_CODE_PASSWORD_POLICY_VIOLATION = "20035"; + +} diff --git a/components/identity-mgt/org.wso2.carbon.identity.mgt/src/main/java/org/wso2/carbon/identity/mgt/policy/PolicyRegistry.java b/components/identity-mgt/org.wso2.carbon.identity.mgt/src/main/java/org/wso2/carbon/identity/mgt/policy/PolicyRegistry.java index e8a610d4adcc..fd190ac85adb 100644 --- a/components/identity-mgt/org.wso2.carbon.identity.mgt/src/main/java/org/wso2/carbon/identity/mgt/policy/PolicyRegistry.java +++ b/components/identity-mgt/org.wso2.carbon.identity.mgt/src/main/java/org/wso2/carbon/identity/mgt/policy/PolicyRegistry.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2014-2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * 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 @@ -18,6 +18,8 @@ package org.wso2.carbon.identity.mgt.policy; +import org.wso2.carbon.identity.mgt.constants.PasswordPolicyStatusCodes; + import java.util.ArrayList; import java.util.List; @@ -36,7 +38,8 @@ public void enforcePasswordPolicies(Object... args) throws PolicyViolationExcept for (PolicyEnforcer policy : policyCollection) { if (policy instanceof AbstractPasswordPolicyEnforcer && !policy.enforce(args)) { - throw new PolicyViolationException(policy.getErrorMessage()); + throw new PolicyViolationException(PasswordPolicyStatusCodes.ERROR_CODE_PASSWORD_POLICY_VIOLATION, + policy.getErrorMessage()); } } diff --git a/components/identity-mgt/org.wso2.carbon.identity.mgt/src/main/java/org/wso2/carbon/identity/mgt/policy/PolicyViolationException.java b/components/identity-mgt/org.wso2.carbon.identity.mgt/src/main/java/org/wso2/carbon/identity/mgt/policy/PolicyViolationException.java index b99faf52f43a..c0614f3c1799 100644 --- a/components/identity-mgt/org.wso2.carbon.identity.mgt/src/main/java/org/wso2/carbon/identity/mgt/policy/PolicyViolationException.java +++ b/components/identity-mgt/org.wso2.carbon.identity.mgt/src/main/java/org/wso2/carbon/identity/mgt/policy/PolicyViolationException.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2014-2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * 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 @@ -24,11 +24,35 @@ public class PolicyViolationException extends IdentityException { private static final long serialVersionUID = 7267202484738844205L; + /** + * Constructs a PolicyViolationException with the specified error message. + * + * @param message the detail message to describe the violation. + */ public PolicyViolationException(String message) { + super(message); } - + + /** + * Constructs a PolicyViolationException with the specified error code and message. + * + * @param errorCode the specific error code for this violation. + * @param message the detail message to describe the violation. + */ + public PolicyViolationException(String errorCode, String message) { + + super(errorCode, message); + } + + /** + * Constructs a PolicyViolationException with the specified message and cause. + * + * @param message the detail message to describe the violation. + * @param e the cause of this exception. + */ public PolicyViolationException(String message, Throwable e) { + super(message, e); } } diff --git a/components/identity-mgt/org.wso2.carbon.identity.mgt/src/test/java/org/wso2/carbon/identity/mgt/policy/PolicyRegistryTest.java b/components/identity-mgt/org.wso2.carbon.identity.mgt/src/test/java/org/wso2/carbon/identity/mgt/policy/PolicyRegistryTest.java new file mode 100644 index 000000000000..ef871dbf0bc9 --- /dev/null +++ b/components/identity-mgt/org.wso2.carbon.identity.mgt/src/test/java/org/wso2/carbon/identity/mgt/policy/PolicyRegistryTest.java @@ -0,0 +1,149 @@ +/* + * 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.policy; + +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.util.List; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.testng.Assert.*; + +public class PolicyRegistryTest { + + private PolicyRegistry policyRegistry; + + @BeforeMethod + public void setUp() { + policyRegistry = new PolicyRegistry(); + } + + /* + Test for the enforcePasswordPolicies method. + */ + @Test + public void testEnforcePasswordPoliciesSuccess() throws PolicyViolationException { + + AbstractPasswordPolicyEnforcer mockPolicy = mock(AbstractPasswordPolicyEnforcer.class); + + when(mockPolicy.enforce(any())).thenReturn(true); + + policyRegistry.addPolicy(mockPolicy); + + policyRegistry.enforcePasswordPolicies("dummyArg"); + + verify(mockPolicy).enforce(any()); + } + + /* + Test for the enforcePasswordPolicies method when a policy violation occurs. + */ + @Test(expectedExceptions = PolicyViolationException.class) + public void testEnforcePasswordPoliciesFailure() throws PolicyViolationException { + + AbstractPasswordPolicyEnforcer mockPolicy = mock(AbstractPasswordPolicyEnforcer.class); + + when(mockPolicy.enforce(any())).thenReturn(false); + when(mockPolicy.getErrorMessage()).thenReturn("Policy violation occurred."); + + policyRegistry.addPolicy(mockPolicy); + + policyRegistry.enforcePasswordPolicies("dummyArg"); + } + + /* + Test for the enforcePasswordPolicies method when no policies are added. + */ + @Test + public void testEnforcePasswordPoliciesNoPolicies() { + + try { + policyRegistry.enforcePasswordPolicies("dummyArg"); + } catch (PolicyViolationException e) { + fail("No policies added, so no exception should be thrown."); + } + } + + /* + Test for the addPolicy method. + */ + @Test + public void testAddPolicy() { + + AbstractPasswordPolicyEnforcer mockPolicy = mock(AbstractPasswordPolicyEnforcer.class); + + policyRegistry.addPolicy(mockPolicy); + + try { + java.lang.reflect.Field field = PolicyRegistry.class.getDeclaredField("policyCollection"); + field.setAccessible(true); + @SuppressWarnings("unchecked") + List policies = (List) field.get(policyRegistry); + + assertEquals(policies.size(), 1); + assertEquals(policies.get(0), mockPolicy); + } catch (NoSuchFieldException | IllegalAccessException e) { + fail("Reflection failed to access private field."); + } + } + + /* + Test for the enforcePasswordPolicies method with multiple policies. + */ + @Test + public void testEnforcePasswordPoliciesWithMultiplePolicies() throws PolicyViolationException { + + AbstractPasswordPolicyEnforcer mockPolicy1 = mock(AbstractPasswordPolicyEnforcer.class); + AbstractPasswordPolicyEnforcer mockPolicy2 = mock(AbstractPasswordPolicyEnforcer.class); + + when(mockPolicy1.enforce(any())).thenReturn(true); + when(mockPolicy2.enforce(any())).thenReturn(true); + + policyRegistry.addPolicy(mockPolicy1); + policyRegistry.addPolicy(mockPolicy2); + + policyRegistry.enforcePasswordPolicies("dummyArg"); + + verify(mockPolicy1).enforce(any()); + verify(mockPolicy2).enforce(any()); + } + + /* + Test for the enforcePasswordPolicies method with multiple policies and mixed results. + */ + @Test(expectedExceptions = PolicyViolationException.class) + public void testEnforcePasswordPoliciesWithMixedResults() throws PolicyViolationException { + + AbstractPasswordPolicyEnforcer mockPolicy1 = mock(AbstractPasswordPolicyEnforcer.class); + AbstractPasswordPolicyEnforcer mockPolicy2 = mock(AbstractPasswordPolicyEnforcer.class); + + when(mockPolicy1.enforce(any())).thenReturn(true); + when(mockPolicy2.enforce(any())).thenReturn(false); + when(mockPolicy2.getErrorMessage()).thenReturn("Second policy violated."); + + policyRegistry.addPolicy(mockPolicy1); + policyRegistry.addPolicy(mockPolicy2); + + policyRegistry.enforcePasswordPolicies("dummyArg"); + } +} diff --git a/components/identity-mgt/org.wso2.carbon.identity.mgt/src/test/resources/testng.xml b/components/identity-mgt/org.wso2.carbon.identity.mgt/src/test/resources/testng.xml index 260ded681d7f..aae9a330040a 100644 --- a/components/identity-mgt/org.wso2.carbon.identity.mgt/src/test/resources/testng.xml +++ b/components/identity-mgt/org.wso2.carbon.identity.mgt/src/test/resources/testng.xml @@ -25,6 +25,7 @@ + diff --git a/components/identity-mgt/pom.xml b/components/identity-mgt/pom.xml index eecbbfa45981..59e7781362be 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.10-SNAPSHOT + 7.7.63-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 fcaeb0e54cc2..757eecfcb9b2 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.10-SNAPSHOT + 7.7.63-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 1a793376ed41..448f13f0fe08 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.10-SNAPSHOT + 7.7.63-SNAPSHOT ../pom.xml @@ -113,6 +113,10 @@ mockito-testng test + + org.wso2.carbon.identity.framework + org.wso2.carbon.identity.action.management + @@ -163,7 +167,8 @@ org.wso2.carbon;version="${carbon.kernel.package.import.version.range}", org.apache.commons.codec.binary; version="${commons-codec.wso2.osgi.version.range}", org.json;version="${json.wso2.version.range}", - org.wso2.carbon.database.utils.*;version="${org.wso2.carbon.database.utils.version.range}" + org.wso2.carbon.database.utils.*;version="${org.wso2.carbon.database.utils.version.range}", + org.wso2.carbon.identity.action.management.*;version="${carbon.identity.package.import.version.range}" !org.wso2.carbon.idp.mgt.internal, diff --git a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/IdentityProviderManagementClientException.java b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/IdentityProviderManagementClientException.java index b5b52eab9f24..5ca8b712efa1 100644 --- a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/IdentityProviderManagementClientException.java +++ b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/IdentityProviderManagementClientException.java @@ -23,6 +23,8 @@ */ public class IdentityProviderManagementClientException extends IdentityProviderManagementException { + private String description; + public IdentityProviderManagementClientException(String message) { super(message); @@ -42,4 +44,15 @@ public IdentityProviderManagementClientException(String errorCode, String messag super(errorCode, message, throwable); } + + public IdentityProviderManagementClientException(String errorCode, String message, String description) { + + super(errorCode, message); + this.description = description; + } + + public String getDescription() { + + return description; + } } diff --git a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/IdentityProviderManager.java b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/IdentityProviderManager.java index e62ac3186f39..c4d08def9d30 100644 --- a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/IdentityProviderManager.java +++ b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/IdentityProviderManager.java @@ -68,9 +68,11 @@ import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.sql.Connection; import java.util.ArrayList; import java.util.Arrays; +import java.util.Base64; import java.util.Collection; import java.util.Collections; import java.util.HashMap; @@ -78,6 +80,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.regex.Pattern; import java.util.stream.Stream; import javax.xml.stream.XMLStreamException; @@ -94,6 +97,8 @@ public class IdentityProviderManager implements IdpManager { private static final int OTP_CODE_MAX_LENGTH = 10; private static CacheBackedIdPMgtDAO dao = new CacheBackedIdPMgtDAO(new IdPManagementDAO()); private static volatile IdentityProviderManager instance = new IdentityProviderManager(); + private final Pattern userDefinedAuthNameRegexPattern = + Pattern.compile(IdPManagementConstants.USER_DEFINED_AUTHENTICATOR_NAME_REGEX); private IdentityProviderManager() { @@ -1499,6 +1504,7 @@ public IdentityProvider addIdPWithResourceId(IdentityProvider identityProvider, markConfidentialPropertiesUsingMetadata(identityProvider); validateAddIdPInputValues(identityProvider.getIdentityProviderName(), tenantDomain); + validateFederatedAuthenticatorConfigName(identityProvider.getFederatedAuthenticatorConfigs(), tenantDomain); validateOutboundProvisioningRoles(identityProvider, tenantDomain); // Invoking the pre listeners. @@ -1879,12 +1885,15 @@ private void updateIDP(IdentityProvider currentIdentityProvider, IdentityProvide } /** - * Get the authenticators registered in the system. + * Get the authenticators registered in the system (system defined federated authenticators). * - * @return FederatedAuthenticatorConfig array. + * @return FederatedAuthenticatorConfig Array of system defined federated authenticators. * @throws IdentityProviderManagementException Error when getting authenticators registered * in the system + * @deprecated It is recommended to use {@link #getAllFederatedAuthenticators(String)}, which return both system + * defined and user defined federated authenticators of the provided tenant. */ + @Deprecated @Override public FederatedAuthenticatorConfig[] getAllFederatedAuthenticators() throws IdentityProviderManagementException { @@ -2181,6 +2190,38 @@ private void validateAddIdPInputValues(String idpName, String tenantDomain) thro } } + private void validateFederatedAuthenticatorConfigName(FederatedAuthenticatorConfig[] federatedAuthConfigs, + String tenantDomain) throws IdentityProviderManagementException { + + if (federatedAuthConfigs == null) { + return; + } + + for (FederatedAuthenticatorConfig config : federatedAuthConfigs) { + if (config.getDefinedByType() == DefinedByType.SYSTEM) { + // Check if there is a system registered authenticator given authenticator name. + if (ApplicationAuthenticatorService.getInstance() + .getFederatedAuthenticatorByName(config.getName()) == null) { + throw IdPManagementUtil.handleClientException(IdPManagementConstants.ErrorMessage + .ERROR_CODE_NO_SYSTEM_AUTHENTICATOR_FOUND, new String( + Base64.getEncoder().encode(config.getName().getBytes(StandardCharsets.UTF_8)))); + } + } else { + // Check if the given authenticator name is already taken. + if (getFederatedAuthenticatorByName(config.getName(), tenantDomain) != null) { + throw IdPManagementUtil.handleClientException(IdPManagementConstants.ErrorMessage + .ERROR_CODE_AUTHENTICATOR_NAME_ALREADY_TAKEN, config.getName()); + } + // Check if the given authenticator name matches the regex pattern. + if (!userDefinedAuthNameRegexPattern.matcher(config.getName()).matches()) { + throw IdPManagementUtil.handleClientException(IdPManagementConstants.ErrorMessage + .ERROR_INVALID_AUTHENTICATOR_NAME, + IdPManagementConstants.USER_DEFINED_AUTHENTICATOR_NAME_REGEX); + } + } + } + } + /** * Validate input parameters for the updateIdPByResourceId function. * @@ -2312,6 +2353,25 @@ public List getValidIdPGroupsByIdPGroupIds(List idpGroupIds, S } } + @Override + public FederatedAuthenticatorConfig[] getAllFederatedAuthenticators(String tenantDomain) + throws IdentityProviderManagementException { + + List allFederatedAuthenticators = + dao.getAllUserDefinedFederatedAuthenticators(IdentityTenantUtil.getTenantId(tenantDomain)); + allFederatedAuthenticators.addAll(Arrays.asList(getAllFederatedAuthenticators())); + return allFederatedAuthenticators.toArray(new FederatedAuthenticatorConfig[0]); + } + + private FederatedAuthenticatorConfig getFederatedAuthenticatorByName(String authenticatorName, String tenantDomain) + throws IdentityProviderManagementException { + + return Arrays.stream(getAllFederatedAuthenticators(tenantDomain)) + .filter(authenticator -> authenticator.getName().equals(authenticatorName)) + .findFirst() + .orElse(null); + } + /** * Method to validate the uniqueness of the IDP Issuer Name. * Ideally used when adding a IDP. @@ -2602,6 +2662,10 @@ private Map> createFedAuthConfidentialPropsMap() throws Ide Map> metaFedAuthConfigMap = new HashMap<>(); FederatedAuthenticatorConfig[] metaFedAuthConfigs = getAllFederatedAuthenticators(); for (FederatedAuthenticatorConfig metaFedAuthConfig : metaFedAuthConfigs) { + // Continuing as user defined authenticators does not have any authenticator properties having secrets. + if (metaFedAuthConfig.getDefinedByType() == DefinedByType.USER) { + continue; + } List secretProperties = new ArrayList<>(); for (Property property : metaFedAuthConfig.getProperties()) { if (property.isConfidential()) { diff --git a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/IdpManager.java b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/IdpManager.java index d42eefcdf856..92fb1f79c4a4 100644 --- a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/IdpManager.java +++ b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/IdpManager.java @@ -546,4 +546,17 @@ default List getValidIdPGroupsByIdPGroupIds(List idpGroupIds, return null; } + + /** + * Get the all federated authenticator of the tenant domain (both system defined and user defined). + * + * @param tenantDomain Tenant Domain. + * @return User all federated authenticators. + * @throws IdentityProviderManagementException If an error occurred while getting all federated authenticator. + */ + default FederatedAuthenticatorConfig[] getAllFederatedAuthenticators(String tenantDomain) + throws IdentityProviderManagementException { + + return new FederatedAuthenticatorConfig[0]; + } } diff --git a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/dao/CacheBackedIdPMgtDAO.java b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/dao/CacheBackedIdPMgtDAO.java index c1e3a060585f..cc95138d0bb7 100644 --- a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/dao/CacheBackedIdPMgtDAO.java +++ b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/dao/CacheBackedIdPMgtDAO.java @@ -23,6 +23,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.identity.application.common.model.FederatedAuthenticatorConfig; import org.wso2.carbon.identity.application.common.model.IdPGroup; import org.wso2.carbon.identity.application.common.model.IdentityProvider; import org.wso2.carbon.identity.application.common.model.IdentityProviderProperty; @@ -55,7 +56,7 @@ public class CacheBackedIdPMgtDAO { private static final Log log = LogFactory.getLog(CacheBackedIdPMgtDAO.class); - private IdPManagementDAO idPMgtDAO = null; + private IdPManagementFacade idPManagementFacade = null; private IdPCacheByName idPCacheByName = null; private IdPCacheByHRI idPCacheByHRI = null; @@ -67,7 +68,7 @@ public class CacheBackedIdPMgtDAO { * @param idPMgtDAO */ public CacheBackedIdPMgtDAO(IdPManagementDAO idPMgtDAO) { - this.idPMgtDAO = idPMgtDAO; + idPManagementFacade = new IdPManagementFacade(idPMgtDAO); idPCacheByName = IdPCacheByName.getInstance(); idPCacheByHRI = IdPCacheByHRI.getInstance(); idPCacheByAuthProperty = IdPCacheByAuthProperty.getInstance(); @@ -85,7 +86,7 @@ public CacheBackedIdPMgtDAO(IdPManagementDAO idPMgtDAO) { public List getIdPs(Connection dbConnection, int tenantId, String tenantDomain) throws IdentityProviderManagementException { - return idPMgtDAO.getIdPs(dbConnection, tenantId, tenantDomain); + return idPManagementFacade.getIdPs(dbConnection, tenantId, tenantDomain); } /** @@ -99,7 +100,7 @@ public List getIdPs(Connection dbConnection, int tenantId, public List getIdPsSearch(Connection dbConnection, int tenantId, String tenantDomain, String filter) throws IdentityProviderManagementException { - return idPMgtDAO.getIdPsSearch(dbConnection, tenantId, tenantDomain, + return idPManagementFacade.getIdPsSearch(dbConnection, tenantId, tenantDomain, filter); } @@ -120,7 +121,7 @@ public List getPaginatedIdPsSearch(int tenantId, List getPaginatedIdPsSearch(int tenantId, List requiredAttributes) throws IdentityProviderManagementServerException, IdentityProviderManagementClientException { - return idPMgtDAO + return idPManagementFacade .getIdPsSearch(tenantId, expressionConditions, limit, offset, sortOrder, sortBy, requiredAttributes); } @@ -167,7 +168,7 @@ public List getPaginatedTrustedTokenIssuersSearch(int tenantId List requiredAttributes) throws IdentityProviderManagementServerException, IdentityProviderManagementClientException { - return idPMgtDAO.getTrustedTokenIssuerSearch(tenantId, expressionConditions, limit, offset, sortOrder, + return idPManagementFacade.getTrustedTokenIssuerSearch(tenantId, expressionConditions, limit, offset, sortOrder, sortBy, requiredAttributes); } @@ -183,7 +184,7 @@ public List getPaginatedTrustedTokenIssuersSearch(int tenantId public int getTotalIdPCount(int tenantId, List expressionConditions) throws IdentityProviderManagementServerException, IdentityProviderManagementClientException { - return idPMgtDAO.getCountOfFilteredIdPs(tenantId, expressionConditions); + return idPManagementFacade.getCountOfFilteredIdPs(tenantId, expressionConditions); } /** @@ -198,7 +199,7 @@ public int getTotalIdPCount(int tenantId, List expressionConditi public int getTotalTrustedTokenIssuerCount(int tenantId, List expressionConditions) throws IdentityProviderManagementServerException, IdentityProviderManagementClientException { - return idPMgtDAO.getCountOfFilteredTokenIssuers(tenantId, expressionConditions); + return idPManagementFacade.getCountOfFilteredTokenIssuers(tenantId, expressionConditions); } /** @@ -226,7 +227,7 @@ public IdentityProvider getIdPByName(Connection dbConnection, String idPName, + ". Fetching entry from DB"); } - IdentityProvider identityProvider = idPMgtDAO.getIdPByName(dbConnection, idPName, + IdentityProvider identityProvider = idPManagementFacade.getIdPByName(dbConnection, idPName, tenantId, tenantDomain); if (identityProvider != null) { @@ -255,7 +256,7 @@ public IdentityProvider getIdPByName(Connection dbConnection, String idPName, public IdentityProvider getIdPById(Connection dbConnection, int id, int tenantId, String tenantDomain) throws IdentityProviderManagementException { - IdentityProvider identityProvider = idPMgtDAO.getIDPbyId(dbConnection, id, + IdentityProvider identityProvider = idPManagementFacade.getIDPbyId(dbConnection, id, tenantId, tenantDomain); if (identityProvider != null) { @@ -305,7 +306,7 @@ public IdentityProvider getIdPByResourceId(String resourceId, int tenantId, Stri log.debug("Cache entry not found for Identity Provider with resource ID: " + resourceId + ". Fetching entry from DB"); } - identityProvider = idPMgtDAO.getIDPbyResourceId(null, resourceId, + identityProvider = idPManagementFacade.getIDPbyResourceId(null, resourceId, tenantId, tenantDomain); if (identityProvider != null) { @@ -351,7 +352,7 @@ public IdentityProvider getUpdatedIdPByResourceId(String resourceId, int tenantI tenantId, tenantDomain); } - identityProvider = idPMgtDAO.getIDPbyResourceId(null, resourceId, tenantId, tenantDomain); + identityProvider = idPManagementFacade.getIDPbyResourceId(null, resourceId, tenantId, tenantDomain); if (identityProvider == null) { if (log.isDebugEnabled()) { @@ -381,7 +382,7 @@ public String getIdPNameByResourceId(String resourceId) throws IdentityProviderM log.debug("Cache entry not found for Identity Provider with resource ID: " + resourceId + ". Fetching the name from DB"); } - return idPMgtDAO.getIDPNameByResourceId(resourceId); + return idPManagementFacade.getIDPNameByResourceId(resourceId); } /** @@ -410,7 +411,7 @@ public IdentityProvider getIdPByAuthenticatorPropertyValue(Connection dbConnecti + " and with value " + value + ". Fetching entry from DB"); } - IdentityProvider identityProvider = idPMgtDAO.getIdPByAuthenticatorPropertyValue(dbConnection, property, value, + IdentityProvider identityProvider = idPManagementFacade.getIdPByAuthenticatorPropertyValue(dbConnection, property, value, tenantId, tenantDomain); if (identityProvider != null) { @@ -460,7 +461,7 @@ public IdentityProvider getIdPByAuthenticatorPropertyValue(Connection dbConnecti + " and with value " + value + ". Fetching entry from DB"); } - IdentityProvider identityProvider = idPMgtDAO.getIdPByAuthenticatorPropertyValue(dbConnection, property, + IdentityProvider identityProvider = idPManagementFacade.getIdPByAuthenticatorPropertyValue(dbConnection, property, value, authenticator, tenantId, tenantDomain); if (identityProvider != null) { @@ -502,7 +503,7 @@ public IdentityProvider getIdPByRealmId(String realmId, int tenantId, + ". Fetching entry from DB"); } - IdentityProvider identityProvider = idPMgtDAO.getIdPByRealmId(realmId, tenantId, tenantDomain); + IdentityProvider identityProvider = idPManagementFacade.getIdPByRealmId(realmId, tenantId, tenantDomain); if (identityProvider != null) { log.debug("Entry fetched from DB for Identity Provider with Home Realm ID " + realmId @@ -551,7 +552,7 @@ public IdentityProvider getEnabledIdPByRealmId(String realmId, int tenantId, } } - IdentityProvider identityProvider = idPMgtDAO.getEnabledIdPByRealmId(realmId, tenantId, tenantDomain); + IdentityProvider identityProvider = idPManagementFacade.getEnabledIdPByRealmId(realmId, tenantId, tenantDomain); if (identityProvider != null) { if (log.isDebugEnabled()) { @@ -581,7 +582,7 @@ public IdentityProvider getEnabledIdPByRealmId(String realmId, int tenantId, public String addIdP(IdentityProvider identityProvider, int tenantId, String tenantDomain) throws IdentityProviderManagementException { - return idPMgtDAO.addIdPWithResourceId(identityProvider, tenantId); + return idPManagementFacade.addIdPWithResourceId(identityProvider, tenantId); } /** @@ -601,7 +602,7 @@ public void updateIdP(IdentityProvider newIdentityProvider, } clearIdpCache(currentIdentityProvider.getIdentityProviderName(), currentIdentityProvider.getResourceId(), tenantId, tenantDomain); - idPMgtDAO.updateIdPWithResourceId(currentIdentityProvider.getResourceId(), + idPManagementFacade.updateIdPWithResourceId(currentIdentityProvider.getResourceId(), newIdentityProvider, currentIdentityProvider, tenantId); } @@ -614,14 +615,14 @@ public void updateIdP(IdentityProvider newIdentityProvider, public void deleteIdP(String idPName, int tenantId, String tenantDomain) throws IdentityProviderManagementException { - if (idPMgtDAO.isIdpReferredBySP(idPName, tenantId)) { + if (idPManagementFacade.isIdpReferredBySP(idPName, tenantId)) { throw new IdentityProviderManagementException("Identity Provider '" + idPName + "' " + "cannot be deleted as it is referred by Service Providers."); } IdentityProvider identityProvider = this.getIdPByName(null, idPName, tenantId, tenantDomain); if (identityProvider != null) { - idPMgtDAO.deleteIdP(idPName, tenantId, tenantDomain); + idPManagementFacade.deleteIdP(idPName, tenantId, tenantDomain); clearIdpCache(idPName, tenantId, tenantDomain); } else { if (log.isDebugEnabled()) { @@ -639,7 +640,7 @@ public void deleteIdP(String idPName, int tenantId, String tenantDomain) */ public void deleteIdPs(int tenantId) throws IdentityProviderManagementException { - idPMgtDAO.deleteIdPs(tenantId); + idPManagementFacade.deleteIdPs(tenantId); if (log.isDebugEnabled()) { log.debug(String.format("All Identity Providers of tenant:%d are deleted", tenantId)); } @@ -658,14 +659,14 @@ public void deleteIdPByResourceId(String resourceId, int tenantId, String tenant IdentityProvider identityProvider = this.getIdPByResourceId(resourceId, tenantId, tenantDomain); if (identityProvider != null) { String idPName = identityProvider.getIdentityProviderName(); - if (idPMgtDAO.isIdpReferredBySP(idPName, tenantId)) { + if (idPManagementFacade.isIdpReferredBySP(idPName, tenantId)) { String data = "Identity Provider '" + idPName + "' cannot be deleted as it is referred by Service " + "Providers."; throw IdPManagementUtil.handleClientException(IdPManagementConstants.ErrorMessage .ERROR_CODE_DELETE_IDP, data); } - idPMgtDAO.deleteIdPByResourceId(resourceId, tenantId, tenantDomain); + idPManagementFacade.deleteIdPByResourceId(resourceId, tenantId, tenantDomain); clearIdpCache(idPName, resourceId, tenantId, tenantDomain); } else { if (log.isDebugEnabled()) { @@ -685,7 +686,7 @@ public void forceDeleteIdP(String idPName, int tenantId, String tenantDomain) // Remove cache entries related to the force deleted idps. IdentityProvider identityProvider = this.getIdPByName(null, idPName, tenantId, tenantDomain); if (identityProvider != null) { - idPMgtDAO.forceDeleteIdP(idPName, tenantId, tenantDomain); + idPManagementFacade.forceDeleteIdP(idPName, tenantId, tenantDomain); clearIdpCache(idPName, tenantId, tenantDomain); } else { if (log.isDebugEnabled()) { @@ -711,7 +712,7 @@ public void forceDeleteIdPByResourceId(String resourceId, int tenantId, String t // Remove cache entries related to the force deleted idps. IdentityProvider identityProvider = this.getIdPByResourceId(resourceId, tenantId, tenantDomain); if (identityProvider != null) { - idPMgtDAO.forceDeleteIdPByResourceId(resourceId, tenantId, tenantDomain); + idPManagementFacade.forceDeleteIdPByResourceId(resourceId, tenantId, tenantDomain); clearIdpCache(identityProvider.getIdentityProviderName(), resourceId, tenantId, tenantDomain); } else { if (log.isDebugEnabled()) { @@ -843,7 +844,7 @@ public void deleteTenantRole(int tenantId, String role, String tenantDomain) } } - idPMgtDAO.deleteTenantRole(tenantId, role, tenantDomain); + idPManagementFacade.deleteTenantRole(tenantId, role, tenantDomain); } /** @@ -881,7 +882,7 @@ public void renameTenantRole(String newRoleName, String oldRoleName, int tenantI } } - idPMgtDAO.renameTenantRole(newRoleName, oldRoleName, tenantId, tenantDomain); + idPManagementFacade.renameTenantRole(newRoleName, oldRoleName, tenantId, tenantDomain); } /** @@ -916,7 +917,7 @@ public void deleteTenantClaimURI(int tenantId, String claimURI, String tenantDom } } - idPMgtDAO.deleteTenantRole(tenantId, claimURI, tenantDomain); + idPManagementFacade.deleteTenantRole(tenantId, claimURI, tenantDomain); } /** @@ -952,7 +953,7 @@ public void renameTenantClaimURI(String newClaimURI, String oldClaimURI, int ten } } - idPMgtDAO.renameTenantRole(newClaimURI, oldClaimURI, tenantId, tenantDomain); + idPManagementFacade.renameTenantRole(newClaimURI, oldClaimURI, tenantId, tenantDomain); } /** @@ -965,7 +966,7 @@ public boolean isIdPAvailableForAuthenticatorProperty(String authenticatorName, String idPEntityId, int tenantId) throws IdentityProviderManagementException { - return idPMgtDAO.isIdPAvailableForAuthenticatorProperty(authenticatorName, propertyName, idPEntityId, tenantId); + return idPManagementFacade.isIdPAvailableForAuthenticatorProperty(authenticatorName, propertyName, idPEntityId, tenantId); } /** @@ -980,14 +981,14 @@ public boolean isIdPAvailableForAuthenticatorProperty(String authenticatorName, public ConnectedAppsResult getConnectedApplications(String resourceId, int limit, int offset) throws IdentityProviderManagementException { - return idPMgtDAO.getConnectedApplications(resourceId, limit, offset); + return idPManagementFacade.getConnectedApplications(resourceId, limit, offset); } public ConnectedAppsResult getConnectedAppsOfLocalAuthenticator(String authenticatorId, int tenantId, Integer limit, Integer offset) throws IdentityProviderManagementException { - return idPMgtDAO.getConnectedAppsOfLocalAuthenticator(authenticatorId, tenantId, limit, offset); + return idPManagementFacade.getConnectedAppsOfLocalAuthenticator(authenticatorId, tenantId, limit, offset); } /** @@ -1021,7 +1022,7 @@ public String getIdPNameByMetadataProperty(Connection dbConnection, String prope } } - idPName = idPMgtDAO.getIdPNameByMetadataProperty(dbConnection, property, value, tenantId); + idPName = idPManagementFacade.getIdPNameByMetadataProperty(dbConnection, property, value, tenantId); if (idPName != null) { if (log.isDebugEnabled()) { log.debug("DB entry IDP name: " + idPName + " found for IDP metadata property name: " @@ -1061,7 +1062,7 @@ private String getIDPIssuerName(IdentityProvider identityProvider) { public Map getIdPNamesById(int tenantId, Set idpIds) throws IdentityProviderManagementException { - return idPMgtDAO.getIdPNamesById(tenantId, idpIds); + return idPManagementFacade.getIdPNamesById(tenantId, idpIds); } /** @@ -1075,6 +1076,20 @@ public Map getIdPNamesById(int tenantId, Set idpIds) public List getIdPGroupsByIds(List idpGroupIds, int tenantId) throws IdentityProviderManagementException { - return idPMgtDAO.getIdPGroupsByIds(idpGroupIds, tenantId); + return idPManagementFacade.getIdPGroupsByIds(idpGroupIds, tenantId); + } + + /** + * Get all user defined federated authenticators. + * + * @param tenantId Tenant ID. + * @return User defined FederatedAuthenticatorConfig list + * @throws IdentityProviderManagementException If an error occurred while retrieving user defined + * federated authenticator list. + */ + public List getAllUserDefinedFederatedAuthenticators(int tenantId) + throws IdentityProviderManagementException { + + return idPManagementFacade.getAllUserDefinedFederatedAuthenticators(tenantId); } } diff --git a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/dao/IdPManagementDAO.java b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/dao/IdPManagementDAO.java index 5c170ad8821b..d79cc2a44259 100644 --- a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/dao/IdPManagementDAO.java +++ b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/dao/IdPManagementDAO.java @@ -42,8 +42,10 @@ import org.wso2.carbon.identity.application.common.model.Property; import org.wso2.carbon.identity.application.common.model.ProvisioningConnectorConfig; import org.wso2.carbon.identity.application.common.model.RoleMapping; +import org.wso2.carbon.identity.application.common.model.UserDefinedFederatedAuthenticatorConfig; import org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants; import org.wso2.carbon.identity.application.common.util.IdentityApplicationManagementUtil; +import org.wso2.carbon.identity.base.AuthenticatorPropertyConstants; import org.wso2.carbon.identity.base.AuthenticatorPropertyConstants.AuthenticationType; import org.wso2.carbon.identity.base.AuthenticatorPropertyConstants.DefinedByType; import org.wso2.carbon.identity.base.IdentityConstants; @@ -55,7 +57,6 @@ import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.core.util.IdentityUtil; -import org.wso2.carbon.identity.secret.mgt.core.SecretsProcessor; import org.wso2.carbon.identity.secret.mgt.core.exception.SecretManagementException; import org.wso2.carbon.idp.mgt.IdentityProviderManagementClientException; import org.wso2.carbon.idp.mgt.IdentityProviderManagementException; @@ -114,6 +115,7 @@ import static org.wso2.carbon.idp.mgt.util.IdPManagementConstants.MySQL; import static org.wso2.carbon.idp.mgt.util.IdPManagementConstants.RESET_PROVISIONING_ENTITIES_ON_CONFIG_UPDATE; import static org.wso2.carbon.idp.mgt.util.IdPManagementConstants.SCOPE_LIST_PLACEHOLDER; +import static org.wso2.carbon.idp.mgt.util.IdPManagementConstants.SQLConstants.DEFINED_BY_COLUMN; import static org.wso2.carbon.idp.mgt.util.IdPManagementConstants.SQLQueries.GET_IDP_NAME_BY_RESOURCE_ID_SQL; import static org.wso2.carbon.idp.mgt.util.IdPManagementConstants.TEMPLATE_ID_IDP_PROPERTY_DISPLAY_NAME; import static org.wso2.carbon.idp.mgt.util.IdPManagementConstants.TEMPLATE_ID_IDP_PROPERTY_NAME; @@ -124,7 +126,7 @@ public class IdPManagementDAO { private static final Log log = LogFactory.getLog(IdPManagementDAO.class); - private final IdPSecretsProcessor idpSecretsProcessorService = new IdPSecretsProcessor();; + private final IdPSecretsProcessor idpSecretsProcessorService = new IdPSecretsProcessor(); private static final String OPENID_IDP_ENTITY_ID = "IdPEntityId"; private static final String ENABLE_SMS_OTP_IF_RECOVERY_NOTIFICATION_ENABLED @@ -1161,7 +1163,8 @@ private FederatedAuthenticatorConfig[] getFederatedAuthenticatorConfigs( rs = prepStmt1.executeQuery(); while (rs.next()) { - FederatedAuthenticatorConfig authnConfig = new FederatedAuthenticatorConfig(); + FederatedAuthenticatorConfig authnConfig = createFederatedAuthenticatorConfig(DefinedByType.valueOf( + rs.getString(DEFINED_BY_COLUMN))); int authnId = rs.getInt("ID"); authnConfig.setName(rs.getString("NAME")); @@ -1172,7 +1175,6 @@ private FederatedAuthenticatorConfig[] getFederatedAuthenticatorConfigs( } authnConfig.setDisplayName(rs.getString("DISPLAY_NAME")); - authnConfig.setDefinedByType(DefinedByType.valueOf(rs.getString("DEFINED_BY"))); if (defaultAuthName != null && authnConfig.getName().equals(defaultAuthName)) { federatedIdp.getDefaultAuthenticatorConfig().setDisplayName(authnConfig.getDisplayName()); @@ -2182,11 +2184,13 @@ public ProvisioningConnectorConfig[] getProvisioningConnectorConfigs(Connection String blobValue = getBlobValue(rs2.getBinaryStream("PROPERTY_BLOB_VALUE")); String propertyType = rs2.getString("PROPERTY_TYPE"); + if (propertyType != null) { + propertyType = propertyType.trim(); + } String isSecret = rs2.getString("IS_SECRET"); property.setName(name); - if (propertyType != null && IdentityApplicationConstants.ConfigElements. - PROPERTY_TYPE_BLOB.equals(propertyType.trim())) { + if (IdentityApplicationConstants.ConfigElements.PROPERTY_TYPE_BLOB.equals(propertyType)) { property.setValue(blobValue); } else { property.setValue(value); @@ -3198,8 +3202,9 @@ private IdentityProvider getIDP(Connection dbConnection, String idPName, int idp federatedIdp.setFederatedAuthenticatorConfigs(getFederatedAuthenticatorConfigs( dbConnection, idPName, federatedIdp, tenantId)); - // Retrieve encrypted secrets from DB, decrypt and set to the federated authenticator configs. - if (federatedIdp.getFederatedAuthenticatorConfigs().length > 0) { + // Retrieve encrypted secrets from DB, decrypt and set to the system federated authenticator configs. + if (federatedIdp.getFederatedAuthenticatorConfigs().length > 0 && + federatedIdp.getFederatedAuthenticatorConfigs()[0].getDefinedByType() == DefinedByType.SYSTEM) { federatedIdp = idpSecretsProcessorService.decryptAssociatedSecrets(federatedIdp); } @@ -3439,7 +3444,7 @@ public IdentityProvider getIdPByAuthenticatorPropertyValue(Connection dbConnecti String roleClaimUri = rs.getString("ROLE_CLAIM_URI"); String defaultAuthenticatorName = rs.getString("DEFAULT_AUTHENTICATOR_NAME"); - String defaultAuthenticatorDefinedByType = rs.getString("DEFINED_BY"); + String defaultAuthenticatorDefinedByType = rs.getString(DEFINED_BY_COLUMN); String defaultProvisioningConnectorConfigName = rs.getString("DEFAULT_PRO_CONNECTOR_NAME"); federatedIdp.setIdentityProviderDescription(rs.getString("DESCRIPTION")); @@ -3919,9 +3924,12 @@ public String addIdPWithResourceId(IdentityProvider identityProvider, int tenant dbConnection, idPId, tenantId); } - // Add federated authenticator secret properties to IDN_SECRET table. identityProvider.setId(createdIDP.getId()); - identityProvider = idpSecretsProcessorService.encryptAssociatedSecrets(identityProvider); + // Add system federated authenticator secret properties to IDN_SECRET table. + if (identityProvider.getFederatedAuthenticatorConfigs().length > 0 && + identityProvider.getFederatedAuthenticatorConfigs()[0].getDefinedByType() == DefinedByType.SYSTEM) { + identityProvider = idpSecretsProcessorService.encryptAssociatedSecrets(identityProvider); + } // add federated authenticators. addFederatedAuthenticatorConfigs(identityProvider.getFederatedAuthenticatorConfigs(), @@ -4255,9 +4263,12 @@ public void updateIdPWithResourceId(String resourceId, IdentityProvider boolean isResidentIdP = IdentityApplicationConstants.RESIDENT_IDP_RESERVED_NAME .equals(newIdentityProvider.getIdentityProviderName()); - // Update secrets in IDN_SECRET table. newIdentityProvider.setId(Integer.toString(idpId)); - newIdentityProvider = idpSecretsProcessorService.encryptAssociatedSecrets(newIdentityProvider); + // Update secrets of system federated authenticator config in IDN_SECRET table. + if (newIdentityProvider.getFederatedAuthenticatorConfigs().length > 0 && newIdentityProvider + .getFederatedAuthenticatorConfigs()[0].getDefinedByType() == DefinedByType.SYSTEM) { + newIdentityProvider = idpSecretsProcessorService.encryptAssociatedSecrets(newIdentityProvider); + } // update federated authenticators. updateFederatedAuthenticatorConfigs( @@ -5953,6 +5964,63 @@ public List getIdPGroupsByIds(List idpGroupIds, int tenantId) } } + /** + * Get all user defined federated authenticators. + * + * @param tenantId Tenant ID. + * @return User defined FederatedAuthenticatorConfig list + * @throws IdentityProviderManagementException If an error occurred while retrieving user defined + * federated authenticator list. + */ + public List getAllUserDefinedFederatedAuthenticators(int tenantId) + throws IdentityProviderManagementException { + + List federatedAuthenticatorConfigs = new ArrayList<>(); + try (Connection connection = IdentityDatabaseUtil.getDBConnection(false); + PreparedStatement prepStmt = connection.prepareStatement( + IdPManagementConstants.SQLQueries.GET_ALL_USER_DEFINED_FEDERATED_AUTHENTICATORS)) { + prepStmt.setInt(1, tenantId); + try (ResultSet resultSet = prepStmt.executeQuery()) { + while (resultSet.next()) { + UserDefinedFederatedAuthenticatorConfig federatedAuthenticatorConfig = + new UserDefinedFederatedAuthenticatorConfig(); + federatedAuthenticatorConfig.setName(resultSet.getString("NAME")); + federatedAuthenticatorConfig.setDisplayName(resultSet.getString("DISPLAY_NAME")); + federatedAuthenticatorConfig.setEnabled(resultSet.getBoolean("IS_ENABLED")); + federatedAuthenticatorConfig.setDefinedByType(DefinedByType.USER); + federatedAuthenticatorConfigs.add(federatedAuthenticatorConfig); + int authnId = resultSet.getInt("ID"); + + getFederatedProperties(connection, authnId, federatedAuthenticatorConfig); + } + } + IdentityDatabaseUtil.commitTransaction(connection); + return federatedAuthenticatorConfigs; + } catch (SQLException e) { + throw new IdentityProviderManagementException("Error occurred while retrieving all user defined federated " + + "authenticators for tenant: " + tenantId, e); + } + } + + private void getFederatedProperties(Connection connection, int authnId, + FederatedAuthenticatorConfig federatedAuthenticatorConfig) throws SQLException{ + + try (PreparedStatement prepStmtProp = connection.prepareStatement( + IdPManagementConstants.SQLQueries.GET_IDP_AUTH_PROPS_SQL)) { + prepStmtProp.setInt(1, authnId); + Set properties = new HashSet(); + try (ResultSet resultSetProp = prepStmtProp.executeQuery()) { + while (resultSetProp.next()) { + Property property = new Property(); + property.setName(resultSetProp.getString(IdPManagementConstants.SQLConstants.PROPERTY_KEY)); + property.setValue(resultSetProp.getString(IdPManagementConstants.SQLConstants.PROPERTY_VALUE)); + properties.add(property); + } + federatedAuthenticatorConfig.setProperties(properties.toArray(new Property[properties.size()])); + } + } + } + private void resolveOtpConnectorProperties( Map propertiesFromConnectors) throws ConnectorException{ @@ -6058,6 +6126,15 @@ private void performConfigCorrectionForPasswordRecoveryConfigs(Connection dbConn updateIdentityProviderProperties(dbConnection, idpId, idpProperties, tenantId); } + private FederatedAuthenticatorConfig createFederatedAuthenticatorConfig(AuthenticatorPropertyConstants.DefinedByType + definedByType) { + + if (definedByType == AuthenticatorPropertyConstants.DefinedByType.SYSTEM) { + return new FederatedAuthenticatorConfig(); + } + return new UserDefinedFederatedAuthenticatorConfig(); + } + private void performConfigCorrectionForUsernameRecoveryConfigs(Connection dbConnection, int tenantId, int idpId, List idpProperties) throws SQLException { diff --git a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/dao/IdPManagementFacade.java b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/dao/IdPManagementFacade.java new file mode 100644 index 000000000000..d81da034e0ab --- /dev/null +++ b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/dao/IdPManagementFacade.java @@ -0,0 +1,366 @@ +/* + * 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.idp.mgt.dao; + +import org.apache.commons.lang.StringUtils; +import org.wso2.carbon.identity.application.common.model.*; +import org.wso2.carbon.identity.base.AuthenticatorPropertyConstants; +import org.wso2.carbon.identity.core.model.ExpressionNode; +import org.wso2.carbon.identity.core.util.IdentityTenantUtil; +import org.wso2.carbon.idp.mgt.IdentityProviderManagementClientException; +import org.wso2.carbon.idp.mgt.IdentityProviderManagementException; +import org.wso2.carbon.idp.mgt.IdentityProviderManagementServerException; +import org.wso2.carbon.idp.mgt.model.ConnectedAppsResult; +import org.wso2.carbon.idp.mgt.util.UserDefinedAuthenticatorEndpointConfigManager; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class IdPManagementFacade { + + private final IdPManagementDAO dao; + private final UserDefinedAuthenticatorEndpointConfigManager endpointConfigurationManager = + new UserDefinedAuthenticatorEndpointConfigManager(); + + public IdPManagementFacade(IdPManagementDAO dao) { + + this.dao = dao; + } + + public List getIdPs(Connection dbConnection, int tenantId, String tenantDomain) + throws IdentityProviderManagementException { + + return dao.getIdPs(dbConnection, tenantId, tenantDomain); + } + + public List getIdPsSearch(int tenantId, List expressionConditions, + int limit, int offset, String sortOrder, String sortBy, + List requiredAttributes) + throws IdentityProviderManagementServerException, IdentityProviderManagementClientException { + + return dao.getIdPsSearch(tenantId, expressionConditions, limit, offset, sortOrder, sortBy, requiredAttributes); + } + + public List getIdPsSearch(int tenantId, List expressionConditions, + int limit, int offset, String sortOrder, String sortBy) + throws IdentityProviderManagementServerException, IdentityProviderManagementClientException { + + return dao.getIdPsSearch(tenantId, expressionConditions, limit, offset, sortOrder, + sortBy); + } + + public List getIdPsSearch(Connection dbConnection, int tenantId, String tenantDomain, + String filter) throws IdentityProviderManagementException { + + return dao.getIdPsSearch(dbConnection, tenantId, tenantDomain, filter); + } + + public List getTrustedTokenIssuerSearch(int tenantId, List expressionNode, + int limit, int offset, String sortOrder, String sortBy, List requiredAttributes) + throws IdentityProviderManagementServerException, IdentityProviderManagementClientException { + + return dao.getTrustedTokenIssuerSearch(tenantId, expressionNode, limit, offset, sortOrder, sortBy, + requiredAttributes); + } + + public int getCountOfFilteredTokenIssuers(int tenantId, List expressionConditions) + throws IdentityProviderManagementServerException, IdentityProviderManagementClientException { + + return dao.getCountOfFilteredTokenIssuers(tenantId, expressionConditions); + } + + public int getCountOfFilteredIdPs(int tenantId, List expressionConditions) + throws IdentityProviderManagementServerException, IdentityProviderManagementClientException { + + return dao.getCountOfFilteredIdPs(tenantId, expressionConditions); + } + + public IdentityProvider getIdPByName(Connection dbConnection, String idPName, int tenantId, String tenantDomain) + throws IdentityProviderManagementException { + + return populateEndpointConfig(dao.getIdPByName(dbConnection, idPName, tenantId, tenantDomain), tenantDomain); + } + + public IdentityProvider getIDPbyId(Connection dbConnection, int idpId, int tenantId, String tenantDomain) + throws IdentityProviderManagementException { + + return populateEndpointConfig(dao.getIDPbyId(dbConnection, idpId, tenantId, tenantDomain), tenantDomain); + } + + public IdentityProvider getIDPbyResourceId(Connection dbConnection, String resourceId, int tenantId, + String tenantDomain) throws IdentityProviderManagementException { + + return populateEndpointConfig(dao.getIDPbyResourceId(dbConnection, resourceId, tenantId, tenantDomain), + tenantDomain); + } + + public String getIDPNameByResourceId(String resourceId) throws IdentityProviderManagementException { + + return dao.getIDPNameByResourceId(resourceId); + } + + public IdentityProvider getIdPByAuthenticatorPropertyValue(Connection dbConnection, String property, String value, + String authenticator, int tenantId, String tenantDomain) + throws IdentityProviderManagementException { + + return populateEndpointConfig(dao.getIdPByAuthenticatorPropertyValue(dbConnection, property, value, + authenticator, tenantId, tenantDomain), tenantDomain); + } + + public IdentityProvider getIdPByAuthenticatorPropertyValue(Connection dbConnection, String property, String value, + int tenantId, String tenantDomain) + throws IdentityProviderManagementException { + + return populateEndpointConfig(dao.getIdPByAuthenticatorPropertyValue(dbConnection, property, value, tenantId, + tenantDomain), tenantDomain); + } + + public IdentityProvider getIdPByRealmId(String realmId, int tenantId, String tenantDomain) + throws IdentityProviderManagementException { + + return populateEndpointConfig(dao.getIdPByRealmId(realmId, tenantId, tenantDomain), tenantDomain); + } + + public IdentityProvider getEnabledIdPByRealmId(String realmId, int tenantId, String tenantDomain) + throws IdentityProviderManagementException { + + return populateEndpointConfig(dao.getEnabledIdPByRealmId(realmId, tenantId, tenantDomain), tenantDomain); + } + + public String addIdPWithResourceId(IdentityProvider identityProvider, int tenantId) + throws IdentityProviderManagementException { + + String tenantDomain = IdentityTenantUtil.getTenantDomain(tenantId); + addEndpointConfig(identityProvider, tenantDomain); + try { + return dao.addIdPWithResourceId(identityProvider, tenantId); + } catch (IdentityProviderManagementException e) { + deleteEndpointConfig(identityProvider, tenantDomain); + throw e; + } + } + + public void updateIdPWithResourceId(String resourceId, IdentityProvider newIdentityProvider, + IdentityProvider currentIdentityProvider, int tenantId) + throws IdentityProviderManagementException { + + updateEndpointConfig(newIdentityProvider, currentIdentityProvider, + IdentityTenantUtil.getTenantDomain(tenantId)); + try { + dao.updateIdPWithResourceId(resourceId, newIdentityProvider, currentIdentityProvider, tenantId); + } catch (IdentityProviderManagementException e) { + updateEndpointConfig(currentIdentityProvider, newIdentityProvider, + IdentityTenantUtil.getTenantDomain(tenantId)); + throw e; + } + } + + public boolean isIdpReferredBySP(String idPName, int tenantId) throws IdentityProviderManagementException { + + return dao.isIdpReferredBySP(idPName, tenantId); + } + + public void deleteIdP(String idPName, int tenantId, String tenantDomain) + throws IdentityProviderManagementException { + + IdentityProvider identityProvider = getIdPByName(null, idPName, tenantId, tenantDomain); + deleteEndpointConfig(identityProvider, tenantDomain); + try { + dao.deleteIdP(idPName, tenantId, tenantDomain); + } catch (IdentityProviderManagementException e) { + addEndpointConfig(identityProvider, tenantDomain); + throw e; + } + } + + public void deleteIdPs(int tenantId) throws IdentityProviderManagementException { + + // TODO: Replace loops with batch operations once issue:https://github.com/wso2/product-is/issues/21783 is done. + List idpList = getIdPs(null, tenantId, + IdentityTenantUtil.getTenantDomain(tenantId)); + for (IdentityProvider idp : idpList) { + deleteEndpointConfig(idp, IdentityTenantUtil.getTenantDomain(tenantId)); + } + try { + dao.deleteIdPs(tenantId); + } catch (IdentityProviderManagementException e) { + for (IdentityProvider idp : idpList) { + addEndpointConfig(idp, IdentityTenantUtil.getTenantDomain(tenantId)); + } + throw e; + } + } + + public void deleteIdPByResourceId(String resourceId, int tenantId, String tenantDomain) + throws IdentityProviderManagementException { + + IdentityProvider identityProvider = getIDPbyResourceId(null, resourceId, tenantId, tenantDomain); + deleteEndpointConfig(identityProvider, tenantDomain); + try { + dao.deleteIdPByResourceId(identityProvider.getResourceId(), tenantId, tenantDomain); + } catch (IdentityProviderManagementException e) { + addEndpointConfig(identityProvider, tenantDomain); + throw e; + } + } + + public void forceDeleteIdP(String idPName, int tenantId, String tenantDomain) + throws IdentityProviderManagementException { + + IdentityProvider identityProvider = getIdPByName(null, idPName, tenantId, tenantDomain); + deleteEndpointConfig(identityProvider, tenantDomain); + try { + dao.forceDeleteIdP(idPName, tenantId, tenantDomain); + } catch (IdentityProviderManagementException e) { + addEndpointConfig(identityProvider, tenantDomain); + throw e; + } + } + + public void forceDeleteIdPByResourceId(String resourceId, int tenantId, String tenantDomain) + throws IdentityProviderManagementException { + + IdentityProvider identityProvider = getIDPbyResourceId(null, resourceId, tenantId, tenantDomain); + deleteEndpointConfig(identityProvider, tenantDomain); + try { + dao.forceDeleteIdPByResourceId(resourceId, tenantId, tenantDomain); + } catch (IdentityProviderManagementException e) { + addEndpointConfig(identityProvider, tenantDomain); + throw e; + } + } + + public void deleteTenantRole(int tenantId, String role, String tenantDomain) + throws IdentityProviderManagementException { + + dao.deleteTenantRole(tenantId, role, tenantDomain); + } + + public void renameTenantRole(String newRoleName, String oldRoleName, int tenantId, String tenantDomain) + throws IdentityProviderManagementException { + + dao.renameTenantRole(newRoleName, oldRoleName, tenantId, tenantDomain); + } + + public boolean isIdPAvailableForAuthenticatorProperty(String authenticatorName, String propertyName, + String idPEntityId, int tenantId) + throws IdentityProviderManagementException { + + return dao.isIdPAvailableForAuthenticatorProperty(authenticatorName, propertyName, idPEntityId, tenantId); + } + + public ConnectedAppsResult getConnectedApplications(String resourceId, int limit, int offset) + throws IdentityProviderManagementException { + + return dao.getConnectedApplications(resourceId, limit, offset); + } + + public ConnectedAppsResult getConnectedAppsOfLocalAuthenticator(String authenticatorId, int tenantId, + Integer limit, Integer offset) + throws IdentityProviderManagementException { + + return dao.getConnectedAppsOfLocalAuthenticator(authenticatorId, tenantId, limit, offset); + } + + public String getIdPNameByMetadataProperty(Connection dbConnection, String property, String value, int tenantId) + throws IdentityProviderManagementException { + + return dao.getIdPNameByMetadataProperty(dbConnection, property, value, tenantId); + } + + public Map getIdPNamesById(int tenantId, Set idpIds) + throws IdentityProviderManagementException { + + return dao.getIdPNamesById(tenantId, idpIds); + } + + public List getIdPGroupsByIds(List idpGroupIds, int tenantId) + throws IdentityProviderManagementException { + + return dao.getIdPGroupsByIds(idpGroupIds, tenantId); + } + + public List getAllUserDefinedFederatedAuthenticators(int tenantId) + throws IdentityProviderManagementException { + + // TODO: Replace loops with batch operations once issue:https://github.com/wso2/product-is/issues/21783 is done. + List configList = dao.getAllUserDefinedFederatedAuthenticators(tenantId); + for (FederatedAuthenticatorConfig config : configList) { + endpointConfigurationManager.resolveEndpointConfig(config, IdentityTenantUtil.getTenantDomain(tenantId)); + } + return configList; + } + + private IdentityProvider populateEndpointConfig(IdentityProvider identityProvider, String tenantDomain) + throws IdentityProviderManagementException { + + if (identityProvider == null || identityProvider.getFederatedAuthenticatorConfigs().length != 1) { + return identityProvider; + } + endpointConfigurationManager.resolveEndpointConfig(identityProvider.getFederatedAuthenticatorConfigs()[0], + tenantDomain); + return identityProvider; + } + + private void addEndpointConfig(IdentityProvider identityProvider, String tenantDomain) + throws IdentityProviderManagementException { + + if (identityProvider == null || identityProvider.getFederatedAuthenticatorConfigs().length != 1) { + return; + } + endpointConfigurationManager.addEndpointConfig(identityProvider.getFederatedAuthenticatorConfigs()[0], + tenantDomain); + } + + private void updateEndpointConfig(IdentityProvider newIdentityProvider, IdentityProvider oldIdentityProvider, + String tenantDomain) + throws IdentityProviderManagementException { + + if (newIdentityProvider == null || newIdentityProvider.getFederatedAuthenticatorConfigs().length != 1) { + return; + } + FederatedAuthenticatorConfig newFederatedAuth = newIdentityProvider.getFederatedAuthenticatorConfigs()[0]; + FederatedAuthenticatorConfig oldFederatedAuth = oldIdentityProvider.getFederatedAuthenticatorConfigs()[0]; + if (newFederatedAuth.getDefinedByType() == AuthenticatorPropertyConstants.DefinedByType.SYSTEM) { + return; + } + + if (StringUtils.equals(newFederatedAuth.getName(), oldFederatedAuth.getName())) { + endpointConfigurationManager.updateEndpointConfig(newIdentityProvider.getFederatedAuthenticatorConfigs()[0], + oldIdentityProvider.getFederatedAuthenticatorConfigs()[0], + tenantDomain); + } + endpointConfigurationManager.deleteEndpointConfig(oldFederatedAuth, tenantDomain); + endpointConfigurationManager.addEndpointConfig(newFederatedAuth, tenantDomain); + } + + private void deleteEndpointConfig(IdentityProvider identityProvider, String tenantDomain) + throws IdentityProviderManagementException { + + if (identityProvider == null || identityProvider.getFederatedAuthenticatorConfigs().length != 1) { + return; + } + endpointConfigurationManager.deleteEndpointConfig(identityProvider.getFederatedAuthenticatorConfigs()[0], + tenantDomain); + } +} + diff --git a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/internal/IdPManagementServiceComponent.java b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/internal/IdPManagementServiceComponent.java index fb0e52a344d9..e6d3e590735e 100644 --- a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/internal/IdPManagementServiceComponent.java +++ b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/internal/IdPManagementServiceComponent.java @@ -33,6 +33,7 @@ import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.identity.action.management.service.ActionManagementService; import org.wso2.carbon.identity.application.common.model.IdentityProvider; import org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants; import org.wso2.carbon.identity.claim.metadata.mgt.ClaimMetadataManagementService; @@ -508,4 +509,21 @@ protected void unsetClaimMetaMgtService(ClaimMetadataManagementService claimMeta IdpMgtServiceComponentHolder.getInstance().setClaimMetadataManagementService(null); } + + @Reference( + name = "action.management.service", + service = ActionManagementService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetActionManagementService" + ) + protected void setActionManagementService(ActionManagementService actionManagementService) { + + IdpMgtServiceComponentHolder.getInstance().setActionManagementService(actionManagementService); + } + + protected void unsetActionManagementService(ActionManagementService actionManagementService) { + + IdpMgtServiceComponentHolder.getInstance().setActionManagementService(null); + } } diff --git a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/internal/IdpMgtServiceComponentHolder.java b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/internal/IdpMgtServiceComponentHolder.java index 02259c3cf601..a46d26abbfe2 100644 --- a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/internal/IdpMgtServiceComponentHolder.java +++ b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/internal/IdpMgtServiceComponentHolder.java @@ -19,6 +19,7 @@ package org.wso2.carbon.idp.mgt.internal; import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.identity.action.management.service.ActionManagementService; import org.wso2.carbon.identity.application.common.model.IdentityProvider; import org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants; import org.wso2.carbon.identity.claim.metadata.mgt.ClaimMetadataManagementService; @@ -57,6 +58,7 @@ public static IdpMgtServiceComponentHolder getInstance() { private ClaimMetadataManagementService claimMetadataManagementService; private SecretManager secretManager; private SecretResolveManager secretResolveManager; + private ActionManagementService actionManagementService; private List metadataConverters = new ArrayList<>(); @@ -188,4 +190,24 @@ public void setClaimMetadataManagementService(ClaimMetadataManagementService cla this.claimMetadataManagementService = claimMetadataManagementService; } + + /** + * Get the Action Management Service. + * + * @return ActionManagementService instance. + */ + public ActionManagementService getActionManagementService() { + + return actionManagementService; + } + + /** + * Set the Action Management Service. + * + * @param actionManagementService ActionManagementService instance. + */ + public void setActionManagementService(ActionManagementService actionManagementService) { + + this.actionManagementService = actionManagementService; + } } diff --git a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/util/IdPManagementConstants.java b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/util/IdPManagementConstants.java index 47d1a1b78ecc..06dd1ad5a73d 100644 --- a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/util/IdPManagementConstants.java +++ b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/util/IdPManagementConstants.java @@ -129,11 +129,21 @@ public class IdPManagementConstants { public static final String SMS_OTP_PASSWORD_RECOVERY_PROPERTY = "Recovery.Notification.Password.smsOtp.Enable"; + // User defined federated authenticator related constants. + public static final String USER_DEFINED_AUTHENTICATOR_NAME_REGEX = "^[a-zA-Z0-9][a-zA-Z0-9-_]*$"; + // Resident IDP Username Recovery Configs. public static final String USERNAME_RECOVERY_PROPERTY = "Recovery.Notification.Username.Enable"; public static final String EMAIL_USERNAME_RECOVERY_PROPERTY = "Recovery.Notification.Username.Email.Enable"; public static final String SMS_USERNAME_RECOVERY_PROPERTY = "Recovery.Notification.Username.SMS.Enable"; + public static class SQLConstants { + + public static final String DEFINED_BY_COLUMN = "DEFINED_BY"; + public static final String PROPERTY_KEY = "PROPERTY_KEY"; + public static final String PROPERTY_VALUE = "PROPERTY_VALUE"; + } + public static class SQLQueries { public static final String GET_IDPS_SQL = "SELECT NAME, IS_PRIMARY, HOME_REALM_ID, DESCRIPTION, " + @@ -590,6 +600,8 @@ public static class SQLQueries { public static final String GET_IDP_GROUPS_BY_IDP_GROUP_IDS = "SELECT IDP_GROUP.UUID, IDP_GROUP.GROUP_NAME, " + "IDP.UUID AS IDP_ID FROM IDP_GROUP LEFT JOIN IDP ON IDP.ID = IDP_GROUP.IDP_ID WHERE " + "IDP_GROUP.TENANT_ID = ? AND IDP_GROUP.UUID IN (" + IDP_GROUP_LIST_PLACEHOLDER + ")"; + public static final String GET_ALL_USER_DEFINED_FEDERATED_AUTHENTICATORS = + "SELECT * FROM IDP_AUTHENTICATOR WHERE TENANT_ID = ? AND DEFINED_BY = 'USER'"; } public enum ErrorMessage { @@ -612,6 +624,12 @@ public enum ErrorMessage { ERROR_CODE_NOT_EXISTING_OUTBOUND_PROVISIONING_ROLE("IDP-60010", "One or more outbound " + "provisioning roles does not exist"), ERROR_CODE_INVALID_CONNECTOR_CONFIGURATION("IDP-60011", "Invalid connector configuration. %s"), + ERROR_CODE_NO_SYSTEM_AUTHENTICATOR_FOUND("IDP-60012", "No system authenticator found for the " + + "provided authenticator Id %s."), + ERROR_CODE_AUTHENTICATOR_NAME_ALREADY_TAKEN("IDP-60013", "Federated authenticator name %s" + + " is already taken."), + ERROR_INVALID_AUTHENTICATOR_NAME("IDP-60014", "Federated authenticator name does not match the" + + " regex pattern %s."), // Server Errors. ERROR_CODE_UNEXPECTED("IDP-65001", "Unexpected Error"), @@ -624,7 +642,15 @@ public enum ErrorMessage { "applications of Identity Provider with resource ID: %s."), ERROR_CODE_VALIDATING_OUTBOUND_PROVISIONING_ROLES("IDP-65008", "Error while validating " + "the outbound provisioning roles"), - ERROR_CODE_RETRIEVING_IDP_GROUPS("IDP-65009", "Error while retrieving IDP groups"); + ERROR_CODE_RETRIEVING_IDP_GROUPS("IDP-65009", "Error while retrieving IDP groups"), + ERROR_CODE_ADDING_ENDPOINT_CONFIG("IDP-65010", "An error occurred while adding" + + " endpoint configuration for authenticator: %s."), + ERROR_CODE_UPDATING_ENDPOINT_CONFIG("IDP-65011", "An error occurred while updating" + + " endpoint configuration for authenticator: %s."), + ERROR_CODE_RETRIEVING_ENDPOINT_CONFIG("IDP-65011", "An error occurred while retrieving" + + " endpoint configuration for authenticator: %s."), + ERROR_CODE_DELETING_ENDPOINT_CONFIG("IDP-65012", "An error occurred while deleting" + + " endpoint configuration for authenticator: %s."); private final String code; private final String message; diff --git a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/util/UserDefinedAuthenticatorEndpointConfigManager.java b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/util/UserDefinedAuthenticatorEndpointConfigManager.java new file mode 100644 index 000000000000..0c10c854c771 --- /dev/null +++ b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/main/java/org/wso2/carbon/idp/mgt/util/UserDefinedAuthenticatorEndpointConfigManager.java @@ -0,0 +1,221 @@ +/* + * 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.idp.mgt.util; + +import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; +import org.wso2.carbon.identity.action.management.exception.ActionMgtException; +import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.EndpointConfig; +import org.wso2.carbon.identity.application.common.model.FederatedAuthenticatorConfig; +import org.wso2.carbon.identity.application.common.model.Property; +import org.wso2.carbon.identity.application.common.model.UserDefinedAuthenticatorEndpointConfig; +import org.wso2.carbon.identity.application.common.model.UserDefinedFederatedAuthenticatorConfig; +import org.wso2.carbon.identity.base.AuthenticatorPropertyConstants; +import org.wso2.carbon.idp.mgt.IdentityProviderManagementClientException; +import org.wso2.carbon.idp.mgt.IdentityProviderManagementException; +import org.wso2.carbon.idp.mgt.IdentityProviderManagementServerException; +import org.wso2.carbon.idp.mgt.internal.IdpMgtServiceComponentHolder; +import org.wso2.carbon.idp.mgt.util.IdPManagementConstants.ErrorMessage; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +/** + * This class responsible for managing authenticator endpoint configurations for the user defined federated + * authenticators. + */ +public class UserDefinedAuthenticatorEndpointConfigManager { + + private static final String ACTION_ID_PROPERTY = "actionId"; + + /** + * Create a new action for given endpoint configurations of the user defined authenticator. + * + * @param config The federated application authenticator configuration. + * @param tenantDomain The id of Tenant domain. + * @throws IdentityProviderManagementServerException If an error occurs while adding the action. + */ + public void addEndpointConfig(FederatedAuthenticatorConfig config, String tenantDomain) + throws IdentityProviderManagementException { + + if (config.getDefinedByType() != AuthenticatorPropertyConstants.DefinedByType.USER) { + return; + } + + try { + UserDefinedFederatedAuthenticatorConfig castedConfig = (UserDefinedFederatedAuthenticatorConfig) config; + Action action = IdpMgtServiceComponentHolder.getInstance().getActionManagementService() + .addAction(Action.ActionTypes.AUTHENTICATION.getPathParam(), + buildActionToCreate(castedConfig.getName(), + castedConfig.getEndpointConfig().getEndpointConfig()), + tenantDomain); + Property endpointProperty = new Property(); + endpointProperty.setName(ACTION_ID_PROPERTY); + endpointProperty.setValue(action.getId()); + endpointProperty.setConfidential(false); + config.setProperties(new Property[]{endpointProperty}); + } catch (ActionMgtException e) { + throw handleActionMgtException(ErrorMessage.ERROR_CODE_ADDING_ENDPOINT_CONFIG, e, config.getName()); + } + } + + /** + * Updated associated action for given updated endpoint configurations of the user defined authenticator. + * + * @param newConfig The federated application authenticator configuration to be updated. + * @param oldConfig The current federated application authenticator configuration. + * @param tenantDomain The id of Tenant domain. + * @throws IdentityProviderManagementServerException If an error occurs while updating associated action. + */ + public void updateEndpointConfig(FederatedAuthenticatorConfig newConfig, FederatedAuthenticatorConfig oldConfig, + String tenantDomain) throws IdentityProviderManagementException { + + if (oldConfig.getDefinedByType() != AuthenticatorPropertyConstants.DefinedByType.USER) { + return; + } + + String actionId = getActionIdFromProperty(oldConfig.getProperties(), oldConfig.getName()); + try { + UserDefinedFederatedAuthenticatorConfig castedConfig = (UserDefinedFederatedAuthenticatorConfig) newConfig; + IdpMgtServiceComponentHolder.getInstance().getActionManagementService() + .updateAction(Action.ActionTypes.AUTHENTICATION.getPathParam(), + actionId, + buildActionToUpdate(castedConfig.getEndpointConfig().getEndpointConfig()), + tenantDomain); + newConfig.setProperties(oldConfig.getProperties()); + } catch (ActionMgtException e) { + throw handleActionMgtException(ErrorMessage.ERROR_CODE_UPDATING_ENDPOINT_CONFIG, e, newConfig.getName()); + } + } + + /** + * Retrieve associated action of the user defined authenticator. + * + * @param config The federated application authenticator configuration. + * @param tenantDomain The id of Tenant domain. + * @return Federated authenticator with endpoint configurations resolved. + * @throws IdentityProviderManagementServerException If an error occurs retrieving updating associated action. + */ + public FederatedAuthenticatorConfig resolveEndpointConfig(FederatedAuthenticatorConfig config, + String tenantDomain) throws IdentityProviderManagementException { + + if (config.getDefinedByType() != AuthenticatorPropertyConstants.DefinedByType.USER) { + return config; + } + + String actionId = getActionIdFromProperty(config.getProperties(), config.getName()); + try { + UserDefinedFederatedAuthenticatorConfig castedConfig = (UserDefinedFederatedAuthenticatorConfig) config; + Action action = IdpMgtServiceComponentHolder.getInstance().getActionManagementService() + .getActionByActionId(Action.ActionTypes.AUTHENTICATION.getPathParam(), + actionId, + tenantDomain); + + castedConfig.setEndpointConfig(buildUserDefinedAuthenticatorEndpointConfig(action.getEndpoint())); + return castedConfig; + } catch (ActionMgtException e) { + throw handleActionMgtException(ErrorMessage.ERROR_CODE_RETRIEVING_ENDPOINT_CONFIG, e, config.getName()); + } + } + + private UserDefinedAuthenticatorEndpointConfig buildUserDefinedAuthenticatorEndpointConfig( + EndpointConfig endpointConfig) { + + Map propMap = new HashMap<>(); + endpointConfig.getAuthentication().getProperties() + .forEach(prop -> propMap.put(prop.getName(), prop.getValue())); + return new UserDefinedAuthenticatorEndpointConfig.UserDefinedAuthenticatorEndpointConfigBuilder() + .uri(endpointConfig.getUri()) + .authenticationType(endpointConfig.getAuthentication().getType().getName()) + .authenticationProperties(propMap) + .build(); + } + + /** + * Delete associated action of the user defined authenticator. + * + * @param config The federated application authenticator configuration. + * @param tenantDomain The id of Tenant domain. + * + * @throws IdentityProviderManagementServerException If an error occurs while deleting associated action. + */ + public void deleteEndpointConfig(FederatedAuthenticatorConfig config, String tenantDomain) throws + IdentityProviderManagementException { + + if (config.getDefinedByType() != AuthenticatorPropertyConstants.DefinedByType.USER) { + return; + } + + String actionId = getActionIdFromProperty(config.getProperties(), config.getName()); + try { + IdpMgtServiceComponentHolder.getInstance().getActionManagementService() + .deleteAction(Action.ActionTypes.AUTHENTICATION.getPathParam(), + actionId, + tenantDomain); + } catch (ActionMgtException e) { + throw handleActionMgtException(ErrorMessage.ERROR_CODE_DELETING_ENDPOINT_CONFIG, e, config.getName()); + } + } + + private Action buildActionToCreate(String authenticatorName, EndpointConfig endpointConfig) { + + Action.ActionRequestBuilder actionRequestBuilder = new Action.ActionRequestBuilder(); + actionRequestBuilder.name(authenticatorName); + actionRequestBuilder.description(String.format("This is the action associated to the user defined federated" + + "authenticator %s.", authenticatorName)); + actionRequestBuilder.endpoint(endpointConfig); + + return actionRequestBuilder.build(); + } + + private Action buildActionToUpdate(EndpointConfig endpointConfig) { + + Action.ActionRequestBuilder actionRequestBuilder = new Action.ActionRequestBuilder(); + actionRequestBuilder.endpoint(endpointConfig); + + return actionRequestBuilder.build(); + } + + private String getActionIdFromProperty(Property[] properties, String authenticatorName) + throws IdentityProviderManagementServerException { + + return Arrays.stream(properties) + .filter(property -> ACTION_ID_PROPERTY.equals(property.getName())) + .map(Property::getValue) + .findFirst() + .orElseThrow(() -> new IdentityProviderManagementServerException( + "No action Id was found in the properties of the authenticator configurations for the " + + "authenticator: " + authenticatorName)); + } + + private static IdentityProviderManagementClientException handleActionMgtException(ErrorMessage idpMgtError, + Throwable actionException, String... data) + throws IdentityProviderManagementException { + + if (actionException instanceof ActionMgtClientException) { + ActionMgtClientException error = (ActionMgtClientException) actionException; + throw new IdentityProviderManagementClientException( + idpMgtError.getCode(), idpMgtError.getMessage(), error.getDescription()); + } + + throw new IdentityProviderManagementServerException(idpMgtError.getCode(), + String.format(idpMgtError.getMessage(), data), actionException); + } +} diff --git a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/test/java/org/wso2/carbon/idp/mgt/IdentityProviderManagementServiceTest.java b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/test/java/org/wso2/carbon/idp/mgt/IdentityProviderManagementServiceTest.java index ec3ba2b88fd7..870c9f6890e9 100644 --- a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/test/java/org/wso2/carbon/idp/mgt/IdentityProviderManagementServiceTest.java +++ b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/test/java/org/wso2/carbon/idp/mgt/IdentityProviderManagementServiceTest.java @@ -27,6 +27,11 @@ import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.wso2.carbon.core.util.CryptoUtil; +import org.wso2.carbon.identity.action.management.exception.ActionMgtClientException; +import org.wso2.carbon.identity.action.management.exception.ActionMgtServerException; +import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.EndpointConfig; +import org.wso2.carbon.identity.action.management.service.ActionManagementService; import org.wso2.carbon.identity.application.common.ApplicationAuthenticatorService; import org.wso2.carbon.identity.application.common.ProvisioningConnectorService; import org.wso2.carbon.identity.application.common.model.Claim; @@ -40,6 +45,8 @@ import org.wso2.carbon.identity.application.common.model.Property; import org.wso2.carbon.identity.application.common.model.ProvisioningConnectorConfig; import org.wso2.carbon.identity.application.common.model.RoleMapping; +import org.wso2.carbon.identity.application.common.model.UserDefinedAuthenticatorEndpointConfig; +import org.wso2.carbon.identity.application.common.model.UserDefinedFederatedAuthenticatorConfig; import org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants; import org.wso2.carbon.identity.base.AuthenticatorPropertyConstants.DefinedByType; import org.wso2.carbon.identity.claim.metadata.mgt.ClaimMetadataManagementServiceImpl; @@ -57,7 +64,9 @@ import org.wso2.carbon.idp.mgt.dao.CacheBackedIdPMgtDAO; import org.wso2.carbon.idp.mgt.dao.IdPManagementDAO; import org.wso2.carbon.idp.mgt.internal.IdpMgtServiceComponentHolder; +import org.wso2.carbon.idp.mgt.util.ActionMgtTestUtil; import org.wso2.carbon.idp.mgt.util.IdPManagementConstants; +import org.wso2.carbon.idp.mgt.util.IdPManagementConstants.ErrorMessage; import org.wso2.carbon.idp.mgt.util.MetadataConverter; import java.io.ByteArrayInputStream; @@ -67,18 +76,26 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; +import java.util.HashMap; import java.util.List; +import java.util.Map; import javax.xml.stream.XMLStreamException; +import static org.junit.Assert.assertThrows; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.when; +import static org.mockito.Mockito.verify; +import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertThrows; import static org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_ID; import static java.lang.Boolean.TRUE; @@ -96,7 +113,20 @@ public class IdentityProviderManagementServiceTest { MetadataConverter mockMetadataConverter; private IdentityProviderManagementService identityProviderManagementService; + private CacheBackedIdPMgtDAO dao; + private CacheBackedIdPMgtDAO daoForException; + private Field field; + private IdentityProviderManager identityProviderManager; private MockedStatic cryptoUtil; + private ActionManagementService actionManagementService; + + private static final String ASSOCIATED_ACTION_ID = "Dummy_Action_ID"; + private static final String CUSTOM_IDP_NAME = "customIdP"; + private static Action action; + private static EndpointConfig endpointConfig; + private static EndpointConfig endpointConfigToBeUpdated; + private IdentityProvider idpForErrorScenarios; + private IdentityProvider userDefinedIdP; @BeforeClass public void setUpClass() throws Exception { @@ -112,12 +142,23 @@ public void setUpClass() throws Exception { CryptoUtil mockCryptoUtil = mock(CryptoUtil.class); cryptoUtil.when(CryptoUtil::getDefaultCryptoUtil).thenReturn(mockCryptoUtil); - CacheBackedIdPMgtDAO dao = new CacheBackedIdPMgtDAO(new IdPManagementDAO()); - IdentityProviderManager identityProviderManager = mock(IdentityProviderManager.class); + dao = new CacheBackedIdPMgtDAO(new IdPManagementDAO()); + identityProviderManager = mock(IdentityProviderManager.class); identityProviderManagementService = new IdentityProviderManagementService(); - Field field = IdentityProviderManager.class.getDeclaredField("dao"); + field = IdentityProviderManager.class.getDeclaredField("dao"); field.setAccessible(true); field.set(identityProviderManager, dao); + + registerSystemAuthenticators(); + + endpointConfig = ActionMgtTestUtil.createEndpointConfig("http://localhost", "admin", "admin"); + endpointConfigToBeUpdated = ActionMgtTestUtil.createEndpointConfig( + "http://localhost1", "admin1", "admin1"); + action = ActionMgtTestUtil.createAction(endpointConfig); + userDefinedIdP = ActionMgtTestUtil.createIdPWithUserDefinedFederatedAuthenticatorConfig( + CUSTOM_IDP_NAME, action.getEndpoint()); + idpForErrorScenarios = ActionMgtTestUtil.createIdPWithUserDefinedFederatedAuthenticatorConfig( + CUSTOM_IDP_NAME + "Error", action.getEndpoint()); } @AfterClass @@ -128,18 +169,121 @@ public void tearDownClass() { @BeforeMethod public void setUp() throws Exception { + field.set(identityProviderManager, dao); mockMetadataConverter = mock(MetadataConverter.class); List metadataConverterList = Arrays.asList(mockMetadataConverter); IdpMgtServiceComponentHolder.getInstance().setMetadataConverters(metadataConverterList); + + actionManagementService = mock(ActionManagementService.class); + IdpMgtServiceComponentHolder.getInstance().setActionManagementService(actionManagementService); + when(actionManagementService.addAction(anyString(), any(), any())).thenReturn(action); + when(actionManagementService.updateAction(anyString(), any(), any(), any())).thenReturn(action); + when(actionManagementService.getActionByActionId(anyString(), any(), any())).thenReturn(action); + doNothing().when(actionManagementService).deleteAction(anyString(), any(), any()); } @AfterMethod public void tearDown() throws Exception { + IdpMgtServiceComponentHolder.getInstance().setActionManagementService(actionManagementService); + field.set(identityProviderManager, dao); // Clear Database after every test. removeTestIdps(); } + private void registerSystemAuthenticators() { + + FederatedAuthenticatorConfig federatedAuthenticatorConfig = new FederatedAuthenticatorConfig(); + federatedAuthenticatorConfig.setDisplayName("DisplayName"); + federatedAuthenticatorConfig.setName("SAMLSSOAuthenticator"); + federatedAuthenticatorConfig.setEnabled(true); + federatedAuthenticatorConfig.setDefinedByType(DefinedByType.SYSTEM); + Property property1 = new Property(); + property1.setName("SPEntityId"); + property1.setConfidential(false); + Property property2 = new Property(); + property2.setName("meta_data_saml"); + property2.setConfidential(false); + federatedAuthenticatorConfig.setProperties(new Property[]{property1, property2}); + ApplicationAuthenticatorService.getInstance().addFederatedAuthenticator(federatedAuthenticatorConfig); + + FederatedAuthenticatorConfig config = new FederatedAuthenticatorConfig(); + config.setName("Name"); + config.setDisplayName("DisplayName"); + config.setEnabled(true); + config.setDefinedByType(DefinedByType.USER); + ApplicationAuthenticatorService.getInstance().addFederatedAuthenticator(config); + } + + @DataProvider + public Object[][] addFederatedAuthenticatorData() { + + FederatedAuthenticatorConfig systemDefinedAuthWithInvalidName = new FederatedAuthenticatorConfig(); + systemDefinedAuthWithInvalidName.setDisplayName("DisplayName1"); + systemDefinedAuthWithInvalidName.setName("NonRegisteredAuthenticator"); + systemDefinedAuthWithInvalidName.setEnabled(true); + systemDefinedAuthWithInvalidName.setDefinedByType(DefinedByType.SYSTEM); + + FederatedAuthenticatorConfig userDefinedAuthWithExistingName = new UserDefinedFederatedAuthenticatorConfig(); + userDefinedAuthWithExistingName.setDisplayName("DisplayName1"); + userDefinedAuthWithExistingName.setName("SAMLSSOAuthenticator"); + userDefinedAuthWithExistingName.setEnabled(true); + userDefinedAuthWithExistingName.setDefinedByType(DefinedByType.USER); + + FederatedAuthenticatorConfig userDefinedAuthWithInvalidName = new UserDefinedFederatedAuthenticatorConfig(); + userDefinedAuthWithInvalidName.setDisplayName("DisplayName1"); + userDefinedAuthWithInvalidName.setName("Invalid regex name"); + userDefinedAuthWithInvalidName.setEnabled(true); + userDefinedAuthWithInvalidName.setDefinedByType(DefinedByType.USER); + + return new Object[][]{ + {systemDefinedAuthWithInvalidName, ErrorMessage.ERROR_CODE_NO_SYSTEM_AUTHENTICATOR_FOUND}, + {userDefinedAuthWithExistingName, ErrorMessage.ERROR_CODE_AUTHENTICATOR_NAME_ALREADY_TAKEN}, + {userDefinedAuthWithInvalidName, ErrorMessage.ERROR_INVALID_AUTHENTICATOR_NAME} + }; + } + + @Test(dataProvider = "addFederatedAuthenticatorData") + public void testFederatedAuthenticatorNameValidation(FederatedAuthenticatorConfig config, ErrorMessage error) { + + IdentityProvider identityProvider = new IdentityProvider(); + identityProvider.setIdentityProviderName("testInvalidIdP"); + identityProvider.setDisplayName("test Invalid IdP"); + identityProvider.setFederatedAuthenticatorConfigs(new FederatedAuthenticatorConfig[]{config}); + + IdentityProviderManagementException thrownException = assertThrows( + IdentityProviderManagementException.class, + () -> identityProviderManagementService.addIdP(identityProvider) + ); + assertEquals(thrownException.getErrorCode(), error.getCode()); + } + + @Test + public void testAddIdPActionException() throws Exception { + + ActionManagementService actionManagementServiceForException = mock(ActionManagementService.class); + when(actionManagementServiceForException.addAction(anyString(), any(), any())) + .thenThrow(ActionMgtServerException.class); + IdpMgtServiceComponentHolder.getInstance().setActionManagementService(actionManagementServiceForException); + + assertThrows(IdentityProviderManagementServerException.class, () -> + identityProviderManagementService.addIdP(idpForErrorScenarios)); + identityProviderManagementService.getIdPByName(idpForErrorScenarios.getIdentityProviderName()); + } + + @Test + public void testAddIdPActionClientException() throws Exception { + + ActionManagementService actionManagementServiceForException = mock(ActionManagementService.class); + when(actionManagementServiceForException.addAction(anyString(), any(), any())) + .thenThrow(ActionMgtClientException.class); + IdpMgtServiceComponentHolder.getInstance().setActionManagementService(actionManagementServiceForException); + + assertThrows(IdentityProviderManagementClientException.class, () -> + identityProviderManagementService.addIdP(idpForErrorScenarios)); + identityProviderManagementService.getIdPByName(idpForErrorScenarios.getIdentityProviderName()); + } + @DataProvider public Object[][] addIdPData() { @@ -224,6 +368,7 @@ public Object[][] addIdPData() { {idp2}, // IDP with only the name. {idp3}, + {userDefinedIdP} }; } @@ -234,9 +379,7 @@ public void testAddIdP(Object identityProvider) throws Exception { identityProviderManagementService.addIdP(((IdentityProvider) identityProvider)); IdentityProvider idpFromDb = identityProviderManagementService.getIdPByName(idpName); - for (FederatedAuthenticatorConfig config: idpFromDb.getFederatedAuthenticatorConfigs()) { - Assert.assertEquals(config.getDefinedByType(), DefinedByType.SYSTEM); - } + assertIdPResult(idpFromDb); Assert.assertEquals(idpFromDb.getIdentityProviderName(), idpName); } @@ -277,6 +420,7 @@ public Object[][] getIdPByNameData() { {"testIdP1"}, {"testIdP2"}, {"testIdP3"}, + {userDefinedIdP.getIdentityProviderName()} }; } @@ -286,9 +430,7 @@ public void testGetIdPByName(String idpName) throws Exception { addTestIdps(); IdentityProvider idpFromDb = identityProviderManagementService.getIdPByName(idpName); - for (FederatedAuthenticatorConfig config: idpFromDb.getFederatedAuthenticatorConfigs()) { - Assert.assertEquals(config.getDefinedByType(), DefinedByType.SYSTEM); - } + assertIdPResult(idpFromDb); Assert.assertEquals(idpFromDb.getIdentityProviderName(), idpName); } @@ -335,7 +477,7 @@ public void testGetAllIdpCount() throws Exception { // With 3 idps in database. addTestIdps(); idpCount = identityProviderManagementService.getAllIdpCount(); - Assert.assertEquals(idpCount, 3); + Assert.assertEquals(idpCount, 4); } @Test @@ -348,19 +490,19 @@ public void testGetAllIdps() throws Exception { // With 3 idps in database. addTestIdps(); idpsList = identityProviderManagementService.getAllIdPs(); - Assert.assertEquals(idpsList.length, 3); + Assert.assertEquals(idpsList.length, 4); // With 3 idps and Shared idp in database. addSharedIdp(); idpsList = identityProviderManagementService.getAllIdPs(); - Assert.assertEquals(idpsList.length, 3); + Assert.assertEquals(idpsList.length, 4); } @DataProvider public Object[][] getAllPaginatedIdpInfoData() { return new Object[][]{ - {1, 3}, + {1, 4}, {2, 0}, }; } @@ -396,10 +538,10 @@ public void testGetAllPaginatedIdpInfoException(int pageNumber) throws Exception public Object[][] getPaginatedIdpInfoData() { return new Object[][]{ - {1, "", 3}, + {1, "", 4}, {1, "name sw test", 3}, {1, "homeRealmIdentifier eq 1", 1}, - {1, "isEnabled co true", 3}, + {1, "isEnabled co true", 4}, {1, "isEnabled eq false", 0}, {1, "id ew NotExist", 0}, {2, "name eq testIdP2", 0}, @@ -439,9 +581,9 @@ public void testGetPaginatedIdpInfoException(int pageNumber, String filter) thro public Object[][] getFilteredIdpCountData() { return new Object[][]{ - {"", 3}, + {"", 4}, {"name ew 1", 1}, - {"name co IdP", 3}, + {"name co IdP", 4}, {"description eq Test Idp 1", 1} }; } @@ -459,7 +601,7 @@ public void testGetFilteredIdpCount(String filter, int idpCount) throws Exceptio public Object[][] getAllIdPsSearchData() { return new Object[][]{ - {"", 3}, + {"", 4}, {"test*", 3}, {"????IdP*", 3}, {"tes_I*", 3}, @@ -488,7 +630,24 @@ public void testGetEnabledAllIdPs() throws Exception { addTestIdps(); IdentityProvider[] idpsList = identityProviderManagementService.getEnabledAllIdPs(); - Assert.assertEquals(idpsList.length, 3); + Assert.assertEquals(idpsList.length, 4); + } + + @Test + public void testDeleteIdPActionException() throws Exception { + + identityProviderManagementService.addIdP(userDefinedIdP); + + ActionManagementService actionManagementServiceForException = mock(ActionManagementService.class); + doThrow(ActionMgtServerException.class).when(actionManagementServiceForException) + .deleteAction(any(), any(), any()); + when(actionManagementServiceForException.getActionByActionId(anyString(), any(), any())).thenReturn(action); + IdpMgtServiceComponentHolder.getInstance().setActionManagementService(actionManagementServiceForException); + + assertThrows(IdentityProviderManagementServerException.class, () -> + identityProviderManagementService.deleteIdP(userDefinedIdP.getIdentityProviderName())); + Assert.assertNotNull(identityProviderManagementService.getIdPByName(userDefinedIdP + .getIdentityProviderName())); } @DataProvider @@ -498,6 +657,7 @@ public Object[][] deleteIdPData() { {"testIdP1"}, {"testIdP2"}, {"testIdP3"}, + {userDefinedIdP.getIdentityProviderName()} }; } @@ -536,6 +696,7 @@ public Object[][] forceDeleteIdPData() { {"testIdP1"}, {"testIdP2"}, {"testIdP3"}, + {userDefinedIdP.getIdentityProviderName()} }; } @@ -549,6 +710,25 @@ public void testForceDeleteIdP(String idpName) throws Exception { Assert.assertNull(identityProviderManagementService.getIdPByName(idpName)); } + @Test(dataProvider = "forceDeleteIdPData") + public void testForceDeleteIdPDAOException(String idpName) throws Exception { + + addTestIdps(); + Assert.assertNotNull(identityProviderManagementService.getIdPByName(idpName)); + + IdPManagementDAO daoForError = mock(IdPManagementDAO.class); + doThrow(IdentityProviderManagementServerException.class).when(daoForError) + .forceDeleteIdPByResourceId(anyString(), anyInt(), anyString()); + daoForException = new CacheBackedIdPMgtDAO(daoForError); + field.set(identityProviderManager, daoForException); + + assertThrows(IdentityProviderManagementException.class, () -> + identityProviderManagementService.forceDeleteIdP(idpName)); + + field.set(identityProviderManager, dao); + Assert.assertNotNull(identityProviderManagementService.getIdPByName(idpName)); + } + @DataProvider public Object[][] forceDeleteIdPExceptionData() { @@ -567,6 +747,26 @@ public void testForceDeleteIdPException(String idpName) throws Exception { identityProviderManagementService.forceDeleteIdP(idpName)); } + @Test + public void testUpdateIdPActionException() throws Exception { + + IdentityProvider idpForErrorScenariosTobeUpdate = ActionMgtTestUtil. + createIdPWithUserDefinedFederatedAuthenticatorConfig( + idpForErrorScenarios.getIdentityProviderName(), endpointConfig); + identityProviderManagementService.addIdP(idpForErrorScenarios); + + ActionManagementService actionManagementServiceForException = mock(ActionManagementService.class); + when(actionManagementServiceForException.updateAction(any(), any(), any(), any())) + .thenThrow(ActionMgtServerException.class); + when(actionManagementServiceForException.getActionByActionId(anyString(), any(), any())).thenReturn(action); + IdpMgtServiceComponentHolder.getInstance().setActionManagementService(actionManagementServiceForException); + + assertThrows(IdentityProviderManagementServerException.class, () -> + identityProviderManagementService.updateIdP(idpForErrorScenariosTobeUpdate.getIdentityProviderName(), + idpForErrorScenarios)); + identityProviderManagementService.getIdPByName(idpForErrorScenarios.getIdentityProviderName()); + } + @DataProvider public Object[][] updateIdPData() { @@ -637,6 +837,13 @@ public Object[][] updateIdPData() { IdentityProvider idp3New = new IdentityProvider(); idp3New.setIdentityProviderName("testIdP3New"); + IdentityProvider updateIdPWithExistingUserDefinedFedAuth = ActionMgtTestUtil. + createIdPWithUserDefinedFederatedAuthenticatorConfig(CUSTOM_IDP_NAME + "new", endpointConfigToBeUpdated); + IdentityProvider updateIdPWithNewUserDefinedFedAuth = ActionMgtTestUtil. + createIdPWithUserDefinedFederatedAuthenticatorConfig(CUSTOM_IDP_NAME + "new", endpointConfigToBeUpdated); + updateIdPWithNewUserDefinedFedAuth.getFederatedAuthenticatorConfigs()[0].setName("New Fed Auth"); + + return new Object[][]{ // IDP with PermissionsAndRoleConfig,FederatedAuthenticatorConfig,ProvisioningConnectorConfig,ClaimConf. {"testIdP1", idp1New}, @@ -644,6 +851,8 @@ public Object[][] updateIdPData() { {"testIdP2", idp2New}, // New IDP with Only name. {"testIdP3", idp3New}, + // IDP with User Defined Federated Authenticator. + {userDefinedIdP.getIdentityProviderName(), updateIdPWithExistingUserDefinedFedAuth} }; } @@ -657,9 +866,7 @@ public void testUpdateIdP(String oldIdpName, Object newIdp) throws Exception { Assert.assertNull(identityProviderManagementService.getIdPByName(oldIdpName)); IdentityProvider newIdpFromDb = identityProviderManagementService.getIdPByName(newIdpName); Assert.assertNotNull(newIdpFromDb); - for (FederatedAuthenticatorConfig config: newIdpFromDb.getFederatedAuthenticatorConfigs()) { - Assert.assertEquals(config.getDefinedByType(), DefinedByType.SYSTEM); - } + assertIdPResult(newIdpFromDb); } @Test(dataProvider = "updateIdPData") @@ -674,9 +881,7 @@ public void testUpdateIdPByResourceId(String oldIdpName, Object newIdp) throws E Assert.assertNull(identityProviderManagementService.getIdPByName(oldIdpName)); IdentityProvider newIdpFromDb = identityProviderManagementService.getIdPByName(newIdpName); Assert.assertNotNull(newIdpFromDb); - for (FederatedAuthenticatorConfig config: newIdpFromDb.getFederatedAuthenticatorConfigs()) { - Assert.assertEquals(config.getDefinedByType(), DefinedByType.SYSTEM); - } + assertIdPResult(newIdpFromDb); } @DataProvider @@ -704,6 +909,20 @@ public void testUpdateIdPException(String oldIdpName, Object newIdp) throws Exce identityProviderManagementService.updateIdP(oldIdpName, (IdentityProvider) newIdp)); } + @Test + public void testGetIdPActionException() throws Exception { + + ActionManagementService actionManagementServiceForException = mock(ActionManagementService.class); + when(actionManagementServiceForException.addAction(anyString(), any(), any())).thenReturn(action); + when(actionManagementServiceForException.getActionByActionId(anyString(), any(), any())) + .thenThrow(ActionMgtServerException.class); + IdpMgtServiceComponentHolder.getInstance().setActionManagementService(actionManagementServiceForException); + + IdentityProviderManagementServerException error = assertThrows(IdentityProviderManagementServerException.class, + () -> identityProviderManagementService.addIdP(idpForErrorScenarios)); + assertEquals(error.getErrorCode(), ErrorMessage.ERROR_CODE_RETRIEVING_ENDPOINT_CONFIG.getCode()); + } + @Test public void testGetAllLocalClaimUris() throws Exception { @@ -738,32 +957,32 @@ public void testGetAllFederatedAuthenticators() throws Exception { FederatedAuthenticatorConfig[] allFederatedAuthenticators = identityProviderManagementService.getAllFederatedAuthenticators(); - Assert.assertEquals(allFederatedAuthenticators.length, 0); + Assert.assertEquals(allFederatedAuthenticators.length, 2); - FederatedAuthenticatorConfig federatedAuthenticatorConfig1 = mock(FederatedAuthenticatorConfig.class); + FederatedAuthenticatorConfig federatedAuthenticatorConfig1 = new FederatedAuthenticatorConfig(); federatedAuthenticatorConfig1.setDisplayName("DisplayName1"); federatedAuthenticatorConfig1.setName("Name1"); federatedAuthenticatorConfig1.setEnabled(true); - FederatedAuthenticatorConfig federatedAuthenticatorConfig2 = mock(FederatedAuthenticatorConfig.class); + FederatedAuthenticatorConfig federatedAuthenticatorConfig2 = new FederatedAuthenticatorConfig(); federatedAuthenticatorConfig2.setDisplayName("DisplayName2"); federatedAuthenticatorConfig2.setName("Name2"); federatedAuthenticatorConfig2.setEnabled(true); ApplicationAuthenticatorService.getInstance().addFederatedAuthenticator(federatedAuthenticatorConfig1); allFederatedAuthenticators = identityProviderManagementService.getAllFederatedAuthenticators(); - Assert.assertEquals(allFederatedAuthenticators.length, 1); + Assert.assertEquals(allFederatedAuthenticators.length, 3); ApplicationAuthenticatorService.getInstance().addFederatedAuthenticator(federatedAuthenticatorConfig2); allFederatedAuthenticators = identityProviderManagementService.getAllFederatedAuthenticators(); - Assert.assertEquals(allFederatedAuthenticators.length, 2); + Assert.assertEquals(allFederatedAuthenticators.length, 4); // Clear after the test. ApplicationAuthenticatorService.getInstance().removeFederatedAuthenticator(federatedAuthenticatorConfig1); ApplicationAuthenticatorService.getInstance().removeFederatedAuthenticator(federatedAuthenticatorConfig2); allFederatedAuthenticators = identityProviderManagementService.getAllFederatedAuthenticators(); - Assert.assertEquals(allFederatedAuthenticators.length, 0); + Assert.assertEquals(allFederatedAuthenticators.length, 2); } @Test @@ -972,6 +1191,61 @@ public void testGetResidentIDPMetadataException() throws Exception { identityProviderManagementService.getResidentIDPMetadata()); } + @Test + public void testAddIdPDAOException() throws Exception { + + IdPManagementDAO daoForError = mock(IdPManagementDAO.class); + doThrow(IdentityProviderManagementServerException.class).when(daoForError) + .addIdPWithResourceId(any(), anyInt()); + daoForException = new CacheBackedIdPMgtDAO(daoForError); + field.set(identityProviderManager, daoForException); + + assertThrows(IdentityProviderManagementServerException.class, () -> + identityProviderManagementService.addIdP(userDefinedIdP)); + + // check ActionManagementService actionManagementService.deleteAction() is called. + verify(actionManagementService, times(1)).deleteAction(anyString(), any(), any()); + } + + @Test + public void testUpdateIdPDAOException() throws Exception { + + identityProviderManagementService.addIdP(userDefinedIdP); + IdPManagementDAO daoForError = mock(IdPManagementDAO.class); + doThrow(IdentityProviderManagementServerException.class).when(daoForError).updateIdPWithResourceId(anyString(), + any(), any(), anyInt()); + when(daoForError.getIdPByName(any(), anyString(), anyInt(), anyString())).thenReturn(userDefinedIdP); + daoForException = new CacheBackedIdPMgtDAO(daoForError); + field.set(identityProviderManager, daoForException); + + assertThrows(IdentityProviderManagementServerException.class, () -> + identityProviderManagementService.updateIdP(userDefinedIdP.getIdentityProviderName(), userDefinedIdP)); + + // check ActionManagementService actionManagementService.deleteAction() is called. + verify(actionManagementService, times(2)).updateAction(anyString(), anyString(), + any(), anyString()); + } + + @Test + public void testDeleteIdPDAOException() throws Exception { + + identityProviderManagementService.addIdP(userDefinedIdP); + IdPManagementDAO daoForError = mock(IdPManagementDAO.class); + doThrow(IdentityProviderManagementException.class).when(daoForError) + .deleteIdPByResourceId(anyString(), anyInt(), anyString()); + when(daoForError.getIdPByName(any(), anyString(), anyInt(), anyString())).thenReturn(userDefinedIdP); + when(daoForError.getIDPbyResourceId(any(), anyString(), anyInt(), anyString())).thenReturn(userDefinedIdP); + daoForException = new CacheBackedIdPMgtDAO(daoForError); + field.set(identityProviderManager, daoForException); + + assertThrows(IdentityProviderManagementException.class, () -> + identityProviderManagementService.deleteIdP(userDefinedIdP.getIdentityProviderName())); + + /* check ActionManagementService actionManagementService.deleteAction() is called. Two time, when creating idp + and rollback when idp deletion. */ + verify(actionManagementService, times(2)).addAction(anyString(), any(), anyString()); + } + private void addTestIdps() throws IdentityProviderManagementException { // Initialize Test Identity Provider 1. @@ -1071,6 +1345,10 @@ private void addTestIdps() throws IdentityProviderManagementException { // IDP with Only name. identityProviderManagementService.addIdP(idp3); + + // User defined IDP. + identityProviderManagementService.addIdP(userDefinedIdP); + userDefinedIdP = identityProviderManagementService.getIdPByName(userDefinedIdP.getIdentityProviderName()); } private void addResidentIdp() throws IdentityProviderManagementException { @@ -1182,4 +1460,18 @@ private FederatedAuthenticatorConfig federatedAuthenticatorConfigWithIdpEntityId return federatedAuthenticatorConfig; } + private void assertIdPResult(IdentityProvider idpResult) { + + for (FederatedAuthenticatorConfig config : idpResult.getFederatedAuthenticatorConfigs()) { + if (config instanceof UserDefinedFederatedAuthenticatorConfig) { + Assert.assertEquals(config.getDefinedByType(), DefinedByType.USER); + Property[] prop = idpResult.getFederatedAuthenticatorConfigs()[0].getProperties(); + assertEquals(prop.length, 1); + assertEquals(prop[0].getName(), "actionId"); + assertEquals(prop[0].getValue(), ASSOCIATED_ACTION_ID); + } else { + Assert.assertEquals(config.getDefinedByType(), DefinedByType.SYSTEM); + } + } + } } diff --git a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/test/java/org/wso2/carbon/idp/mgt/dao/CacheBackedIdPMgtDAOTest.java b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/test/java/org/wso2/carbon/idp/mgt/dao/CacheBackedIdPMgtDAOTest.java index a5057473fa80..8a58a33886f9 100644 --- a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/test/java/org/wso2/carbon/idp/mgt/dao/CacheBackedIdPMgtDAOTest.java +++ b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/test/java/org/wso2/carbon/idp/mgt/dao/CacheBackedIdPMgtDAOTest.java @@ -22,30 +22,24 @@ import org.apache.commons.lang.StringUtils; 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.base.MultitenantConstants; import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.identity.application.common.model.Claim; -import org.wso2.carbon.identity.application.common.model.ClaimConfig; -import org.wso2.carbon.identity.application.common.model.ClaimMapping; -import org.wso2.carbon.identity.application.common.model.FederatedAuthenticatorConfig; -import org.wso2.carbon.identity.application.common.model.IdentityProvider; -import org.wso2.carbon.identity.application.common.model.IdentityProviderProperty; -import org.wso2.carbon.identity.application.common.model.JustInTimeProvisioningConfig; -import org.wso2.carbon.identity.application.common.model.LocalRole; -import org.wso2.carbon.identity.application.common.model.PermissionsAndRoleConfig; -import org.wso2.carbon.identity.application.common.model.Property; -import org.wso2.carbon.identity.application.common.model.ProvisioningConnectorConfig; -import org.wso2.carbon.identity.application.common.model.RoleMapping; +import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.EndpointConfig; +import org.wso2.carbon.identity.action.management.service.ActionManagementService; +import org.wso2.carbon.identity.application.common.model.*; import org.wso2.carbon.identity.base.AuthenticatorPropertyConstants.DefinedByType; +import org.wso2.carbon.identity.common.testng.WithCarbonHome; import org.wso2.carbon.identity.core.model.ExpressionNode; import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.core.util.IdentityUtil; -import org.wso2.carbon.identity.secret.mgt.core.SecretManager; -import org.wso2.carbon.identity.secret.mgt.core.SecretResolveManager; +import org.wso2.carbon.identity.secret.mgt.core.SecretManagerImpl; +import org.wso2.carbon.identity.secret.mgt.core.model.SecretType; import org.wso2.carbon.idp.mgt.IdentityProviderManagementClientException; import org.wso2.carbon.idp.mgt.IdentityProviderManagementException; import org.wso2.carbon.idp.mgt.cache.IdPCacheByHRI; @@ -59,6 +53,7 @@ import org.wso2.carbon.idp.mgt.cache.IdPResourceIdCacheKey; import org.wso2.carbon.idp.mgt.internal.IdpMgtServiceComponentHolder; import org.wso2.carbon.idp.mgt.model.ConnectedAppsResult; +import org.wso2.carbon.idp.mgt.util.ActionMgtTestUtil; import org.wso2.carbon.idp.mgt.util.IdPManagementConstants; import org.wso2.carbon.idp.mgt.util.IdPSecretsProcessor; @@ -68,45 +63,48 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.mockStatic; -import static org.mockito.Mockito.when; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.*; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertThrows; +import static org.testng.Assert.assertTrue; import static org.wso2.carbon.idp.mgt.util.IdPManagementConstants.RESET_PROVISIONING_ENTITIES_ON_CONFIG_UPDATE; /** * Unit tests for CacheBackedIdPManagementDAO. */ +@WithCarbonHome public class CacheBackedIdPMgtDAOTest { private static final String DB_NAME = "test"; - private static final Integer SAMPLE_TENANT_ID1 = -1234; - private static final Integer SAMPLE_TENANT_ID2 = 1; - private static final Integer SAMPLE_TENANT_ID3 = 2; - private static final Integer NOT_EXISTING_TENANT_ID = 4; - private static final String TENANT_DOMAIN = "carbon.super"; + private static final String IDP_GROUP1 = "idpGroup1"; + private static final String IDP_GROUP2 = "idpGroup2"; + private static final String IDP_GROUP2_ID = "idpGroup2Id"; - private static Map dataSourceMap = new HashMap<>(); + private static final String CUSTOM_IDP_NAME = "customIdP"; + private static Action action; + private static EndpointConfig endpointConfig; + private static EndpointConfig endpointConfigToBeUpdated; + private IdentityProvider idpForErrorScenarios; + private IdentityProvider userDefinedIdP; + private static Map dataSourceMap = new HashMap<>(); private CacheBackedIdPMgtDAO cacheBackedIdPMgtDAO; + private CacheBackedIdPMgtDAO cacheBackedIdPMgtDAOForException; private IdPManagementDAO idPManagementDAO; - + private IdPManagementDAO idPManagementDAOForException; + private ActionManagementService actionManagementService; MockedStatic identityTenantUtil; MockedStatic idpMgtServiceComponentHolder; @@ -148,6 +146,32 @@ private static Connection getConnection(String database) throws SQLException { throw new RuntimeException("No datasource initiated for database: " + database); } + @BeforeClass + public void setUpClass() throws Exception { + + SecretManagerImpl secretManager = mock(SecretManagerImpl.class); + SecretType secretType = mock(SecretType.class); + IdpMgtServiceComponentHolder.getInstance().setSecretManager(secretManager); + when(secretType.getId()).thenReturn("secretId"); + doReturn(secretType).when(secretManager).getSecretType(any()); + when(secretManager.isSecretExist(anyString(), anyString())).thenReturn(false); + + endpointConfig = ActionMgtTestUtil.createEndpointConfig("http://localhost", "admin", "admin"); + endpointConfigToBeUpdated = ActionMgtTestUtil.createEndpointConfig( + "http://localhost1", "admin1", "admin1"); + action = ActionMgtTestUtil.createAction(endpointConfig); + userDefinedIdP = ActionMgtTestUtil.createIdPWithUserDefinedFederatedAuthenticatorConfig( + CUSTOM_IDP_NAME, action.getEndpoint()); + idpForErrorScenarios = ActionMgtTestUtil.createIdPWithUserDefinedFederatedAuthenticatorConfig( + CUSTOM_IDP_NAME + "Error", action.getEndpoint()); + + actionManagementService = mock(ActionManagementService.class); + when(actionManagementService.addAction(anyString(), any(), any())).thenReturn(action); + when(actionManagementService.updateAction(anyString(), any(), any(), any())).thenReturn(action); + when(actionManagementService.getActionByActionId(anyString(), any(), any())).thenReturn(action); + doNothing().when(actionManagementService).deleteAction(anyString(), any(), any()); + } + @BeforeMethod public void setup() throws Exception { @@ -157,6 +181,8 @@ public void setup() throws Exception { when(idpSecretsProcessor.encryptAssociatedSecrets(any())).thenAnswer( invocation -> invocation.getArguments()[0]); idPManagementDAO = new IdPManagementDAO(); + idPManagementDAOForException = mock(IdPManagementDAO.class); + cacheBackedIdPMgtDAOForException = new CacheBackedIdPMgtDAO(idPManagementDAOForException); Field idpSecretsProcessorField = IdPManagementDAO.class.getDeclaredField("idpSecretsProcessorService"); idpSecretsProcessorField.setAccessible(true); @@ -171,6 +197,7 @@ public void setup() throws Exception { IdpMgtServiceComponentHolder mockIdpMgtServiceComponentHolder = mock(IdpMgtServiceComponentHolder.class); idpMgtServiceComponentHolder.when( IdpMgtServiceComponentHolder::getInstance).thenReturn(mockIdpMgtServiceComponentHolder); + when(mockIdpMgtServiceComponentHolder.getActionManagementService()).thenReturn(actionManagementService); } @AfterMethod @@ -196,7 +223,7 @@ public void tearDown() throws Exception { public Object[][] getIdPsData() { return new Object[][]{ - {SAMPLE_TENANT_ID1, 2}, + {SAMPLE_TENANT_ID1, 3}, {SAMPLE_TENANT_ID2, 1}, {NOT_EXISTING_TENANT_ID, 0} }; @@ -242,7 +269,7 @@ public Object[][] getIdPsSearchData() { return new Object[][]{ {SAMPLE_TENANT_ID1, "testIdP1", 1}, {SAMPLE_TENANT_ID2, "testIdP3", 1}, - {SAMPLE_TENANT_ID1, "", 2}, + {SAMPLE_TENANT_ID1, "", 3}, {SAMPLE_TENANT_ID1, "test*", 2}, {SAMPLE_TENANT_ID1, "????IdP*", 2}, {SAMPLE_TENANT_ID1, "tes_I*", 2}, @@ -356,7 +383,7 @@ public Object[][] getTotalIdPCountData() { expressionNodesList2.add(expressionNode2); return new Object[][]{ - {SAMPLE_TENANT_ID1, expressionNodesList1, 2}, + {SAMPLE_TENANT_ID1, expressionNodesList1, 3}, {SAMPLE_TENANT_ID1, expressionNodesList2, 2}, {SAMPLE_TENANT_ID2, expressionNodesList1, 1}, }; @@ -438,7 +465,7 @@ public Object[][] getIdPByIdData() { return new Object[][]{ {"testIdP1", 1, SAMPLE_TENANT_ID1, true}, {"testIdP3", 3, SAMPLE_TENANT_ID2, true}, - {"notExist", 4, SAMPLE_TENANT_ID1, false}, + {"notExist", 99, SAMPLE_TENANT_ID1, false}, }; } @@ -469,6 +496,29 @@ public void testGetIdPById(String idpName, int idpId, int tenantId, boolean isEx } } + @Test + public void testGetIdPNamesById() throws Exception { + + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + Connection connection = getConnection(DB_NAME)) { + identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())).thenReturn(connection); + identityDatabaseUtil.when(IdentityDatabaseUtil::getDataSource).thenReturn(dataSourceMap.get(DB_NAME)); + addTestIdps(); + + Set idpIds = new HashSet<>(Arrays.asList( + cacheBackedIdPMgtDAO.getIdPByName(connection, "testIdP1", SAMPLE_TENANT_ID1, TENANT_DOMAIN) + .getId(), + cacheBackedIdPMgtDAO.getIdPByName(connection, "testIdP2", SAMPLE_TENANT_ID1, TENANT_DOMAIN) + .getId() + )); + // Retrieving IDP form DB and adding to cache. + Map idpNameMap = cacheBackedIdPMgtDAO.getIdPNamesById(SAMPLE_TENANT_ID1, idpIds); + + assertTrue(idpNameMap.containsValue("testIdP1")); + assertTrue(idpNameMap.containsValue("testIdP2")); + } + } + @DataProvider public Object[][] getIDPbyResourceIdData() { @@ -522,6 +572,327 @@ public Object[][] getIDPNameByResourceIdData() { }; } + @Test + public void getAllUserDefinedFederatedAuthenticators() throws Exception { + + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + Connection connection = getConnection(DB_NAME)) { + identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())).thenReturn(connection); + identityDatabaseUtil.when(IdentityDatabaseUtil::getDBConnection).thenReturn(connection); + identityDatabaseUtil.when(IdentityDatabaseUtil::getDataSource).thenReturn(dataSourceMap.get(DB_NAME)); + addTestIdps(); + + List result = cacheBackedIdPMgtDAO + .getAllUserDefinedFederatedAuthenticators(SAMPLE_TENANT_ID1); + assertEquals(result.size(), 1); + assertEquals(result.get(0).getName(), userDefinedIdP.getFederatedAuthenticatorConfigs()[0].getName()); + } + } + + @DataProvider + public Object[][] getIdPsSearchWithExpressionNodesData() { + + ExpressionNode expressionNode1 = new ExpressionNode(); + expressionNode1.setAttributeValue("name"); + expressionNode1.setOperation("co"); + expressionNode1.setValue("IdP"); + List expressionNodesList1 = new ArrayList<>(); + expressionNodesList1.add(expressionNode1); + + ExpressionNode expressionNode2 = new ExpressionNode(); + List expressionNodesList2 = new ArrayList<>(); + expressionNode2.setAttributeValue("name"); + expressionNode2.setOperation("eq"); + expressionNode2.setValue("testIdP1"); + expressionNodesList2.add(expressionNode2); + + ExpressionNode expressionNode3 = new ExpressionNode(); + List expressionNodesList3 = new ArrayList<>(); + expressionNode3.setAttributeValue("name"); + expressionNode3.setOperation("ew"); + expressionNode3.setValue("2"); + expressionNodesList3.add(expressionNode3); + + return new Object[][]{ + {SAMPLE_TENANT_ID1, expressionNodesList1, 2, 0, "ASC", "NAME", 2, "customIdP"}, + {SAMPLE_TENANT_ID1, expressionNodesList1, 2, 0, "DESC", "NAME", 2, "testIdP2"}, + {SAMPLE_TENANT_ID2, expressionNodesList1, 1, 0, "ASC", "NAME", 1, "testIdP3"}, + {SAMPLE_TENANT_ID1, expressionNodesList2, 1, 0, "ASC", "NAME", 1, "testIdP1"}, + {SAMPLE_TENANT_ID1, expressionNodesList3, 1, 0, "ASC", "NAME", 1, "testIdP2"}, + }; + } + + @Test + public void testGetIdPGroupsByIds() throws Exception { + + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + Connection connection = getConnection(DB_NAME)) { + identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())).thenReturn(connection); + identityDatabaseUtil.when(IdentityDatabaseUtil::getDataSource).thenReturn(dataSourceMap.get(DB_NAME)); + + IdPManagementDAO mockedIdPManagementDAO = mock(IdPManagementDAO.class); + CacheBackedIdPMgtDAO mockedCacheBackedIdPMgtDAO = new CacheBackedIdPMgtDAO(mockedIdPManagementDAO); + + mockedCacheBackedIdPMgtDAO.getIdPGroupsByIds(Arrays.asList("testIdP1", "testIdP2"), SAMPLE_TENANT_ID1); + verify(mockedIdPManagementDAO, times(1)) + .getIdPGroupsByIds(any(), anyInt()); + } + } + + public void testGetConnectedAppsOfLocalAuthenticator() throws Exception { + + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + Connection connection = getConnection(DB_NAME)) { + identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())).thenReturn(connection); + identityDatabaseUtil.when(IdentityDatabaseUtil::getDataSource).thenReturn(dataSourceMap.get(DB_NAME)); + + IdPManagementDAO mockedIdPManagementDAO = mock(IdPManagementDAO.class); + CacheBackedIdPMgtDAO mockedCacheBackedIdPMgtDAO = new CacheBackedIdPMgtDAO(mockedIdPManagementDAO); + + mockedCacheBackedIdPMgtDAO.getConnectedAppsOfLocalAuthenticator("testIdP1", SAMPLE_TENANT_ID1, 5, 0); + verify(mockedIdPManagementDAO, times(1)) + .getConnectedAppsOfLocalAuthenticator(anyString(), anyInt(), any(), any()); + } + } + + @Test(dataProvider = "getIdPsSearchWithExpressionNodesData") + public void testGetIdPsSearchWithExpressionNodes(int tenantId, List expressionNodes, int limit, + int offset, String sortOrder, String sortBy, int count, + String firstIdp) throws Exception { + + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + Connection connection = getConnection(DB_NAME)) { + identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())).thenReturn(connection); + identityDatabaseUtil.when(IdentityDatabaseUtil::getDBConnection).thenReturn(connection); + identityDatabaseUtil.when(IdentityDatabaseUtil::getDataSource).thenReturn(dataSourceMap.get(DB_NAME)); + addTestIdps(); + + List idps = cacheBackedIdPMgtDAO.getPaginatedIdPsSearch( + tenantId, expressionNodes, limit, offset, sortOrder, sortBy); + assertEquals(idps.size(), count); + if (count > 0) { + assertEquals(idps.get(0).getIdentityProviderName(), firstIdp); + } + } + } + + @DataProvider + public Object[][] getIdPDatForSearch() { + + return new Object[][]{ + {SAMPLE_TENANT_ID1, TENANT_DOMAIN, "testIdP1", 1}, + {SAMPLE_TENANT_ID2, TENANT_DOMAIN, "testIdP3", 1}, + {SAMPLE_TENANT_ID1, TENANT_DOMAIN, "", 2}, + {SAMPLE_TENANT_ID1, TENANT_DOMAIN, "test*", 2}, + {SAMPLE_TENANT_ID1, TENANT_DOMAIN, "????IdP*", 2}, + {SAMPLE_TENANT_ID1, TENANT_DOMAIN, "tes_I*", 2}, + {SAMPLE_TENANT_ID1, TENANT_DOMAIN, "*1", 1}, + {SAMPLE_TENANT_ID1, TENANT_DOMAIN, "Notexist", 0}, + }; + } + + @Test(dataProvider = "getIdPDatForSearch") + public void testGetTrustedTokenIssuersException(int tenantId, String tenantDomain, String filter, int resultCount) + throws Exception { + + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class)) { + try (Connection connection = getConnection(DB_NAME)) { + identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())).thenReturn(connection); + identityDatabaseUtil.when(IdentityDatabaseUtil::getDBConnection).thenReturn(connection); + identityDatabaseUtil.when(IdentityDatabaseUtil::getDataSource).thenReturn(dataSourceMap.get(DB_NAME)); + addTestIdps(); + } + + assertThrows(IdentityProviderManagementException.class, () -> + cacheBackedIdPMgtDAO.getIdPsSearch(null, tenantId, tenantDomain, filter)); + } + } + + @DataProvider + public Object[][] getTrustedTokenIssuersData() { + + ExpressionNode expressionNode = new ExpressionNode(); + List expressionNodesList = new ArrayList<>(); + expressionNodesList.add(expressionNode); + + List attributes1 = Arrays.asList("id", "name", "description", "isEnabled", "image", "isPrimary"); + List attributes2 = Arrays.asList("homeRealmIdentifier", "isFederationHub", "certificate", "alias", + "claims", "roles", "federatedAuthenticators", "provisioning"); + + return new Object[][]{ + {SAMPLE_TENANT_ID1, expressionNodesList, 2, 0, "ASC", "NAME", attributes1, 1}, + {SAMPLE_TENANT_ID1, expressionNodesList, 1, 1, "ASC", "NAME", attributes2, 0}, + {SAMPLE_TENANT_ID1, expressionNodesList, 2, 0, "DESC", "NAME", attributes1, 1}, + }; + } + + @Test(dataProvider = "getTrustedTokenIssuersData") + public void testGetTrustedTokenIssuers(int tenantId, List expressionNodes, int limit, int offset, + String sortOrder, String sortBy, List attributes, int resultCount) + throws Exception { + + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + Connection connection = getConnection(DB_NAME)) { + identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())).thenReturn(connection); + identityDatabaseUtil.when(IdentityDatabaseUtil::getDBConnection).thenReturn(connection); + identityDatabaseUtil.when(IdentityDatabaseUtil::getDataSource).thenReturn(dataSourceMap.get(DB_NAME)); + addTestTrustedTokenIssuers(); + + List idps1 = cacheBackedIdPMgtDAO.getPaginatedTrustedTokenIssuersSearch(tenantId, + expressionNodes, limit, offset, sortOrder, sortBy, attributes); + assertEquals(idps1.size(), resultCount); + } + } + + @DataProvider + public Object[][] getCountOfFilteredTrustedTokenIssuersData() { + + ExpressionNode expressionNode1 = new ExpressionNode(); + List expressionNodesList1 = new ArrayList<>(); + expressionNodesList1.add(expressionNode1); + ExpressionNode expressionNode2 = new ExpressionNode(); + expressionNode2.setAttributeValue("name"); + expressionNode2.setOperation("sw"); + expressionNode2.setValue("test"); + List expressionNodesList2 = new ArrayList<>(); + expressionNodesList2.add(expressionNode2); + + return new Object[][]{ + {SAMPLE_TENANT_ID1, expressionNodesList1, 1}, + {SAMPLE_TENANT_ID1, expressionNodesList2, 1}, + {SAMPLE_TENANT_ID2, expressionNodesList1, 0}, + }; + } + + @Test(dataProvider = "getCountOfFilteredTrustedTokenIssuersData") + public void testGetCountOfFilteredTrustedTokenIssuers(int tenantId, List expNodes, int count) + throws Exception { + + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + Connection connection = getConnection(DB_NAME)) { + identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())).thenReturn(connection); + identityDatabaseUtil.when(IdentityDatabaseUtil::getDBConnection).thenReturn(connection); + identityDatabaseUtil.when(IdentityDatabaseUtil::getDataSource).thenReturn(dataSourceMap.get(DB_NAME)); + addTestTrustedTokenIssuers(); + + int resultCount = cacheBackedIdPMgtDAO.getTotalTrustedTokenIssuerCount(tenantId, expNodes); + assertEquals(resultCount, count); + } + } + + private void addTestTrustedTokenIssuers() throws IdentityProviderManagementException { + + // Initialize Test Identity Provider 1. + IdentityProvider idp1 = new IdentityProvider(); + idp1.setIdentityProviderName("testIdP1"); + idp1.setHomeRealmId("1"); + idp1.setEnable(true); + idp1.setPrimary(true); + idp1.setFederationHub(true); + idp1.setCertificate(""); + + RoleMapping roleMapping1 = new RoleMapping(); + roleMapping1.setRemoteRole("Role1"); + roleMapping1.setLocalRole(new LocalRole("1", "LocalRole1")); + RoleMapping roleMapping2 = new RoleMapping(); + roleMapping2.setRemoteRole("Role2"); + roleMapping2.setLocalRole(new LocalRole("2", "LocalRole2")); + + PermissionsAndRoleConfig permissionsAndRoleConfig = new PermissionsAndRoleConfig(); + permissionsAndRoleConfig.setIdpRoles(new String[]{"Role1", "Role2"}); + permissionsAndRoleConfig.setRoleMappings(new RoleMapping[]{roleMapping1, roleMapping2}); + idp1.setPermissionAndRoleConfig(permissionsAndRoleConfig); + + FederatedAuthenticatorConfig federatedAuthenticatorConfig = new FederatedAuthenticatorConfig(); + federatedAuthenticatorConfig.setDisplayName("DisplayName1"); + federatedAuthenticatorConfig.setName("Name"); + federatedAuthenticatorConfig.setEnabled(true); + federatedAuthenticatorConfig.setDefinedByType(DefinedByType.SYSTEM); + Property property1 = new Property(); + property1.setName("Property1"); + property1.setValue("value1"); + property1.setConfidential(true); + Property property2 = new Property(); + property2.setName("Property2"); + property2.setValue("value2"); + property2.setConfidential(false); + federatedAuthenticatorConfig.setProperties(new Property[]{property1, property2}); + idp1.setFederatedAuthenticatorConfigs(new FederatedAuthenticatorConfig[]{federatedAuthenticatorConfig}); + + ProvisioningConnectorConfig provisioningConnectorConfig1 = new ProvisioningConnectorConfig(); + provisioningConnectorConfig1.setName("ProvisiningConfig1"); + provisioningConnectorConfig1.setProvisioningProperties(new Property[]{property1}); + ProvisioningConnectorConfig provisioningConnectorConfig2 = new ProvisioningConnectorConfig(); + provisioningConnectorConfig2.setName("ProvisiningConfig2"); + provisioningConnectorConfig2.setProvisioningProperties(new Property[]{property2}); + provisioningConnectorConfig2.setEnabled(true); + provisioningConnectorConfig2.setBlocking(true); + idp1.setProvisioningConnectorConfigs(new ProvisioningConnectorConfig[]{provisioningConnectorConfig1, + provisioningConnectorConfig2}); + + IdentityProviderProperty identityProviderProperty = new IdentityProviderProperty(); + identityProviderProperty.setDisplayName("idpDisplayName"); + identityProviderProperty.setName("idpPropertyName"); + identityProviderProperty.setValue("idpPropertyValue"); + idp1.setIdpProperties(new IdentityProviderProperty[]{identityProviderProperty}); + + ClaimConfig claimConfig = new ClaimConfig(); + claimConfig.setLocalClaimDialect(false); + claimConfig.setRoleClaimURI("Country"); + claimConfig.setUserClaimURI("Country"); + ClaimMapping claimMapping = ClaimMapping.build("http://wso2.org/claims/country", "Country", "", true); + Claim remoteClaim = new Claim(); + remoteClaim.setClaimId(0); + remoteClaim.setClaimUri("Country"); + claimConfig.setClaimMappings(new ClaimMapping[]{claimMapping}); + claimConfig.setIdpClaims(new Claim[]{remoteClaim}); + idp1.setClaimConfig(claimConfig); + + IdPGroup idPGroup1 = new IdPGroup(); + idPGroup1.setIdpGroupName(IDP_GROUP1); + IdPGroup idPGroup2 = new IdPGroup(); + idPGroup2.setIdpGroupName(IDP_GROUP2); + idp1.setIdPGroupConfig(new IdPGroup[]{idPGroup1, idPGroup2}); + + idp1.setTrustedTokenIssuer(true); + + // Initialize Test Identity Provider 2. + IdentityProvider idp2 = new IdentityProvider(); + idp2.setIdentityProviderName("testIdP2"); + idp2.setHomeRealmId("2"); + + ClaimConfig claimConfig2 = new ClaimConfig(); + claimConfig2.setLocalClaimDialect(true); + claimConfig2.setRoleClaimURI("http://wso2.org/claims/role"); + claimConfig2.setUserClaimURI("http://wso2.org/claims/fullname"); + ClaimMapping claimMapping2 = new ClaimMapping(); + Claim localClaim2 = new Claim(); + localClaim2.setClaimId(0); + localClaim2.setClaimUri("http://wso2.org/claims/fullname"); + claimMapping2.setLocalClaim(localClaim2); + claimConfig2.setClaimMappings(new ClaimMapping[]{claimMapping2}); + idp2.setClaimConfig(claimConfig2); + + IdPGroup idPGroup3 = new IdPGroup(); + idPGroup3.setIdpGroupName(IDP_GROUP1); + IdPGroup idPGroup4 = new IdPGroup(); + idPGroup4.setIdpGroupName(IDP_GROUP2); + idPGroup4.setIdpGroupId(IDP_GROUP2_ID); + idp2.setIdPGroupConfig(new IdPGroup[]{idPGroup3, idPGroup4}); + + // Initialize Test Identity Provider 3. + IdentityProvider idp3 = new IdentityProvider(); + idp3.setIdentityProviderName("testIdP3"); + idp3.setHomeRealmId("3"); + + // IDP with PermissionsAndRoleConfig, FederatedAuthenticatorConfigs, ProvisioningConnectorConfigs, ClaimConfigs. + idPManagementDAO.addIdP(idp1, SAMPLE_TENANT_ID1); + // IDP with Local Cliam Dialect ClaimConfigs. + idPManagementDAO.addIdP(idp2, SAMPLE_TENANT_ID1); + // IDP with Only name. + idPManagementDAO.addIdP(idp3, SAMPLE_TENANT_ID2); + } + @Test(dataProvider = "getIDPNameByResourceIdData") public void testGetIdPNameByResourceId(String idpName, int tenantId) throws Exception { @@ -558,6 +929,31 @@ public void testGetIdPNameByResourceId(String idpName, int tenantId) throws Exce } } + @Test(dataProvider = "getIDPNameByResourceIdData") + public void testGetIdPNameByResourceIdFromDB(String idpName, int tenantId) throws Exception { + + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + Connection connection = getConnection(DB_NAME)) { + identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())).thenReturn(connection); + identityDatabaseUtil.when(IdentityDatabaseUtil::getDBConnection).thenReturn(connection); + identityDatabaseUtil.when(IdentityDatabaseUtil::getDataSource).thenReturn(dataSourceMap.get(DB_NAME)); + addTestIdps(); + + try (MockedStatic carbonContext = mockStatic(CarbonContext.class)) { + CarbonContext mockCarbonContext = mock(CarbonContext.class); + carbonContext.when(CarbonContext::getThreadLocalCarbonContext).thenReturn(mockCarbonContext); + when(CarbonContext.getThreadLocalCarbonContext().getTenantDomain()).thenReturn(TENANT_DOMAIN); + + // Retrieving IDP from DB. + IdentityProvider idPResult = idPManagementDAO.getIdPByName(connection, idpName, tenantId, TENANT_DOMAIN); + String uuid = idPResult.getResourceId(); + + String nameFromDB = cacheBackedIdPMgtDAO.getIdPNameByResourceId(uuid); + assertEquals(nameFromDB, idpName); + } + } + } + @DataProvider public Object[][] getIdPByAuthenticatorPropertyValueWithoutAuthenticatorData() { @@ -1113,7 +1509,7 @@ public void testDeleteIdPs(int tenantId) throws Exception { identityDatabaseUtil.when(IdentityDatabaseUtil::getDataSource).thenReturn(dataSourceMap.get(DB_NAME)); addTestIdps(); // Deleting multiple IDPs on a tenant. - idPManagementDAO.deleteIdPs(tenantId); + cacheBackedIdPMgtDAO.deleteIdPs(tenantId); } try (Connection connection = getConnection(DB_NAME)) { @@ -1131,6 +1527,28 @@ public void testDeleteIdPs(int tenantId) throws Exception { } } + @Test + public void testDeleteIdPsDAOException() throws Exception { + + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + Connection connection = getConnection(DB_NAME)) { + identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())).thenReturn(connection); + identityDatabaseUtil.when(IdentityDatabaseUtil::getDBConnection).thenReturn(connection); + identityDatabaseUtil.when(IdentityDatabaseUtil::getDataSource).thenReturn(dataSourceMap.get(DB_NAME)); + addTestIdps(); + + List idpList = idPManagementDAO.getIdPs(connection, SAMPLE_TENANT_ID1, TENANT_DOMAIN); + when(idPManagementDAOForException.getIdPs(any(), anyInt(), anyString())) + .thenReturn(idpList); + doThrow(IdentityProviderManagementException.class).when(idPManagementDAOForException).deleteIdPs(anyInt()); + + // Deleting multiple IDPs on a tenant. + assertThrows(IdentityProviderManagementException.class, () -> + cacheBackedIdPMgtDAOForException.deleteIdPs(SAMPLE_TENANT_ID1)); + verify(actionManagementService, times(1)).addAction(anyString(), any(), anyString()); + } + } + @Test(dataProvider = "deleteIdPData") public void testDeleteIdPByResourceId(String idpName, int tenantId) throws Exception { @@ -1173,6 +1591,73 @@ public void testForceDeleteIdPByResourceId(String idpName, int tenantId) throws } } + @Test(dataProvider = "deleteIdPData") + public void testForceDeleteIdP(String idpName, int tenantId) throws Exception { + + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + Connection connection = getConnection(DB_NAME)) { + identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())).thenReturn(connection); + identityDatabaseUtil.when(IdentityDatabaseUtil::getDBConnection).thenReturn(connection); + identityDatabaseUtil.when(IdentityDatabaseUtil::getDataSource).thenReturn(dataSourceMap.get(DB_NAME)); + addTestIdps(); + + // Force delete IDP using resourceId. + cacheBackedIdPMgtDAO.forceDeleteIdP(idpName, tenantId, TENANT_DOMAIN); + int resultSize = getIdPCount(connection, idpName, tenantId); + assertEquals(resultSize, 0, "'forceDeleteIdP' method fails"); + IdentityProvider idpFromCache = idpFromCacheByName(idpName); + assertNull(idpFromCache, "'deleteIdPByResourceId' method fails"); + } + } + + @Test + public void testForceDeleteIdPDAOException() throws Exception { + + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + Connection connection = getConnection(DB_NAME)) { + identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())).thenReturn(connection); + identityDatabaseUtil.when(IdentityDatabaseUtil::getDBConnection).thenReturn(connection); + identityDatabaseUtil.when(IdentityDatabaseUtil::getDataSource).thenReturn(dataSourceMap.get(DB_NAME)); + addTestIdps(); + + doThrow(IdentityProviderManagementException.class).when(idPManagementDAOForException).forceDeleteIdP( + anyString(), anyInt(), anyString()); + when(idPManagementDAOForException.getIdPByName(any(), anyString(), anyInt(), anyString())) + .thenReturn(userDefinedIdP); + + // Deleting multiple IDPs on a tenant. + assertThrows(IdentityProviderManagementException.class, () -> + cacheBackedIdPMgtDAOForException.forceDeleteIdP( + userDefinedIdP.getIdentityProviderName(), SAMPLE_TENANT_ID1, TENANT_DOMAIN)); + + verify(actionManagementService, times(2)).addAction(anyString(), any(), anyString()); + } + } + + @Test + public void testDeleteIdPDAOException() throws Exception { + + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + Connection connection = getConnection(DB_NAME)) { + identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())).thenReturn(connection); + identityDatabaseUtil.when(IdentityDatabaseUtil::getDBConnection).thenReturn(connection); + identityDatabaseUtil.when(IdentityDatabaseUtil::getDataSource).thenReturn(dataSourceMap.get(DB_NAME)); + addTestIdps(); + + doThrow(IdentityProviderManagementException.class).when(idPManagementDAOForException).deleteIdP( + anyString(), anyInt(), anyString()); + when(idPManagementDAOForException.getIdPByName(any(), anyString(), anyInt(), anyString())) + .thenReturn(userDefinedIdP); + + // Deleting multiple IDPs on a tenant. + assertThrows(IdentityProviderManagementException.class, () -> + cacheBackedIdPMgtDAOForException.deleteIdP( + userDefinedIdP.getIdentityProviderName(), SAMPLE_TENANT_ID1, TENANT_DOMAIN)); + + verify(actionManagementService, times(1)).addAction(anyString(), any(), anyString()); + } + } + @DataProvider public Object[][] addIdPCacheData() { @@ -1527,6 +2012,10 @@ private void addTestIdps() throws IdentityProviderManagementException { idPManagementDAO.addIdP(idp2, SAMPLE_TENANT_ID1); // IDP with Only name. idPManagementDAO.addIdP(idp3, SAMPLE_TENANT_ID2); + // IDP with user defined federated authenticators. + idPManagementDAO.addIdP(userDefinedIdP, SAMPLE_TENANT_ID1); + userDefinedIdP = idPManagementDAO.getIdPByName(null, userDefinedIdP.getIdentityProviderName(), + SAMPLE_TENANT_ID1, TENANT_DOMAIN); } private void addTestIdps(Connection connection) throws IdentityProviderManagementException { diff --git a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/test/java/org/wso2/carbon/idp/mgt/dao/IdPManagementDAOTest.java b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/test/java/org/wso2/carbon/idp/mgt/dao/IdPManagementDAOTest.java index b33dd78ef7eb..d26215fcd0e2 100644 --- a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/test/java/org/wso2/carbon/idp/mgt/dao/IdPManagementDAOTest.java +++ b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/test/java/org/wso2/carbon/idp/mgt/dao/IdPManagementDAOTest.java @@ -30,6 +30,8 @@ import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.core.util.CryptoUtil; +import org.wso2.carbon.identity.action.management.model.Authentication; +import org.wso2.carbon.identity.action.management.model.EndpointConfig; import org.wso2.carbon.identity.application.common.model.Claim; import org.wso2.carbon.identity.application.common.model.ClaimConfig; import org.wso2.carbon.identity.application.common.model.ClaimMapping; @@ -43,12 +45,13 @@ import org.wso2.carbon.identity.application.common.model.Property; import org.wso2.carbon.identity.application.common.model.ProvisioningConnectorConfig; import org.wso2.carbon.identity.application.common.model.RoleMapping; +import org.wso2.carbon.identity.application.common.model.UserDefinedAuthenticatorEndpointConfig; +import org.wso2.carbon.identity.application.common.model.UserDefinedFederatedAuthenticatorConfig; import org.wso2.carbon.identity.base.AuthenticatorPropertyConstants.DefinedByType; import org.wso2.carbon.identity.core.model.ExpressionNode; import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.core.util.IdentityUtil; -import org.wso2.carbon.identity.secret.mgt.core.SecretManager; import org.wso2.carbon.identity.secret.mgt.core.SecretManagerImpl; import org.wso2.carbon.identity.secret.mgt.core.model.SecretType; import org.wso2.carbon.idp.mgt.IdentityProviderManagementClientException; @@ -56,6 +59,7 @@ import org.wso2.carbon.idp.mgt.IdentityProviderManagementServerException; import org.wso2.carbon.idp.mgt.internal.IdpMgtServiceComponentHolder; import org.wso2.carbon.idp.mgt.model.ConnectedAppsResult; +import org.wso2.carbon.idp.mgt.util.ActionMgtTestUtil; import org.wso2.carbon.idp.mgt.util.IdPManagementConstants; import org.wso2.carbon.idp.mgt.util.IdPSecretsProcessor; @@ -68,8 +72,10 @@ 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.Set; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; @@ -101,6 +107,13 @@ public class IdPManagementDAOTest { private static final String IDP_GROUP2_ID = "idpGroup2Id"; private static Map dataSourceMap = new HashMap<>(); + private static final String ASSOCIATED_ACTION_ID = "Dummy_Action_ID"; + private static final String CUSTOM_IDP_NAME = "customIdP"; + private static EndpointConfig endpointConfig; + private static EndpointConfig endpointConfigToBeUpdated; + private IdentityProvider idpForErrorScenarios; + private IdentityProvider userDefinedIdP; + MockedStatic identityTenantUtil; MockedStatic cryptoUtil; private SecretManagerImpl secretManager; @@ -161,6 +174,12 @@ public void setUp() throws Exception { cryptoUtil.when(CryptoUtil::getDefaultCryptoUtil).thenReturn(mockCryptoUtil); when(mockCryptoUtil.encryptAndBase64Encode(any())).thenReturn("ENCRYPTED_VALUE2"); when(mockCryptoUtil.base64DecodeAndDecrypt(anyString())).thenReturn("ENCRYPTED_VALUE2".getBytes()); + + endpointConfig = ActionMgtTestUtil.createEndpointConfig("http://localhost", "admin", "admin"); + endpointConfigToBeUpdated = ActionMgtTestUtil.createEndpointConfig("http://localhost1", "admin1", "admin1"); + userDefinedIdP = ActionMgtTestUtil.createIdPWithUserDefinedFederatedAuthenticatorConfig(CUSTOM_IDP_NAME, endpointConfig); + idpForErrorScenarios = ActionMgtTestUtil.createIdPWithUserDefinedFederatedAuthenticatorConfig( + CUSTOM_IDP_NAME + "Error", endpointConfig); } @AfterClass @@ -199,7 +218,7 @@ public Object[][] getIdPsData() { return new Object[][]{ {SAMPLE_TENANT_ID, TENANT_DOMAIN, 2}, - {SAMPLE_TENANT_ID2, TENANT_DOMAIN, 1}, + {SAMPLE_TENANT_ID2, TENANT_DOMAIN, 2}, {4, TENANT_DOMAIN, 0}, }; } @@ -364,7 +383,7 @@ public Object[][] getIdPsSearchWithExpressionNodesData() { return new Object[][]{ {SAMPLE_TENANT_ID, expressionNodesList1, 2, 0, "ASC", "NAME", 2, "testIdP1"}, {SAMPLE_TENANT_ID, expressionNodesList1, 2, 0, "DESC", "NAME", 2, "testIdP2"}, - {SAMPLE_TENANT_ID2, expressionNodesList1, 1, 1, "ASC", "NAME", 0, ""}, + {SAMPLE_TENANT_ID2, expressionNodesList1, 1, 1, "ASC", "NAME", 1, "testIdP3"}, {SAMPLE_TENANT_ID, expressionNodesList2, 1, 0, "ASC", "NAME", 1, "testIdP1"}, {SAMPLE_TENANT_ID, expressionNodesList3, 1, 0, "ASC", "NAME", 1, "testIdP2"}, }; @@ -524,7 +543,7 @@ public Object[][] getCountOfFilteredIdPsData() { return new Object[][]{ {SAMPLE_TENANT_ID, expressionNodesList1, 2}, {SAMPLE_TENANT_ID, expressionNodesList2, 2}, - {SAMPLE_TENANT_ID2, expressionNodesList1, 1}, + {SAMPLE_TENANT_ID2, expressionNodesList1, 2}, }; } @@ -680,11 +699,13 @@ public Object[][] addIdPData() { {idp2, SAMPLE_TENANT_ID}, // IDP with Only name. {idp3, SAMPLE_TENANT_ID2}, + // IDP with User Defined Federated Authenticator. + {userDefinedIdP, SAMPLE_TENANT_ID2}, }; } @Test(dataProvider = "addIdPData") - public void testAddIdP(Object identityProvider, int tenantId) throws Exception { + public void testAddIdP(IdentityProvider identityProvider, int tenantId) throws Exception { try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); Connection connection = getConnection(DB_NAME)) { @@ -692,6 +713,8 @@ public void testAddIdP(Object identityProvider, int tenantId) throws Exception { identityDatabaseUtil.when(IdentityDatabaseUtil::getDataSource).thenReturn(dataSourceMap.get(DB_NAME)); idPManagementDAO.addIdP(((IdentityProvider) identityProvider), tenantId); + int idpId = -1; + int authnId = -1; String query = IdPManagementConstants.SQLQueries.GET_IDP_BY_NAME_SQL; PreparedStatement statement = connection.prepareStatement(query); statement.setInt(1, tenantId); @@ -701,9 +724,41 @@ public void testAddIdP(Object identityProvider, int tenantId) throws Exception { String resultName = ""; if (resultSet.next()) { resultName = resultSet.getString("NAME"); + idpId = resultSet.getInt("ID"); } statement.close(); assertEquals(resultName, ((IdentityProvider) identityProvider).getIdentityProviderName()); + + // check whether there is a actionId property in the database for user defined fed authenticators. + if (identityProvider.getDefaultAuthenticatorConfig() instanceof UserDefinedFederatedAuthenticatorConfig) { + + String sqlStmt = IdPManagementConstants.SQLQueries.GET_ALL_IDP_AUTH_SQL; + PreparedStatement prepStmt1 = connection.prepareStatement(sqlStmt); + prepStmt1.setInt(1, idpId); + ResultSet rs = prepStmt1.executeQuery(); + + while (rs.next()) { + authnId = rs.getInt("ID"); + } + String sqlStmt1 = IdPManagementConstants.SQLQueries.GET_IDP_AUTH_PROPS_SQL; + PreparedStatement prepStmt2 = connection.prepareStatement(sqlStmt1); + prepStmt2.setInt(1, authnId); + ResultSet proprs = prepStmt2.executeQuery(); + Set properties = new HashSet(); + while (proprs.next()) { + Property property = new Property(); + property.setName(proprs.getString("PROPERTY_KEY")); + property.setValue(proprs.getString("PROPERTY_VALUE")); + if ((IdPManagementConstants.IS_TRUE_VALUE).equals(proprs.getString("IS_SECRET"))) { + property.setConfidential(true); + } + properties.add(property); + } + statement.close(); + assertEquals(properties.size(), 1); + assertEquals(properties.iterator().next().getName(), "actionId"); + assertEquals(properties.iterator().next().getValue(), ASSOCIATED_ACTION_ID); + } } } @@ -721,6 +776,32 @@ public void testAddIdPException(Object identityProvider, int tenantId) throws Ex } } + @DataProvider + public Object[][] getAllFederatedData() { + + return new Object[][]{ + {1, 1}, + {2, 0} + }; + } + + @Test(dataProvider = "getAllFederatedData") + public void testGetAllUserDefinedFederatedAuthenticators(int tenantId, int numberOfFederatedAuthenticators) + throws Exception { + + try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + Connection connection = getConnection(DB_NAME)) { + identityDatabaseUtil.when(() -> IdentityDatabaseUtil.getDBConnection(anyBoolean())).thenReturn(connection); + identityDatabaseUtil.when(IdentityDatabaseUtil::getDBConnection).thenReturn(connection); + identityDatabaseUtil.when(IdentityDatabaseUtil::getDataSource).thenReturn(dataSourceMap.get(DB_NAME)); + addTestIdps(); + List actualAuthenticators = idPManagementDAO + .getAllUserDefinedFederatedAuthenticators(tenantId); + + assertEquals(actualAuthenticators.size(), numberOfFederatedAuthenticators); + } + } + @DataProvider public Object[][] getPermissionsAndRoleConfigurationData() { @@ -839,6 +920,7 @@ public Object[][] getIdPByNameData() { return new Object[][]{ {"testIdP1", SAMPLE_TENANT_ID, true}, {"testIdP3", SAMPLE_TENANT_ID2, true}, + {"testIdP4", SAMPLE_TENANT_ID, false}, {"notExist", SAMPLE_TENANT_ID, false}, }; } @@ -854,14 +936,7 @@ public void testGetIdPByName(String idpName, int tenantId, boolean isExist) thro addTestIdps(); IdentityProvider idpResult = idPManagementDAO.getIdPByName(connection, idpName, tenantId, TENANT_DOMAIN); - if (isExist) { - assertEquals(idpResult.getIdentityProviderName(), idpName, "'getIdPByName' method fails"); - for (FederatedAuthenticatorConfig config : idpResult.getFederatedAuthenticatorConfigs()) { - assertEquals(config.getDefinedByType(), DefinedByType.SYSTEM); - } - } else { - assertNull(idpResult, "'getIdPByName' method fails"); - } + assertIdPResult(idpResult, idpName, isExist); } } @@ -872,6 +947,7 @@ public Object[][] getIdPByIdData() { {"testIdP1", 1, SAMPLE_TENANT_ID, true}, {"testIdP3", 3, SAMPLE_TENANT_ID2, true}, {"notExist", 4, SAMPLE_TENANT_ID, false}, + {userDefinedIdP.getIdentityProviderName(), 4, SAMPLE_TENANT_ID2, true}, }; } @@ -886,14 +962,7 @@ public void testGetIdPById(String idpName, int idpId, int tenantId, boolean isEx addTestIdps(); IdentityProvider idpResult = idPManagementDAO.getIDPbyId(connection, idpId, tenantId, TENANT_DOMAIN); - if (isExist) { - assertEquals(idpResult.getIdentityProviderName(), idpName, "'getIDPbyId' method fails"); - for (FederatedAuthenticatorConfig config : idpResult.getFederatedAuthenticatorConfigs()) { - assertEquals(config.getDefinedByType(), DefinedByType.SYSTEM); - } - } else { - assertNull(idpResult, "'getIDPbyId' method fails"); - } + assertIdPResult(idpResult, idpName, isExist); } } @@ -904,6 +973,7 @@ public Object[][] getIDPbyResourceIdData() { {"testIdP1", SAMPLE_TENANT_ID, true}, {"testIdP3", SAMPLE_TENANT_ID2, true}, {"notExist", SAMPLE_TENANT_ID, false}, + {userDefinedIdP.getIdentityProviderName(), SAMPLE_TENANT_ID2, true} }; } @@ -924,14 +994,7 @@ public void testGetIDPbyResourceId(String idpName, int tenantId, boolean isExist } IdentityProvider idpResult = idPManagementDAO.getIDPbyResourceId(connection, uuid, tenantId, TENANT_DOMAIN); - if (isExist) { - assertEquals(idpResult.getIdentityProviderName(), idpName, "'getIDPbyResourceId' method fails"); - for (FederatedAuthenticatorConfig config : idpResult.getFederatedAuthenticatorConfigs()) { - assertEquals(config.getDefinedByType(), DefinedByType.SYSTEM); - } - } else { - assertNull(idpResult, "'getIDPbyResourceId' method fails"); - } + assertIdPResult(idpResult, idpName, isExist); } } @@ -956,6 +1019,7 @@ public void testGetIdPByRealmId(String idpName, String realmId, int tenantId, bo addTestIdps(); IdentityProvider idpResult = idPManagementDAO.getIdPByRealmId(realmId, tenantId, TENANT_DOMAIN); + if (isExist) { assertEquals(idpResult.getIdentityProviderName(), idpName, "'getIDPbyRealmId' method fails"); } else { @@ -1248,6 +1312,9 @@ public Object[][] updateIdPData() { IdentityProvider idp3New = new IdentityProvider(); idp3New.setIdentityProviderName("testIdP3New"); + IdentityProvider userDefinedIdPToBeUpdated = ActionMgtTestUtil + .createIdPWithUserDefinedFederatedAuthenticatorConfig(CUSTOM_IDP_NAME + "new", ActionMgtTestUtil.createEndpointConfig("http://localhostnew1", "adminnew1", "adminnew1")); + return new Object[][]{ // Update PermissionsAndRoleConfig,FederatedAuthenticatorConfig,ProvisioningConnectorConfig,ClaimConfig. {idp1, idp1New, SAMPLE_TENANT_ID}, @@ -1255,13 +1322,14 @@ public Object[][] updateIdPData() { {idp2, idp2New, SAMPLE_TENANT_ID}, // Update name. {idp3, idp3New, SAMPLE_TENANT_ID2}, + // IDP with User Defined Federated Authenticator. + {userDefinedIdP, userDefinedIdPToBeUpdated, SAMPLE_TENANT_ID2}, }; } @Test(dataProvider = "updateIdPData") public void testUpdateIdP(Object oldIdp, Object newIdp, int tenantId) throws Exception { - try (MockedStatic identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); MockedStatic identityUtil = mockStatic(IdentityUtil.class); Connection connection = getConnection(DB_NAME)) { @@ -1276,9 +1344,7 @@ public void testUpdateIdP(Object oldIdp, Object newIdp, int tenantId) throws Exc String newIdpName = ((IdentityProvider) newIdp).getIdentityProviderName(); IdentityProvider idpResult = idPManagementDAO.getIdPByName(connection, newIdpName, tenantId, TENANT_DOMAIN); - for (FederatedAuthenticatorConfig config : idpResult.getFederatedAuthenticatorConfigs()) { - assertEquals(config.getDefinedByType(), DefinedByType.SYSTEM); - } + assertIdPResult(idpResult, newIdpName, true); assertEquals(idpResult.getIdentityProviderName(), newIdpName); } } @@ -1305,6 +1371,7 @@ public Object[][] deleteIdPData() { return new Object[][]{ {"testIdP1", SAMPLE_TENANT_ID}, {"testIdP3", SAMPLE_TENANT_ID2}, + {userDefinedIdP.getIdentityProviderName(), SAMPLE_TENANT_ID2}, }; } @@ -1859,6 +1926,8 @@ private void addTestIdps() throws IdentityProviderManagementException { idPManagementDAO.addIdP(idp2, SAMPLE_TENANT_ID); // IDP with Only name. idPManagementDAO.addIdP(idp3, SAMPLE_TENANT_ID2); + // IDP with a User defined authenticator. + idPManagementDAO.addIdP(userDefinedIdP, SAMPLE_TENANT_ID2); } // Add enabled and disabled IdPs used for tests. @@ -2012,5 +2081,25 @@ private int getIdPCount(Connection connection, String idpName, int tenantId) thr statement.close(); return resultSize; } + + private void assertIdPResult(IdentityProvider idpResult, String idpName, boolean isExist) { + + if (isExist) { + assertEquals(idpResult.getIdentityProviderName(), idpName, "'getIdPByName' method fails"); + for (FederatedAuthenticatorConfig config : idpResult.getFederatedAuthenticatorConfigs()) { + if (config instanceof UserDefinedFederatedAuthenticatorConfig) { + assertEquals(config.getDefinedByType(), DefinedByType.USER); + Property[] prop = idpResult.getDefaultAuthenticatorConfig().getProperties(); + assertEquals(prop.length, 1); + assertEquals(prop[0].getName(), "actionId"); + assertEquals(prop[0].getValue(), ASSOCIATED_ACTION_ID); + } else { + assertEquals(config.getDefinedByType(), DefinedByType.SYSTEM); + } + } + } else { + assertNull(idpResult, "'getIdPByName' method fails"); + } + } } diff --git a/components/idp-mgt/org.wso2.carbon.idp.mgt/src/test/java/org/wso2/carbon/idp/mgt/util/ActionMgtTestUtil.java b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/test/java/org/wso2/carbon/idp/mgt/util/ActionMgtTestUtil.java new file mode 100644 index 000000000000..6319dbc10ef9 --- /dev/null +++ b/components/idp-mgt/org.wso2.carbon.idp.mgt/src/test/java/org/wso2/carbon/idp/mgt/util/ActionMgtTestUtil.java @@ -0,0 +1,96 @@ +/* + * 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.idp.mgt.util; + +import org.wso2.carbon.identity.action.management.model.Action; +import org.wso2.carbon.identity.action.management.model.Authentication; +import org.wso2.carbon.identity.action.management.model.EndpointConfig; +import org.wso2.carbon.identity.application.common.model.FederatedAuthenticatorConfig; +import org.wso2.carbon.identity.application.common.model.IdentityProvider; +import org.wso2.carbon.identity.application.common.model.Property; +import org.wso2.carbon.identity.application.common.model.UserDefinedAuthenticatorEndpointConfig; +import org.wso2.carbon.identity.application.common.model.UserDefinedFederatedAuthenticatorConfig; + +import java.util.HashMap; +import java.util.Map; + +public class ActionMgtTestUtil { + + public static final String ASSOCIATED_ACTION_ID = "Dummy_Action_ID"; + + public static Action createAction(EndpointConfig endpointConfig) { + + Action.ActionResponseBuilder actionResponseBuilder = new Action.ActionResponseBuilder(); + actionResponseBuilder.id(ASSOCIATED_ACTION_ID); + actionResponseBuilder.name("SampleAssociatedAction"); + actionResponseBuilder.type(Action.ActionTypes.AUTHENTICATION); + actionResponseBuilder.description("SampleDescription"); + actionResponseBuilder.status(Action.Status.ACTIVE); + actionResponseBuilder.endpoint(endpointConfig); + return actionResponseBuilder.build(); + } + + public static EndpointConfig createEndpointConfig(String uri, String username, String password) { + + EndpointConfig.EndpointConfigBuilder endpointConfigBuilder = new EndpointConfig.EndpointConfigBuilder(); + endpointConfigBuilder.uri(uri); + endpointConfigBuilder.authentication( + new Authentication.BasicAuthBuilder(username, password).build()); + return endpointConfigBuilder.build(); + } + + public static IdentityProvider createIdPWithUserDefinedFederatedAuthenticatorConfig(String idpName, + EndpointConfig endpointConfig) { + + // Initialize Test Identity Provider 4 with custom user defined federated authenticator. + IdentityProvider newUserDefinedIdp = new IdentityProvider(); + newUserDefinedIdp.setIdentityProviderName(idpName); + + UserDefinedFederatedAuthenticatorConfig userDefinedFederatedAuthenticatorConfig = new + UserDefinedFederatedAuthenticatorConfig(); + userDefinedFederatedAuthenticatorConfig.setDisplayName("DisplayName1"); + userDefinedFederatedAuthenticatorConfig.setName("customFedAuthenticator"); + userDefinedFederatedAuthenticatorConfig.setEnabled(true); + userDefinedFederatedAuthenticatorConfig.setEndpointConfig( + buildUserDefinedAuthenticatorEndpointConfig(endpointConfig)); + Property property = new Property(); + property.setName("actionId"); + property.setValue(ASSOCIATED_ACTION_ID); + property.setConfidential(false); + userDefinedFederatedAuthenticatorConfig.setProperties(new Property[]{property}); + newUserDefinedIdp.setFederatedAuthenticatorConfigs( + new FederatedAuthenticatorConfig[]{userDefinedFederatedAuthenticatorConfig}); + newUserDefinedIdp.setDefaultAuthenticatorConfig(userDefinedFederatedAuthenticatorConfig); + return newUserDefinedIdp; + } + + public static UserDefinedAuthenticatorEndpointConfig buildUserDefinedAuthenticatorEndpointConfig( + EndpointConfig endpointConfig) { + + UserDefinedAuthenticatorEndpointConfig.UserDefinedAuthenticatorEndpointConfigBuilder endpointConfigBuilder = + new UserDefinedAuthenticatorEndpointConfig.UserDefinedAuthenticatorEndpointConfigBuilder(); + endpointConfigBuilder.uri(endpointConfig.getUri()); + endpointConfigBuilder.authenticationType(endpointConfig.getAuthentication().getType().getName()); + Map propMap = new HashMap<>(); + endpointConfig.getAuthentication().getProperties() + .forEach(prop -> propMap.put(prop.getName(), prop.getValue())); + endpointConfigBuilder.authenticationProperties(propMap); + return endpointConfigBuilder.build(); + } +} diff --git a/components/idp-mgt/pom.xml b/components/idp-mgt/pom.xml index f3e1503852a4..ee437153eb00 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.10-SNAPSHOT + 7.7.63-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 5ef6d908632b..3862d498a057 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.10-SNAPSHOT + 7.7.63-SNAPSHOT ../pom.xml diff --git a/components/input-validation-mgt/org.wso2.carbon.identity.input.validation.mgt/src/main/java/org/wso2/carbon/identity/input/validation/mgt/listener/InputValidationListener.java b/components/input-validation-mgt/org.wso2.carbon.identity.input.validation.mgt/src/main/java/org/wso2/carbon/identity/input/validation/mgt/listener/InputValidationListener.java index d5d2f637474f..60c1d9e59f74 100644 --- a/components/input-validation-mgt/org.wso2.carbon.identity.input.validation.mgt/src/main/java/org/wso2/carbon/identity/input/validation/mgt/listener/InputValidationListener.java +++ b/components/input-validation-mgt/org.wso2.carbon.identity.input.validation.mgt/src/main/java/org/wso2/carbon/identity/input/validation/mgt/listener/InputValidationListener.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). + * Copyright (c) 2022-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 @@ -51,6 +51,7 @@ import static org.wso2.carbon.identity.input.validation.mgt.utils.Constants.Configs.USERNAME; import static org.wso2.carbon.identity.input.validation.mgt.utils.Constants.ErrorMessages.ERROR_WHILE_UPDATING_CONFIGURATIONS; import static org.wso2.carbon.identity.input.validation.mgt.utils.Constants.INPUT_VALIDATION_USERNAME_ENABLED_CONFIG; +import static org.wso2.carbon.identity.mgt.constants.PasswordPolicyStatusCodes.ERROR_CODE_PASSWORD_POLICY_VIOLATION; /** * Lister class to validate the password. @@ -167,7 +168,7 @@ private boolean validate(Map inputValuesForFieldsMap, UserStoreM e.getDescription(), field)); } throw new UserStoreException(ERROR_CODE_PREFIX + e.getErrorCode() + ":" + e.getDescription(), - new PolicyViolationException(e.getDescription())); + new PolicyViolationException(ERROR_CODE_PASSWORD_POLICY_VIOLATION, e.getDescription())); } } } diff --git a/components/input-validation-mgt/org.wso2.carbon.identity.input.validation.mgt/src/main/java/org/wso2/carbon/identity/input/validation/mgt/model/handlers/PasswordValidationConfigurationHandler.java b/components/input-validation-mgt/org.wso2.carbon.identity.input.validation.mgt/src/main/java/org/wso2/carbon/identity/input/validation/mgt/model/handlers/PasswordValidationConfigurationHandler.java index 1b3eabee79e3..81f910582a5a 100644 --- a/components/input-validation-mgt/org.wso2.carbon.identity.input.validation.mgt/src/main/java/org/wso2/carbon/identity/input/validation/mgt/model/handlers/PasswordValidationConfigurationHandler.java +++ b/components/input-validation-mgt/org.wso2.carbon.identity.input.validation.mgt/src/main/java/org/wso2/carbon/identity/input/validation/mgt/model/handlers/PasswordValidationConfigurationHandler.java @@ -73,7 +73,7 @@ public ValidationConfiguration getDefaultValidationConfiguration(String tenantDo if (isRuleBasedValidationByDefault()) { rules.add(getRuleConfig(LengthValidator.class.getSimpleName(), MIN_LENGTH, "8")); - rules.add(getRuleConfig(LengthValidator.class.getSimpleName(), MAX_LENGTH, "30")); + rules.add(getRuleConfig(LengthValidator.class.getSimpleName(), MAX_LENGTH, "64")); rules.add(getRuleConfig(NumeralValidator.class.getSimpleName(), MIN_LENGTH, "1")); rules.add(getRuleConfig(UpperCaseValidator.class.getSimpleName(), MIN_LENGTH, "1")); rules.add(getRuleConfig(LowerCaseValidator.class.getSimpleName(), MIN_LENGTH, "1")); @@ -85,7 +85,7 @@ public ValidationConfiguration getDefaultValidationConfiguration(String tenantDo } } else { rules.add(getRuleConfig(LengthValidator.class.getSimpleName(), MIN_LENGTH, "8")); - rules.add(getRuleConfig(LengthValidator.class.getSimpleName(), MAX_LENGTH, "30")); + rules.add(getRuleConfig(LengthValidator.class.getSimpleName(), MAX_LENGTH, "64")); rules.add(getRuleConfig(NumeralValidator.class.getSimpleName(), MIN_LENGTH, "1")); rules.add(getRuleConfig(UpperCaseValidator.class.getSimpleName(), MIN_LENGTH, "1")); rules.add(getRuleConfig(LowerCaseValidator.class.getSimpleName(), MIN_LENGTH, "1")); diff --git a/components/input-validation-mgt/org.wso2.carbon.identity.input.validation.mgt/src/main/java/org/wso2/carbon/identity/input/validation/mgt/model/validators/AbstractRulesValidator.java b/components/input-validation-mgt/org.wso2.carbon.identity.input.validation.mgt/src/main/java/org/wso2/carbon/identity/input/validation/mgt/model/validators/AbstractRulesValidator.java index 59a6f6ffae82..00ee1868d36e 100644 --- a/components/input-validation-mgt/org.wso2.carbon.identity.input.validation.mgt/src/main/java/org/wso2/carbon/identity/input/validation/mgt/model/validators/AbstractRulesValidator.java +++ b/components/input-validation-mgt/org.wso2.carbon.identity.input.validation.mgt/src/main/java/org/wso2/carbon/identity/input/validation/mgt/model/validators/AbstractRulesValidator.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). + * Copyright (c) 2022-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 @@ -22,6 +22,7 @@ import org.apache.commons.lang.math.NumberUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.input.validation.mgt.exceptions.InputValidationMgtClientException; import org.wso2.carbon.identity.input.validation.mgt.model.Property; import org.wso2.carbon.identity.input.validation.mgt.model.ValidationContext; @@ -33,11 +34,14 @@ import java.util.stream.Collectors; import static org.wso2.carbon.identity.input.validation.mgt.utils.Constants.Configs.MAX_LENGTH; +import static org.wso2.carbon.identity.input.validation.mgt.utils.Constants.Configs.MAX_PASSWORD_ALLOWED_LENGTH; import static org.wso2.carbon.identity.input.validation.mgt.utils.Constants.Configs.MIN_LENGTH; +import static org.wso2.carbon.identity.input.validation.mgt.utils.Constants.Configs.PASSWORD; import static org.wso2.carbon.identity.input.validation.mgt.utils.Constants.ErrorMessages.ERROR_DEFAULT_MIN_MAX_MISMATCH; import static org.wso2.carbon.identity.input.validation.mgt.utils.Constants.ErrorMessages.ERROR_INVALID_VALIDATOR_PROPERTY_VALUE; import static org.wso2.carbon.identity.input.validation.mgt.utils.Constants.ErrorMessages.ERROR_PROPERTY_NOT_SUPPORTED; import static org.wso2.carbon.identity.input.validation.mgt.utils.Constants.ErrorMessages.ERROR_PROPERTY_TYPE_MISMATCH; +import static org.wso2.carbon.identity.input.validation.mgt.utils.Constants.ErrorMessages.ERROR_VALIDATION_MAX_LENGTH_MISMATCH; import static org.wso2.carbon.identity.input.validation.mgt.utils.Constants.SUPPORTED_PARAMS; /** @@ -93,6 +97,21 @@ public boolean validateProps(ValidationContext context) throws InputValidationMg String.format(ERROR_DEFAULT_MIN_MAX_MISMATCH.getDescription(), this.getClass().getSimpleName(), properties.get(MIN_LENGTH), properties.get(MAX_LENGTH))); } + + // Validate the max length for the password field. + if (PASSWORD.equals(context.getField())) { + int maxPasswordValue = Integer.parseInt(IdentityUtil.getProperty(MAX_PASSWORD_ALLOWED_LENGTH)); + if (properties.get(MAX_LENGTH) != null && + Integer.parseInt(properties.get(MAX_LENGTH)) > maxPasswordValue) { + if (log.isDebugEnabled()) { + log.debug(String.format("The property %s should be less than or equal to %s for the tenant %s.", + MAX_LENGTH, maxPasswordValue, context.getTenantDomain())); + } + throw new InputValidationMgtClientException(ERROR_VALIDATION_MAX_LENGTH_MISMATCH.getCode(), + String.format(ERROR_VALIDATION_MAX_LENGTH_MISMATCH.getDescription(), PASSWORD, maxPasswordValue, + context.getTenantDomain())); + } + } return true; } diff --git a/components/input-validation-mgt/org.wso2.carbon.identity.input.validation.mgt/src/main/java/org/wso2/carbon/identity/input/validation/mgt/utils/Constants.java b/components/input-validation-mgt/org.wso2.carbon.identity.input.validation.mgt/src/main/java/org/wso2/carbon/identity/input/validation/mgt/utils/Constants.java index f5c71c629c74..862bab71065e 100644 --- a/components/input-validation-mgt/org.wso2.carbon.identity.input.validation.mgt/src/main/java/org/wso2/carbon/identity/input/validation/mgt/utils/Constants.java +++ b/components/input-validation-mgt/org.wso2.carbon.identity.input.validation.mgt/src/main/java/org/wso2/carbon/identity/input/validation/mgt/utils/Constants.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, WSO2 LLC. (http://www.wso2.com). + * Copyright (c) 2022-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 @@ -69,6 +69,7 @@ public static class Configs { public static final String MAX_CONSECUTIVE_CHR = "max.consecutive.character"; public static final String ENABLE_VALIDATOR = "enable.validator"; public static final String ENABLE_SPECIAL_CHARACTERS = "enable.special.characters"; + public static final String MAX_PASSWORD_ALLOWED_LENGTH = "PasswordPolicy.MaxPasswordAllowedLength"; // Keys for password regEx validation. public static final String JS_REGEX = "regex"; diff --git a/components/input-validation-mgt/org.wso2.carbon.identity.input.validation.mgt/src/test/java/org/wso2/carbon/identity/input/validation/mgt/test/model/validators/AbstractRulesValidatorTest.java b/components/input-validation-mgt/org.wso2.carbon.identity.input.validation.mgt/src/test/java/org/wso2/carbon/identity/input/validation/mgt/test/model/validators/AbstractRulesValidatorTest.java new file mode 100644 index 000000000000..c76349cf85d6 --- /dev/null +++ b/components/input-validation-mgt/org.wso2.carbon.identity.input.validation.mgt/src/test/java/org/wso2/carbon/identity/input/validation/mgt/test/model/validators/AbstractRulesValidatorTest.java @@ -0,0 +1,145 @@ +/* + * 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.input.validation.mgt.test.model.validators; + +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.DataProvider; +import org.testng.annotations.Test; +import org.wso2.carbon.identity.core.util.IdentityUtil; +import org.wso2.carbon.identity.input.validation.mgt.exceptions.InputValidationMgtClientException; +import org.wso2.carbon.identity.input.validation.mgt.model.ValidationContext; +import org.wso2.carbon.identity.input.validation.mgt.model.validators.AbstractRulesValidator; +import org.wso2.carbon.identity.input.validation.mgt.model.validators.LengthValidator; + +import java.util.HashMap; +import java.util.Map; + +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.fail; +import static org.wso2.carbon.identity.input.validation.mgt.utils.Constants.Configs.MAX_LENGTH; +import static org.wso2.carbon.identity.input.validation.mgt.utils.Constants.Configs.MAX_PASSWORD_ALLOWED_LENGTH; +import static org.wso2.carbon.identity.input.validation.mgt.utils.Constants.Configs.MIN_LENGTH; +import static org.wso2.carbon.identity.input.validation.mgt.utils.Constants.Configs.PASSWORD; + +/** + * Testing the AbstractRulesValidator class + */ +public class AbstractRulesValidatorTest { + + // Test constants. + private static final String TENANT_DOMAIN = "carbon.super"; + @Mock + private ValidationContext mockContext; + private MockedStatic identityUtil; + + @BeforeMethod + public void setup() { + + MockitoAnnotations.openMocks(this); + identityUtil = mockStatic(IdentityUtil.class); + } + + @AfterMethod + public void tearDown() { + + identityUtil.close(); + } + + @DataProvider(name = "validationScenarios") + public Object[][] validationScenarios() { + + Map validProperties = new HashMap<>(); + validProperties.put(MIN_LENGTH, "5"); + validProperties.put(MAX_LENGTH, "10"); + + Map invalidMinProperties = new HashMap<>(); + invalidMinProperties.put(MIN_LENGTH, "-1"); + + Map invalidMaxProperties = new HashMap<>(); + invalidMaxProperties.put(MAX_LENGTH, "-1"); + + Map minGreaterThanMaxProperties = new HashMap<>(); + minGreaterThanMaxProperties.put(MIN_LENGTH, "15"); + minGreaterThanMaxProperties.put(MAX_LENGTH, "10"); + + Map maxLengthExceedsPassword = new HashMap<>(); + maxLengthExceedsPassword.put(MAX_LENGTH, "65"); + + Map validPasswordProperties = new HashMap<>(); + validPasswordProperties.put(MAX_LENGTH, "64"); + + Map passwordPropertiesWithoutMax = new HashMap<>(); + passwordPropertiesWithoutMax.put(MIN_LENGTH, "8"); + + return new Object[][]{ + // Valid scenario. + {validProperties, "VALID_FIELD", TENANT_DOMAIN, true, null}, + + // Invalid MIN_LENGTH. + {invalidMinProperties, "VALID_FIELD", TENANT_DOMAIN, false, InputValidationMgtClientException.class}, + + // Invalid MAX_LENGTH. + {invalidMaxProperties, "VALID_FIELD", TENANT_DOMAIN, false, InputValidationMgtClientException.class}, + + // MIN_LENGTH greater than MAX_LENGTH. + {minGreaterThanMaxProperties, "VALID_FIELD", TENANT_DOMAIN, false, + InputValidationMgtClientException.class}, + + // MAX_LENGTH exceeds max password length. + {maxLengthExceedsPassword, PASSWORD, TENANT_DOMAIN, false, InputValidationMgtClientException.class}, + + // Valid password properties. + {validPasswordProperties, PASSWORD, TENANT_DOMAIN, true, null}, + + // Password properties without MAX_LENGTH. + {passwordPropertiesWithoutMax, PASSWORD, TENANT_DOMAIN, true, null}}; + } + + @Test(dataProvider = "validationScenarios") + public void testValidateProps(Map properties, String field, String tenantDomain, + boolean expectedResult, Class expectedException) { + // Mock context. + when(mockContext.getProperties()).thenReturn(properties); + when(mockContext.getField()).thenReturn(field); + when(mockContext.getTenantDomain()).thenReturn(tenantDomain); + + // Mock IdentityUtil. + when(IdentityUtil.getProperty(MAX_PASSWORD_ALLOWED_LENGTH)).thenReturn("64"); + + // Test execution. + AbstractRulesValidator validator = new LengthValidator(); // Replace with your validator class name + try { + boolean result = validator.validateProps(mockContext); + assertEquals(result, expectedResult, "Unexpected validation result."); + if (expectedException != null) { + fail("Expected exception but none was thrown."); + } + } catch (Exception e) { + if (expectedException == null || !expectedException.isInstance(e)) { + fail("Unexpected exception: " + e.getMessage()); + } + } + } +} + diff --git a/components/input-validation-mgt/org.wso2.carbon.identity.input.validation.mgt/src/test/resources/testng.xml b/components/input-validation-mgt/org.wso2.carbon.identity.input.validation.mgt/src/test/resources/testng.xml index 9a0dc73db57d..68c16b8b6dea 100644 --- a/components/input-validation-mgt/org.wso2.carbon.identity.input.validation.mgt/src/test/resources/testng.xml +++ b/components/input-validation-mgt/org.wso2.carbon.identity.input.validation.mgt/src/test/resources/testng.xml @@ -1,5 +1,5 @@ + diff --git a/components/input-validation-mgt/pom.xml b/components/input-validation-mgt/pom.xml index 7f3cc363c63d..7e88003fab3e 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.10-SNAPSHOT + 7.7.63-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 ec36bb68d787..a1ae5679e710 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.10-SNAPSHOT + 7.7.63-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 9cba7cf2ac05..e55589818b10 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.10-SNAPSHOT + 7.7.63-SNAPSHOT ../pom.xml 4.0.0 diff --git a/components/multi-attribute-login/org.wso2.carbon.identity.unique.claim.mgt/src/main/java/org/wso2/carbon/identity/unique/claim/mgt/listener/UniqueClaimUserOperationEventListener.java b/components/multi-attribute-login/org.wso2.carbon.identity.unique.claim.mgt/src/main/java/org/wso2/carbon/identity/unique/claim/mgt/listener/UniqueClaimUserOperationEventListener.java index 8a86481bf032..562e508d89e5 100644 --- a/components/multi-attribute-login/org.wso2.carbon.identity.unique.claim.mgt/src/main/java/org/wso2/carbon/identity/unique/claim/mgt/listener/UniqueClaimUserOperationEventListener.java +++ b/components/multi-attribute-login/org.wso2.carbon.identity.unique.claim.mgt/src/main/java/org/wso2/carbon/identity/unique/claim/mgt/listener/UniqueClaimUserOperationEventListener.java @@ -23,6 +23,7 @@ import org.apache.commons.logging.LogFactory; import org.wso2.carbon.identity.claim.metadata.mgt.exception.ClaimMetadataException; import org.wso2.carbon.identity.claim.metadata.mgt.model.LocalClaim; +import org.wso2.carbon.identity.claim.metadata.mgt.util.ClaimConstants; import org.wso2.carbon.identity.core.AbstractIdentityUserOperationEventListener; import org.wso2.carbon.identity.core.model.IdentityEventListenerConfig; import org.wso2.carbon.identity.core.util.IdentityCoreConstants; @@ -102,8 +103,9 @@ public boolean doPreSetUserClaimValue(String userName, String claimURI, String c } try { String tenantDomain = getTenantDomain(userStoreManager); - if (isUniqueClaim(claimURI, tenantDomain)) { - return !isClaimDuplicated(userName, claimURI, claimValue, profile, userStoreManager); + ClaimConstants.ClaimUniquenessScope uniquenessScope = getClaimUniquenessScope(claimURI, tenantDomain); + if (shouldValidateUniqueness(uniquenessScope)) { + return !isClaimDuplicated(userName, claimURI, claimValue, profile, userStoreManager, uniquenessScope); } } catch (org.wso2.carbon.user.api.UserStoreException | ClaimMetadataException e) { log.error("Error while retrieving details. " + e.getMessage(), e); @@ -132,7 +134,9 @@ private void checkClaimUniqueness(String username, Map claims, S Claim claimObject = null; for (Map.Entry claim : claims.entrySet()) { try { - if (StringUtils.isNotEmpty(claim.getValue()) && isUniqueClaim(claim.getKey(), tenantDomain)) { + ClaimConstants.ClaimUniquenessScope uniquenessScope = + getClaimUniquenessScope(claim.getKey(), tenantDomain); + if (StringUtils.isNotEmpty(claim.getValue()) && shouldValidateUniqueness(uniquenessScope)) { try { claimObject = userStoreManager.getClaimManager().getClaim(claim.getKey()); } catch (org.wso2.carbon.user.api.UserStoreException e) { @@ -147,7 +151,8 @@ private void checkClaimUniqueness(String username, Map claims, S claimObject.getDisplayTag() + "!"; throw new UserStoreException(errorMessage, new PolicyViolationException(errorMessage)); } - if (isClaimDuplicated(username, claim.getKey(), claim.getValue(), profile, userStoreManager)) { + if (isClaimDuplicated(username, claim.getKey(), claim.getValue(), profile, userStoreManager, + uniquenessScope)) { String displayTag = claimObject.getDisplayTag(); if (StringUtils.isBlank(displayTag)) { displayTag = claim.getKey(); @@ -175,14 +180,15 @@ private void checkClaimUniqueness(String username, Map claims, S } private boolean isClaimDuplicated(String username, String claimUri, String claimValue, String profile, - UserStoreManager userStoreManager) throws UserStoreException { + UserStoreManager userStoreManager, + ClaimConstants.ClaimUniquenessScope uniquenessScope) throws UserStoreException { String domainName = userStoreManager.getRealmConfiguration().getUserStoreProperty( UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME); String[] userList; // Get UserStoreManager from realm since the received one might be for a secondary user store UserStoreManager userStoreMgrFromRealm = getUserstoreManager(userStoreManager.getTenantId()); - if (isScopeWithinUserstore()) { + if (ClaimConstants.ClaimUniquenessScope.WITHIN_USERSTORE.equals(uniquenessScope)) { String claimValueWithDomain = domainName + UserCoreConstants.DOMAIN_SEPARATOR + claimValue; userList = userStoreMgrFromRealm.getUserList(claimUri, claimValueWithDomain, profile); } else { @@ -200,17 +206,67 @@ private boolean isClaimDuplicated(String username, String claimUri, String claim return true; } - public boolean isUniqueClaim(String claimUrI, String tenantDomain) throws ClaimMetadataException { + /** + * Determines the uniqueness validation scope for a given claim URI. + * This method checks the claim properties to determine how uniqueness should be enforced: + * 1. First checks for explicit uniquenessScope property + * 2. If not found, checks for legacy isUnique property + * 3. If claim is unique, scope is determined by isScopeWithinUserstore server-level configuration + * 4. Defaults to NONE if no uniqueness requirements are found + * + * @param claimUri The URI of the claim to check + * @param tenantDomain The tenant domain where the claim exists + * @return The ClaimUniquenessScope (NONE, WITHIN_USERSTORE, or ACROSS_USERSTORES) + * @throws ClaimMetadataException If there is an error accessing claim metadata + */ + private ClaimConstants.ClaimUniquenessScope getClaimUniquenessScope(String claimUri, String tenantDomain) + throws ClaimMetadataException { + + List localClaims = UniqueClaimUserOperationDataHolder.getInstance() + .getClaimMetadataManagementService().getLocalClaims(tenantDomain); + + LocalClaim targetLocalClaim = localClaims.stream() + .filter(claim -> claim.getClaimURI().equals(claimUri)) + .findFirst() + .orElse(null); + + if (targetLocalClaim != null) { + String uniquenessScope = targetLocalClaim.getClaimProperty(ClaimConstants.CLAIM_UNIQUENESS_SCOPE_PROPERTY); + if (StringUtils.isNotBlank(uniquenessScope)) { + try { + return ClaimConstants.ClaimUniquenessScope.valueOf(uniquenessScope); + } catch (IllegalArgumentException e) { + if (log.isWarnEnabled()) { + log.warn("Invalid uniqueness validation scope '" + uniquenessScope + "' provided for " + + "claim URI: " + claimUri + ". Defaulting to NONE, where no uniqueness validation " + + "will be performed."); + } + return ClaimConstants.ClaimUniquenessScope.NONE; + } + } - List localClaims = UniqueClaimUserOperationDataHolder.getInstance(). - getClaimMetadataManagementService().getLocalClaims(tenantDomain); - for (LocalClaim localClaim : localClaims) { - if (localClaim.getClaimURI().equals(claimUrI) && - Boolean.parseBoolean(localClaim.getClaimProperty(IS_UNIQUE_CLAIM))) { - return true; + boolean isUniqueClaim = Boolean.parseBoolean(targetLocalClaim.getClaimProperty(IS_UNIQUE_CLAIM)); + if (isUniqueClaim) { + return isScopeWithinUserstore() + ? ClaimConstants.ClaimUniquenessScope.WITHIN_USERSTORE + : ClaimConstants.ClaimUniquenessScope.ACROSS_USERSTORES; } } - return false; + + return ClaimConstants.ClaimUniquenessScope.NONE; + } + + /** + * Determines whether uniqueness validation should be performed for a given uniqueness scope. + * Returns true for any scope other than NONE. + * + * @param uniquenessScope The ClaimUniquenessScope to check + * @return true if uniqueness validation should be performed, false otherwise + * @throws ClaimMetadataException If there is an error processing the metadata + */ + private boolean shouldValidateUniqueness(ClaimConstants.ClaimUniquenessScope uniquenessScope) { + + return !ClaimConstants.ClaimUniquenessScope.NONE.equals(uniquenessScope); } private void checkUsernameUniqueness(String username, UserStoreManager userStoreManager) throws UserStoreException { @@ -219,8 +275,9 @@ private void checkUsernameUniqueness(String username, UserStoreManager userStore String tenantDomain = getTenantDomain(userStoreManager); try { - if (isUniqueClaim(USERNAME_CLAIM, tenantDomain) && - isClaimDuplicated(username, USERNAME_CLAIM, username, null, userStoreManager)) { + ClaimConstants.ClaimUniquenessScope uniquenessScope = getClaimUniquenessScope(USERNAME_CLAIM, tenantDomain); + if (shouldValidateUniqueness(uniquenessScope) && + isClaimDuplicated(username, USERNAME_CLAIM, username, null, userStoreManager, uniquenessScope)) { errorMessage = "Username " + username + " is already in use by a different user!"; throw new UserStoreException(errorMessage, new PolicyViolationException(errorMessage)); diff --git a/components/multi-attribute-login/pom.xml b/components/multi-attribute-login/pom.xml index efa02f486459..f68c13e4acac 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.10-SNAPSHOT + 7.7.63-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 2f9d67dd6543..a39620dd2551 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.10-SNAPSHOT + 7.7.63-SNAPSHOT ../pom.xml diff --git a/components/notification-mgt/pom.xml b/components/notification-mgt/pom.xml index 654cd6bba3ec..045011dd22e8 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.10-SNAPSHOT + 7.7.63-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 96291654f795..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.10-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