Search in sources :

Example 31 with GovernanceArtifact

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;
}
Also used : ArrayList(java.util.ArrayList) APICategory(org.wso2.carbon.apimgt.api.model.APICategory)

Example 32 with GovernanceArtifact

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();
    }
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) QuotaPolicy(org.wso2.carbon.apimgt.api.model.policy.QuotaPolicy) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager) RequestCountLimit(org.wso2.carbon.apimgt.api.model.policy.RequestCountLimit) GovernanceArtifact(org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact) Resource(org.wso2.carbon.registry.core.Resource) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) ApiMgtDAO(org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) APIUtil.getOAuthConfigurationFromTenantRegistry(org.wso2.carbon.apimgt.impl.utils.APIUtil.getOAuthConfigurationFromTenantRegistry) Registry(org.wso2.carbon.registry.core.Registry) CORSConfiguration(org.wso2.carbon.apimgt.api.model.CORSConfiguration) RealmService(org.wso2.carbon.user.core.service.RealmService) API(org.wso2.carbon.apimgt.api.model.API) File(java.io.File) APIMConfigService(org.wso2.carbon.apimgt.impl.config.APIMConfigService) ThrottleProperties(org.wso2.carbon.apimgt.impl.dto.ThrottleProperties) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 33 with GovernanceArtifact

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"));
}
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) HashMap(java.util.HashMap) GovernanceArtifact(org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) ArrayList(java.util.ArrayList) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) SortedSet(java.util.SortedSet) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) ArrayList(java.util.ArrayList) List(java.util.List) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 34 with GovernanceArtifact

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());
    }
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) PaginationContext(org.wso2.carbon.registry.core.pagination.PaginationContext) GovernanceArtifact(org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact) ArrayList(java.util.ArrayList) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) RealmService(org.wso2.carbon.user.core.service.RealmService) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) JSONObject(org.json.simple.JSONObject) ArrayList(java.util.ArrayList) List(java.util.List) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 35 with GovernanceArtifact

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;
}
Also used : GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) GovernanceArtifact(org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact) ArrayList(java.util.ArrayList) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) APINameComparator(org.wso2.carbon.apimgt.impl.utils.APINameComparator) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) JSONObject(org.json.simple.JSONObject) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)

Aggregations

API (org.wso2.carbon.apimgt.api.model.API)28 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)24 ArrayList (java.util.ArrayList)23 GovernanceArtifact (org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact)23 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)19 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)17 Registry (org.wso2.carbon.registry.core.Registry)17 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)17 GovernanceException (org.wso2.carbon.governance.api.exception.GovernanceException)16 Test (org.junit.Test)15 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)15 HashSet (java.util.HashSet)13 Resource (org.wso2.carbon.registry.core.Resource)13 GenericArtifactManager (org.wso2.carbon.governance.api.generic.GenericArtifactManager)12 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)11 JSONObject (org.json.simple.JSONObject)10 UserStoreException (org.wso2.carbon.user.api.UserStoreException)10 Tier (org.wso2.carbon.apimgt.api.model.Tier)9 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)9 RealmService (org.wso2.carbon.user.core.service.RealmService)9