Search in sources :

Example 61 with APIPolicy

use of org.wso2.carbon.apimgt.api.model.policy.APIPolicy in project carbon-apimgt by wso2.

the class APIProviderImplTest method testGetAPIPolicy.

@Test
public void testGetAPIPolicy() throws APIManagementException {
    APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apimgtDAO, scopesDAO);
    PowerMockito.when(APIUtil.getTenantId("testUser")).thenReturn(1111);
    APIPolicy apiPolicy = Mockito.mock(APIPolicy.class);
    Mockito.when(apimgtDAO.getAPIPolicy("testPolicy", 1111)).thenReturn(apiPolicy);
    assertNotNull(apiProvider.getAPIPolicy("testUser", "testPolicy"));
}
Also used : APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 62 with APIPolicy

use of org.wso2.carbon.apimgt.api.model.policy.APIPolicy in project carbon-apimgt by wso2.

the class AbstractAPIManagerTestCase method testGetPolicies.

@Test
public void testGetPolicies() throws APIManagementException, org.wso2.carbon.user.api.UserStoreException, RegistryException, XMLStreamException {
    APIPolicy[] policies1 = { new APIPolicy("policy1") };
    ApplicationPolicy[] policies2 = { new ApplicationPolicy("policy2"), new ApplicationPolicy("policy3") };
    SubscriptionPolicy[] policies3 = { new SubscriptionPolicy("policy4"), new SubscriptionPolicy("policy5"), new SubscriptionPolicy("policy6") };
    GlobalPolicy[] policies4 = { new GlobalPolicy("policy7"), new GlobalPolicy("policy8"), new GlobalPolicy("policy9"), new GlobalPolicy("policy0") };
    PowerMockito.mockStatic(APIUtil.class);
    BDDMockito.when(APIUtil.getTenantId(Mockito.anyString())).thenReturn(-1234);
    PowerMockito.when(APIUtil.replaceSystemProperty(Mockito.anyString())).thenAnswer((Answer<String>) invocation -> {
        Object[] args = invocation.getArguments();
        return (String) args[0];
    });
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(apiMgtDAO);
    Mockito.when(apiMgtDAO.getAPIPolicies(Mockito.anyInt())).thenReturn(policies1);
    Mockito.when(apiMgtDAO.getApplicationPolicies(Mockito.anyInt())).thenReturn(policies2);
    Mockito.when(apiMgtDAO.getSubscriptionPolicies(Mockito.anyInt())).thenReturn(policies3);
    Mockito.when(apiMgtDAO.getGlobalPolicies(Mockito.anyInt())).thenReturn(policies4);
    ServiceReferenceHolder sh = mockRegistryAndUserRealm(-1234);
    APIManagerConfigurationService amConfigService = Mockito.mock(APIManagerConfigurationService.class);
    APIManagerConfiguration amConfig = Mockito.mock(APIManagerConfiguration.class);
    ThrottleProperties throttleProperties = Mockito.mock(ThrottleProperties.class, Mockito.RETURNS_MOCKS);
    PowerMockito.when(sh.getAPIManagerConfigurationService()).thenReturn(amConfigService);
    PowerMockito.when(amConfigService.getAPIManagerConfiguration()).thenReturn(amConfig);
    PowerMockito.when(amConfig.getThrottleProperties()).thenReturn(throttleProperties);
    Assert.assertEquals(abstractAPIManager.getPolicies(API_PROVIDER, PolicyConstants.POLICY_LEVEL_API).length, 1);
    Assert.assertEquals(abstractAPIManager.getPolicies(API_PROVIDER, PolicyConstants.POLICY_LEVEL_APP).length, 2);
    PowerMockito.when(throttleProperties.isEnableUnlimitedTier()).thenReturn(false);
    Assert.assertEquals(3, abstractAPIManager.getPolicies(API_PROVIDER, PolicyConstants.POLICY_LEVEL_SUB).length);
    Assert.assertEquals(4, abstractAPIManager.getPolicies(API_PROVIDER, PolicyConstants.POLICY_LEVEL_GLOBAL).length);
    Assert.assertEquals(0, abstractAPIManager.getPolicies(API_PROVIDER, "Test").length);
}
Also used : RegistryAuthorizationManager(org.wso2.carbon.registry.core.jdbc.realm.RegistryAuthorizationManager) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) PaginationContext(org.wso2.carbon.registry.core.pagination.PaginationContext) RealmService(org.wso2.carbon.user.core.service.RealmService) ResourceImpl(org.wso2.carbon.registry.core.ResourceImpl) Map(java.util.Map) XMLStreamException(javax.xml.stream.XMLStreamException) ApplicationPolicy(org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy) DocumentationType(org.wso2.carbon.apimgt.api.model.DocumentationType) ContentType(org.apache.http.entity.ContentType) Set(java.util.Set) StandardCharsets(java.nio.charset.StandardCharsets) Matchers.any(org.mockito.Matchers.any) IOUtils(org.apache.commons.io.IOUtils) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) GraphQLSchemaDefinition(org.wso2.carbon.apimgt.impl.definitions.GraphQLSchemaDefinition) MultitenantUtils(org.wso2.carbon.utils.multitenancy.MultitenantUtils) QName(javax.xml.namespace.QName) TestUtils.mockRegistryAndUserRealm(org.wso2.carbon.apimgt.impl.TestUtils.mockRegistryAndUserRealm) CarbonConstants(org.wso2.carbon.CarbonConstants) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) BlockConditionNotFoundException(org.wso2.carbon.apimgt.api.BlockConditionNotFoundException) Mock(org.mockito.Mock) GovernanceArtifact(org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact) CARBON_HOME(org.wso2.carbon.utils.ServerConstants.CARBON_HOME) RunWith(org.junit.runner.RunWith) GlobalPolicy(org.wso2.carbon.apimgt.api.model.policy.GlobalPolicy) Association(org.wso2.carbon.registry.core.Association) ArrayList(java.util.ArrayList) Answer(org.mockito.stubbing.Answer) RegistryConstants(org.wso2.carbon.registry.core.RegistryConstants) ResourceDO(org.wso2.carbon.registry.core.jdbc.dataobjects.ResourceDO) Resource(org.wso2.carbon.registry.core.Resource) Collection(org.wso2.carbon.registry.core.Collection) PowerMockito(org.powermock.api.mockito.PowerMockito) PublisherAPISearchResult(org.wso2.carbon.apimgt.persistence.dto.PublisherAPISearchResult) Before(org.junit.Before) GenericArtifactImpl(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifactImpl) Wsdl(org.wso2.carbon.apimgt.api.model.Wsdl) ThrottleProperties(org.wso2.carbon.apimgt.impl.dto.ThrottleProperties) Test(org.junit.Test) PolicyNotFoundException(org.wso2.carbon.apimgt.api.PolicyNotFoundException) IOException(java.io.IOException) APIMgtResourceAlreadyExistsException(org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException) ScopesDAO(org.wso2.carbon.apimgt.impl.dao.ScopesDAO) Field(java.lang.reflect.Field) ApiMgtDAO(org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO) BDDMockito(org.mockito.BDDMockito) TreeMap(java.util.TreeMap) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) Mediation(org.wso2.carbon.apimgt.api.model.Mediation) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) KeyManagerHolder(org.wso2.carbon.apimgt.impl.factory.KeyManagerHolder) KeyManagerDto(org.wso2.carbon.apimgt.impl.dto.KeyManagerDto) Assert(org.junit.Assert) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) RegistryContext(org.wso2.carbon.registry.core.config.RegistryContext) SortedSet(java.util.SortedSet) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager) RegistryUtils(org.wso2.carbon.registry.core.utils.RegistryUtils) PolicyConstants(org.wso2.carbon.apimgt.api.model.policy.PolicyConstants) APIPersistence(org.wso2.carbon.apimgt.persistence.APIPersistence) PublisherAPIInfo(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIInfo) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) GovernanceUtils(org.wso2.carbon.governance.api.util.GovernanceUtils) Application(org.wso2.carbon.apimgt.api.model.Application) AXIOMUtil(org.apache.axiom.om.util.AXIOMUtil) APIUtil(org.wso2.carbon.apimgt.impl.utils.APIUtil) OASPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.OASPersistenceException) UUID(java.util.UUID) UserContext(org.wso2.carbon.apimgt.persistence.dto.UserContext) List(java.util.List) Modifier(java.lang.reflect.Modifier) ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) SortedMap(java.util.SortedMap) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) HashMap(java.util.HashMap) HashSet(java.util.HashSet) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) ArrayInputStream(org.apache.derby.iapi.services.io.ArrayInputStream) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) PowerMockRunner(org.powermock.modules.junit4.PowerMockRunner) API(org.wso2.carbon.apimgt.api.model.API) ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) DEFAULT_DIALECT_URI(org.wso2.carbon.apimgt.impl.token.ClaimsRetriever.DEFAULT_DIALECT_URI) Tier(org.wso2.carbon.apimgt.api.model.Tier) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) DocumentationPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.DocumentationPersistenceException) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) Mockito(org.mockito.Mockito) UserStoreException(org.wso2.carbon.user.core.UserStoreException) Registry(org.wso2.carbon.registry.core.Registry) Identifier(org.wso2.carbon.apimgt.api.model.Identifier) CollectionImpl(org.wso2.carbon.registry.core.CollectionImpl) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) OASParserUtil(org.wso2.carbon.apimgt.impl.definitions.OASParserUtil) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) InputStream(java.io.InputStream) ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) GlobalPolicy(org.wso2.carbon.apimgt.api.model.policy.GlobalPolicy) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) ApplicationPolicy(org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy) ThrottleProperties(org.wso2.carbon.apimgt.impl.dto.ThrottleProperties) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 63 with APIPolicy

