Search in sources :

Example 81 with Group

use of org.wso2.charon.core.objects.Group in project carbon-apimgt by wso2.

the class ThrottleConditionEvaluator method getApplicableConditions.

/**
 * When called, provides a list of Applicable Condition Groups for the current request.
 *
 * @param synapseContext        Message Context of the incoming request.
 * @param authenticationContext AuthenticationContext populated by {@code APIAuthenticationHandler}
 * @param inputConditionGroups  All Condition Groups Attached with the resource/API being invoked.
 * @return List of ConditionGroups applicable for the current request.
 */
public List<ConditionGroupDTO> getApplicableConditions(org.apache.synapse.MessageContext synapseContext, AuthenticationContext authenticationContext, ConditionGroupDTO[] inputConditionGroups) {
    ArrayList<ConditionGroupDTO> matchingConditions = new ArrayList<>(inputConditionGroups.length);
    ConditionGroupDTO defaultGroup = null;
    for (ConditionGroupDTO conditionGroup : inputConditionGroups) {
        if (APIConstants.THROTTLE_POLICY_DEFAULT.equals(conditionGroup.getConditionGroupId())) {
            defaultGroup = conditionGroup;
        } else if (isConditionGroupApplicable(synapseContext, authenticationContext, conditionGroup)) {
            matchingConditions.add(conditionGroup);
        }
    }
    // If no matching ConditionGroups are present, apply the default group.
    if (matchingConditions.isEmpty()) {
        matchingConditions.add(defaultGroup);
    }
    return matchingConditions;
}
Also used : ArrayList(java.util.ArrayList) ConditionGroupDTO(org.wso2.carbon.apimgt.api.dto.ConditionGroupDTO)

Example 82 with Group

use of org.wso2.charon.core.objects.Group in project carbon-apimgt by wso2.

the class SubscriptionValidationDataUtil method fromApiPolicyToApiPolicyListDTO.

public static ApiPolicyListDTO fromApiPolicyToApiPolicyListDTO(List<APIPolicy> model) {
    ApiPolicyListDTO apiPolicyListDTO = new ApiPolicyListDTO();
    if (model != null) {
        for (APIPolicy apiPolicyModel : model) {
            ApiPolicyDTO policyDTO = new ApiPolicyDTO();
            policyDTO.setName(apiPolicyModel.getName());
            policyDTO.setQuotaType(apiPolicyModel.getQuotaType());
            policyDTO.setTenantId(apiPolicyModel.getTenantId());
            policyDTO.setTenantDomain(apiPolicyModel.getTenantDomain());
            policyDTO.setApplicableLevel(apiPolicyModel.getApplicableLevel());
            policyDTO.setDefaultLimit(getThrottleLimitDTO(apiPolicyModel));
            apiPolicyListDTO.getList().add(policyDTO);
            List<APIPolicyConditionGroup> retrievedGroups = apiPolicyModel.getConditionGroups();
            List<ApiPolicyConditionGroupDTO> condGroups = new ArrayList<ApiPolicyConditionGroupDTO>();
            for (APIPolicyConditionGroup retGroup : retrievedGroups) {
                ApiPolicyConditionGroupDTO group = new ApiPolicyConditionGroupDTO();
                group.setConditionGroupId(retGroup.getConditionGroupId());
                group.setQuotaType(retGroup.getQuotaType());
                group.setDefaultLimit(getThrottleLimitDTO(retGroup));
                group.setPolicyId(retGroup.getPolicyId());
                List<org.wso2.carbon.apimgt.internal.service.dto.ConditionDTO> condition = new ArrayList<org.wso2.carbon.apimgt.internal.service.dto.ConditionDTO>();
                List<ConditionDTO> retrievedConditions = retGroup.getConditionDTOS();
                for (ConditionDTO retrievedCondition : retrievedConditions) {
                    org.wso2.carbon.apimgt.internal.service.dto.ConditionDTO conditionDTO = new org.wso2.carbon.apimgt.internal.service.dto.ConditionDTO();
                    conditionDTO.setConditionType(retrievedCondition.getConditionType());
                    conditionDTO.setIsInverted(retrievedCondition.isInverted());
                    conditionDTO.setName(retrievedCondition.getConditionName());
                    conditionDTO.setValue(retrievedCondition.getConditionValue());
                    condition.add(conditionDTO);
                }
                group.setCondition(condition);
                condGroups.add(group);
            }
            policyDTO.setConditionGroups(condGroups);
        }
        apiPolicyListDTO.setCount(model.size());
    } else {
        apiPolicyListDTO.setCount(0);
    }
    return apiPolicyListDTO;
}
Also used : APIPolicyConditionGroup(org.wso2.carbon.apimgt.api.model.subscription.APIPolicyConditionGroup) ArrayList(java.util.ArrayList) ApiPolicyConditionGroupDTO(org.wso2.carbon.apimgt.internal.service.dto.ApiPolicyConditionGroupDTO) ApiPolicyDTO(org.wso2.carbon.apimgt.internal.service.dto.ApiPolicyDTO) ConditionDTO(org.wso2.carbon.apimgt.api.dto.ConditionDTO) APIPolicy(org.wso2.carbon.apimgt.api.model.subscription.APIPolicy) ApiPolicyListDTO(org.wso2.carbon.apimgt.internal.service.dto.ApiPolicyListDTO)

