Search in sources :

Example 96 with ApiPolicy

use of org.wso2.carbon.apimgt.keymgt.model.entity.ApiPolicy in project carbon-apimgt by wso2.

the class ApiMgtDAO method getAPIPolicies.

/**
 * Get API level policies. Result only contains basic details of the policy,
 * it doesn't contain pipeline information.
 *
 * @param tenantID policies are selected using tenantID
 * @return APIPolicy ArrayList
 * @throws APIManagementException
 */
public APIPolicy[] getAPIPolicies(int tenantID) throws APIManagementException {
    List<APIPolicy> policies = new ArrayList<APIPolicy>();
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    String sqlQuery = SQLConstants.ThrottleSQLConstants.GET_API_POLICIES;
    if (forceCaseInsensitiveComparisons) {
        sqlQuery = SQLConstants.ThrottleSQLConstants.GET_API_POLICIES;
    }
    try {
        conn = APIMgtDBUtil.getConnection();
        ps = conn.prepareStatement(sqlQuery);
        ps.setInt(1, tenantID);
        rs = ps.executeQuery();
        while (rs.next()) {
            APIPolicy apiPolicy = new APIPolicy(rs.getString(ThrottlePolicyConstants.COLUMN_NAME));
            setCommonPolicyDetails(apiPolicy, rs);
            apiPolicy.setUserLevel(rs.getString(ThrottlePolicyConstants.COLUMN_APPLICABLE_LEVEL));
            policies.add(apiPolicy);
        }
    } catch (SQLException e) {
        handleException("Error while executing SQL", e);
    } finally {
        APIMgtDBUtil.closeAllConnections(ps, conn, rs);
    }
    return policies.toArray(new APIPolicy[policies.size()]);
}
Also used : SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy)

Example 97 with ApiPolicy

use of org.wso2.carbon.apimgt.keymgt.model.entity.ApiPolicy in project carbon-apimgt by wso2.

the class ApiMgtDAO method isAnyPolicyContentAware.

