org.wso2.carbon.governance.api.util.GovernanceUtils Java Examples

The following examples show how to use org.wso2.carbon.governance.api.util.GovernanceUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: APIConsumerImplTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetAPIsWithTag() throws Exception {
    APIConsumerImpl apiConsumer = new APIConsumerImplWrapper();
    PowerMockito.doNothing().when(APIUtil.class, "loadTenantRegistry", Mockito.anyInt());
    PowerMockito.mockStatic(GovernanceUtils.class);
    GenericArtifactManager artifactManager = Mockito.mock(GenericArtifactManager.class);
    PowerMockito.when(APIUtil.getArtifactManager(apiConsumer.registry, APIConstants.API_KEY)).
            thenReturn(artifactManager);
    List<GovernanceArtifact> governanceArtifacts = new ArrayList<GovernanceArtifact>();
    GenericArtifact artifact = Mockito.mock(GenericArtifact.class);
    governanceArtifacts.add(artifact);
    Mockito.when(GovernanceUtils.findGovernanceArtifacts(Mockito.anyString(),(UserRegistry)Mockito.anyObject(),
            Mockito.anyString())).thenReturn(governanceArtifacts);
    APIIdentifier apiId1 = new APIIdentifier("admin", "API1", "1.0.0");
    API api = new API(apiId1);
    Mockito.when(APIUtil.getAPI(artifact)).thenReturn(api);
    Mockito.when(artifact.getAttribute("overview_status")).thenReturn("PUBLISHED");
    assertNotNull(apiConsumer.getAPIsWithTag("testTag", "testDomain"));
}
 
Example #2
Source File: RegistryProviderUtil.java    From product-es with Apache License 2.0 6 votes vote down vote up
public Registry getGovernanceRegistry (Registry registry, AutomationContext automationContext)
        throws Exception {

    Registry governance = null;
    TestFrameworkUtils.setKeyStoreProperties(automationContext);
    System.setProperty("carbon.repo.write.mode", "true");
    try {
        governance =
                GovernanceUtils.getGovernanceUserRegistry(registry,
                automationContext.getContextTenant().getContextUser().getUserName());

    } catch (Exception e) {
        handleException("Failed to instantiate governance registry instance ", e);
    }
    return governance;
}
 
Example #3
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Before
public void init() {
    System.setProperty(CARBON_HOME, "");
    privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);
    PowerMockito.mockStatic(GovernanceUtils.class);
    paginationContext = Mockito.mock(PaginationContext.class);
    PowerMockito.mockStatic(PaginationContext.class);
    PowerMockito.when(PaginationContext.getInstance()).thenReturn(paginationContext);
    apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
    registry = Mockito.mock(Registry.class);
    genericArtifactManager = Mockito.mock(GenericArtifactManager.class);
    registryService = Mockito.mock(RegistryService.class);
    tenantManager = Mockito.mock(TenantManager.class);
    graphQLSchemaDefinition = Mockito.mock(GraphQLSchemaDefinition.class);
    keyManager = Mockito.mock(KeyManager.class);
    PowerMockito.mockStatic(KeyManagerHolder.class);
    PowerMockito.when(KeyManagerHolder.getKeyManagerInstance("carbon.super")).thenReturn(keyManager);
}
 
Example #4
Source File: APIConsumerImplTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetPaginatedAPIsWithTag() throws Exception {
    APIConsumerImpl apiConsumer = new APIConsumerImplWrapper();
    PowerMockito.doNothing().when(APIUtil.class, "loadTenantRegistry", Mockito.anyInt());

    PowerMockito.mockStatic(GovernanceUtils.class);
    GovernanceArtifact governanceArtifact = new GenericArtifactImpl(UUID.randomUUID().toString(), new QName(UUID.randomUUID().toString(), "UUID.randomUUID().toString()"),
            "api");
    List<GovernanceArtifact> governanceArtifactList = new ArrayList();
    governanceArtifactList.add(governanceArtifact);
    Mockito.when(GovernanceUtils.findGovernanceArtifacts(Mockito.anyString(), (Registry) Mockito.anyObject(),
            Mockito.anyString())).thenReturn(governanceArtifactList);

    assertNotNull(apiConsumer.getPaginatedAPIsWithTag("testTag", 0, 10, MultitenantConstants
            .SUPER_TENANT_DOMAIN_NAME));
}
 
Example #5
Source File: APIConsumerImplTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetTagsWithAttributes() throws Exception {
    Registry userRegistry = Mockito.mock(Registry.class);
    APIConsumerImpl apiConsumer = new APIConsumerImplWrapper(userRegistry, apiMgtDAO);
    System.setProperty(CARBON_HOME, "");
    PowerMockito.mockStatic(GovernanceUtils.class);
    UserRegistry userRegistry1 = Mockito.mock(UserRegistry.class);
    Mockito.when(registryService.getGovernanceUserRegistry(Mockito.anyString(), Mockito.anyInt())).
            thenReturn(userRegistry1);
    Mockito.when(registryService.getGovernanceSystemRegistry(Mockito.anyInt())).thenReturn(userRegistry1);
    List<TermData> list = new ArrayList<TermData>();
    TermData termData = new TermData("testTerm", 10);
    list.add(termData);
    Mockito.when(GovernanceUtils.getTermDataList(Mockito.anyMap(), Mockito.anyString(), Mockito.anyString(),
            Mockito.anyBoolean())).thenReturn(list);
    ResourceDO resourceDO = Mockito.mock(ResourceDO.class);
    Resource resource = new ResourceImpl("dw", resourceDO);
    resource.setContent("testContent");
    Mockito.when(userRegistry1.resourceExists(Mockito.anyString())).thenReturn(true);
    Mockito.when(userRegistry1.get(Mockito.anyString())).thenReturn(resource);
    assertNotNull(apiConsumer.getTagsWithAttributes("testDomain"));
}
 
