Search in sources :

Example 86 with Condition

use of org.wso2.carbon.user.core.model.Condition in project carbon-apimgt by wso2.

the class ThrottlePolicyTemplateBuilder method getThrottlePolicyForAPILevel.

/**
 * Generate policy for API level throttling
 *
 * @param policy Policy with level 'api'. Policy can have multiple pipelines and a default condition which will be
 *               used as else condition
 * @return a Map containing a set of policies for each condition group
 * @throws APITemplateException if failed to generate policy
 */
public Map<String, String> getThrottlePolicyForAPILevel(ApiPolicy policy) throws APITemplateException {
    if (log.isDebugEnabled()) {
        log.debug("Generating policy for API Level :" + policy.toString());
    }
    Map<String, String> policyArray = new HashMap<>();
    try {
        VelocityEngine velocityengine = new VelocityEngine();
        APIUtil.initializeVelocityContext(velocityengine);
        velocityengine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, CarbonUtils.getCarbonHome());
        velocityengine.init();
        Template template = velocityengine.getTemplate(getTemplatePathForAPI());
        StringWriter writer;
        VelocityContext context;
        if (policy.getConditionGroups() != null) {
            for (APIPolicyConditionGroup conditionGroup : policy.getConditionGroups()) {
                if (conditionGroup.getDefaultLimit() == null) {
                    continue;
                }
                context = new VelocityContext();
                setConstantContext(context);
                context.put("policy", policy);
                context.put("quotaPolicy", conditionGroup.getDefaultLimit());
                context.put("pipeline", "condition_" + conditionGroup.getConditionGroupId());
                String conditionString = getPolicyCondition(conditionGroup.getCondition());
                JSONArray conditions = new JSONArray();
                conditions.add(getPolicyConditionJson(conditionGroup.getCondition()));
                context.put("condition", " AND " + conditionString);
                context.put("evaluatedConditions", new String(Base64.encodeBase64(conditions.toJSONString().getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8));
                writer = new StringWriter();
                template.merge(context, writer);
                if (log.isDebugEnabled()) {
                    log.debug("Policy : " + writer.toString());
                }
                String policyName = policy.getTenantDomain() + APIConstants.DELEM_UNDERSCORE + PolicyConstants.POLICY_LEVEL_RESOURCE + APIConstants.DELEM_UNDERSCORE + policy.getName() + APIConstants.THROTTLE_POLICY_CONDITION + conditionGroup.getConditionGroupId();
                policyArray.put(policyName, writer.toString());
            }
        }
    } catch (VelocityException e) {
        log.error("Velocity Error", e);
        throw new APITemplateException("Velocity Error", e);
    }
    return policyArray;
}
Also used : VelocityEngine(org.apache.velocity.app.VelocityEngine) APIPolicyConditionGroup(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.APIPolicyConditionGroup) StringWriter(java.io.StringWriter) HashMap(java.util.HashMap) VelocityContext(org.apache.velocity.VelocityContext) JSONArray(org.json.simple.JSONArray) VelocityException(org.apache.velocity.exception.VelocityException) APITemplateException(org.wso2.carbon.apimgt.impl.template.APITemplateException) Template(org.apache.velocity.Template)

Example 87 with Condition

use of org.wso2.carbon.user.core.model.Condition in project carbon-apimgt by wso2.

the class APIMappingUtil method handleAWSCredentials.

/**
 * Set AWS Secret Key based on preserveCredentials state
 *
 * @param awsEndpointConfig   Endpoint configuration of the API
 * @param preserveCredentials Condition to preserve credentials
 * @return Updated endpoint config
 */
