Search in sources :

Example 1 with ConditionType

use of org.wso2.carbon.identity.configuration.mgt.core.search.constant.ConditionType in project carbon-apimgt by wso2.

the class PolicyDAOImpl method addBlockConditions.

@Override
public String addBlockConditions(BlockConditions blockConditions) throws APIMgtDAOException {
    boolean status = false;
    boolean valid = false;
    String uuid = null;
    String conditionType = blockConditions.getConditionType();
    String conditionValue = blockConditions.getConditionValue();
    try {
        String query = "INSERT INTO AM_BLOCK_CONDITIONS (TYPE, VALUE, ENABLED, UUID) VALUES (?,?,?,?)";
        if (APIMgtConstants.ThrottlePolicyConstants.BLOCKING_CONDITIONS_API.equals(conditionType)) {
            if (isValidContext(conditionValue)) {
                valid = true;
            } else {
                throw new APIMgtDAOException("Couldn't Save Block Condition Due to Invalid API Context : " + conditionValue, ExceptionCodes.BLOCK_CONDITION_UNSUPPORTED_API_CONTEXT);
            }
        } else if (APIMgtConstants.ThrottlePolicyConstants.BLOCKING_CONDITIONS_APPLICATION.equals(conditionType)) {
            String[] appArray = conditionValue.split(":");
            if (appArray.length > 1) {
                String appUuid = appArray[0];
                String appName = appArray[1];
                if (isValidApplication(appName, appUuid)) {
                    valid = true;
                } else {
                    throw new APIMgtDAOException("Couldn't Save Block Condition Due to Invalid Application : " + appName + ", UUID :" + appUuid, ExceptionCodes.BLOCK_CONDITION_UNSUPPORTED_APP_ID_NAME);
                }
            }
        } else if (APIMgtConstants.ThrottlePolicyConstants.BLOCKING_CONDITIONS_USER.equals(conditionType)) {
            valid = true;
        } else if (APIMgtConstants.ThrottlePolicyConstants.BLOCKING_CONDITIONS_IP.equals(conditionType)) {
            valid = true;
        } else if (APIMgtConstants.ThrottlePolicyConstants.BLOCKING_CONDITION_IP_RANGE.equals(conditionType)) {
            valid = isIPRangeConditionValid(blockConditions.getStartingIP(), blockConditions.getEndingIP());
        }
        if (valid) {
            try (Connection connection = DAOUtil.getConnection();
                PreparedStatement insertPreparedStatement = connection.prepareStatement(query)) {
                try {
                    connection.setAutoCommit(false);
                    if (!isBlockConditionExist(blockConditions)) {
                        uuid = UUID.randomUUID().toString();
                        insertPreparedStatement.setString(1, conditionType);
                        insertPreparedStatement.setString(2, conditionValue);
                        insertPreparedStatement.setBoolean(3, blockConditions.isEnabled());
                        insertPreparedStatement.setString(4, uuid);
                        insertPreparedStatement.execute();
                        if (APIMgtConstants.ThrottlePolicyConstants.BLOCKING_CONDITION_IP_RANGE.equals(conditionType)) {
                            String ipConditionQuery = "INSERT INTO AM_IP_RANGE_CONDITION " + "(STARTING_IP, ENDING_IP, UUID) VALUES (?, ?, ?)";
                            try (PreparedStatement ipStatement = connection.prepareStatement(ipConditionQuery)) {
                                ipStatement.setString(1, blockConditions.getStartingIP());
                                ipStatement.setString(2, blockConditions.getEndingIP());
                                ipStatement.setString(3, uuid);
                                ipStatement.execute();
                            } catch (SQLException e) {
                                connection.rollback();
                            }
                        }
                        connection.commit();
                    } else {
                        throw new APIMgtDAOException("Condition with type: " + conditionType + ", value: " + conditionValue + " already exists", ExceptionCodes.BLOCK_CONDITION_ALREADY_EXISTS);
                    }
                } catch (SQLException e) {
                    connection.rollback();
                    throw new APIMgtDAOException(DAOUtil.DAO_ERROR_PREFIX + "adding block condition: " + conditionType + " and " + conditionValue, e);
                } finally {
                    connection.setAutoCommit(DAOUtil.isAutoCommit());
                }
            }
        }
    } catch (SQLException e) {
        throw new APIMgtDAOException(DAOUtil.DAO_ERROR_PREFIX + "adding block condition: " + conditionType + " and " + conditionValue, e);
    }
    return uuid;
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement)