Example #6
Source File: CustomAPIIndexerTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Before
public void init() throws RegistryException {
    PowerMockito.mockStatic(GovernanceUtils.class);
    PowerMockito.mockStatic(IndexingManager.class);
    IndexingManager indexingManager = Mockito.mock(IndexingManager.class);
    PowerMockito.when(IndexingManager.getInstance()).thenReturn(indexingManager);
    userRegistry = Mockito.mock(UserRegistry.class);
    Mockito.doReturn(userRegistry).when(indexingManager).getRegistry(Mockito.anyInt());
    Mockito.doReturn(true).when(userRegistry).resourceExists(Mockito.anyString());
    PowerMockito.when(GovernanceUtils.getGovernanceSystemRegistry(userRegistry)).thenReturn(userRegistry);
    String path = RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + "/api";
    file2Index = new AsyncIndexer.File2Index("".getBytes(), null, path, -1234, "");
    indexer = new CustomAPIIndexer();
}
 
Example #7
Source File: EmailUserNameMigrationClient.java    From product-es with Apache License 2.0 5 votes vote down vote up
/**
 * This method extracts the artifact types which contains '@{overview_provider}' in the storage path, and call the
 * migration method.
 * @param tenant The tenant object
 * @throws UserStoreException
 * @throws RegistryException
 * @throws XMLStreamException
 */
private void migrate(Tenant tenant)
        throws UserStoreException, RegistryException, XMLStreamException{

    int tenantId = tenant.getId();
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenant.getDomain(), true);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId);
        String adminName = ServiceHolder.getRealmService().getTenantUserRealm(tenantId).getRealmConfiguration()
                .getAdminUserName();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(adminName);
        ServiceHolder.getTenantRegLoader().loadTenantRegistry(tenantId);
        Registry registry = ServiceHolder.getRegistryService().getGovernanceUserRegistry(adminName, tenantId);
        GovernanceUtils.loadGovernanceArtifacts((UserRegistry) registry);
        List<GovernanceArtifactConfiguration> configurations = GovernanceUtils.
                findGovernanceArtifactConfigurations(registry);
        for (GovernanceArtifactConfiguration governanceArtifactConfiguration : configurations) {
            String pathExpression = governanceArtifactConfiguration.getPathExpression();
            if (pathExpression.contains(Constants.OVERVIEW_PROVIDER) ||
                hasOverviewProviderElement(governanceArtifactConfiguration)) {
                String shortName = governanceArtifactConfiguration.getKey();
                GenericArtifactManager artifactManager = new GenericArtifactManager(registry, shortName);
                GenericArtifact[] artifacts = artifactManager.getAllGenericArtifacts();
                migrateArtifactsWithEmailUserName(artifacts, registry);
            }
        }
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }

}
 
Example #8
Source File: CustomAPIIndexer.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public IndexDocument getIndexedDocument(AsyncIndexer.File2Index fileData) throws SolrException, RegistryException {
    Registry registry = GovernanceUtils
            .getGovernanceSystemRegistry(IndexingManager.getInstance().getRegistry(fileData.tenantId));
    String resourcePath = fileData.path.substring(RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH.length());
    Resource resource = null;

    if (registry.resourceExists(resourcePath)) {
        resource = registry.get(resourcePath);
    }
    if (log.isDebugEnabled()) {
        log.debug("CustomAPIIndexer is currently indexing the api at path " + resourcePath);
    }

    // Here we are adding properties as fields, so that we can search the properties as we do for attributes.
    IndexDocument indexDocument = super.getIndexedDocument(fileData);
    Map<String, List<String>> fields = indexDocument.getFields();
    if (resource != null) {
        Properties properties = resource.getProperties();
        Enumeration propertyNames = properties.propertyNames();
        while (propertyNames.hasMoreElements()) {
            String property = (String) propertyNames.nextElement();
            if (log.isDebugEnabled()) {
                log.debug("API at " + resourcePath + " has " + property + " property");
            }
            if (property.startsWith(APIConstants.API_RELATED_CUSTOM_PROPERTIES_PREFIX)) {
                fields.put((OVERVIEW_PREFIX + property), getLowerCaseList(resource.getPropertyValues(property)));
                if (log.isDebugEnabled()) {
                    log.debug(property + " is added as " + (OVERVIEW_PREFIX + property) + " field for indexing");
                }
            }
        }
        indexDocument.setFields(fields);
    }
    return indexDocument;
}
 