private static JSONObject handleAWSCredentials(JSONObject awsEndpointConfig, boolean preserveCredentials) {
    if (StringUtils.isNotEmpty((String) awsEndpointConfig.get(APIConstants.AMZN_SECRET_KEY))) {
        if (!preserveCredentials) {
            awsEndpointConfig.put(APIConstants.AMZN_SECRET_KEY, APIConstants.AWS_SECRET_KEY);
            return awsEndpointConfig;
        } else {
            String secretKey = (String) awsEndpointConfig.get(APIConstants.AMZN_SECRET_KEY);
            // Decrypting the key since CTL project goes between environments which have different encryption keys.
            try {
                CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil();
                String decryptedSecret = new String(cryptoUtil.base64DecodeAndDecrypt(secretKey), APIConstants.DigestAuthConstants.CHARSET);
                awsEndpointConfig.put(APIConstants.AMZN_SECRET_KEY, decryptedSecret);
                return awsEndpointConfig;
            } catch (CryptoException | UnsupportedEncodingException e) {
                log.error("Error while decrypting the Amazon key", e);
            }
        }
    }
    return awsEndpointConfig;
}
Also used : CryptoUtil(org.wso2.carbon.core.util.CryptoUtil) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CryptoException(org.wso2.carbon.core.util.CryptoException)

Example 88 with Condition

use of org.wso2.carbon.user.core.model.Condition in project carbon-apimgt by wso2.

the class SearchResultMappingUtil method setPaginationParams.

/**
 * Sets pagination urls for a SearchResultListDTO object given pagination parameters and url parameters.
 *
 * @param resultListDTO a SearchResultListDTO object
 * @param query         search condition
 * @param limit         max number of objects returned
 * @param offset        starting index
 * @param size          max offset
 */
public static void setPaginationParams(SearchResultListDTO resultListDTO, String query, int offset, int limit, int size) {
    // acquiring pagination parameters and setting pagination urls
    Map<String, Integer> paginatedParams = RestApiCommonUtil.getPaginationParams(offset, limit, size);
    String paginatedPrevious = "";
    String paginatedNext = "";
    if (paginatedParams.get(RestApiConstants.PAGINATION_PREVIOUS_OFFSET) != null) {
        paginatedPrevious = RestApiCommonUtil.getAPIPaginatedURL(paginatedParams.get(RestApiConstants.PAGINATION_PREVIOUS_OFFSET), paginatedParams.get(RestApiConstants.PAGINATION_PREVIOUS_LIMIT), query);
    }
    if (paginatedParams.get(RestApiConstants.PAGINATION_NEXT_OFFSET) != null) {
        paginatedNext = RestApiCommonUtil.getAPIPaginatedURL(paginatedParams.get(RestApiConstants.PAGINATION_NEXT_OFFSET), paginatedParams.get(RestApiConstants.PAGINATION_NEXT_LIMIT), query);
    }
    PaginationDTO paginationDTO = new PaginationDTO();
    paginationDTO.setNext(paginatedNext);
    paginationDTO.setPrevious(paginatedPrevious);
    paginationDTO.setOffset(offset);
    paginationDTO.setLimit(limit);
    paginationDTO.setTotal(size);
    resultListDTO.setPagination(paginationDTO);
}
Also used : PaginationDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.PaginationDTO)

Example 89 with Condition

use of org.wso2.carbon.user.core.model.Condition in project carbon-apimgt by wso2.

the class PolicyMappingUtil method mapCondition.

/**
 * Map a org.wso2.carbon.apimgt.throttle.policy.deployer.dto.Condition to a
 * org.wso2.carbon.apimgt.api.model.policy.Condition
 *
 * @param conditionDTO org.wso2.carbon.apimgt.throttle.policy.deployer.dto.Condition
 * @return org.wso2.carbon.apimgt.api.model.policy.Condition object
 */
