Search in sources :

Example 36 with ConditionGroupDTO

use of org.wso2.carbon.apimgt.api.dto.ConditionGroupDTO in project carbon-apimgt by wso2.

the class ApiMgtDAO method extractURITemplates.

private ArrayList<URITemplate> extractURITemplates(ResultSet rs) throws SQLException, APIManagementException {
    Map<String, Set<ConditionGroupDTO>> mapByHttpVerbURLPatternToId = new HashMap<String, Set<ConditionGroupDTO>>();
    ArrayList<URITemplate> uriTemplates = new ArrayList<URITemplate>();
    while (rs != null && rs.next()) {
        int uriTemplateId = rs.getInt("URL_MAPPING_ID");
        String httpVerb = rs.getString("HTTP_METHOD");
        String authType = rs.getString("AUTH_SCHEME");
        String urlPattern = rs.getString("URL_PATTERN");
        String policyName = rs.getString("THROTTLING_TIER");
        String conditionGroupId = rs.getString("CONDITION_GROUP_ID");
        String applicableLevel = rs.getString("APPLICABLE_LEVEL");
        String policyConditionGroupId = "_condition_" + conditionGroupId;
        boolean isContentAware = PolicyConstants.BANDWIDTH_TYPE.equals(rs.getString(ThrottlePolicyConstants.COLUMN_DEFAULT_QUOTA_POLICY_TYPE));
        String key = httpVerb + ":" + urlPattern;
        if (mapByHttpVerbURLPatternToId.containsKey(key)) {
            if (StringUtils.isEmpty(conditionGroupId)) {
                continue;
            }
            // Converting ConditionGroup to a lightweight ConditionGroupDTO.
            ConditionGroupDTO groupDTO = createConditionGroupDTO(Integer.parseInt(conditionGroupId));
            groupDTO.setConditionGroupId(policyConditionGroupId);
            mapByHttpVerbURLPatternToId.get(key).add(groupDTO);
        } else {
            String script = null;
            URITemplate uriTemplate = new URITemplate();
            uriTemplate.setId(uriTemplateId);
            uriTemplate.setThrottlingTier(policyName);
            uriTemplate.setThrottlingTiers(policyName + PolicyConstants.THROTTLING_TIER_CONTENT_AWARE_SEPERATOR + isContentAware);
            uriTemplate.setAuthType(authType);
            uriTemplate.setHTTPVerb(httpVerb);
            uriTemplate.setUriTemplate(urlPattern);
            uriTemplate.setApplicableLevel(applicableLevel);
            InputStream mediationScriptBlob = rs.getBinaryStream("MEDIATION_SCRIPT");
            if (mediationScriptBlob != null) {
                script = APIMgtDBUtil.getStringFromInputStream(mediationScriptBlob);
            }
            uriTemplate.setMediationScript(script);
            Set<ConditionGroupDTO> conditionGroupIdSet = new HashSet<ConditionGroupDTO>();
            mapByHttpVerbURLPatternToId.put(key, conditionGroupIdSet);
            uriTemplates.add(uriTemplate);
            if (StringUtils.isEmpty(conditionGroupId)) {
                continue;
            }
            ConditionGroupDTO groupDTO = createConditionGroupDTO(Integer.parseInt(conditionGroupId));
            groupDTO.setConditionGroupId(policyConditionGroupId);
            conditionGroupIdSet.add(groupDTO);
        }
    }
    for (URITemplate uriTemplate : uriTemplates) {
        String key = uriTemplate.getHTTPVerb() + ":" + uriTemplate.getUriTemplate();
        if (mapByHttpVerbURLPatternToId.containsKey(key)) {
            if (!mapByHttpVerbURLPatternToId.get(key).isEmpty()) {
                Set<ConditionGroupDTO> conditionGroupDTOs = mapByHttpVerbURLPatternToId.get(key);
                ConditionGroupDTO defaultGroup = new ConditionGroupDTO();
                defaultGroup.setConditionGroupId(APIConstants.THROTTLE_POLICY_DEFAULT);
                conditionGroupDTOs.add(defaultGroup);
                uriTemplate.getThrottlingConditions().add(APIConstants.THROTTLE_POLICY_DEFAULT);
                uriTemplate.setConditionGroups(conditionGroupDTOs.toArray(new ConditionGroupDTO[] {}));
            }
        }
        if (uriTemplate.getThrottlingConditions().isEmpty()) {
            uriTemplate.getThrottlingConditions().add(APIConstants.THROTTLE_POLICY_DEFAULT);
            ConditionGroupDTO defaultGroup = new ConditionGroupDTO();
            defaultGroup.setConditionGroupId(APIConstants.THROTTLE_POLICY_DEFAULT);
            uriTemplate.setConditionGroups(new ConditionGroupDTO[] { defaultGroup });
        }
    }
    return uriTemplates;
}
Also used : ResultSet(java.sql.ResultSet) Set(java.util.Set) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) ArrayList(java.util.ArrayList) ConditionGroupDTO(org.wso2.carbon.apimgt.api.dto.ConditionGroupDTO) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 37 with ConditionGroupDTO