Example #9
Source File: APIConsumerImplTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAllPaginatedAPIs() throws Exception {
    Registry userRegistry = Mockito.mock(Registry.class);
    APIConsumerImpl apiConsumer = new APIConsumerImplWrapper(userRegistry, apiMgtDAO);
    PowerMockito.mockStatic(GovernanceUtils.class);
    PowerMockito.doNothing().when(APIUtil.class, "loadTenantRegistry", Mockito.anyInt());
    PowerMockito.when(APIUtil.isAllowDisplayMultipleVersions()).thenReturn(false, true);
    UserRegistry userRegistry1 = Mockito.mock(UserRegistry.class);
    Mockito.when(registryService.getGovernanceUserRegistry(Mockito.anyString(), Mockito.anyInt())).
            thenReturn(userRegistry1);
    Mockito.when(registryService.getGovernanceSystemRegistry(Mockito.anyInt())).thenReturn(userRegistry1);
    GenericArtifactManager artifactManager = Mockito.mock(GenericArtifactManager.class);
    PowerMockito.when(APIUtil.getArtifactManager((UserRegistry)(Mockito.anyObject()), Mockito.anyString())).
            thenReturn(artifactManager);
    GenericArtifact artifact = Mockito.mock(GenericArtifact.class);
    GenericArtifact[] genericArtifacts = new GenericArtifact[]{artifact};
    Mockito.when(artifactManager.findGenericArtifacts(Mockito.anyMap())).thenReturn(genericArtifacts);
    APIIdentifier apiId1 = new APIIdentifier("admin", "API1", "1.0.0");
    API api = new API(apiId1);
    Mockito.when(APIUtil.getAPI(artifact)).thenReturn(api);
    assertNotNull(apiConsumer.getAllPaginatedAPIs(MultitenantConstants
            .SUPER_TENANT_DOMAIN_NAME, 0, 10));
    assertNotNull(apiConsumer.getAllPaginatedAPIs(MultitenantConstants
            .SUPER_TENANT_DOMAIN_NAME, 0, 10));

    //artifact manager null path
    PowerMockito.when(APIUtil.getArtifactManager((UserRegistry)(Mockito.anyObject()), Mockito.anyString())).
            thenReturn(null);
    assertNotNull(apiConsumer.getAllPaginatedAPIs(MultitenantConstants
            .SUPER_TENANT_DOMAIN_NAME, 0, 10));

    //generic artifact null path
    PowerMockito.when(APIUtil.getArtifactManager((UserRegistry)(Mockito.anyObject()), Mockito.anyString())).
            thenReturn(artifactManager);
    Mockito.when(artifactManager.findGenericArtifacts(Mockito.anyMap())).thenReturn(null);
    assertNotNull(apiConsumer.getAllPaginatedAPIs(MultitenantConstants
            .SUPER_TENANT_DOMAIN_NAME, 0, 10));
}
 
Example #10
Source File: APIConsumerImplTest.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetRecentlyAddedAPIs() throws Exception {
    Registry userRegistry = Mockito.mock(Registry.class);
    APIConsumerImpl apiConsumer = new APIConsumerImplWrapper(userRegistry, apiMgtDAO);
    UserRegistry userRegistry1 = Mockito.mock(UserRegistry.class);
    APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
    APIManagerConfigurationService apiManagerConfigurationService = Mockito.
            mock(APIManagerConfigurationService.class);
    Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigurationService);
    Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
    Mockito.when(apiManagerConfiguration.getFirstProperty(Mockito.anyString())).thenReturn("true", "false");

    API api = Mockito.mock(API.class);
    Set<API> recentlyAddedAPI = new HashSet<API>();
    recentlyAddedAPI.add(api);
    PowerMockito.mockStatic(Caching.class);

    CacheManager cacheManager = Mockito.mock(CacheManager.class);
    Cache<Object, Object> cache = Mockito.mock(Cache.class);
    Mockito.when(Caching.getCacheManager(Mockito.anyString())).thenReturn(cacheManager);
    Mockito.when(cacheManager.getCache(Mockito.anyString())).thenReturn(cache);
    Mockito.when(cache.get(Mockito.anyObject())).thenReturn(recentlyAddedAPI);
    Resource resource = new ResourceImpl();
    resource.setProperty("overview_status", "overview_status");
    resource.setProperty("store_view_roles", "store_view_roles");
    String path = "testPath";
    Mockito.when(APIUtil.getAPIPath((APIIdentifier) Mockito.anyObject())).thenReturn(path);
    Mockito.when(userRegistry1.get(Mockito.anyString())).thenReturn(resource);

    PowerMockito.mockStatic(GovernanceUtils.class);
    PowerMockito.doNothing().when(APIUtil.class, "loadTenantRegistry", Mockito.anyInt());
    PowerMockito.when(APIUtil.isAllowDisplayMultipleVersions()).thenReturn(true, false);
    System.setProperty(CARBON_HOME, "");

    Mockito.when(registryService.getGovernanceUserRegistry(Mockito.anyString(), Mockito.anyInt())).
            thenReturn(userRegistry1);
    Mockito.when(registryService.getGovernanceSystemRegistry(Mockito.anyInt())).thenReturn(userRegistry1);
    GenericArtifactManager artifactManager = Mockito.mock(GenericArtifactManager.class);
    PowerMockito.when(APIUtil.getArtifactManager((UserRegistry)(Mockito.anyObject()), Mockito.anyString())).
            thenReturn(artifactManager);
    GenericArtifact artifact = Mockito.mock(GenericArtifact.class);
    GenericArtifact[] genericArtifacts = new GenericArtifact[]{artifact};
    Mockito.when(artifactManager.findGovernanceArtifacts(Mockito.anyString())).thenReturn(genericArtifacts);

    APIIdentifier apiId1 = new APIIdentifier("admin", "API1", "1.0.0");
    API api1 = new API(apiId1);
    Mockito.when(APIUtil.getAPI(artifact)).thenReturn(api1);
    //set isAllowDisplayMultipleVersions true
    assertNotNull(apiConsumer.getRecentlyAddedAPIs(10, "testDomain"));
    //set isAllowDisplayMultipleVersions false
    assertNotNull(apiConsumer.getRecentlyAddedAPIs(10, "testDomain"));
}
 