public static Condition mapCondition(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.Condition conditionDTO) {
    switch(conditionDTO.getConditionType()) {
        case PolicyConstants.IP_RANGE_TYPE:
            IPCondition ipRangeCondition = new IPCondition(PolicyConstants.IP_RANGE_TYPE);
            ipRangeCondition.setInvertCondition(conditionDTO.isInverted());
            ipRangeCondition.setStartingIP(conditionDTO.getName());
            ipRangeCondition.setEndingIP(conditionDTO.getValue());
            return ipRangeCondition;
        case PolicyConstants.IP_SPECIFIC_TYPE:
            IPCondition ipSpecificCondition = new IPCondition(PolicyConstants.IP_SPECIFIC_TYPE);
            ipSpecificCondition.setInvertCondition(conditionDTO.isInverted());
            ipSpecificCondition.setSpecificIP(conditionDTO.getValue());
            return ipSpecificCondition;
        case PolicyConstants.HEADER_TYPE:
            HeaderCondition headerCondition = new HeaderCondition();
            headerCondition.setInvertCondition(conditionDTO.isInverted());
            headerCondition.setHeader(conditionDTO.getName());
            headerCondition.setValue(conditionDTO.getValue());
            return headerCondition;
        case PolicyConstants.JWT_CLAIMS_TYPE:
            JWTClaimsCondition jwtClaimsCondition = new JWTClaimsCondition();
            jwtClaimsCondition.setInvertCondition(conditionDTO.isInverted());
            jwtClaimsCondition.setClaimUrl(conditionDTO.getName());
            jwtClaimsCondition.setAttribute(conditionDTO.getValue());
            return jwtClaimsCondition;
        case PolicyConstants.QUERY_PARAMETER_TYPE:
            QueryParameterCondition queryParameterCondition = new QueryParameterCondition();
            queryParameterCondition.setInvertCondition(conditionDTO.isInverted());
            queryParameterCondition.setParameter(conditionDTO.getName());
            queryParameterCondition.setValue(conditionDTO.getValue());
            return queryParameterCondition;
        default:
            return null;
    }
}
Also used : IPCondition(org.wso2.carbon.apimgt.api.model.policy.IPCondition) JWTClaimsCondition(org.wso2.carbon.apimgt.api.model.policy.JWTClaimsCondition) HeaderCondition(org.wso2.carbon.apimgt.api.model.policy.HeaderCondition) QueryParameterCondition(org.wso2.carbon.apimgt.api.model.policy.QueryParameterCondition)

Example 90 with Condition

use of org.wso2.carbon.user.core.model.Condition in project carbon-apimgt by wso2.

the class PolicyUtil method deployPolicy.

/**
 * Deploy the given throttle policy in the Traffic Manager.
 *
 * @param policy      policy object
 * @param policyEvent policy event object which was triggered
 */