use of org.wso2.carbon.apimgt.api.dto.ConditionGroupDTO in project carbon-apimgt by wso2.

the class ApiMgtDAO method createConditionGroupDTO.

/**
 * Converts an {@code Pipeline} object into a {@code ConditionGroupDTO}.{@code ConditionGroupDTO} class tries to
 * contain the same information held by  {@code Pipeline}, but in a much lightweight fashion.
 *
 * @param conditionGroup Id of the condition group ({@code Pipeline}) to be converted
 * @return An object of {@code ConditionGroupDTO} type.
 * @throws APIManagementException
 */
public ConditionGroupDTO createConditionGroupDTO(int conditionGroup) throws APIManagementException {
    List<Condition> conditions = getConditions(conditionGroup);
    ArrayList<ConditionDTO> conditionDTOs = new ArrayList<ConditionDTO>(conditions.size());
    for (Condition condition : conditions) {
        ConditionDTO conditionDTO = new ConditionDTO();
        conditionDTO.setConditionType(condition.getType());
        conditionDTO.isInverted(condition.isInvertCondition());
        if (PolicyConstants.IP_RANGE_TYPE.equals(condition.getType())) {
            IPCondition ipRangeCondition = (IPCondition) condition;
            conditionDTO.setConditionName(ipRangeCondition.getStartingIP());
            conditionDTO.setConditionValue(ipRangeCondition.getEndingIP());
        } else if (PolicyConstants.IP_SPECIFIC_TYPE.equals(condition.getType())) {
            IPCondition ipCondition = (IPCondition) condition;
            conditionDTO.setConditionName(PolicyConstants.IP_SPECIFIC_TYPE);
            conditionDTO.setConditionValue(ipCondition.getSpecificIP());
        } else if (PolicyConstants.HEADER_TYPE.equals(condition.getType())) {
            HeaderCondition headerCondition = (HeaderCondition) condition;
            conditionDTO.setConditionName(headerCondition.getHeaderName());
            conditionDTO.setConditionValue(headerCondition.getValue());
        } else if (PolicyConstants.JWT_CLAIMS_TYPE.equals(condition.getType())) {
            JWTClaimsCondition jwtClaimsCondition = (JWTClaimsCondition) condition;
            conditionDTO.setConditionName(jwtClaimsCondition.getClaimUrl());
            conditionDTO.setConditionValue(jwtClaimsCondition.getAttribute());
        } else if (PolicyConstants.QUERY_PARAMETER_TYPE.equals(condition.getType())) {
            QueryParameterCondition parameterCondition = (QueryParameterCondition) condition;
            conditionDTO.setConditionName(parameterCondition.getParameter());
            conditionDTO.setConditionValue(parameterCondition.getValue());
        }
        conditionDTOs.add(conditionDTO);
    }
    ConditionGroupDTO conditionGroupDTO = new ConditionGroupDTO();
    conditionGroupDTO.setConditions(conditionDTOs.toArray(new ConditionDTO[] {}));
    return conditionGroupDTO;
}
Also used : QueryParameterCondition(org.wso2.carbon.apimgt.api.model.policy.QueryParameterCondition) Condition(org.wso2.carbon.apimgt.api.model.policy.Condition) IPCondition(org.wso2.carbon.apimgt.api.model.policy.IPCondition) HeaderCondition(org.wso2.carbon.apimgt.api.model.policy.HeaderCondition) JWTClaimsCondition(org.wso2.carbon.apimgt.api.model.policy.JWTClaimsCondition) 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) ConditionDTO(org.wso2.carbon.apimgt.api.dto.ConditionDTO) ArrayList(java.util.ArrayList) ConditionGroupDTO(org.wso2.carbon.apimgt.api.dto.ConditionGroupDTO) QueryParameterCondition(org.wso2.carbon.apimgt.api.model.policy.QueryParameterCondition)

