Search in sources :

Example 86 with Condition

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

the class AbstractKeyValidationHandler method validate.

private APIKeyValidationInfoDTO validate(APIKeyValidationInfoDTO infoDTO, String apiTenantDomain, int tenantId, SubscriptionDataStore datastore, API api, ApplicationKeyMapping key, Application app, Subscription sub, String keyManager) {
    String subscriptionStatus = sub.getSubscriptionState();
    String type = key.getKeyType();
    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 subscriberTenant = MultitenantUtils.getTenantDomain(app.getSubName());
    ApplicationPolicy appPolicy = datastore.getApplicationPolicyByName(app.getPolicy(), APIUtil.getTenantIdFromTenantDomain(app.getOrganization()));
    if (appPolicy == null) {
        try {
            appPolicy = new SubscriptionDataLoaderImpl().getApplicationPolicy(app.getPolicy(), app.getOrganization());
            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 87 with Condition

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

the class ApiMgtDAO method getBlockCondition.

/**
 * Get details of a block condition by Id
 *
 * @param conditionId id of the condition
 * @return Block conditoin represented by the UUID
 * @throws APIManagementException
 */
public BlockConditionsDTO getBlockCondition(int conditionId) throws APIManagementException {
    Connection connection = null;
    PreparedStatement selectPreparedStatement = null;
    ResultSet resultSet = null;
    BlockConditionsDTO blockCondition = null;
    try {
        String query = SQLConstants.ThrottleSQLConstants.GET_BLOCK_CONDITION_SQL;
        connection = APIMgtDBUtil.getConnection();
        connection.setAutoCommit(true);
        selectPreparedStatement = connection.prepareStatement(query);
        selectPreparedStatement.setInt(1, conditionId);
        resultSet = selectPreparedStatement.executeQuery();
        if (resultSet.next()) {
            blockCondition = new BlockConditionsDTO();
            blockCondition.setEnabled(resultSet.getBoolean("ENABLED"));
            blockCondition.setConditionType(resultSet.getString("TYPE"));
            blockCondition.setConditionValue(resultSet.getString("BLOCK_CONDITION"));
            blockCondition.setConditionId(conditionId);
            blockCondition.setTenantDomain(resultSet.getString("DOMAIN"));
            blockCondition.setUUID(resultSet.getString("UUID"));
        }
    } catch (SQLException e) {
        if (connection != null) {
            try {
                connection.rollback();
            } catch (SQLException ex) {
                handleException("Failed to rollback getting Block condition with id " + conditionId, ex);
            }
        }
        handleException("Failed to get Block condition with id " + conditionId, e);
    } finally {
        APIMgtDBUtil.closeAllConnections(selectPreparedStatement, connection, resultSet);
    }
    return blockCondition;
}
Also used : BlockConditionsDTO(org.wso2.carbon.apimgt.api.model.BlockConditionsDTO) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 88 with Condition

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

the class ApiMgtDAO method setHeaderConditions.

/**
 * Add Header conditions of pipeline with pipeline Id: <code>pipelineId</code> to a
 * provided {@link Condition} array
 *
 * @param pipelineId Id of the pipeline
 * @param conditions condition array to populate
 * @throws APIManagementException
 */
private void setHeaderConditions(int pipelineId, ArrayList<Condition> conditions) throws APIManagementException {
    Connection connection = null;
    PreparedStatement conditionsStatement = null;
    ResultSet resultSet = null;
    try {
        connection = APIMgtDBUtil.getConnection();
        conditionsStatement = connection.prepareStatement(SQLConstants.ThrottleSQLConstants.GET_HEADER_CONDITIONS_SQL);
        conditionsStatement.setInt(1, pipelineId);
        resultSet = conditionsStatement.executeQuery();
        while (resultSet.next()) {
            HeaderCondition headerCondition = new HeaderCondition();
            headerCondition.setHeader(resultSet.getString(ThrottlePolicyConstants.COLUMN_HEADER_FIELD_NAME));
            headerCondition.setValue(resultSet.getString(ThrottlePolicyConstants.COLUMN_HEADER_FIELD_VALUE));
            headerCondition.setInvertCondition(resultSet.getBoolean(ThrottlePolicyConstants.COLUMN_IS_HEADER_FIELD_MAPPING));
            conditions.add(headerCondition);
        }
    } catch (SQLException e) {
        handleException("Failed to get header conditions for pipelineId: " + pipelineId, e);
    } finally {
        APIMgtDBUtil.closeAllConnections(conditionsStatement, connection, resultSet);
    }
}
Also used : HeaderCondition(org.wso2.carbon.apimgt.api.model.policy.HeaderCondition) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 89 with Condition

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

the class AbstractAPIManagerTestCase method testGetTiersForTenant.

@Test
public void testGetTiersForTenant() throws APIManagementException {
    Mockito.when(privilegedCarbonContext.getTenantId()).thenReturn(-1234, -1, 1);
    Map<String, Tier> tierMap1 = new HashMap<String, Tier>();
    Map<String, Tier> tierMap2 = new HashMap<String, Tier>();
    Map<String, Tier> tierMap3 = new HashMap<String, Tier>();
    Tier tier1 = new Tier("tier1");
    Tier tier2 = new Tier("tier2");
    Tier tier3 = new Tier("tier3");
    tierMap1.put("Gold", tier1);
    tierMap2.put("Gold", tier1);
    tierMap2.put("Silver", tier2);
    tierMap3.put("Gold", tier1);
    tierMap3.put("Silver", tier2);
    tierMap3.put("Platinum", tier3);
    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.when(APIUtil.getTiers()).thenReturn(tierMap1);
    PowerMockito.when(APIUtil.getTiers(Mockito.anyInt())).thenReturn(tierMap2);
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(null, null, null, null);
    PowerMockito.when(APIUtil.getTiersFromPolicies(Mockito.anyString(), Mockito.anyInt())).thenReturn(tierMap1);
    Assert.assertEquals(abstractAPIManager.getTiers(SAMPLE_TENANT_DOMAIN_1).size(), 1);
    // verify next branch of if
    Assert.assertEquals(abstractAPIManager.getTiers(SAMPLE_TENANT_DOMAIN_1).size(), 1);
    // condition
    PowerMockito.when(APIUtil.getTiersFromPolicies(Mockito.anyString(), Mockito.anyInt())).thenReturn(tierMap2);
    Assert.assertEquals(abstractAPIManager.getTiers(SAMPLE_TENANT_DOMAIN_1).size(), 2);
    PowerMockito.when(APIUtil.getTiersFromPolicies(Mockito.anyString(), Mockito.anyInt())).thenReturn(tierMap3);
    Assert.assertEquals(abstractAPIManager.getTiers(SAMPLE_TENANT_DOMAIN_1).size(), 3);
}
Also used : Tier(org.wso2.carbon.apimgt.api.model.Tier) HashMap(java.util.HashMap) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 90 with Condition

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

the class APIProviderImplTest method getPolicyAPILevelPerUser.

private APIPolicy getPolicyAPILevelPerUser() {
    APIPolicy policy = new APIPolicy("custom1");
    policy.setUserLevel(PolicyConstants.PER_USER);
    policy.setDescription("Description");
    // policy.setPolicyLevel("api");
    policy.setTenantDomain("carbon.super");
    RequestCountLimit defaultLimit = new RequestCountLimit();
    defaultLimit.setTimeUnit("min");
    defaultLimit.setUnitTime(5);
    defaultLimit.setRequestCount(400);
    QuotaPolicy defaultQuotaPolicy = new QuotaPolicy();
    defaultQuotaPolicy.setLimit(defaultLimit);
    defaultQuotaPolicy.setType("RequestCount");
    policy.setDefaultQuotaPolicy(defaultQuotaPolicy);
    List<Pipeline> pipelines;
    Pipeline p;
    QuotaPolicy quotaPolicy;
    List<Condition> condition;
    RequestCountLimit countlimit;
    Condition cond;
    pipelines = new ArrayList<Pipeline>();
    // /////////pipeline item start//////
    p = new Pipeline();
    quotaPolicy = new QuotaPolicy();
    quotaPolicy.setType("RequestCount");
    countlimit = new RequestCountLimit();
    countlimit.setTimeUnit("min");
    countlimit.setUnitTime(5);
    countlimit.setRequestCount(100);
    quotaPolicy.setLimit(countlimit);
    condition = new ArrayList<Condition>();
    HTTPVerbCondition verbCond = new HTTPVerbCondition();
    verbCond.setHttpVerb("POST");
    condition.add(verbCond);
    p.setQuotaPolicy(quotaPolicy);
    p.setConditions(condition);
    pipelines.add(p);
    // /////////pipeline item end//////
    policy.setPipelines(pipelines);
    return policy;
}
Also used : HTTPVerbCondition(org.wso2.carbon.apimgt.api.model.policy.HTTPVerbCondition) Condition(org.wso2.carbon.apimgt.api.model.policy.Condition) RequestCountLimit(org.wso2.carbon.apimgt.api.model.policy.RequestCountLimit) QuotaPolicy(org.wso2.carbon.apimgt.api.model.policy.QuotaPolicy) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy) Pipeline(org.wso2.carbon.apimgt.api.model.policy.Pipeline) HTTPVerbCondition(org.wso2.carbon.apimgt.api.model.policy.HTTPVerbCondition)

Aggregations

HashMap (java.util.HashMap)39 Test (org.junit.Test)32 Test (org.testng.annotations.Test)31 ArrayList (java.util.ArrayList)30 List (java.util.List)26 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)26 ConditionDto (org.wso2.carbon.apimgt.impl.dto.ConditionDto)26 MessageContext (org.apache.synapse.MessageContext)25 PreparedStatement (java.sql.PreparedStatement)23 Map (java.util.Map)22 ResultSet (java.sql.ResultSet)20 BlockConditions (org.wso2.carbon.apimgt.core.models.BlockConditions)18 ThrottleProperties (org.wso2.carbon.apimgt.impl.dto.ThrottleProperties)18 Connection (java.sql.Connection)16 SQLException (java.sql.SQLException)16 TreeMap (java.util.TreeMap)16 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