Example #11
Source File: APIConsumerImplTest.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetPublishedAPIsByProvider1()
        throws APIManagementException, RegistryException, org.wso2.carbon.user.core.UserStoreException {
    APIConsumerImpl apiConsumer = new APIConsumerImplWrapper(userRegistry, apiMgtDAO);
    String providerId = "1";
    API api = new API(new APIIdentifier(API_PROVIDER, SAMPLE_API_NAME, SAMPLE_API_VERSION));
    API api1 = new API(new APIIdentifier(API_PROVIDER, "pizza_api", "2.0.0"));
    PowerMockito.when(APIUtil.isAllowDisplayMultipleVersions()).thenReturn(true, false);
    PowerMockito.when(APIUtil.isAllowDisplayAPIsWithMultipleStatus()).thenReturn(true, false);
    PowerMockito.when(APIUtil.getArtifactManager(userRegistry, APIConstants.API_KEY))
            .thenReturn(genericArtifactManager);
    PowerMockito.when(APIUtil.getMountedPath(Mockito.any(), Mockito.anyString())).thenReturn("system/governance");
    PowerMockito.when(APIUtil.getAPI(Mockito.any())).thenReturn(api);
    PowerMockito.when(APIUtil.replaceEmailDomainBack(Mockito.anyString())).thenReturn(providerId);
    PowerMockito.when(APIUtil.getLcStateFromArtifact((GovernanceArtifact) Mockito.any()))
            .thenReturn(APIConstants.PUBLISHED);
    GenericArtifact genericArtifact1 = new GenericArtifactImpl(new QName("local"), "artifact1");
    GenericArtifact genericArtifact2 = new GenericArtifactImpl(new QName("local"), "artifact2");
    GenericArtifact[] genericArtifacts = new GenericArtifact[] { genericArtifact1, genericArtifact2 };
    Mockito.when(genericArtifactManager.findGenericArtifacts((Map<String, List<String>>) Mockito.any()))
            .thenThrow(GovernanceException.class).thenReturn(genericArtifacts);
    PowerMockito.mockStatic(GovernanceUtils.class);
    PowerMockito.when(GovernanceUtils.getArtifactPath(Mockito.any(), Mockito.anyString())).thenReturn("/path1");
    PowerMockito.when(RegistryUtils.getAbsolutePath(Mockito.any(), Mockito.anyString())).thenReturn("/path1");
    Assert.assertNull(apiConsumer.getPublishedAPIsByProvider("1", "test_user", 5, API_PROVIDER, "John"));
    Assert.assertEquals(0,
            apiConsumer.getPublishedAPIsByProvider("1", "test_user", 5, API_PROVIDER, "John").size());
    Mockito.when(
            authorizationManager.isUserAuthorized(Mockito.anyString(), Mockito.anyString(), Mockito.anyString()))
            .thenReturn(true);
    Resource resource = new ResourceImpl();
    resource.setUUID(UUID.randomUUID().toString());
    Mockito.when(userRegistry.get(Mockito.anyString())).thenReturn(resource);
    GenericArtifact genericArtifact = Mockito.mock(GenericArtifactImpl.class);
    Mockito.when(genericArtifactManager.getGenericArtifact(Mockito.anyString())).thenReturn(genericArtifact);
    Assert.assertEquals(1,
            apiConsumer.getPublishedAPIsByProvider("1", "test_user", 1, API_PROVIDER, "John").size());
    api.setVisibility("specific_to_roles");
    PowerMockito.when(MultitenantUtils.getTenantDomain(Mockito.anyString()))
            .thenReturn("carbon.super", "carbon.super", SAMPLE_TENANT_DOMAIN_1);
    PowerMockito.when(APIUtil.getAPI((GenericArtifact) Mockito.any())).thenReturn(api, api1);
    Assert.assertEquals(1,
            apiConsumer.getPublishedAPIsByProvider("1", "test_user", 5, API_PROVIDER, "John").size());
    Mockito.when(
            authorizationManager.isRoleAuthorized(Mockito.anyString(), Mockito.anyString(), Mockito.anyString()))
            .thenReturn(true);
    Assert.assertEquals(1, apiConsumer.getPublishedAPIsByProvider("1", "", 5, API_PROVIDER, "John").size());

}
 