Example 2 with ConditionType

use of org.wso2.carbon.identity.configuration.mgt.core.search.constant.ConditionType in project carbon-apimgt by wso2.

the class SampleTestObjectCreator method createDefaultBlockCondition.

public static BlockConditions createDefaultBlockCondition(String conditionType) {
    BlockConditions blockConditions = new BlockConditions();
    blockConditions.setConditionType(conditionType);
    blockConditions.setEnabled(true);
    if (conditionType.equals(APIMgtConstants.ThrottlePolicyConstants.BLOCKING_CONDITIONS_IP)) {
        blockConditions.setConditionValue(SAMPLE_IP_1);
    } else if (conditionType.equals(APIMgtConstants.ThrottlePolicyConstants.BLOCKING_CONDITION_IP_RANGE)) {
        blockConditions.setStartingIP(SAMPLE_IP_1);
        blockConditions.setEndingIP(SAMPLE_IP_2);
    } else if (conditionType.equals(APIMgtConstants.ThrottlePolicyConstants.BLOCKING_CONDITIONS_API)) {
        try {
            API.APIBuilder apiBuilder = SampleTestObjectCreator.createDefaultAPI();
            API api = apiBuilder.build();
            DAOFactory.getApiDAO().addAPI(api);
            blockConditions.setConditionValue(api.getContext());
        } catch (APIMgtDAOException e) {
            log.error("Error while adding default api in default block condition", e);
        }
    } else if (conditionType.equals(APIMgtConstants.ThrottlePolicyConstants.BLOCKING_CONDITIONS_APPLICATION)) {
        try {
            Application app = createDefaultApplication();
            DAOFactory.getApplicationDAO().addApplication(app);
            blockConditions.setConditionValue(app.getId() + ":" + app.getName());
        } catch (APIMgtDAOException e) {
            log.error("Error while adding default app in default block condition", e);
        }
    } else if (conditionType.equals(APIMgtConstants.ThrottlePolicyConstants.BLOCKING_CONDITIONS_USER)) {
        blockConditions.setConditionValue(ADMIN);
    }
    return blockConditions;
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) BlockConditions(org.wso2.carbon.apimgt.core.models.BlockConditions) CompositeAPI(org.wso2.carbon.apimgt.core.models.CompositeAPI) API(org.wso2.carbon.apimgt.core.models.API) Application(org.wso2.carbon.apimgt.core.models.Application)

Example 3 with ConditionType

use of org.wso2.carbon.identity.configuration.mgt.core.search.constant.ConditionType in project carbon-apimgt by wso2.

the class APIProviderImpl method addBlockCondition.

@Override
public String addBlockCondition(String conditionType, String conditionValue) throws APIManagementException {
    if (APIConstants.BLOCKING_CONDITIONS_USER.equals(conditionType)) {
        conditionValue = MultitenantUtils.getTenantAwareUsername(conditionValue);
        conditionValue = conditionValue + "@" + tenantDomain;
    }
    BlockConditionsDTO blockConditionsDTO = new BlockConditionsDTO();
    blockConditionsDTO.setConditionType(conditionType);
    blockConditionsDTO.setConditionValue(conditionValue);
    blockConditionsDTO.setTenantDomain(tenantDomain);
    blockConditionsDTO.setEnabled(true);
    blockConditionsDTO.setUUID(UUID.randomUUID().toString());
    BlockConditionsDTO createdBlockConditionsDto = apiMgtDAO.addBlockConditions(blockConditionsDTO);
    if (createdBlockConditionsDto != null) {
        publishBlockingEvent(createdBlockConditionsDto, "true");
    }
    return createdBlockConditionsDto.getUUID();
}
Also used : BlockConditionsDTO(org.wso2.carbon.apimgt.api.model.BlockConditionsDTO)