Example 83 with Group

use of org.wso2.charon.core.objects.Group in project carbon-apimgt by wso2.

the class CommonThrottleMappingUtil method fromConditionalGroupDTOToPipeline.

/**
 * Converts a single Conditional Group DTO into a Pipeline object
 *
 * @param dto Conditional Group DTO
 * @return Derived Pipeline object from Conditional Group DTO
 * @throws UnsupportedThrottleLimitTypeException
 * @throws UnsupportedThrottleConditionTypeException
 */
public static Pipeline fromConditionalGroupDTOToPipeline(ConditionalGroupDTO dto) throws UnsupportedThrottleLimitTypeException, UnsupportedThrottleConditionTypeException {
    Pipeline pipeline = new Pipeline();
    pipeline.setDescription(dto.getDescription());
    pipeline.setEnabled(true);
    pipeline.setQuotaPolicy(fromDTOToQuotaPolicy(dto.getLimit()));
    List<Condition> conditions = fromDTOListToConditionList(dto.getConditions());
    pipeline.setConditions(conditions);
    return pipeline;
}
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) Pipeline(org.wso2.carbon.apimgt.api.model.policy.Pipeline)

Example 84 with Group

use of org.wso2.charon.core.objects.Group 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 85 with Group

use of org.wso2.charon.core.objects.Group in project carbon-apimgt by wso2.

the class TestUtil method getPolicyGlobalLevel.

/**
 * Generate a dummy Global Policy object
 *
 * @return an Global Policy
 */
public static GlobalPolicy getPolicyGlobalLevel() {
    GlobalPolicy globalPolicy = new GlobalPolicy();
    globalPolicy.setId(1);
    globalPolicy.setTenantId(-1234);
    globalPolicy.setTenantDomain("carbon.super");
    globalPolicy.setName("policy1");
    globalPolicy.setQuotaType("requestCount");
    QuotaPolicy defaultLimit = new QuotaPolicy();
    defaultLimit.setQuotaType("requestCount");
    RequestCountLimit requestCountLimit = new RequestCountLimit();
    requestCountLimit.setRequestCount(1);
    requestCountLimit.setTimeUnit("min");
    requestCountLimit.setUnitTime(1);
    defaultLimit.setRequestCount(requestCountLimit);
    globalPolicy.setDefaultLimit(defaultLimit);
    globalPolicy.setSiddhiQuery("FROM   RequestStream SELECT   userId,   " + "(userId == 'admin@carbon.super') AS isEligible,   " + "str :concat('admin@carbon.super', '') as throttleKey INSERT INTO   " + "EligibilityStream; FROM   EligibilityStream [isEligible==true] " + "#throttler:timeBatch(1 min) SELECT throttleKey, (count(userId) >= 15) " + "as isThrottled, expiryTimeStamp group by throttleKey INSERT ALL EVENTS " + "into ResultStream;");
    globalPolicy.setKeyTemplate("$userId:$apiContext:$apiVersion");
    return globalPolicy;
}
Also used : RequestCountLimit(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.RequestCountLimit) GlobalPolicy(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.GlobalPolicy) QuotaPolicy(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.QuotaPolicy)

Aggregations

Test (org.testng.annotations.Test)155 SiddhiManager (org.wso2.siddhi.core.SiddhiManager)99 SiddhiAppRuntime (org.wso2.siddhi.core.SiddhiAppRuntime)94 Event (org.wso2.siddhi.core.event.Event)89 InputHandler (org.wso2.siddhi.core.stream.input.InputHandler)80 Group (org.wso2.charon3.core.objects.Group)57 QueryCallback (org.wso2.siddhi.core.query.output.callback.QueryCallback)53 CharonException (org.wso2.charon3.core.exceptions.CharonException)43 HashMap (java.util.HashMap)38 Connection (java.sql.Connection)34 SQLException (java.sql.SQLException)34 ArrayList (java.util.ArrayList)34 IdentitySCIMException (org.wso2.carbon.identity.scim2.common.exceptions.IdentitySCIMException)34 SCIMResourceTypeSchema (org.wso2.charon3.core.schema.SCIMResourceTypeSchema)33 SCIMResponse (org.wso2.charon3.core.protocol.SCIMResponse)32 PreparedStatement (java.sql.PreparedStatement)29 ResultSet (java.sql.ResultSet)29 Operation (io.swagger.v3.oas.annotations.Operation)27 ApiResponses (io.swagger.v3.oas.annotations.responses.ApiResponses)27 Response (javax.ws.rs.core.Response)27