use of org.wso2.carbon.apimgt.api.model.subscription.SubscriptionPolicy in project carbon-apimgt by wso2.
the class APIUtil method getAPI.
public static API getAPI(GovernanceArtifact artifact) throws APIManagementException {
API api;
try {
String providerName = artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
String apiName = artifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
String apiVersion = artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
APIIdentifier apiIdentifier = new APIIdentifier(providerName, apiName, apiVersion);
api = new API(apiIdentifier);
int apiId = ApiMgtDAO.getInstance().getAPIID(artifact.getId());
if (apiId == -1) {
return null;
}
// set uuid
api.setUUID(artifact.getId());
api.setRating(getAverageRating(apiId));
api.setThumbnailUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL));
api.setStatus(getLcStateFromArtifact(artifact));
api.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT));
api.setVisibility(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY));
api.setVisibleRoles(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES));
api.setVisibleTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_TENANTS));
api.setTransports(artifact.getAttribute(APIConstants.API_OVERVIEW_TRANSPORTS));
api.setInSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_INSEQUENCE));
api.setOutSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_OUTSEQUENCE));
api.setFaultSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_FAULTSEQUENCE));
api.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
api.setResponseCache(artifact.getAttribute(APIConstants.API_OVERVIEW_RESPONSE_CACHING));
api.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
api.setEnableStore(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENABLE_STORE)));
api.setTestKey(artifact.getAttribute(APIConstants.API_OVERVIEW_TESTKEY));
int cacheTimeout = APIConstants.API_RESPONSE_CACHE_TIMEOUT;
try {
cacheTimeout = Integer.parseInt(artifact.getAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT));
} catch (NumberFormatException e) {
// ignore
}
api.setCacheTimeout(cacheTimeout);
String apiLevelTier = ApiMgtDAO.getInstance().getAPILevelTier(apiId);
api.setApiLevelPolicy(apiLevelTier);
Set<Tier> availablePolicy = new HashSet<Tier>();
String[] subscriptionPolicy = ApiMgtDAO.getInstance().getPolicyNames(PolicyConstants.POLICY_LEVEL_SUB, replaceEmailDomainBack(providerName));
List<String> definedPolicyNames = Arrays.asList(subscriptionPolicy);
String policies = artifact.getAttribute(APIConstants.API_OVERVIEW_TIER);
if (policies != null && !"".equals(policies)) {
String[] policyNames = policies.split("\\|\\|");
for (String policyName : policyNames) {
if (definedPolicyNames.contains(policyName) || APIConstants.UNLIMITED_TIER.equals(policyName)) {
Tier p = new Tier(policyName);
availablePolicy.add(p);
} else {
log.warn("Unknown policy: " + policyName + " found on API: " + apiName);
}
}
}
api.addAvailableTiers(availablePolicy);
String tenantDomainName = MultitenantUtils.getTenantDomain(replaceEmailDomainBack(providerName));
api.setMonetizationCategory(getAPIMonetizationCategory(availablePolicy, tenantDomainName));
api.setRedirectURL(artifact.getAttribute(APIConstants.API_OVERVIEW_REDIRECT_URL));
api.setApiOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_OWNER));
api.setAdvertiseOnly(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY)));
api.setEndpointConfig(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG));
api.setSubscriptionAvailability(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY));
api.setSubscriptionAvailableTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS));
api.setAsDefaultVersion(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_DEFAULT_VERSION)));
api.setImplementation(artifact.getAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION));
api.setTechnicalOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER));
api.setTechnicalOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER_EMAIL));
api.setBusinessOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER));
api.setBusinessOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER_EMAIL));
ArrayList<URITemplate> urlPatternsList;
urlPatternsList = ApiMgtDAO.getInstance().getAllURITemplates(api.getContext(), api.getId().getVersion());
Set<URITemplate> uriTemplates = new HashSet<URITemplate>(urlPatternsList);
for (URITemplate uriTemplate : uriTemplates) {
uriTemplate.setResourceURI(api.getUrl());
uriTemplate.setResourceSandboxURI(api.getSandboxUrl());
}
api.setUriTemplates(uriTemplates);
String environments = artifact.getAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS);
api.setEnvironments(extractEnvironmentsForAPI(environments));
api.setCorsConfiguration(getCorsConfigurationFromArtifact(artifact));
api.setAuthorizationHeader(artifact.getAttribute(APIConstants.API_OVERVIEW_AUTHORIZATION_HEADER));
api.setApiSecurity(artifact.getAttribute(APIConstants.API_OVERVIEW_API_SECURITY));
// non empty URLs to API object
try {
api.setEnvironmentList(extractEnvironmentListForAPI(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG)));
} catch (ParseException e) {
String msg = "Failed to parse endpoint config JSON of API: " + apiName + " " + apiVersion;
log.error(msg, e);
throw new APIManagementException(msg, e);
} catch (ClassCastException e) {
String msg = "Invalid endpoint config JSON found in API: " + apiName + " " + apiVersion;
log.error(msg, e);
throw new APIManagementException(msg, e);
}
} catch (GovernanceException e) {
String msg = "Failed to get API from artifact ";
throw new APIManagementException(msg, e);
}
return api;
}
use of org.wso2.carbon.apimgt.api.model.subscription.SubscriptionPolicy in project carbon-apimgt by wso2.
the class APIUtil method addDefaultSuperTenantAdvancedThrottlePolicies.
public static void addDefaultSuperTenantAdvancedThrottlePolicies() throws APIManagementException {
int tenantId = MultitenantConstants.SUPER_TENANT_ID;
ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
/* Check if 'Unlimited' policy is available in AM_POLICY_APPLICATION table, to determine whether the default policies are loaded into the database at lease once.
If yes, default policies won't be added to database again.
*/
if (apiMgtDAO.isPolicyExist(PolicyConstants.POLICY_LEVEL_APP, tenantId, APIConstants.DEFAULT_APP_POLICY_UNLIMITED)) {
log.debug("Default Throttling Policies are not written into the database again, as they were added once at initial server startup");
return;
}
long[] requestCount = new long[] { 50, 20, 10, Integer.MAX_VALUE };
// Adding application level throttle policies
String[] appPolicies = new String[] { APIConstants.DEFAULT_APP_POLICY_FIFTY_REQ_PER_MIN, APIConstants.DEFAULT_APP_POLICY_TWENTY_REQ_PER_MIN, APIConstants.DEFAULT_APP_POLICY_TEN_REQ_PER_MIN, APIConstants.DEFAULT_APP_POLICY_UNLIMITED };
String[] appPolicyDecs = new String[] { APIConstants.DEFAULT_APP_POLICY_LARGE_DESC, APIConstants.DEFAULT_APP_POLICY_MEDIUM_DESC, APIConstants.DEFAULT_APP_POLICY_SMALL_DESC, APIConstants.DEFAULT_APP_POLICY_UNLIMITED_DESC };
String policyName;
// Add application level throttle policies
for (int i = 0; i < appPolicies.length; i++) {
policyName = appPolicies[i];
if (!apiMgtDAO.isPolicyExist(PolicyConstants.POLICY_LEVEL_APP, tenantId, policyName)) {
ApplicationPolicy applicationPolicy = new ApplicationPolicy(policyName);
applicationPolicy.setDisplayName(policyName);
applicationPolicy.setDescription(appPolicyDecs[i]);
applicationPolicy.setTenantId(tenantId);
applicationPolicy.setDeployed(true);
QuotaPolicy defaultQuotaPolicy = new QuotaPolicy();
RequestCountLimit requestCountLimit = new RequestCountLimit();
requestCountLimit.setRequestCount(requestCount[i]);
requestCountLimit.setUnitTime(1);
requestCountLimit.setTimeUnit(APIConstants.TIME_UNIT_MINUTE);
defaultQuotaPolicy.setType(PolicyConstants.REQUEST_COUNT_TYPE);
defaultQuotaPolicy.setLimit(requestCountLimit);
applicationPolicy.setDefaultQuotaPolicy(defaultQuotaPolicy);
apiMgtDAO.addApplicationPolicy(applicationPolicy);
}
}
// Adding Subscription level policies
long[] requestCountSubPolicies = new long[] { 5000, 2000, 1000, 500, Integer.MAX_VALUE };
String[] subPolicies = new String[] { APIConstants.DEFAULT_SUB_POLICY_GOLD, APIConstants.DEFAULT_SUB_POLICY_SILVER, APIConstants.DEFAULT_SUB_POLICY_BRONZE, APIConstants.DEFAULT_SUB_POLICY_UNAUTHENTICATED, APIConstants.DEFAULT_SUB_POLICY_UNLIMITED };
String[] subPolicyDecs = new String[] { APIConstants.DEFAULT_SUB_POLICY_GOLD_DESC, APIConstants.DEFAULT_SUB_POLICY_SILVER_DESC, APIConstants.DEFAULT_SUB_POLICY_BRONZE_DESC, APIConstants.DEFAULT_SUB_POLICY_UNAUTHENTICATED_DESC, APIConstants.DEFAULT_SUB_POLICY_UNLIMITED_DESC };
for (int i = 0; i < subPolicies.length; i++) {
policyName = subPolicies[i];
if (!apiMgtDAO.isPolicyExist(PolicyConstants.POLICY_LEVEL_SUB, tenantId, policyName)) {
SubscriptionPolicy subscriptionPolicy = new SubscriptionPolicy(policyName);
subscriptionPolicy.setDisplayName(policyName);
subscriptionPolicy.setDescription(subPolicyDecs[i]);
subscriptionPolicy.setTenantId(tenantId);
subscriptionPolicy.setDeployed(true);
QuotaPolicy defaultQuotaPolicy = new QuotaPolicy();
RequestCountLimit requestCountLimit = new RequestCountLimit();
requestCountLimit.setRequestCount(requestCountSubPolicies[i]);
requestCountLimit.setUnitTime(1);
requestCountLimit.setTimeUnit(APIConstants.TIME_UNIT_MINUTE);
defaultQuotaPolicy.setType(PolicyConstants.REQUEST_COUNT_TYPE);
defaultQuotaPolicy.setLimit(requestCountLimit);
subscriptionPolicy.setDefaultQuotaPolicy(defaultQuotaPolicy);
subscriptionPolicy.setStopOnQuotaReach(true);
subscriptionPolicy.setBillingPlan(APIConstants.BILLING_PLAN_FREE);
apiMgtDAO.addSubscriptionPolicy(subscriptionPolicy);
}
}
// Adding Event based subscription level policies for async policies (WS & SSE)
long[] eventCountSubPolicyValues = new long[] { 50000, 25000, 5000, Integer.MAX_VALUE };
String[] eventCountSubPolicyNames = new String[] { APIConstants.DEFAULT_SUB_POLICY_ASYNC_GOLD, APIConstants.DEFAULT_SUB_POLICY_ASYNC_SILVER, APIConstants.DEFAULT_SUB_POLICY_ASYNC_BRONZE, APIConstants.DEFAULT_SUB_POLICY_ASYNC_UNLIMITED };
String[] eventCountSubPolicyDescriptions = new String[] { APIConstants.DEFAULT_SUB_POLICY_ASYNC_GOLD_DESC, APIConstants.DEFAULT_SUB_POLICY_ASYNC_SILVER_DESC, APIConstants.DEFAULT_SUB_POLICY_ASYNC_BRONZE_DESC, APIConstants.DEFAULT_SUB_POLICY_ASYNC_UNLIMITED_DESC };
for (int i = 0; i < eventCountSubPolicyNames.length; i++) {
policyName = eventCountSubPolicyNames[i];
if (!apiMgtDAO.isPolicyExist(PolicyConstants.POLICY_LEVEL_SUB, tenantId, policyName)) {
SubscriptionPolicy subscriptionPolicy = new SubscriptionPolicy(policyName);
subscriptionPolicy.setDisplayName(policyName);
subscriptionPolicy.setDescription(eventCountSubPolicyDescriptions[i]);
subscriptionPolicy.setTenantId(tenantId);
subscriptionPolicy.setDeployed(true);
QuotaPolicy defaultQuotaPolicy = new QuotaPolicy();
EventCountLimit eventCountLimit = new EventCountLimit();
eventCountLimit.setEventCount(eventCountSubPolicyValues[i]);
eventCountLimit.setUnitTime(1);
eventCountLimit.setTimeUnit(APIConstants.TIME_UNIT_DAY);
defaultQuotaPolicy.setType(PolicyConstants.EVENT_COUNT_TYPE);
defaultQuotaPolicy.setLimit(eventCountLimit);
subscriptionPolicy.setDefaultQuotaPolicy(defaultQuotaPolicy);
subscriptionPolicy.setStopOnQuotaReach(true);
subscriptionPolicy.setBillingPlan(APIConstants.BILLING_PLAN_FREE);
apiMgtDAO.addSubscriptionPolicy(subscriptionPolicy);
}
}
// Adding Event based Webhooks API specific policies (WEBSUB)
long[] eventCountWHSubPolicyValues = new long[] { 10000, 5000, 1000, Integer.MAX_VALUE };
int[] subscriptionCountValues = new int[] { 1000, 500, 100, Integer.MAX_VALUE };
String[] eventCountWHSubPolicyNames = new String[] { APIConstants.DEFAULT_SUB_POLICY_ASYNC_WH_GOLD, APIConstants.DEFAULT_SUB_POLICY_ASYNC_WH_SILVER, APIConstants.DEFAULT_SUB_POLICY_ASYNC_WH_BRONZE, APIConstants.DEFAULT_SUB_POLICY_ASYNC_WH_UNLIMITED };
String[] eventCountWHSubPolicyDescriptions = new String[] { APIConstants.DEFAULT_SUB_POLICY_ASYNC_WH_GOLD_DESC, APIConstants.DEFAULT_SUB_POLICY_ASYNC_WH_SILVER_DESC, APIConstants.DEFAULT_SUB_POLICY_ASYNC_WH_BRONZE_DESC, APIConstants.DEFAULT_SUB_POLICY_ASYNC_WH_UNLIMITED_DESC };
for (int i = 0; i < eventCountWHSubPolicyNames.length; i++) {
policyName = eventCountWHSubPolicyNames[i];
if (!apiMgtDAO.isPolicyExist(PolicyConstants.POLICY_LEVEL_SUB, tenantId, policyName)) {
SubscriptionPolicy subscriptionPolicy = new SubscriptionPolicy(policyName);
subscriptionPolicy.setDisplayName(policyName);
subscriptionPolicy.setDescription(eventCountWHSubPolicyDescriptions[i]);
subscriptionPolicy.setTenantId(tenantId);
subscriptionPolicy.setDeployed(true);
QuotaPolicy defaultQuotaPolicy = new QuotaPolicy();
EventCountLimit eventCountLimit = new EventCountLimit();
eventCountLimit.setEventCount(eventCountWHSubPolicyValues[i]);
eventCountLimit.setUnitTime(1);
eventCountLimit.setTimeUnit(APIConstants.TIME_UNIT_MONTH);
defaultQuotaPolicy.setType(PolicyConstants.EVENT_COUNT_TYPE);
defaultQuotaPolicy.setLimit(eventCountLimit);
subscriptionPolicy.setDefaultQuotaPolicy(defaultQuotaPolicy);
subscriptionPolicy.setStopOnQuotaReach(true);
subscriptionPolicy.setBillingPlan(APIConstants.BILLING_PLAN_FREE);
subscriptionPolicy.setSubscriberCount(subscriptionCountValues[i]);
apiMgtDAO.addSubscriptionPolicy(subscriptionPolicy);
}
}
// Adding Resource level policies
String[] apiPolicies = new String[] { APIConstants.DEFAULT_API_POLICY_FIFTY_THOUSAND_REQ_PER_MIN, APIConstants.DEFAULT_API_POLICY_TWENTY_THOUSAND_REQ_PER_MIN, APIConstants.DEFAULT_API_POLICY_TEN_THOUSAND_REQ_PER_MIN, APIConstants.DEFAULT_API_POLICY_UNLIMITED };
String[] apiPolicyDecs = new String[] { APIConstants.DEFAULT_API_POLICY_ULTIMATE_DESC, APIConstants.DEFAULT_API_POLICY_PLUS_DESC, APIConstants.DEFAULT_API_POLICY_BASIC_DESC, APIConstants.DEFAULT_API_POLICY_UNLIMITED_DESC };
long[] requestCountApiPolicies = new long[] { 50000, 20000, 10000, Integer.MAX_VALUE };
for (int i = 0; i < apiPolicies.length; i++) {
policyName = apiPolicies[i];
if (!apiMgtDAO.isPolicyExist(PolicyConstants.POLICY_LEVEL_API, tenantId, policyName)) {
APIPolicy apiPolicy = new APIPolicy(policyName);
apiPolicy.setDisplayName(policyName);
apiPolicy.setDescription(apiPolicyDecs[i]);
apiPolicy.setTenantId(tenantId);
apiPolicy.setUserLevel(APIConstants.API_POLICY_API_LEVEL);
apiPolicy.setDeployed(true);
QuotaPolicy defaultQuotaPolicy = new QuotaPolicy();
RequestCountLimit requestCountLimit = new RequestCountLimit();
requestCountLimit.setRequestCount(requestCountApiPolicies[i]);
requestCountLimit.setUnitTime(1);
requestCountLimit.setTimeUnit(APIConstants.TIME_UNIT_MINUTE);
defaultQuotaPolicy.setType(PolicyConstants.REQUEST_COUNT_TYPE);
defaultQuotaPolicy.setLimit(requestCountLimit);
apiPolicy.setDefaultQuotaPolicy(defaultQuotaPolicy);
apiMgtDAO.addAPIPolicy(apiPolicy);
}
}
}
use of org.wso2.carbon.apimgt.api.model.subscription.SubscriptionPolicy in project carbon-apimgt by wso2.
the class APIUtilTest method testGetAPIForPublishing.
@Test
public void testGetAPIForPublishing() throws Exception {
API expectedAPI = getUniqueAPI();
final String provider = expectedAPI.getId().getProviderName();
final String tenantDomain = org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
final int tenantId = -1234;
GovernanceArtifact artifact = Mockito.mock(GovernanceArtifact.class);
Registry registry = Mockito.mock(Registry.class);
ApiMgtDAO apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
Resource resource = Mockito.mock(Resource.class);
ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
RealmService realmService = Mockito.mock(RealmService.class);
TenantManager tenantManager = Mockito.mock(TenantManager.class);
APIManagerConfigurationService apiManagerConfigurationService = Mockito.mock(APIManagerConfigurationService.class);
APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
ThrottleProperties throttleProperties = Mockito.mock(ThrottleProperties.class);
SubscriptionPolicy policy = Mockito.mock(SubscriptionPolicy.class);
SubscriptionPolicy[] policies = new SubscriptionPolicy[] { policy };
QuotaPolicy quotaPolicy = Mockito.mock(QuotaPolicy.class);
RequestCountLimit limit = Mockito.mock(RequestCountLimit.class);
PowerMockito.mockStatic(ApiMgtDAO.class);
PowerMockito.mockStatic(GovernanceUtils.class);
PowerMockito.mockStatic(MultitenantUtils.class);
PowerMockito.mockStatic(ServiceReferenceHolder.class);
Mockito.when(ApiMgtDAO.getInstance()).thenReturn(apiMgtDAO);
Mockito.when(apiMgtDAO.getAPIID(Mockito.any(String.class))).thenReturn(123);
Mockito.when(artifact.getId()).thenReturn("");
Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER)).thenReturn(provider);
Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT)).thenReturn("15");
Mockito.when(MultitenantUtils.getTenantDomain(provider)).thenReturn(tenantDomain);
Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
Mockito.when(tenantManager.getTenantId(tenantDomain)).thenReturn(tenantId);
String artifactPath = "";
Mockito.when(GovernanceUtils.getArtifactPath(registry, "")).thenReturn(artifactPath);
Mockito.when(registry.get(artifactPath)).thenReturn(resource);
Mockito.when(resource.getLastModified()).thenReturn(expectedAPI.getLastUpdated());
Mockito.when(resource.getCreatedTime()).thenReturn(expectedAPI.getLastUpdated());
Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigurationService);
Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
Mockito.when(apiManagerConfiguration.getThrottleProperties()).thenReturn(throttleProperties);
Mockito.when(apiMgtDAO.getSubscriptionPolicies(tenantId)).thenReturn(policies);
Mockito.when(policy.getPolicyName()).thenReturn("policy");
Mockito.when(policy.getDefaultQuotaPolicy()).thenReturn(quotaPolicy);
Mockito.when(quotaPolicy.getLimit()).thenReturn(limit);
Mockito.when(registry.getTags(artifactPath)).thenReturn(getTagsFromSet(expectedAPI.getTags()));
HashMap<String, String> urlPatterns = getURLTemplatePattern(expectedAPI.getUriTemplates());
Mockito.when(apiMgtDAO.getURITemplatesPerAPIAsString(Mockito.any(String.class))).thenReturn(urlPatterns);
CORSConfiguration corsConfiguration = expectedAPI.getCorsConfiguration();
Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_HEADERS)).thenReturn(corsConfiguration.getAccessControlAllowHeaders().toString());
Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_METHODS)).thenReturn(corsConfiguration.getAccessControlAllowMethods().toString());
Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_ORIGIN)).thenReturn(corsConfiguration.getAccessControlAllowOrigins().toString());
Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG)).thenReturn("{\"production_endpoints\":{\"url\":\"http://www.mocky.io/v2/5b21fe0f2e00002a00e313fe\"," + "\"config\":null,\"template_not_supported\":false}," + "\"sandbox_endpoints\":{\"url\":\"http://www.mocky.io/v2/5b21fe0f2e00002a00e313fe\"," + "\"config\":null,\"template_not_supported\":false},\"endpoint_type\":\"http\"}");
API api = APIUtil.getAPIForPublishing(artifact, registry);
Assert.assertNotNull(api);
Set<String> testEnvironmentList = new HashSet<String>();
testEnvironmentList.add("PRODUCTION");
testEnvironmentList.add("SANDBOX");
Assert.assertThat(SetUtils.isEqualSet(api.getEnvironmentList(), testEnvironmentList), is(true));
}
use of org.wso2.carbon.apimgt.api.model.subscription.SubscriptionPolicy in project carbon-apimgt by wso2.
the class APIUtilTest method testGetAPIWithGovernanceArtifactAdvancedThrottlingDisabled.
@Test
public void testGetAPIWithGovernanceArtifactAdvancedThrottlingDisabled() throws Exception {
System.setProperty("carbon.home", APIUtilTest.class.getResource("/").getFile());
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID);
API expectedAPI = getUniqueAPI();
final String provider = expectedAPI.getId().getProviderName();
final String tenantDomain = org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
final int tenantId = -1234;
System.setProperty("carbon.home", "");
File siteConfFile = new File(Thread.currentThread().getContextClassLoader().getResource("tenant-conf.json").getFile());
String tenantConfValue = FileUtils.readFileToString(siteConfFile);
GovernanceArtifact artifact = Mockito.mock(GovernanceArtifact.class);
Registry registry = Mockito.mock(Registry.class);
ApiMgtDAO apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
Resource resource = Mockito.mock(Resource.class);
ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
RealmService realmService = Mockito.mock(RealmService.class);
TenantManager tenantManager = Mockito.mock(TenantManager.class);
APIManagerConfigurationService apiManagerConfigurationService = Mockito.mock(APIManagerConfigurationService.class);
APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
ThrottleProperties throttleProperties = Mockito.mock(ThrottleProperties.class);
SubscriptionPolicy policy = Mockito.mock(SubscriptionPolicy.class);
SubscriptionPolicy[] policies = new SubscriptionPolicy[] { policy };
QuotaPolicy quotaPolicy = Mockito.mock(QuotaPolicy.class);
RequestCountLimit limit = Mockito.mock(RequestCountLimit.class);
RegistryService registryService = Mockito.mock(RegistryService.class);
UserRegistry userRegistry = Mockito.mock(UserRegistry.class);
APIMConfigService apimConfigService = Mockito.mock(APIMConfigService.class);
Mockito.when(serviceReferenceHolder.getApimConfigService()).thenReturn(apimConfigService);
Mockito.when(apimConfigService.getTenantConfig(tenantDomain)).thenReturn(tenantConfValue);
PowerMockito.mockStatic(ApiMgtDAO.class);
PowerMockito.mockStatic(GovernanceUtils.class);
PowerMockito.mockStatic(MultitenantUtils.class);
PowerMockito.mockStatic(ServiceReferenceHolder.class);
Mockito.when(ApiMgtDAO.getInstance()).thenReturn(apiMgtDAO);
Mockito.when(apiMgtDAO.getAPIID(Mockito.any(String.class))).thenReturn(123);
Mockito.when(apiMgtDAO.getPolicyNames(PolicyConstants.POLICY_LEVEL_SUB, provider)).thenReturn(new String[] { "Unlimited" });
Mockito.when(artifact.getId()).thenReturn("");
Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER)).thenReturn(provider);
Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT)).thenReturn("15");
Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_TIER)).thenReturn("Unlimited");
Mockito.when(MultitenantUtils.getTenantDomain(provider)).thenReturn(tenantDomain);
Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
Mockito.when(tenantManager.getTenantId(tenantDomain)).thenReturn(tenantId);
Mockito.when(registryService.getConfigSystemRegistry(tenantId)).thenReturn(userRegistry);
String artifactPath = "";
Mockito.when(GovernanceUtils.getArtifactPath(registry, "")).thenReturn(artifactPath);
Mockito.when(registry.get(artifactPath)).thenReturn(resource);
Mockito.when(resource.getLastModified()).thenReturn(expectedAPI.getLastUpdated());
Mockito.when(resource.getCreatedTime()).thenReturn(expectedAPI.getLastUpdated());
Mockito.when(resource.getContent()).thenReturn(tenantConfValue.getBytes());
Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigurationService);
Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
Mockito.when(apiManagerConfiguration.getThrottleProperties()).thenReturn(throttleProperties);
Mockito.when(apiMgtDAO.getSubscriptionPolicies(tenantId)).thenReturn(policies);
Mockito.when(policy.getDefaultQuotaPolicy()).thenReturn(quotaPolicy);
Mockito.when(quotaPolicy.getLimit()).thenReturn(limit);
Mockito.when(registry.getTags(artifactPath)).thenReturn(getTagsFromSet(expectedAPI.getTags()));
ArrayList<URITemplate> urlList = getURLTemplateList(expectedAPI.getUriTemplates());
Mockito.when(apiMgtDAO.getAllURITemplates(Mockito.anyString(), Mockito.anyString())).thenReturn(urlList);
CORSConfiguration corsConfiguration = expectedAPI.getCorsConfiguration();
Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_HEADERS)).thenReturn(corsConfiguration.getAccessControlAllowHeaders().toString());
Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_METHODS)).thenReturn(corsConfiguration.getAccessControlAllowMethods().toString());
Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_ORIGIN)).thenReturn(corsConfiguration.getAccessControlAllowOrigins().toString());
API api = APIUtil.getAPI(artifact);
Assert.assertNotNull(api);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
use of org.wso2.carbon.apimgt.api.model.subscription.SubscriptionPolicy in project carbon-apimgt by wso2.
the class APIUtilTierTest method mockPolicyRetrieval.
private void mockPolicyRetrieval(ApiMgtDAO apiMgtDAO) throws Exception {
QuotaPolicy quotaPolicy = Mockito.mock(QuotaPolicy.class);
ApplicationPolicy applicationPolicy = Mockito.mock(ApplicationPolicy.class);
SubscriptionPolicy subscriptionPolicy = Mockito.mock(SubscriptionPolicy.class);
APIPolicy apiPolicy = Mockito.mock(APIPolicy.class);
Mockito.when(applicationPolicy.getDefaultQuotaPolicy()).thenReturn(quotaPolicy);
Mockito.when(subscriptionPolicy.getDefaultQuotaPolicy()).thenReturn(quotaPolicy);
Mockito.when(apiPolicy.getDefaultQuotaPolicy()).thenReturn(quotaPolicy);
Mockito.when(apiMgtDAO.getApplicationPolicy(anyString(), anyInt())).thenReturn(applicationPolicy);
Mockito.when(apiMgtDAO.getSubscriptionPolicy(anyString(), anyInt())).thenReturn(subscriptionPolicy);
Mockito.when(apiMgtDAO.getAPIPolicy(anyString(), anyInt())).thenReturn(apiPolicy);
ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
Map<String, List<Notifier>> notifierMap = Mockito.mock(Map.class);
List<Notifier> notifierList = new ArrayList<>();
Mockito.when(notifierMap.get(any())).thenReturn(notifierList);
Mockito.when(serviceReferenceHolder.getNotifiersMap()).thenReturn(notifierMap);
APIManagerConfigurationService apiManagerConfigurationService = Mockito.mock(APIManagerConfigurationService.class);
APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
ThrottleProperties throttleProperties = Mockito.mock(ThrottleProperties.class);
Map<String, Long> defaultLimits = new HashMap<>();
Mockito.when(throttleProperties.getDefaultThrottleTierLimits()).thenReturn(defaultLimits);
Mockito.when(apiManagerConfiguration.getThrottleProperties()).thenReturn(throttleProperties);
Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigurationService);
PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
}
Aggregations