Example 38 with ConditionGroupDTO

use of org.wso2.carbon.apimgt.api.dto.ConditionGroupDTO in project carbon-apimgt by wso2.

the class APIKeyValidationService method getTemplates.

private ArrayList<URITemplate> getTemplates(String context, String version) throws APIManagementException {
    String tenantDomain = MultitenantUtils.getTenantDomainFromRequestURL(context);
    if (tenantDomain == null) {
        tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    }
    ArrayList<URITemplate> templates = new ArrayList<URITemplate>();
    SubscriptionDataStore store = SubscriptionDataHolder.getInstance().getTenantSubscriptionStore(tenantDomain);
    if (store == null) {
        return templates;
    }
    API api = store.getApiByContextAndVersion(context, version);
    if (api == null) {
        log.debug("SubscriptionDataStore didn't contains API metadata reading from rest api context: " + context + " And version " + version);
        api = new SubscriptionDataLoaderImpl().getApi(context, version);
        if (api != null) {
            store.addOrUpdateAPI(api);
            if (log.isDebugEnabled()) {
                log.debug("Update SubscriptionDataStore api for " + api.getCacheKey());
            }
        }
    }
    if (api == null || api.getApiId() == 0) {
        return templates;
    }
    List<URLMapping> mapping = api.getResources();
    if (mapping == null || mapping.isEmpty()) {
        return templates;
    }
    int apiTenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(api.getApiProvider()));
    if (log.isDebugEnabled()) {
        log.debug("Tenant domain: " + tenantDomain + " tenantId: " + apiTenantId);
    }
    ApiPolicy apiPolicy;
    URITemplate template;
    for (URLMapping urlMapping : mapping) {
        template = new URITemplate();
        template.setHTTPVerb(urlMapping.getHttpMethod());
        template.setAuthType(urlMapping.getAuthScheme());
        template.setUriTemplate(urlMapping.getUrlPattern());
        template.setThrottlingTier(urlMapping.getThrottlingPolicy());
        if (store.isApiPoliciesInitialized()) {
            log.debug("SubscriptionDataStore Initialized. Reading API Policies from SubscriptionDataStore");
            apiPolicy = store.getApiPolicyByName(urlMapping.getThrottlingPolicy(), apiTenantId);
            if (apiPolicy == null) {
                // could be null for situations where invoke before map is updated
                log.debug("API Policies not found in the SubscriptionDataStore. Retrieving from the Rest API");
                apiPolicy = new SubscriptionDataLoaderImpl().getAPIPolicy(urlMapping.getThrottlingPolicy(), tenantDomain);
                if (apiPolicy != null) {
                    if (apiPolicy.getName() != null) {
                        store.addOrUpdateApiPolicy(apiPolicy);
                        if (log.isDebugEnabled()) {
                            log.debug("Update SubscriptionDataStore API Policy for " + apiPolicy.getCacheKey());
                        }
                    } else {
                        throw new APIManagementException("Exception while loading api policy for " + urlMapping.getThrottlingPolicy() + " for domain " + tenantDomain);
                    }
                }
            }
        } else {
            log.debug("SubscriptionDataStore not Initialized. Reading API Policies from Rest API");
            apiPolicy = new SubscriptionDataLoaderImpl().getAPIPolicy(urlMapping.getThrottlingPolicy(), tenantDomain);
            if (apiPolicy != null) {
                if (apiPolicy.getName() != null) {
                    store.addOrUpdateApiPolicy(apiPolicy);
                    if (log.isDebugEnabled()) {
                        log.debug("Update SubscriptionDataStore API Policy for " + apiPolicy.getCacheKey());
                    }
                } else {
                    throw new APIManagementException("Exception while loading api policy for " + urlMapping.getThrottlingPolicy() + " for domain " + tenantDomain);
                }
            }
        }
        List<String> tiers = new ArrayList<String>();
        tiers.add(urlMapping.getThrottlingPolicy() + ">" + apiPolicy.isContentAware());
        template.setThrottlingTiers(tiers);
        template.setApplicableLevel(apiPolicy.getApplicableLevel());
        List<APIPolicyConditionGroup> conditions = apiPolicy.getConditionGroups();
        List<ConditionGroupDTO> conditionGroupsList = new ArrayList<ConditionGroupDTO>();
        for (APIPolicyConditionGroup cond : conditions) {
            Set<Condition> condSet = cond.getCondition();
            if (condSet.isEmpty()) {
                continue;
            }
            List<ConditionDTO> conditionDtoList = new ArrayList<ConditionDTO>();
            for (Condition condition : condSet) {
                ConditionDTO item = new ConditionDTO();
                item.setConditionName(condition.getName());
                item.setConditionType(condition.getConditionType());
                item.setConditionValue(condition.getValue());
                item.isInverted(condition.isInverted());
                conditionDtoList.add(item);
            }
            ConditionGroupDTO group = new ConditionGroupDTO();
            group.setConditionGroupId("_condition_" + cond.getConditionGroupId());
            group.setConditions(conditionDtoList.toArray(new ConditionDTO[] {}));
            conditionGroupsList.add(group);
        }
        ConditionGroupDTO defaultGroup = new ConditionGroupDTO();
        defaultGroup.setConditionGroupId(APIConstants.THROTTLE_POLICY_DEFAULT);
        conditionGroupsList.add(defaultGroup);
        template.getThrottlingConditions().add(APIConstants.THROTTLE_POLICY_DEFAULT);
        template.setConditionGroups(conditionGroupsList.toArray(new ConditionGroupDTO[] {}));
        templates.add(template);
    }
    return templates;
}
Also used : Condition(org.wso2.carbon.apimgt.keymgt.model.entity.Condition) APIPolicyConditionGroup(org.wso2.carbon.apimgt.keymgt.model.entity.APIPolicyConditionGroup) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) ArrayList(java.util.ArrayList) ApiPolicy(org.wso2.carbon.apimgt.keymgt.model.entity.ApiPolicy) SubscriptionDataStore(org.wso2.carbon.apimgt.keymgt.model.SubscriptionDataStore) ConditionGroupDTO(org.wso2.carbon.apimgt.api.dto.ConditionGroupDTO) SubscriptionDataLoaderImpl(org.wso2.carbon.apimgt.keymgt.model.impl.SubscriptionDataLoaderImpl) URLMapping(org.wso2.carbon.apimgt.api.model.subscription.URLMapping) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ConditionDTO(org.wso2.carbon.apimgt.api.dto.ConditionDTO) API(org.wso2.carbon.apimgt.keymgt.model.entity.API)

Aggregations

ConditionGroupDTO (org.wso2.carbon.apimgt.api.dto.ConditionGroupDTO)37 AuthenticationContext (org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext)31 Test (org.junit.Test)29 MessageContext (org.apache.synapse.MessageContext)21 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)21 ConditionDTO (org.wso2.carbon.apimgt.api.dto.ConditionDTO)19 ArrayList (java.util.ArrayList)18 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)12 ThrottleDataHolder (org.wso2.carbon.apimgt.gateway.throttling.ThrottleDataHolder)12 SynapseEnvironment (org.apache.synapse.core.SynapseEnvironment)6 HashMap (java.util.HashMap)3 Map (java.util.Map)2 TreeMap (java.util.TreeMap)2 Before (org.junit.Before)2 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)2 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)2 VerbInfoDTO (org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO)2 Timer (org.wso2.carbon.metrics.manager.Timer)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 InputStream (java.io.InputStream)1