use of org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact in project carbon-apimgt by wso2.
the class RegistryPersistenceUtil method getAPICategoriesFromAPIGovernanceArtifact.
/**
* This method returns the categories attached to the API
*
* @param artifact API artifact
* @param tenantID tenant ID of API Provider
* @return List<APICategory> list of categories
*/
private static List<APICategory> getAPICategoriesFromAPIGovernanceArtifact(GovernanceArtifact artifact, int tenantID) throws GovernanceException, APIManagementException {
String[] categoriesOfAPI = artifact.getAttributes(APIConstants.API_CATEGORIES_CATEGORY_NAME);
List<APICategory> categoryList = new ArrayList<>();
if (ArrayUtils.isNotEmpty(categoriesOfAPI)) {
for (String categoryName : categoriesOfAPI) {
APICategory category = new APICategory();
category.setName(categoryName);
categoryList.add(category);
}
}
return categoryList;
}
use of org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact in project carbon-apimgt by wso2.
the class APIUtilTest method testGetAPIWithGovernanceArtifact.
@Test
public void testGetAPIWithGovernanceArtifact() 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);
PrivilegedCarbonContext carbonContext = Mockito.mock(PrivilegedCarbonContext.class);
RegistryService registryService = Mockito.mock(RegistryService.class);
UserRegistry userRegistry = Mockito.mock(UserRegistry.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(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);
APIMConfigService apimConfigService = Mockito.mock(APIMConfigService.class);
Mockito.when(serviceReferenceHolder.getApimConfigService()).thenReturn(apimConfigService);
Mockito.when(apimConfigService.getTenantConfig(tenantDomain)).thenReturn(tenantConfValue);
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.governance.api.common.dataobjects.GovernanceArtifact in project carbon-apimgt by wso2.
the class AbstractAPIManagerTestCase method testSearchPaginatedAPIs.
@Test
public void testSearchPaginatedAPIs() throws APIManagementException, org.wso2.carbon.user.api.UserStoreException, RegistryException, XMLStreamException {
Map<String, Object> subContextResult = new HashMap<String, Object>();
subContextResult.put("1", new Object());
UserRegistry registry = Mockito.mock(UserRegistry.class);
AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapperExtended(null, registryService, registry, tenantManager);
Mockito.when(tenantManager.getTenantId(Mockito.anyString())).thenReturn(-1234);
Mockito.when(registryService.getGovernanceUserRegistry(Mockito.anyString(), Mockito.anyInt())).thenThrow(RegistryException.class).thenReturn(registry);
PowerMockito.mockStatic(APIUtil.class);
PowerMockito.when(APIUtil.replaceSystemProperty(Mockito.anyString())).thenAnswer((Answer<String>) invocation -> {
Object[] args = invocation.getArguments();
return (String) args[0];
});
try {
abstractAPIManager.searchPaginatedAPIs("search", API_PROVIDER, 0, 5, false);
Assert.fail("Exception not thrown for error scenario");
} catch (APIManagementException e) {
Assert.assertTrue(e.getMessage().contains("Failed to Search APIs"));
}
API api = new API(getAPIIdentifier(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION));
Documentation documentation = new Documentation(DocumentationType.HOWTO, "DOC1");
Map<Documentation, API> documentationAPIMap = new HashMap<>();
BDDMockito.when(APIUtil.searchAPIsByDoc(Mockito.any(), Mockito.anyInt(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(documentationAPIMap);
Assert.assertEquals(abstractAPIManager.searchPaginatedAPIs("doc=search", SAMPLE_TENANT_DOMAIN_1, 0, 5, false).get("length"), 0);
documentationAPIMap.put(documentation, api);
Assert.assertEquals(abstractAPIManager.searchPaginatedAPIs("doc=search", null, 0, 5, false).get("length"), 5);
// Test related with searches with custom properties
Map<String, Object> actualAPIs = abstractAPIManager.searchPaginatedAPIs("secured=*true*", SAMPLE_TENANT_DOMAIN_1, 0, 5, false);
List<API> retrievedAPIs = (List<API>) actualAPIs.get("apis");
Assert.assertEquals("Searching with additional property failed", 1, actualAPIs.get("length"));
Assert.assertNotNull("Search with additional property failed", retrievedAPIs);
Assert.assertEquals("Search with additional property failed", 1, retrievedAPIs.size());
Assert.assertEquals("Search with additional property failed", "sxy", retrievedAPIs.get(0).getId().getApiName());
actualAPIs = abstractAPIManager.searchPaginatedAPIs("name=*test*&secured=*true*", SAMPLE_TENANT_DOMAIN_1, 0, 5, false);
retrievedAPIs = (List<API>) actualAPIs.get("apis");
Assert.assertEquals("Searching with additional property failed", 1, actualAPIs.get("length"));
Assert.assertNotNull("Search with additional property failed", retrievedAPIs);
Assert.assertEquals("Search with additional property failed", 1, retrievedAPIs.size());
Assert.assertEquals("Search with additional property failed", "sxy12", retrievedAPIs.get(0).getId().getApiName());
TestUtils.mockAPIMConfiguration(APIConstants.API_STORE_APIS_PER_PAGE, null, -1234);
Assert.assertEquals(abstractAPIManager.searchPaginatedAPIs("search", null, 0, 5, false).get("length"), 0);
TestUtils.mockAPIMConfiguration(APIConstants.API_STORE_APIS_PER_PAGE, "5", -1234);
GovernanceArtifact governanceArtifact = getGenericArtifact(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION, "qname");
List<GovernanceArtifact> governanceArtifactList = new ArrayList<GovernanceArtifact>();
governanceArtifactList.add(governanceArtifact);
Assert.assertEquals(abstractAPIManager.searchPaginatedAPIs("search", null, 0, 5, false).get("length"), 0);
Assert.assertEquals(abstractAPIManager.searchPaginatedAPIs(APIConstants.API_OVERVIEW_PROVIDER, null, 0, 5, false).get("length"), 0);
BDDMockito.when(GovernanceUtils.findGovernanceArtifacts(Mockito.anyString(), Mockito.any(Registry.class), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(RegistryException.class).thenReturn(governanceArtifactList);
try {
abstractAPIManager.searchPaginatedAPIs(APIConstants.API_OVERVIEW_PROVIDER, null, 0, 5, false);
Assert.fail("APIM exception not thrown for error scenario");
} catch (APIManagementException e) {
Assert.assertTrue(e.getMessage().contains("Failed to Search APIs"));
}
API api1 = new API(getAPIIdentifier("api1", API_PROVIDER, "v1"));
BDDMockito.when(APIUtil.getAPI((GovernanceArtifact) Mockito.any(), (Registry) Mockito.any())).thenReturn(api1);
BDDMockito.when(APIUtil.getAPIIdentifierFromUUID((String) Mockito.any())).thenReturn(getAPIIdentifier("api1", API_PROVIDER, "v1"));
SortedSet<API> apiSet = (SortedSet<API>) abstractAPIManager.searchPaginatedAPIs(APIConstants.API_OVERVIEW_PROVIDER, null, 0, 5, false).get("apis");
Assert.assertEquals(apiSet.size(), 1);
Assert.assertEquals(apiSet.first().getId().getApiName(), "api1");
Assert.assertEquals(abstractAPIManager.searchPaginatedAPIs(APIConstants.API_OVERVIEW_PROVIDER, null, 0, 5, true).get("length"), 0);
PowerMockito.when(paginationContext.getLength()).thenReturn(12);
Assert.assertTrue((Boolean) abstractAPIManager.searchPaginatedAPIs(APIConstants.API_OVERVIEW_PROVIDER, null, 0, 5, true).get("isMore"));
}
use of org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact in project carbon-apimgt by wso2.
the class APIProviderImplTest method testGetAllPaginatedAPIs.
@Test
public void testGetAllPaginatedAPIs() throws RegistryException, UserStoreException, APIManagementException, XMLStreamException {
APIIdentifier apiId1 = new APIIdentifier("admin", "API1", "1.0.0");
API api1 = new API(apiId1);
api1.setContext("/test");
APIIdentifier apiId2 = new APIIdentifier("admin", "API2", "1.0.0");
API api2 = new API(apiId2);
api2.setContext("/test1");
PaginationContext paginationCtx = Mockito.mock(PaginationContext.class);
PowerMockito.when(PaginationContext.getInstance()).thenReturn(paginationCtx);
Mockito.when(paginationCtx.getLength()).thenReturn(2);
APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apimgtDAO, scopesDAO);
ServiceReferenceHolder sh = TestUtils.getServiceReferenceHolder();
RegistryService registryService = Mockito.mock(RegistryService.class);
PowerMockito.when(sh.getRegistryService()).thenReturn(registryService);
UserRegistry userReg = Mockito.mock(UserRegistry.class);
PowerMockito.when(registryService.getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, -1234)).thenReturn(userReg);
PowerMockito.when(APIUtil.getArtifactManager(userReg, APIConstants.API_KEY)).thenReturn(artifactManager);
APIManagerConfigurationService amConfigService = Mockito.mock(APIManagerConfigurationService.class);
APIManagerConfiguration amConfig = Mockito.mock(APIManagerConfiguration.class);
PowerMockito.when(sh.getAPIManagerConfigurationService()).thenReturn(amConfigService);
PowerMockito.when(amConfigService.getAPIManagerConfiguration()).thenReturn(amConfig);
PowerMockito.when(amConfig.getFirstProperty(APIConstants.API_PUBLISHER_APIS_PER_PAGE)).thenReturn("2");
RealmService realmService = Mockito.mock(RealmService.class);
TenantManager tm = Mockito.mock(TenantManager.class);
PowerMockito.when(sh.getRealmService()).thenReturn(realmService);
PowerMockito.when(realmService.getTenantManager()).thenReturn(tm);
PowerMockito.when(tm.getTenantId("carbon.super")).thenReturn(-1234);
GenericArtifact genericArtifact1 = Mockito.mock(GenericArtifact.class);
GenericArtifact genericArtifact2 = Mockito.mock(GenericArtifact.class);
Mockito.when(APIUtil.getAPI(genericArtifact1)).thenReturn(api1);
Mockito.when(APIUtil.getAPI(genericArtifact2)).thenReturn(api2);
List<GovernanceArtifact> governanceArtifacts = new ArrayList<GovernanceArtifact>();
governanceArtifacts.add(genericArtifact1);
governanceArtifacts.add(genericArtifact2);
List<GovernanceArtifact> governanceArtifacts1 = new ArrayList<GovernanceArtifact>();
PowerMockito.when(GovernanceUtils.findGovernanceArtifacts(Mockito.anyMap(), any(Registry.class), Mockito.anyString())).thenReturn(governanceArtifacts, governanceArtifacts1);
Map<String, Object> result = apiProvider.getAllPaginatedAPIs("carbon.super", 0, 10);
List<API> apiList = (List<API>) result.get("apis");
Assert.assertEquals(2, apiList.size());
Assert.assertEquals("API1", apiList.get(0).getId().getApiName());
Assert.assertEquals("API2", apiList.get(1).getId().getApiName());
Assert.assertEquals(2, result.get("totalLength"));
// No APIs available
Map<String, Object> result1 = apiProvider.getAllPaginatedAPIs("carbon.super", 0, 10);
List<API> apiList1 = (List<API>) result1.get("apis");
Assert.assertEquals(0, apiList1.size());
// Registry Exception while retrieving artifacts
Mockito.when(artifactManager.findGenericArtifacts(Matchers.anyMap())).thenThrow(RegistryException.class);
try {
apiProvider.getAllPaginatedAPIs("carbon.super", 0, 10);
} catch (APIManagementException e) {
Assert.assertEquals("Failed to get all APIs", e.getMessage());
}
}
use of org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact in project carbon-apimgt by wso2.
the class APIProviderImpl method getAllPaginatedAPIs.
@Override
public Map<String, Object> getAllPaginatedAPIs(String tenantDomain, int start, int end) throws APIManagementException {
Map<String, Object> result = new HashMap<String, Object>();
List<API> apiSortedList = new ArrayList<API>();
int totalLength = 0;
boolean isTenantFlowStarted = false;
try {
String paginationLimit = getAPIManagerConfiguration().getFirstProperty(APIConstants.API_PUBLISHER_APIS_PER_PAGE);
// If the Config exists use it to set the pagination limit
final int maxPaginationLimit;
if (paginationLimit != null) {
// The additional 1 added to the maxPaginationLimit is to help us determine if more
// APIs may exist so that we know that we are unable to determine the actual total
// API count. We will subtract this 1 later on so that it does not interfere with
// the logic of the rest of the application
int pagination = Integer.parseInt(paginationLimit);
// leading to some of the APIs not being displayed
if (pagination < 11) {
pagination = 11;
log.warn("Value of '" + APIConstants.API_PUBLISHER_APIS_PER_PAGE + "' is too low, defaulting to 11");
}
maxPaginationLimit = start + pagination + 1;
} else // Else if the config is not specifed we go with default functionality and load all
{
maxPaginationLimit = Integer.MAX_VALUE;
}
Registry userRegistry;
boolean isTenantMode = (tenantDomain != null);
if ((isTenantMode && this.tenantDomain == null) || (isTenantMode && isTenantDomainNotMatching(tenantDomain))) {
if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
isTenantFlowStarted = true;
}
int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
APIUtil.loadTenantRegistry(tenantId);
userRegistry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantId);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME);
} else {
userRegistry = registry;
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(this.username);
}
PaginationContext.init(start, end, "ASC", APIConstants.PROVIDER_OVERVIEW_NAME, maxPaginationLimit);
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(userRegistry, APIConstants.API_KEY);
if (artifactManager != null) {
List<GovernanceArtifact> genericArtifacts = null;
if (isAccessControlRestrictionEnabled && !APIUtil.hasPermission(userNameWithoutChange, APIConstants.Permissions.APIM_ADMIN)) {
genericArtifacts = GovernanceUtils.findGovernanceArtifacts(getUserRoleListQuery(), userRegistry, APIConstants.API_RXT_MEDIA_TYPE, true);
} else {
genericArtifacts = GovernanceUtils.findGovernanceArtifacts(new HashMap<String, List<String>>(), userRegistry, APIConstants.API_RXT_MEDIA_TYPE);
}
totalLength = PaginationContext.getInstance().getLength();
if (genericArtifacts == null || genericArtifacts.isEmpty()) {
result.put("apis", apiSortedList);
result.put("totalLength", totalLength);
return result;
}
// Check to see if we can speculate that there are more APIs to be loaded
if (maxPaginationLimit == totalLength) {
// performance hit
// Remove the additional 1 we added earlier when setting max pagination limit
--totalLength;
}
int tempLength = 0;
for (GovernanceArtifact artifact : genericArtifacts) {
API api = APIUtil.getAPI(artifact);
if (api != null) {
apiSortedList.add(api);
}
tempLength++;
if (tempLength >= totalLength) {
break;
}
}
Collections.sort(apiSortedList, new APINameComparator());
} else {
String errorMessage = "Failed to retrieve artifact manager when getting paginated APIs of tenant " + tenantDomain;
log.error(errorMessage);
throw new APIManagementException(errorMessage);
}
} catch (RegistryException e) {
handleException("Failed to get all APIs", e);
} catch (UserStoreException e) {
handleException("Failed to get all APIs", e);
} finally {
PaginationContext.destroy();
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
result.put("apis", apiSortedList);
result.put("totalLength", totalLength);
return result;
}
Aggregations