Example 4 with ConditionType

use of org.wso2.carbon.identity.configuration.mgt.core.search.constant.ConditionType in project carbon-apimgt by wso2.

the class CommonThrottleMappingUtil method fromDTOListToConditionList.

/**
 * Converts a list of Throttle Condition DTOs into a list of Condition model objects
 *
 * @param throttleConditionDTOs list of Throttle Condition DTOs
 * @return Derived list of Condition model objects from Throttle Condition DTOs
 * @throws UnsupportedThrottleConditionTypeException
 */
public static List<Condition> fromDTOListToConditionList(List<ThrottleConditionDTO> throttleConditionDTOs) throws UnsupportedThrottleConditionTypeException {
    List<Condition> conditions = new ArrayList<>();
    String errorMessage;
    if (throttleConditionDTOs != null) {
        for (ThrottleConditionDTO dto : throttleConditionDTOs) {
            ThrottleConditionDTO.TypeEnum conditionType = dto.getType();
            if (conditionType != null) {
                switch(conditionType) {
                    case HEADERCONDITION:
                        {
                            if (dto.getHeaderCondition() != null) {
                                conditions.add(fromDTOToHeaderCondition(dto.getHeaderCondition(), dto.isInvertCondition()));
                            } else {
                                errorMessage = RestApiAdminUtils.constructMissingThrottleObjectErrorMessage(ThrottleConditionDTO.TypeEnum.HEADERCONDITION) + dto.toString();
                                throw new UnsupportedThrottleConditionTypeException(errorMessage);
                            }
                            break;
                        }
                    case IPCONDITION:
                        {
                            if (dto.getIpCondition() != null) {
                                conditions.add(fromDTOToIPCondition(dto.getIpCondition(), dto.isInvertCondition()));
                            } else {
                                errorMessage = RestApiAdminUtils.constructMissingThrottleObjectErrorMessage(ThrottleConditionDTO.TypeEnum.IPCONDITION) + dto.toString();
                                throw new UnsupportedThrottleConditionTypeException(errorMessage);
                            }
                            break;
                        }
                    case QUERYPARAMETERCONDITION:
                        {
                            if (dto.getQueryParameterCondition() != null) {
                                conditions.add(fromDTOToQueryParameterCondition(dto.getQueryParameterCondition(), dto.isInvertCondition()));
                            } else {
                                errorMessage = RestApiAdminUtils.constructMissingThrottleObjectErrorMessage(ThrottleConditionDTO.TypeEnum.QUERYPARAMETERCONDITION) + dto.toString();
                                throw new UnsupportedThrottleConditionTypeException(errorMessage);
                            }
                            break;
                        }
                    case JWTCLAIMSCONDITION:
                        {
                            if (dto.getJwtClaimsCondition() != null) {
                                conditions.add(fromDTOToJWTClaimsCondition(dto.getJwtClaimsCondition(), dto.isInvertCondition()));
                            } else {
                                errorMessage = RestApiAdminUtils.constructMissingThrottleObjectErrorMessage(ThrottleConditionDTO.TypeEnum.JWTCLAIMSCONDITION) + dto.toString();
                                throw new UnsupportedThrottleConditionTypeException(errorMessage);
                            }
                            break;
                        }
                    default:
                        return null;
                }
            } else {
                errorMessage = "Condition item 'type' property has not been specified\n" + dto.toString();
                throw new UnsupportedThrottleConditionTypeException(errorMessage);
            }
        }
    }
    return conditions;
}
Also used : IPCondition(org.wso2.carbon.apimgt.api.model.policy.IPCondition) QueryParameterCondition(org.wso2.carbon.apimgt.api.model.policy.QueryParameterCondition) HeaderCondition(org.wso2.carbon.apimgt.api.model.policy.HeaderCondition) Condition(org.wso2.carbon.apimgt.api.model.policy.Condition) JWTClaimsCondition(org.wso2.carbon.apimgt.api.model.policy.JWTClaimsCondition) ArrayList(java.util.ArrayList) UnsupportedThrottleConditionTypeException(org.wso2.carbon.apimgt.api.UnsupportedThrottleConditionTypeException) ThrottleConditionDTO(org.wso2.carbon.apimgt.rest.api.admin.v1.dto.ThrottleConditionDTO)