use of org.wso2.carbon.apimgt.api.model.policy.APIPolicy in project carbon-apimgt by wso2.

the class APIProviderImplTest method testGetAPIPolicyByUUID.

@Test
public void testGetAPIPolicyByUUID() throws APIManagementException {
    APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apimgtDAO, scopesDAO);
    APIPolicy apiPolicy = Mockito.mock(APIPolicy.class);
    Mockito.when(apimgtDAO.getAPIPolicyByUUID("1111")).thenReturn(apiPolicy, null);
    apiProvider.getAPIPolicyByUUID("1111");
    try {
        assertNotNull(apiProvider.getAPIPolicyByUUID("1111"));
    } catch (APIManagementException e) {
        assertEquals("Advanced Policy: 1111 was not found.", e.getMessage());
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 64 with APIPolicy

use of org.wso2.carbon.apimgt.api.model.policy.APIPolicy in project carbon-apimgt by wso2.

the class APIMgtDAOTest method testDeleteSubscriptionsForapiId.

@Test
public void testDeleteSubscriptionsForapiId() throws Exception {
    Subscriber subscriber = new Subscriber("testCreateApplicationRegistrationEntry");
    String organization = "testOrg";
    subscriber.setTenantId(-1234);
    subscriber.setEmail("abc@wso2.com");
    subscriber.setSubscribedDate(new Date(System.currentTimeMillis()));
    apiMgtDAO.addSubscriber(subscriber, null);
    Policy applicationPolicy = getApplicationPolicy("testCreateApplicationRegistrationEntry");
    SubscriptionPolicy subscriptionPolicy = (SubscriptionPolicy) getSubscriptionPolicy("testCreateApplicationRegistrationEntry");
    subscriptionPolicy.setMonetizationPlan(APIConstants.Monetization.FIXED_RATE);
    apiMgtDAO.addSubscriptionPolicy((SubscriptionPolicy) subscriptionPolicy);
    applicationPolicy.setTenantId(-1234);
    apiMgtDAO.addApplicationPolicy((ApplicationPolicy) applicationPolicy);
    Application application = new Application("testCreateApplicationRegistrationEntry", subscriber);
    application.setTier("testCreateApplicationRegistrationEntry");
    application.setId(apiMgtDAO.addApplication(application, "testCreateApplicationRegistrationEntry", organization));
    application.setDescription("updated description");
    apiMgtDAO.updateApplication(application);
    assertEquals(apiMgtDAO.getApplicationById(application.getId()).getDescription(), "updated description");
    APIIdentifier apiId = new APIIdentifier("testCreateApplicationRegistrationEntry", "testCreateApplicationRegistrationEntry", "1.0.0");
    API api = new API(apiId);
    api.setContext("/testCreateApplicationRegistrationEntry");
    api.setContextTemplate("/testCreateApplicationRegistrationEntry/{version}");
    api.setVersionTimestamp(String.valueOf(System.currentTimeMillis()));
    APIPolicy apiPolicy = (APIPolicy) getPolicyAPILevelPerUser("testCreateApplicationRegistrationEntry");
    api.setApiLevelPolicy(apiPolicy.getPolicyName());
    api.setUUID(UUID.randomUUID().toString());
    api.getId().setId(apiMgtDAO.addAPI(api, -1234, organization));
    apiId.setTier(subscriptionPolicy.getPolicyName());
    ApiTypeWrapper apiTypeWrapper = new ApiTypeWrapper(api);
    int subsId = apiMgtDAO.addSubscription(apiTypeWrapper, application, APIConstants.SubscriptionStatus.ON_HOLD, subscriber.getName());
    assertTrue(apiMgtDAO.getApplicationsByTier(subscriptionPolicy.getPolicyName()).length > 0);
    String subStatus = apiMgtDAO.getSubscriptionStatusById(subsId);
    assertEquals(subStatus, APIConstants.SubscriptionStatus.ON_HOLD);
    SubscribedAPI subscribedAPI = apiMgtDAO.getSubscriptionById(subsId);
    String clientIdProduction = UUID.randomUUID().toString();
    String clientIdSandbox = UUID.randomUUID().toString();
    apiMgtDAO.createApplicationKeyTypeMappingForManualClients(APIConstants.API_KEY_TYPE_PRODUCTION, application.getId(), clientIdProduction, "Default", UUID.randomUUID().toString());
    apiMgtDAO.createApplicationKeyTypeMappingForManualClients(APIConstants.API_KEY_TYPE_SANDBOX, application.getId(), clientIdSandbox, "Default", UUID.randomUUID().toString());
    assertTrue(apiMgtDAO.getSubscriptionCount(subscriber, application.getName(), null) > 0);
    OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo();
    Mockito.when(keyManager.retrieveApplication(clientIdProduction)).thenReturn(oAuthApplicationInfo);
    Mockito.when(keyManager.retrieveApplication(clientIdSandbox)).thenReturn(oAuthApplicationInfo);
    assertTrue(apiMgtDAO.getSubscribedAPIs(organization, subscriber, null).size() > 0);
    assertEquals(subscribedAPI.getSubCreatedStatus(), APIConstants.SubscriptionCreatedStatus.SUBSCRIBE);
    assertEquals(subscribedAPI.getApiId(), apiId);
    assertEquals(subscribedAPI.getApplication().getId(), application.getId());
    SubscribedAPI subscribedAPIFromUuid = apiMgtDAO.getSubscriptionByUUID(subscribedAPI.getUUID());
    assertEquals(subscribedAPIFromUuid.getSubCreatedStatus(), APIConstants.SubscriptionCreatedStatus.SUBSCRIBE);
    assertEquals(subscribedAPIFromUuid.getApiId(), apiId);
    assertEquals(subscribedAPIFromUuid.getApplication().getId(), application.getId());
    apiMgtDAO.updateApplicationStatus(application.getId(), APIConstants.ApplicationStatus.APPLICATION_APPROVED);
    String status = apiMgtDAO.getApplicationStatus("testCreateApplicationRegistrationEntry", "testCreateApplicationRegistrationEntry");
    assertEquals(status, APIConstants.ApplicationStatus.APPLICATION_APPROVED);
    boolean applicationExist = apiMgtDAO.isApplicationExist(application.getName(), subscriber.getName(), null, organization);
    assertTrue(applicationExist);
    Set<SubscribedAPI> subscribedAPIS = apiMgtDAO.getSubscribedAPIs(subscriber, application.getName(), null);
    assertEquals(subscribedAPIS.size(), 1);
    apiMgtDAO.updateSubscription(apiId, APIConstants.SubscriptionStatus.BLOCKED, application.getId(), organization);
    subscribedAPI.setSubStatus(APIConstants.SubscriptionStatus.REJECTED);
    apiMgtDAO.updateSubscription(subscribedAPI);
    assertTrue(apiMgtDAO.hasSubscription(subscriptionPolicy.getPolicyName(), subscriber.getName(), PolicyConstants.POLICY_LEVEL_SUB));
    assertTrue(apiMgtDAO.hasSubscription(applicationPolicy.getPolicyName(), subscriber.getName(), PolicyConstants.POLICY_LEVEL_APP));
    assertTrue(apiMgtDAO.hasSubscription(apiPolicy.getPolicyName(), subscriber.getName(), PolicyConstants.POLICY_LEVEL_API));
    assertTrue(apiPolicy.getPolicyName().equals(apiMgtDAO.getAPILevelTier(apiMgtDAO.getAPIID(api.getUuid()))));
    apiMgtDAO.recordAPILifeCycleEvent(api.getUuid(), "CREATED", "PUBLISHED", "testCreateApplicationRegistrationEntry", -1234);
    apiMgtDAO.updateDefaultAPIPublishedVersion(apiId);
    apiMgtDAO.removeAllSubscriptions(api.getUuid());
    assertTrue(apiMgtDAO.getAPINamesMatchingContext(api.getContext()).size() > 0);
    apiMgtDAO.deleteAPI(api.getUuid());
    apiMgtDAO.deleteApplication(application);
    apiMgtDAO.removeThrottlePolicy(PolicyConstants.POLICY_LEVEL_APP, "testCreateApplicationRegistrationEntry", -1234);
    apiMgtDAO.deleteApplicationKeyMappingByConsumerKey(clientIdProduction);
    apiMgtDAO.deleteApplicationMappingByConsumerKey(clientIdSandbox);
    deleteSubscriber(subscriber.getId());
}
Also used : QuotaPolicy(org.wso2.carbon.apimgt.api.model.policy.QuotaPolicy) ApplicationPolicy(org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) Policy(org.wso2.carbon.apimgt.api.model.policy.Policy) GlobalPolicy(org.wso2.carbon.apimgt.api.model.policy.GlobalPolicy) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) Date(java.util.Date) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) API(org.wso2.carbon.apimgt.api.model.API) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy) Application(org.wso2.carbon.apimgt.api.model.Application) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 65 with APIPolicy