private boolean isAnyPolicyContentAware(Connection conn, String apiPolicy, String appPolicy, String subPolicy, int subscriptionTenantId, int appTenantId, int apiId) throws APIManagementException {
    boolean isAnyContentAware = false;
    // only check if using CEP based throttling.
    ResultSet resultSet = null;
    PreparedStatement ps = null;
    String sqlQuery = SQLConstants.ThrottleSQLConstants.IS_ANY_POLICY_CONTENT_AWARE_SQL;
    try {
        String dbProdName = conn.getMetaData().getDatabaseProductName();
        ps = conn.prepareStatement(sqlQuery);
        ps.setString(1, apiPolicy);
        ps.setInt(2, subscriptionTenantId);
        ps.setString(3, apiPolicy);
        ps.setInt(4, subscriptionTenantId);
        ps.setInt(5, apiId);
        ps.setInt(6, subscriptionTenantId);
        ps.setInt(7, apiId);
        ps.setInt(8, subscriptionTenantId);
        ps.setString(9, subPolicy);
        ps.setInt(10, subscriptionTenantId);
        ps.setString(11, appPolicy);
        ps.setInt(12, appTenantId);
        resultSet = ps.executeQuery();
        // We only expect one result if all are not content aware.
        if (resultSet == null) {
            throw new APIManagementException(" Result set Null");
        }
        int count = 0;
        if (resultSet.next()) {
            count = resultSet.getInt(1);
            if (count > 0) {
                isAnyContentAware = true;
            }
        }
    } catch (SQLException e) {
        handleException("Failed to get content awareness of the policies ", e);
    } finally {
        APIMgtDBUtil.closeAllConnections(ps, null, resultSet);
    }
    return isAnyContentAware;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 98 with ApiPolicy

use of org.wso2.carbon.apimgt.keymgt.model.entity.ApiPolicy in project carbon-apimgt by wso2.

the class ApiMgtDAO method getAPIPolicy.

/**
 * Retrieves {@link APIPolicy} with name <code>policyName</code> and tenant Id <code>tenantNId</code>
 * <p>This will retrieve complete details about the APIPolicy with all pipelins and conditions.</p>
 *
 * @param policyName name of the policy to retrieve from the database
 * @param tenantId   tenantId of the policy
 * @return {@link APIPolicy}
 * @throws APIManagementException
 */
public APIPolicy getAPIPolicy(String policyName, int tenantId) throws APIManagementException {
    APIPolicy policy = null;
    Connection connection = null;
    PreparedStatement selectStatement = null;
    ResultSet resultSet = null;
    String sqlQuery = SQLConstants.ThrottleSQLConstants.GET_API_POLICY_SQL;
    if (forceCaseInsensitiveComparisons) {
        sqlQuery = SQLConstants.ThrottleSQLConstants.GET_API_POLICY_SQL;
    }
    try {
        connection = APIMgtDBUtil.getConnection();
        selectStatement = connection.prepareStatement(sqlQuery);
        selectStatement.setString(1, policyName);
        selectStatement.setInt(2, tenantId);
        // Should return only single result
        resultSet = selectStatement.executeQuery();
        if (resultSet.next()) {
            policy = new APIPolicy(resultSet.getString(ThrottlePolicyConstants.COLUMN_NAME));
            setCommonPolicyDetails(policy, resultSet);
            policy.setUserLevel(resultSet.getString(ThrottlePolicyConstants.COLUMN_APPLICABLE_LEVEL));
            policy.setPipelines(getPipelines(policy.getPolicyId()));
        }
    } catch (SQLException e) {
        handleException("Failed to get api policy: " + policyName + '-' + tenantId, e);
    } finally {
        APIMgtDBUtil.closeAllConnections(selectStatement, connection, resultSet);
    }
    return policy;
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy)

Example 99 with ApiPolicy

use of org.wso2.carbon.apimgt.keymgt.model.entity.ApiPolicy in project carbon-apimgt by wso2.

the class AbstractKeyValidationHandler method validate.

private APIKeyValidationInfoDTO validate(APIKeyValidationInfoDTO infoDTO, String apiTenantDomain, int tenantId, SubscriptionDataStore datastore, API api, Application app, Subscription sub) {
    String subscriptionStatus = sub.getSubscriptionState();
    String type = app.getTokenType();
    if (APIConstants.SubscriptionStatus.BLOCKED.equals(subscriptionStatus)) {
        infoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_BLOCKED);
        infoDTO.setAuthorized(false);
        return infoDTO;
    } else if (APIConstants.SubscriptionStatus.ON_HOLD.equals(subscriptionStatus) || APIConstants.SubscriptionStatus.REJECTED.equals(subscriptionStatus)) {
        infoDTO.setValidationStatus(APIConstants.KeyValidationStatus.SUBSCRIPTION_INACTIVE);
        infoDTO.setAuthorized(false);
        return infoDTO;
    } else if (APIConstants.SubscriptionStatus.PROD_ONLY_BLOCKED.equals(subscriptionStatus) && !APIConstants.API_KEY_TYPE_SANDBOX.equals(type)) {
        infoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_BLOCKED);
        infoDTO.setType(type);
        infoDTO.setAuthorized(false);
        return infoDTO;
    }
    infoDTO.setTier(sub.getPolicyId());
    infoDTO.setSubscriber(app.getSubName());
    infoDTO.setApplicationId(app.getId().toString());
    infoDTO.setApiName(api.getApiName());
    infoDTO.setApiVersion(api.getApiVersion());
    infoDTO.setApiPublisher(api.getApiProvider());
    infoDTO.setApplicationName(app.getName());
    infoDTO.setApplicationTier(app.getPolicy());
    infoDTO.setApplicationUUID(app.getUUID());
    infoDTO.setAppAttributes(app.getAttributes());
    infoDTO.setType(type);
    // Advanced Level Throttling Related Properties
    String apiTier = api.getApiTier();
    String subscriberUserId = sub.getSubscriptionId();
    String subscriberTenant = MultitenantUtils.getTenantDomain(app.getSubName());
    ApplicationPolicy appPolicy = datastore.getApplicationPolicyByName(app.getPolicy(), tenantId);
    if (appPolicy == null) {
        try {
            appPolicy = new SubscriptionDataLoaderImpl().getApplicationPolicy(app.getPolicy(), apiTenantDomain);
            datastore.addOrUpdateApplicationPolicy(appPolicy);
        } catch (DataLoadingException e) {
            log.error("Error while loading ApplicationPolicy");
        }
    }
    SubscriptionPolicy subPolicy = datastore.getSubscriptionPolicyByName(sub.getPolicyId(), tenantId);
    if (subPolicy == null) {
        try {
            subPolicy = new SubscriptionDataLoaderImpl().getSubscriptionPolicy(sub.getPolicyId(), apiTenantDomain);
            datastore.addOrUpdateSubscriptionPolicy(subPolicy);
        } catch (DataLoadingException e) {
            log.error("Error while loading SubscriptionPolicy");
        }
    }
    ApiPolicy apiPolicy = datastore.getApiPolicyByName(api.getApiTier(), tenantId);
    boolean isContentAware = false;
    if (appPolicy.isContentAware() || subPolicy.isContentAware() || (apiPolicy != null && apiPolicy.isContentAware())) {
        isContentAware = true;
    }
    infoDTO.setContentAware(isContentAware);
    // TODO this must implement as a part of throttling implementation.
    int spikeArrest = 0;
    String apiLevelThrottlingKey = "api_level_throttling_key";
    if (subPolicy.getRateLimitCount() > 0) {
        spikeArrest = subPolicy.getRateLimitCount();
    }
    String spikeArrestUnit = null;
    if (subPolicy.getRateLimitTimeUnit() != null) {
        spikeArrestUnit = subPolicy.getRateLimitTimeUnit();
    }
    boolean stopOnQuotaReach = subPolicy.isStopOnQuotaReach();
    int graphQLMaxDepth = 0;
    if (subPolicy.getGraphQLMaxDepth() > 0) {
        graphQLMaxDepth = subPolicy.getGraphQLMaxDepth();
    }
    int graphQLMaxComplexity = 0;
    if (subPolicy.getGraphQLMaxComplexity() > 0) {
        graphQLMaxComplexity = subPolicy.getGraphQLMaxComplexity();
    }
    List<String> list = new ArrayList<String>();
    list.add(apiLevelThrottlingKey);
    infoDTO.setSpikeArrestLimit(spikeArrest);
    infoDTO.setSpikeArrestUnit(spikeArrestUnit);
    infoDTO.setStopOnQuotaReach(stopOnQuotaReach);
    infoDTO.setSubscriberTenantDomain(subscriberTenant);
    infoDTO.setGraphQLMaxDepth(graphQLMaxDepth);
    infoDTO.setGraphQLMaxComplexity(graphQLMaxComplexity);
    if (apiTier != null && apiTier.trim().length() > 0) {
        infoDTO.setApiTier(apiTier);
    }
    // We also need to set throttling data list associated with given API. This need to have
    // policy id and
    // condition id list for all throttling tiers associated with this API.
    infoDTO.setThrottlingDataList(list);
    infoDTO.setAuthorized(true);
    return infoDTO;
}
Also used : SubscriptionDataLoaderImpl(org.wso2.carbon.apimgt.keymgt.model.impl.SubscriptionDataLoaderImpl) DataLoadingException(org.wso2.carbon.apimgt.keymgt.model.exception.DataLoadingException) SubscriptionPolicy(org.wso2.carbon.apimgt.keymgt.model.entity.SubscriptionPolicy) ApplicationPolicy(org.wso2.carbon.apimgt.keymgt.model.entity.ApplicationPolicy) ApiPolicy(org.wso2.carbon.apimgt.keymgt.model.entity.ApiPolicy) ArrayList(java.util.ArrayList)