Example #12
Source File: APIConsumerImplTest.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetAllPaginatedAPIsByStatusSet() throws Exception {
    Registry userRegistry = Mockito.mock(Registry.class);
    APIConsumerImpl apiConsumer = new APIConsumerImplWrapper(userRegistry, apiMgtDAO);
    PowerMockito.mockStatic(GovernanceUtils.class);
    APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
    APIManagerConfigurationService apiManagerConfigurationService = Mockito.
            mock(APIManagerConfigurationService.class);
    Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigurationService);
    Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
    Mockito.when(apiManagerConfiguration.getFirstProperty(Mockito.anyString())).thenReturn("10", "20");

    PowerMockito.doNothing().when(APIUtil.class, "loadTenantRegistry", Mockito.anyInt());
    GenericArtifactManager artifactManager = Mockito.mock(GenericArtifactManager.class);
    PowerMockito.when(APIUtil.isAllowDisplayMultipleVersions()).thenReturn(false, true);
    PowerMockito.when(APIUtil.getArtifactManager((UserRegistry)(Mockito.anyObject()), Mockito.anyString())).
            thenReturn(artifactManager);
    List<GovernanceArtifact> governanceArtifacts = new ArrayList<GovernanceArtifact>();
    GenericArtifact artifact = Mockito.mock(GenericArtifact.class);
    governanceArtifacts.add(artifact);
    Mockito.when(GovernanceUtils.findGovernanceArtifacts(Mockito.anyString(),(UserRegistry)Mockito.anyObject(),
            Mockito.anyString())).thenReturn(governanceArtifacts);
    APIIdentifier apiId1 = new APIIdentifier("admin", "API1", "1.0.0");
    API api = new API(apiId1);
    Mockito.when(APIUtil.getAPI(artifact)).thenReturn(api);
    String artifactPath = "artifact/path";
    PowerMockito.when(GovernanceUtils.getArtifactPath(userRegistry, artifact.getId())).
            thenReturn(artifactPath);
    Tag tag = new Tag();
    Tag[] tags = new Tag[]{tag};
    Mockito.when(userRegistry.getTags(artifactPath)).thenReturn(tags);
    assertNotNull(apiConsumer.getAllPaginatedAPIsByStatus(MultitenantConstants
            .SUPER_TENANT_DOMAIN_NAME, 0, 10, new String[]{"testStatus"}, false));
    assertNotNull(apiConsumer.getAllPaginatedAPIsByStatus(MultitenantConstants
            .SUPER_TENANT_DOMAIN_NAME, 0, 10, new String[]{"testStatus"}, true));

    //artifact manager null path
    PowerMockito.when(APIUtil.getArtifactManager((UserRegistry)(Mockito.anyObject()), Mockito.anyString())).
            thenReturn(null);
    assertNotNull(apiConsumer.getAllPaginatedAPIsByStatus(MultitenantConstants
            .SUPER_TENANT_DOMAIN_NAME, 0, 10, new String[]{"testStatus"}, true));

    //generic artifact null path
    PowerMockito.when(APIUtil.getArtifactManager((UserRegistry)(Mockito.anyObject()), Mockito.anyString())).
            thenReturn(artifactManager);
    Mockito.when(GovernanceUtils.findGovernanceArtifacts(Mockito.anyString(),(UserRegistry)Mockito.anyObject(),
            Mockito.anyString())).thenReturn(null);
    assertNotNull(apiConsumer.getAllPaginatedAPIsByStatus(MultitenantConstants
            .SUPER_TENANT_DOMAIN_NAME, 0, 10, new String[]{"testStatus"}, true));
}
 