use of org.wso2.carbon.apimgt.api.model.policy.APIPolicy in project carbon-apimgt by wso2.

the class APIProviderImpl method updatePolicy.

public void updatePolicy(Policy policy) throws APIManagementException {
    String oldKeyTemplate = null;
    String newKeyTemplate = null;
    if (policy instanceof APIPolicy) {
        APIPolicy apiPolicy = (APIPolicy) policy;
        apiPolicy.setUserLevel(PolicyConstants.ACROSS_ALL);
        // TODO this has done due to update policy method not deleting the second level entries when delete on cascade
        // TODO Need to fix appropriately
        List<Pipeline> pipelineList = apiPolicy.getPipelines();
        if (pipelineList != null && pipelineList.size() != 0) {
            Iterator<Pipeline> pipelineIterator = pipelineList.iterator();
            while (pipelineIterator.hasNext()) {
                Pipeline pipeline = pipelineIterator.next();
                if (!pipeline.isEnabled()) {
                    pipelineIterator.remove();
                } else {
                    if (pipeline.getConditions() != null && pipeline.getConditions().size() != 0) {
                        Iterator<Condition> conditionIterator = pipeline.getConditions().iterator();
                        while (conditionIterator.hasNext()) {
                            Condition condition = conditionIterator.next();
                            if (JavaUtils.isFalseExplicitly(condition.getConditionEnabled())) {
                                conditionIterator.remove();
                            }
                        }
                    } else {
                        pipelineIterator.remove();
                    }
                }
            }
        }
        APIPolicy existingPolicy = apiMgtDAO.getAPIPolicy(policy.getPolicyName(), policy.getTenantId());
        apiPolicy = apiMgtDAO.updateAPIPolicy(apiPolicy);
        // TODO rename level to  resource or appropriate name
        APIManagerConfiguration config = getAPIManagerConfiguration();
        if (log.isDebugEnabled()) {
            log.debug("Calling invalidation cache for API Policy for tenant ");
        }
        String policyContext = APIConstants.POLICY_CACHE_CONTEXT + "/t/" + apiPolicy.getTenantDomain() + "/";
        invalidateResourceCache(policyContext, null, Collections.EMPTY_SET);
        List<Integer> addedConditionGroupIds = new ArrayList<>();
        List<Integer> deletedConditionGroupIds = new ArrayList<>();
        for (Pipeline pipeline : existingPolicy.getPipelines()) {
            deletedConditionGroupIds.add(pipeline.getId());
        }
        for (Pipeline pipeline : apiPolicy.getPipelines()) {
            addedConditionGroupIds.add(pipeline.getId());
        }
        APIPolicyEvent apiPolicyEvent = new APIPolicyEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.POLICY_UPDATE.name(), tenantId, apiPolicy.getTenantDomain(), apiPolicy.getPolicyId(), apiPolicy.getPolicyName(), apiPolicy.getDefaultQuotaPolicy().getType(), addedConditionGroupIds, deletedConditionGroupIds);
        APIUtil.sendNotification(apiPolicyEvent, APIConstants.NotifierType.POLICY.name());
    } else if (policy instanceof ApplicationPolicy) {
        ApplicationPolicy appPolicy = (ApplicationPolicy) policy;
        apiMgtDAO.updateApplicationPolicy(appPolicy);
        // policy id is not set. retrieving policy to get the id.
        ApplicationPolicy retrievedPolicy = apiMgtDAO.getApplicationPolicy(appPolicy.getPolicyName(), tenantId);
        ApplicationPolicyEvent applicationPolicyEvent = new ApplicationPolicyEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.POLICY_UPDATE.name(), tenantId, appPolicy.getTenantDomain(), retrievedPolicy.getPolicyId(), appPolicy.getPolicyName(), appPolicy.getDefaultQuotaPolicy().getType());
        APIUtil.sendNotification(applicationPolicyEvent, APIConstants.NotifierType.POLICY.name());
    } else if (policy instanceof SubscriptionPolicy) {
        SubscriptionPolicy subPolicy = (SubscriptionPolicy) policy;
        apiMgtDAO.updateSubscriptionPolicy(subPolicy);
        String monetizationPlan = subPolicy.getMonetizationPlan();
        Map<String, String> monetizationPlanProperties = subPolicy.getMonetizationPlanProperties();
        // call the monetization extension point to create plans (if any)
        if (StringUtils.isNotBlank(monetizationPlan) && MapUtils.isNotEmpty(monetizationPlanProperties)) {
            updateMonetizationPlan(subPolicy);
        }
        // policy id is not set. retrieving policy to get the id.
        SubscriptionPolicy retrievedPolicy = apiMgtDAO.getSubscriptionPolicy(subPolicy.getPolicyName(), tenantId);
        SubscriptionPolicyEvent subscriptionPolicyEvent = new SubscriptionPolicyEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.POLICY_UPDATE.name(), tenantId, subPolicy.getTenantDomain(), retrievedPolicy.getPolicyId(), subPolicy.getPolicyName(), subPolicy.getDefaultQuotaPolicy().getType(), subPolicy.getRateLimitCount(), subPolicy.getRateLimitTimeUnit(), subPolicy.isStopOnQuotaReach(), subPolicy.getGraphQLMaxDepth(), subPolicy.getGraphQLMaxComplexity(), subPolicy.getSubscriberCount());
        APIUtil.sendNotification(subscriptionPolicyEvent, APIConstants.NotifierType.POLICY.name());
    } else if (policy instanceof GlobalPolicy) {
        GlobalPolicy globalPolicy = (GlobalPolicy) policy;
        // getting key templates before updating database
        GlobalPolicy oldGlobalPolicy = apiMgtDAO.getGlobalPolicy(policy.getPolicyName());
        oldKeyTemplate = oldGlobalPolicy.getKeyTemplate();
        newKeyTemplate = globalPolicy.getKeyTemplate();
        apiMgtDAO.updateGlobalPolicy(globalPolicy);
        GlobalPolicy retrievedPolicy = apiMgtDAO.getGlobalPolicy(globalPolicy.getPolicyName());
        GlobalPolicyEvent globalPolicyEvent = new GlobalPolicyEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.POLICY_UPDATE.name(), tenantId, globalPolicy.getTenantDomain(), retrievedPolicy.getPolicyId(), globalPolicy.getPolicyName());
        APIUtil.sendNotification(globalPolicyEvent, APIConstants.NotifierType.POLICY.name());
    } else {
        String msg = "Policy type " + policy.getClass().getName() + " is not supported";
        log.error(msg);
        throw new UnsupportedPolicyTypeException(msg);
    }
    // publishing keytemplate after update
    if (oldKeyTemplate != null && newKeyTemplate != null) {
        publishKeyTemplateEvent(oldKeyTemplate, "remove");
        publishKeyTemplateEvent(newKeyTemplate, "add");
    }
}
Also used : Condition(org.wso2.carbon.apimgt.api.model.policy.Condition) GlobalPolicy(org.wso2.carbon.apimgt.api.model.policy.GlobalPolicy) UnsupportedPolicyTypeException(org.wso2.carbon.apimgt.api.UnsupportedPolicyTypeException) ArrayList(java.util.ArrayList) ApplicationPolicyEvent(org.wso2.carbon.apimgt.impl.notifier.events.ApplicationPolicyEvent) SubscriptionPolicyEvent(org.wso2.carbon.apimgt.impl.notifier.events.SubscriptionPolicyEvent) Pipeline(org.wso2.carbon.apimgt.api.model.policy.Pipeline) APIPolicyEvent(org.wso2.carbon.apimgt.impl.notifier.events.APIPolicyEvent) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) ApplicationPolicy(org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy) GlobalPolicyEvent(org.wso2.carbon.apimgt.impl.notifier.events.GlobalPolicyEvent)

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