Example 5 with ConditionType

use of org.wso2.carbon.identity.configuration.mgt.core.search.constant.ConditionType in project carbon-apimgt by wso2.

the class ApiMgtDAO method addBlockConditions.

/**
 * Add a block condition
 *
 * @return uuid of the block condition if successfully added
 * @throws APIManagementException
 */
public BlockConditionsDTO addBlockConditions(BlockConditionsDTO blockConditionsDTO) throws APIManagementException {
    Connection connection = null;
    PreparedStatement insertPreparedStatement = null;
    boolean status = false;
    boolean valid = false;
    ResultSet rs = null;
    String uuid = blockConditionsDTO.getUUID();
    String conditionType = blockConditionsDTO.getConditionType();
    String conditionValue = blockConditionsDTO.getConditionValue();
    String tenantDomain = blockConditionsDTO.getTenantDomain();
    String conditionStatus = String.valueOf(blockConditionsDTO.isEnabled());
    try {
        String query = SQLConstants.ThrottleSQLConstants.ADD_BLOCK_CONDITIONS_SQL;
        if (APIConstants.BLOCKING_CONDITIONS_API.equals(conditionType)) {
            String extractedTenantDomain = MultitenantUtils.getTenantDomainFromRequestURL(conditionValue);
            if (extractedTenantDomain == null) {
                extractedTenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
            }
            if (tenantDomain.equals(extractedTenantDomain) && isValidContext(conditionValue)) {
                valid = true;
            } else {
                throw new APIManagementException("Couldn't Save Block Condition Due to Invalid API Context " + conditionValue);
            }
        } else if (APIConstants.BLOCKING_CONDITIONS_APPLICATION.equals(conditionType)) {
            String[] appArray = conditionValue.split(":");
            if (appArray.length > 1) {
                String appOwner = appArray[0];
                String appName = appArray[1];
                if ((MultitenantUtils.getTenantDomain(appOwner).equals(tenantDomain)) && isValidApplication(appOwner, appName)) {
                    valid = true;
                } else {
                    throw new APIManagementException("Couldn't Save Block Condition Due to Invalid Application " + "name " + appName + " from Application " + "Owner " + appOwner);
                }
            }
        } else if (APIConstants.BLOCKING_CONDITIONS_USER.equals(conditionType)) {
            if (MultitenantUtils.getTenantDomain(conditionValue).equals(tenantDomain)) {
                valid = true;
            } else {
                throw new APIManagementException("Invalid User in Tenant Domain " + tenantDomain);
            }
        } else if (APIConstants.BLOCKING_CONDITIONS_IP.equals(conditionType) || APIConstants.BLOCK_CONDITION_IP_RANGE.equals(conditionType)) {
            valid = true;
        } else if (APIConstants.BLOCKING_CONDITIONS_SUBSCRIPTION.equals(conditionType)) {
            /* ATM this condition type will be used internally to handle subscription blockings for JWT type access
                   tokens.
                */
            String[] conditionsArray = conditionValue.split(":");
            if (conditionsArray.length > 0) {
                String apiContext = conditionsArray[0];
                String applicationIdentifier = conditionsArray[2];
                String[] app = applicationIdentifier.split("-", 2);
                String appOwner = app[0];
                String appName = app[1];
                // Check whether the given api context exists in tenant
                String extractedTenantDomain = MultitenantUtils.getTenantDomainFromRequestURL(apiContext);
                if (extractedTenantDomain == null) {
                    extractedTenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
                }
                if (tenantDomain.equals(extractedTenantDomain) && isValidContext(apiContext)) {
                    valid = true;
                } else {
                    throw new APIManagementException("Couldn't Save Subscription Block Condition Due to Invalid API Context " + apiContext);
                }
                // Check whether the given application is valid
                if ((MultitenantUtils.getTenantDomain(appOwner).equals(tenantDomain)) && isValidApplication(appOwner, appName)) {
                    valid = true;
                } else {
                    throw new APIManagementException("Couldn't Save Subscription Block Condition Due to Invalid Application " + "name " + appName + " from Application " + "Owner " + appOwner);
                }
            } else {
                throw new APIManagementException("Invalid subscription block condition with insufficient data : " + conditionValue);
            }
        }
        if (valid) {
            connection = APIMgtDBUtil.getConnection();
            connection.setAutoCommit(false);
            if (!isBlockConditionExist(conditionType, conditionValue, tenantDomain, connection)) {
                String dbProductName = connection.getMetaData().getDatabaseProductName();
                insertPreparedStatement = connection.prepareStatement(query, new String[] { DBUtils.getConvertedAutoGeneratedColumnName(dbProductName, "CONDITION_ID") });
                insertPreparedStatement.setString(1, conditionType);
                insertPreparedStatement.setString(2, conditionValue);
                insertPreparedStatement.setString(3, conditionStatus);
                insertPreparedStatement.setString(4, tenantDomain);
                insertPreparedStatement.setString(5, uuid);
                insertPreparedStatement.execute();
                ResultSet generatedKeys = insertPreparedStatement.getGeneratedKeys();
                if (generatedKeys != null && generatedKeys.next()) {
                    blockConditionsDTO.setConditionId(generatedKeys.getInt(1));
                }
                connection.commit();
                status = true;
            } else {
                throw new BlockConditionAlreadyExistsException("Condition with type: " + conditionType + ", value: " + conditionValue + " already exists");
            }
        }
    } catch (SQLException e) {
        if (connection != null) {
            try {
                connection.rollback();
            } catch (SQLException ex) {
                handleException("Failed to rollback adding Block condition : " + conditionType + " and " + conditionValue, ex);
            }
        }
        handleException("Failed to add Block condition : " + conditionType + " and " + conditionValue, e);
    } finally {
        APIMgtDBUtil.closeAllConnections(insertPreparedStatement, connection, null);
    }
    if (status) {
        return blockConditionsDTO;
    } else {
        return null;
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) BlockConditionAlreadyExistsException(org.wso2.carbon.apimgt.api.BlockConditionAlreadyExistsException)

Aggregations

Connection (java.sql.Connection)2 PreparedStatement (java.sql.PreparedStatement)2 SQLException (java.sql.SQLException)2 BlockConditionsDTO (org.wso2.carbon.apimgt.api.model.BlockConditionsDTO)2 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)2 BlockConditions (org.wso2.carbon.apimgt.core.models.BlockConditions)2 ResultSet (java.sql.ResultSet)1 ArrayList (java.util.ArrayList)1 Random (java.util.Random)1 ThreadLocalRandom (java.util.concurrent.ThreadLocalRandom)1 JSONObject (org.json.simple.JSONObject)1 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)1 BlockConditionAlreadyExistsException (org.wso2.carbon.apimgt.api.BlockConditionAlreadyExistsException)1 UnsupportedThrottleConditionTypeException (org.wso2.carbon.apimgt.api.UnsupportedThrottleConditionTypeException)1 LifeCycleEvent (org.wso2.carbon.apimgt.api.model.LifeCycleEvent)1 Condition (org.wso2.carbon.apimgt.api.model.policy.Condition)1 HeaderCondition (org.wso2.carbon.apimgt.api.model.policy.HeaderCondition)1 IPCondition (org.wso2.carbon.apimgt.api.model.policy.IPCondition)1 JWTClaimsCondition (org.wso2.carbon.apimgt.api.model.policy.JWTClaimsCondition)1 QueryParameterCondition (org.wso2.carbon.apimgt.api.model.policy.QueryParameterCondition)1