Example 100 with ApiPolicy

use of org.wso2.carbon.apimgt.keymgt.model.entity.ApiPolicy in project carbon-apimgt by wso2.

the class TestUtil method getPolicyAPILevel.

/**
 * Generate a dummy API Policy object
 *
 * @return an API Policy
 */
public static ApiPolicy getPolicyAPILevel() {
    ApiPolicy apiPolicy = new ApiPolicy();
    apiPolicy.setId(1);
    apiPolicy.setTenantId(-1234);
    apiPolicy.setTenantDomain("carbon.super");
    apiPolicy.setName("policy1");
    apiPolicy.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);
    apiPolicy.setDefaultLimit(defaultLimit);
    apiPolicy.setApplicableLevel("apiLevel");
    List<APIPolicyConditionGroup> conditionGroups = new ArrayList<>();
    APIPolicyConditionGroup conditionGroup1 = new APIPolicyConditionGroup();
    conditionGroup1.setPolicyId(1);
    conditionGroup1.setQuotaType("requestCount");
    conditionGroup1.setConditionGroupId(1);
    Set<Condition> conditions = new HashSet<>();
    Condition condition1 = new Condition();
    condition1.setConditionType("IPSpecific");
    condition1.setName("IPSpecific");
    condition1.setValue("127.0.0.1");
    condition1.setInverted(false);
    conditions.add(condition1);
    conditionGroup1.setCondition(conditions);
    QuotaPolicy defaultLimitCondGroup1 = new QuotaPolicy();
    defaultLimitCondGroup1.setQuotaType("requestCount");
    RequestCountLimit requestCountLimitCondGroup1 = new RequestCountLimit();
    requestCountLimitCondGroup1.setRequestCount(1);
    requestCountLimitCondGroup1.setTimeUnit("min");
    requestCountLimitCondGroup1.setUnitTime(1);
    defaultLimitCondGroup1.setRequestCount(requestCountLimitCondGroup1);
    conditionGroup1.setDefaultLimit(defaultLimitCondGroup1);
    conditionGroups.add(conditionGroup1);
    apiPolicy.setConditionGroups(conditionGroups);
    return apiPolicy;
}
Also used : Condition(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.Condition) RequestCountLimit(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.RequestCountLimit) APIPolicyConditionGroup(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.APIPolicyConditionGroup) ApiPolicy(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.ApiPolicy) ArrayList(java.util.ArrayList) QuotaPolicy(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.QuotaPolicy) HashSet(java.util.HashSet)

Aggregations

APIPolicy (org.wso2.carbon.apimgt.core.models.policy.APIPolicy)87 Test (org.testng.annotations.Test)44 SubscriptionPolicy (org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy)40 PolicyDAO (org.wso2.carbon.apimgt.core.dao.PolicyDAO)39 ArrayList (java.util.ArrayList)38 API (org.wso2.carbon.apimgt.core.models.API)33 APIPolicy (org.wso2.carbon.apimgt.api.model.policy.APIPolicy)30 APIGateway (org.wso2.carbon.apimgt.core.api.APIGateway)27 HashMap (java.util.HashMap)25 APILifecycleManager (org.wso2.carbon.apimgt.core.api.APILifecycleManager)22 GatewaySourceGenerator (org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator)22 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)22 APIBuilder (org.wso2.carbon.apimgt.core.models.API.APIBuilder)21 Policy (org.wso2.carbon.apimgt.core.models.policy.Policy)20 HashSet (java.util.HashSet)19 Test (org.junit.Test)19 QuotaPolicy (org.wso2.carbon.apimgt.core.models.policy.QuotaPolicy)19 ApplicationPolicy (org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy)18 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)17 PreparedStatement (java.sql.PreparedStatement)15