Example #13
Source File: APIUtilTest.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetAPIInformation() throws Exception {
    GovernanceArtifact artifact = Mockito.mock(GovernanceArtifact.class);
    Registry registry = Mockito.mock(Registry.class);
    Resource resource = Mockito.mock(Resource.class);

    API expectedAPI = getUniqueAPI();

    String artifactPath = "";
    PowerMockito.mockStatic(GovernanceUtils.class);
    Mockito.when(GovernanceUtils.getArtifactPath(registry, expectedAPI.getUUID())).thenReturn(artifactPath);
    Mockito.when(registry.get(artifactPath)).thenReturn(resource);
    Mockito.when(resource.getLastModified()).thenReturn(expectedAPI.getLastUpdated());

    DateFormat df = new SimpleDateFormat("E MMM dd HH:mm:ss zzz yyyy", Locale.US);
    Date createdTime = df.parse(expectedAPI.getCreatedTime());
    Mockito.when(resource.getCreatedTime()).thenReturn(createdTime);

    ServiceReferenceHolderMockCreator holderMockCreator = new ServiceReferenceHolderMockCreator(1);
    APIManagerConfiguration apimConfiguration = holderMockCreator.getConfigurationServiceMockCreator().
            getConfigurationMockCreator().getMock();

    CORSConfiguration corsConfiguration = expectedAPI.getCorsConfiguration();

    Mockito.when(apimConfiguration.getFirstProperty(APIConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_HEADERS)).
            thenReturn(corsConfiguration.getAccessControlAllowHeaders().toString());
    Mockito.when(apimConfiguration.getFirstProperty(APIConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_METHODS)).
            thenReturn(corsConfiguration.getAccessControlAllowMethods().toString());
    Mockito.when(apimConfiguration.getFirstProperty(APIConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_ORIGIN)).
            thenReturn(corsConfiguration.getAccessControlAllowOrigins().toString());


    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER)).
            thenReturn(expectedAPI.getId().getProviderName());
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_NAME)).
            thenReturn(expectedAPI.getId().getApiName());
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION)).
            thenReturn(expectedAPI.getId().getVersion());
    Mockito.when(artifact.getId()).thenReturn(expectedAPI.getUUID());

    API api = APIUtil.getAPIInformation(artifact, registry);

    Assert.assertEquals(expectedAPI.getId(), api.getId());
    Assert.assertEquals(expectedAPI.getUUID(), api.getUUID());

    Mockito.verify(artifact, Mockito.atLeastOnce()).getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
    Mockito.verify(artifact, Mockito.atLeastOnce()).getAttribute(APIConstants.API_OVERVIEW_NAME);
    Mockito.verify(artifact, Mockito.atLeastOnce()).getAttribute(APIConstants.API_OVERVIEW_VERSION);
    Mockito.verify(artifact, Mockito.atLeastOnce()).getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL);
    Mockito.verify(artifact, Mockito.atLeastOnce()).getLifecycleState();
    Mockito.verify(artifact, Mockito.atLeastOnce()).getAttribute(APIConstants.API_OVERVIEW_CONTEXT);
    Mockito.verify(artifact, Mockito.atLeastOnce()).getAttribute(APIConstants.API_OVERVIEW_VISIBILITY);
    Mockito.verify(artifact, Mockito.atLeastOnce()).getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES);
    Mockito.verify(artifact, Mockito.atLeastOnce()).getAttribute(APIConstants.API_OVERVIEW_VISIBLE_TENANTS);
    Mockito.verify(artifact, Mockito.atLeastOnce()).getAttribute(APIConstants.API_OVERVIEW_TRANSPORTS);
    Mockito.verify(artifact, Mockito.atLeastOnce()).getAttribute(APIConstants.API_OVERVIEW_INSEQUENCE);
    Mockito.verify(artifact, Mockito.atLeastOnce()).getAttribute(APIConstants.API_OVERVIEW_OUTSEQUENCE);
    Mockito.verify(artifact, Mockito.atLeastOnce()).getAttribute(APIConstants.API_OVERVIEW_FAULTSEQUENCE);
    Mockito.verify(artifact, Mockito.atLeastOnce()).getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION);
    Mockito.verify(artifact, Mockito.atLeastOnce()).getAttribute(APIConstants.API_OVERVIEW_REDIRECT_URL);
    Mockito.verify(artifact, Mockito.atLeastOnce()).getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER);
    Mockito.verify(artifact, Mockito.atLeastOnce()).getAttribute(APIConstants.API_OVERVIEW_OWNER);
    Mockito.verify(artifact, Mockito.atLeastOnce()).getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY);
    Mockito.verify(artifact, Mockito.atLeastOnce()).getAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS);
}
 
Example #14
Source File: APIUtilTest.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetAPI() 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(MultitenantUtils.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    Mockito.when(ApiMgtDAO.getInstance()).thenReturn(apiMgtDAO);
    Mockito.when(apiMgtDAO.getAPIID(Mockito.any(APIIdentifier.class), eq((Connection) null))).thenReturn(123);
    Mockito.when(artifact.getId()).thenReturn("");
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER)).thenReturn(provider);
    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 = "";
    PowerMockito.mockStatic(GovernanceUtils.class);
    Mockito.when(GovernanceUtils.getArtifactPath(registry, "")).thenReturn(artifactPath);
    Mockito.when(registry.get(artifactPath)).thenReturn(resource);
    Mockito.when(resource.getLastModified()).thenReturn(expectedAPI.getLastUpdated());
    Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigurationService);
    Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
    Mockito.when(apiManagerConfiguration.getThrottleProperties()).thenReturn(throttleProperties);
    Mockito.when(throttleProperties.isEnabled()).thenReturn(true);
    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(APIIdentifier.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());

    API api = APIUtil.getAPI(artifact, registry);

    Assert.assertNotNull(api);
}
 
Example #15
Source File: APIUtilTest.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@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(APIIdentifier.class), eq((Connection) null))).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(throttleProperties.isEnabled()).thenReturn(true);
    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(APIIdentifier.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));
}
 
Example #16
Source File: APIUtilTest.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@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(APIIdentifier.class), eq((Connection) null))).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);
        Mockito.when(userRegistry.resourceExists(APIConstants.API_TENANT_CONF_LOCATION)).thenReturn(true);
        Mockito.when(userRegistry.get(APIConstants.API_TENANT_CONF_LOCATION)).thenReturn(resource);

        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(throttleProperties.isEnabled()).thenReturn(true);
        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();
    }
}
 
Example #17
Source File: APIUtilTest.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@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);

    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(APIIdentifier.class), eq((Connection) null))).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);
    Mockito.when(userRegistry.resourceExists(APIConstants.API_TENANT_CONF_LOCATION)).thenReturn(true);
    Mockito.when(userRegistry.get(APIConstants.API_TENANT_CONF_LOCATION)).thenReturn(resource);

    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(throttleProperties.isEnabled()).thenReturn(false);
    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();
    }
}
 