public static void deployPolicy(Policy policy, PolicyEvent policyEvent) {
    EventProcessorService eventProcessorService = ServiceReferenceHolder.getInstance().getEventProcessorService();
    ThrottlePolicyTemplateBuilder policyTemplateBuilder = new ThrottlePolicyTemplateBuilder();
    Map<String, String> policiesToDeploy = new HashMap<>();
    List<String> policiesToUndeploy = new ArrayList<>();
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(APIConstants.SUPER_TENANT_DOMAIN, true);
        String policyFile;
        String policyString;
        if (Policy.PolicyType.SUBSCRIPTION.equals(policy.getType()) && policy instanceof SubscriptionPolicy) {
            // Add Subscription policy
            policyFile = String.join(APIConstants.DELEM_UNDERSCORE, policy.getTenantDomain(), PolicyConstants.POLICY_LEVEL_SUB, policy.getName());
            policyString = policyTemplateBuilder.getThrottlePolicyForSubscriptionLevel((SubscriptionPolicy) policy);
            policiesToDeploy.put(policyFile, policyString);
        } else if (Policy.PolicyType.APPLICATION.equals(policy.getType()) && policy instanceof ApplicationPolicy) {
            // Add Application policy
            policyFile = String.join(APIConstants.DELEM_UNDERSCORE, policy.getTenantDomain(), PolicyConstants.POLICY_LEVEL_APP, policy.getName());
            policyString = policyTemplateBuilder.getThrottlePolicyForAppLevel((ApplicationPolicy) policy);
            policiesToDeploy.put(policyFile, policyString);
        } else if (Policy.PolicyType.API.equals(policy.getType()) && policy instanceof ApiPolicy) {
            // Add API policy
            policiesToDeploy = policyTemplateBuilder.getThrottlePolicyForAPILevel((ApiPolicy) policy);
            String defaultPolicy = policyTemplateBuilder.getThrottlePolicyForAPILevelDefault((ApiPolicy) policy);
            policyFile = String.join(APIConstants.DELEM_UNDERSCORE, policy.getTenantDomain(), PolicyConstants.POLICY_LEVEL_RESOURCE, policy.getName());
            String defaultPolicyName = policyFile + APIConstants.THROTTLE_POLICY_DEFAULT;
            policiesToDeploy.put(defaultPolicyName, defaultPolicy);
            if (policyEvent instanceof APIPolicyEvent) {
                List<Integer> deletedConditionGroupIds = ((APIPolicyEvent) policyEvent).getDeletedConditionGroupIds();
                // Undeploy removed condition groups
                if (deletedConditionGroupIds != null) {
                    for (int conditionGroupId : deletedConditionGroupIds) {
                        policiesToUndeploy.add(policyFile + APIConstants.THROTTLE_POLICY_CONDITION + conditionGroupId);
                    }
                }
            }
        } else if (Policy.PolicyType.GLOBAL.equals(policy.getType()) && policy instanceof GlobalPolicy) {
            // Add Global policy
            GlobalPolicy globalPolicy = (GlobalPolicy) policy;
            policyFile = String.join(APIConstants.DELEM_UNDERSCORE, PolicyConstants.POLICY_LEVEL_GLOBAL, policy.getName());
            policyString = policyTemplateBuilder.getThrottlePolicyForGlobalLevel(globalPolicy);
            policiesToDeploy.put(policyFile, policyString);
        }
        // Undeploy removed policies
        undeployPolicies(policiesToUndeploy);
        for (Map.Entry<String, String> pair : policiesToDeploy.entrySet()) {
            String policyPlanName = pair.getKey();
            String flowString = pair.getValue();
            String executionPlan = null;
            try {
                executionPlan = eventProcessorService.getActiveExecutionPlan(policyPlanName);
            } catch (ExecutionPlanConfigurationException e) {
                // Deploy new policies
                eventProcessorService.deployExecutionPlan(flowString);
            }
            if (executionPlan != null) {
                // Update existing policies
                eventProcessorService.editActiveExecutionPlan(flowString, policyPlanName);
            }
        }
    } catch (APITemplateException e) {
        log.error("Error in creating execution plan", e);
    } catch (ExecutionPlanConfigurationException | ExecutionPlanDependencyValidationException e) {
        log.error("Error in deploying execution plan", e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
Also used : HashMap(java.util.HashMap) GlobalPolicy(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.GlobalPolicy) ArrayList(java.util.ArrayList) ApiPolicy(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.ApiPolicy) ExecutionPlanConfigurationException(org.wso2.carbon.event.processor.core.exception.ExecutionPlanConfigurationException) EventProcessorService(org.wso2.carbon.event.processor.core.EventProcessorService) ExecutionPlanDependencyValidationException(org.wso2.carbon.event.processor.core.exception.ExecutionPlanDependencyValidationException) SubscriptionPolicy(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.SubscriptionPolicy) APIPolicyEvent(org.wso2.carbon.apimgt.impl.notifier.events.APIPolicyEvent) ApplicationPolicy(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.ApplicationPolicy) APITemplateException(org.wso2.carbon.apimgt.impl.template.APITemplateException) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

ArrayList (java.util.ArrayList)43 HashMap (java.util.HashMap)40 Test (org.testng.annotations.Test)34 Test (org.junit.Test)32 PreparedStatement (java.sql.PreparedStatement)29 List (java.util.List)28 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)26 ConditionDto (org.wso2.carbon.apimgt.impl.dto.ConditionDto)26 MessageContext (org.apache.synapse.MessageContext)25 ResultSet (java.sql.ResultSet)24 Map (java.util.Map)24 SQLException (java.sql.SQLException)22 Connection (java.sql.Connection)21 BlockConditions (org.wso2.carbon.apimgt.core.models.BlockConditions)18 ThrottleProperties (org.wso2.carbon.apimgt.impl.dto.ThrottleProperties)18 HeaderCondition (org.wso2.carbon.apimgt.api.model.policy.HeaderCondition)15 JWTClaimsCondition (org.wso2.carbon.apimgt.api.model.policy.JWTClaimsCondition)15 QueryParameterCondition (org.wso2.carbon.apimgt.api.model.policy.QueryParameterCondition)15 SiddhiAppRuntime (org.wso2.siddhi.core.SiddhiAppRuntime)15 SiddhiManager (org.wso2.siddhi.core.SiddhiManager)15