use of org.wso2.carbon.apimgt.api.model.subscription.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"));
}
use of org.wso2.carbon.apimgt.api.model.subscription.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);
}
use of org.wso2.carbon.apimgt.api.model.subscription.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());
}
}
use of org.wso2.carbon.apimgt.api.model.subscription.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());
}
use of org.wso2.carbon.apimgt.api.model.subscription.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");
}
}
Aggregations