Example #18
Source File: APIConsumerImplTest.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetAllPaginatedAPIsByStatus() throws Exception {
    Registry userRegistry = Mockito.mock(Registry.class);
    APIConsumerImpl apiConsumer = new APIConsumerImplWrapper(userRegistry, apiMgtDAO);
    System.setProperty(CARBON_HOME, "");

    APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
    APIManagerConfigurationService apiManagerConfigurationService = Mockito.
            mock(APIManagerConfigurationService.class);
    Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigurationService);
    Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
    Mockito.when(apiManagerConfiguration.getFirstProperty(Mockito.anyString())).thenReturn("10", "20");

    PowerMockito.mockStatic(GovernanceUtils.class);
    PowerMockito.mockStatic(GovernanceUtils.class);
    PowerMockito.doNothing().when(APIUtil.class, "loadTenantRegistry", Mockito.anyInt());
    GenericArtifactManager artifactManager = Mockito.mock(GenericArtifactManager.class);
    PowerMockito.when(APIUtil.isAllowDisplayMultipleVersions()).thenReturn(false, true);
    PowerMockito.when(APIUtil.getArtifactManager((UserRegistry)(Mockito.anyObject()), Mockito.anyString())).
            thenReturn(artifactManager);
    GenericArtifact artifact = Mockito.mock(GenericArtifact.class);
    GenericArtifact[] genericArtifacts = new GenericArtifact[]{artifact};
    Mockito.when(artifactManager.findGenericArtifacts(Mockito.anyMap())).thenReturn(genericArtifacts);
    APIIdentifier apiId1 = new APIIdentifier("admin", "API1", "1.0.0");
    API api = new API(apiId1);
    Mockito.when(APIUtil.getAPI(artifact)).thenReturn(api);
    String artifactPath = "artifact/path";
    PowerMockito.when(GovernanceUtils.getArtifactPath(userRegistry, artifact.getId())).
            thenReturn(artifactPath);
    Tag tag = new Tag();
    Tag[] tags = new Tag[]{tag};
    Mockito.when(userRegistry.getTags(artifactPath)).thenReturn(tags);
    assertNotNull(apiConsumer.getAllPaginatedAPIsByStatus(MultitenantConstants
            .SUPER_TENANT_DOMAIN_NAME, 0, 10, "testStatus", false));
    assertNotNull(apiConsumer.getAllPaginatedAPIsByStatus(MultitenantConstants
            .SUPER_TENANT_DOMAIN_NAME, 0, 10, "testStatus", true));

    //artifact manager null path
    PowerMockito.when(APIUtil.getArtifactManager((UserRegistry)(Mockito.anyObject()), Mockito.anyString())).
            thenReturn(null);
    assertNotNull(apiConsumer.getAllPaginatedAPIsByStatus(MultitenantConstants
            .SUPER_TENANT_DOMAIN_NAME, 0, 10, "testStatus", true));

    //generic artifact null path
    PowerMockito.when(APIUtil.getArtifactManager((UserRegistry)(Mockito.anyObject()), Mockito.anyString())).
            thenReturn(artifactManager);
    Mockito.when(artifactManager.findGenericArtifacts(Mockito.anyMap())).thenReturn(null);
    assertNotNull(apiConsumer.getAllPaginatedAPIsByStatus(MultitenantConstants
            .SUPER_TENANT_DOMAIN_NAME, 0, 10, "testStatus", true));
}
 
Example #19
Source File: APIExecutorTestCase.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Before
public void setup() throws Exception {

    System.setProperty(CARBON_HOME, "");
    PrivilegedCarbonContext privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);
    Mockito.when(privilegedCarbonContext.getUsername()).thenReturn(USER_NAME);

    PowerMockito.mockStatic(CarbonContext.class);
    CarbonContext carbonContext = Mockito.mock(CarbonContext.class);
    PowerMockito.when(CarbonContext.getThreadLocalCarbonContext()).thenReturn(carbonContext);
    Mockito.when(carbonContext.getTenantDomain()).thenReturn(TENANT_DOMAIN);

    Mockito.when(resource.getUUID()).thenReturn(ARTIFACT_ID);
    Mockito.when(requestContext.getResource()).thenReturn(resource);
    Mockito.when(genericArtifactManager.getGenericArtifact(ARTIFACT_ID)).thenReturn(genericArtifact);
    Mockito.when(genericArtifact.getLifecycleState()).thenReturn("CREATED");

    Mockito.when(apiProvider.propergateAPIStatusChangeToGateways(apiIdentifier, APIConstants.PUBLISHED))
            .thenReturn(new HashMap<>());
    Mockito.when(apiProvider.updateAPIforStateChange(apiIdentifier, APIConstants.PUBLISHED, new HashMap<>())).thenReturn
            (true);
    Mockito.when(userRegistry.get("/apimgt/applicationdata/provider/john/pizza-shack/2.0.0/api"))
            .thenReturn(resource);

    Mockito.when(api.getId()).thenReturn(apiIdentifier);
    Mockito.when(apiIdentifier.getProviderName()).thenReturn(USER_NAME);
    Mockito.when(apiIdentifier.getApiName()).thenReturn(API_NAME);
    Mockito.when(apiIdentifier.getVersion()).thenReturn(API_VERSION);
    Mockito.when(api.getEndpointConfig()).thenReturn("http://bar.com");

    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    TestTenantManager tenantManager = new TestTenantManager();
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.when(APIUtil.getArtifactManager(requestContext.getSystemRegistry(),APIConstants.API_KEY)).thenReturn(genericArtifactManager);

    PowerMockito.when(APIUtil.replaceEmailDomainBack(tenantAwareUserName)).thenReturn(tenantAwareUserName);
    PowerMockito.when(APIUtil.replaceEmailDomain(USER_NAME)).thenReturn(USER_NAME);
    PowerMockito.when(APIUtil.getAPIPath(apiIdentifier)).thenCallRealMethod();
    PowerMockito.when(APIUtil.getLcStateFromArtifact(genericArtifact)).thenReturn("CREATED");

    Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
    Mockito.when(registryService.getGovernanceUserRegistry(USER_NAME,TENANT_ID)).thenReturn(userRegistry);

    PowerMockito.when(APIUtil.getAPI(genericArtifact)).thenReturn(api);

    PowerMockito.mockStatic(APIManagerFactory.class);
    PowerMockito.when(APIManagerFactory.getInstance()).thenReturn(apiManagerFactory);
    Mockito.when(apiManagerFactory.getAPIProvider(USER_NAME+'@'+TENANT_DOMAIN)).thenReturn(apiProvider);
    CheckListItemBean checkListItemBean1 = new CheckListItemBean();
    checkListItemBean1.setName(APIConstants.DEPRECATE_CHECK_LIST_ITEM);
    checkListItemBean1.setOrder(0);
    CheckListItemBean checkListItemBean2 = new CheckListItemBean();
    checkListItemBean2.setName(APIConstants.RESUBSCRIBE_CHECK_LIST_ITEM);
    checkListItemBean2.setOrder(1);
    CheckListItemBean[] checkListItemBeans = { checkListItemBean1, checkListItemBean2 };
    PowerMockito.mockStatic(GovernanceUtils.class);
    PowerMockito
            .when(GovernanceUtils.getAllCheckListItemBeans(resource, genericArtifact, APIConstants.API_LIFE_CYCLE))
            .thenReturn(checkListItemBeans);

    Tier tier1 = new Tier("GOLD");
    Tier tier2 = new Tier("SILVER");
    Set<Tier> hashSet = new HashSet<Tier>();
    hashSet.add(tier1);
    hashSet.add(tier2);
    Mockito.when(api.getAvailableTiers()).thenReturn(hashSet);
}
 
Example #20
Source File: AbstractAPIManager.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * Returns APIProduct Search result based on the provided query.
 *
 * @param registry
 * @param searchQuery Ex: provider=*admin*
 * @return APIProduct result
 * @throws APIManagementException
 */

public Map<String, Object> searchPaginatedAPIProducts(Registry registry, String searchQuery, int start, int end)
        throws APIManagementException {
    SortedSet<APIProduct> productSet = new TreeSet<APIProduct>(new APIProductNameComparator());
    List<APIProduct> productList = new ArrayList<APIProduct>();
    Map<String, Object> result = new HashMap<String, Object>();
    int totalLength = 0;
    boolean isMore = false;
    try {
        //for now will use the same config for api products too todo: change this
        String paginationLimit = getAPIManagerConfiguration()
                .getFirstProperty(APIConstants.API_STORE_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);

            // Because the store jaggery pagination logic is 10 results per a page we need to set pagination
            // limit to at least 11 or the pagination done at this level will conflict with the store pagination
            // leading to some of the APIs not being displayed
            if (pagination < 11) {
                pagination = 11;
                log.warn("Value of '" + APIConstants.API_STORE_APIS_PER_PAGE + "' is too low, defaulting to 11");
            }
            maxPaginationLimit = start + pagination + 1;
        }
        // Else if the config is not specified we go with default functionality and load all
        else {
            maxPaginationLimit = Integer.MAX_VALUE;
        }
        PaginationContext.init(start, end, "ASC", APIConstants.API_OVERVIEW_NAME, maxPaginationLimit);

        List<GovernanceArtifact> governanceArtifacts = GovernanceUtils
                .findGovernanceArtifacts(getSearchQuery(searchQuery), registry, APIConstants.API_RXT_MEDIA_TYPE,
                        true);
        totalLength = PaginationContext.getInstance().getLength();
        boolean isFound = true;

        if (!isFound) {
            result.put("products", productSet);
            result.put("length", 0);
            result.put("isMore", isMore);
            return result;
        }

        // Check to see if we can speculate that there are more APIs to be loaded
        if (maxPaginationLimit == totalLength) {
            isMore = true;  // More APIs exist, cannot determine total API count without incurring perf hit
            --totalLength; // Remove the additional 1 added earlier when setting max pagination limit
        }

        int tempLength = 0;
        for (GovernanceArtifact artifact : governanceArtifacts) {
            APIProduct resultAPIProduct = APIUtil.getAPIProduct(artifact, registry);
            if (resultAPIProduct != null) {
                productList.add(resultAPIProduct);
            }

            // Ensure the APIs returned matches the length, there could be an additional API
            // returned due incrementing the pagination limit when getting from registry
            tempLength++;
            if (tempLength >= totalLength) {
                break;
            }
        }

        productSet.addAll(productList);
    } catch (RegistryException e) {
        String msg = "Failed to search APIProducts with type";
        throw new APIManagementException(msg, e);
    } finally {
        PaginationContext.destroy();
    }
    result.put("products", productSet);
    result.put("length", totalLength);
    result.put("isMore", isMore);
    return result;
}