Search in sources :

Example 6 with APIMConfigService

use of org.wso2.carbon.apimgt.impl.config.APIMConfigService in project carbon-apimgt by wso2.

the class APIAdminImplTest method updateTenantConfigNegative3.

// valid json element missing
@Test
public void updateTenantConfigNegative3() throws Exception {
    String tenantConf = "{\"hello\":\"world\"}";
    PowerMockito.doNothing().when(APIUtil.class, "validateRestAPIScopes", tenantConf);
    APIAdmin apiAdmin = new APIAdminImpl();
    Schema schema = Mockito.mock(Schema.class);
    PowerMockito.when(APIUtil.class, "retrieveTenantConfigJsonSchema").thenReturn(schema);
    Mockito.doThrow(ValidationException.class).when(schema).validate(Mockito.any());
    Mockito.doNothing().when(apimConfigService).updateTenantConfig("abc.com", tenantConf);
    try {
        apiAdmin.updateTenantConfig("abc.com", tenantConf);
        Assert.fail("Method successfully invoked");
    } catch (APIManagementException e) {
        Assert.assertEquals(e.getMessage(), "tenant-config validation failure");
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIAdmin(org.wso2.carbon.apimgt.api.APIAdmin) Schema(org.everit.json.schema.Schema) APIUtil(org.wso2.carbon.apimgt.impl.utils.APIUtil) Test(org.junit.Test) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 7 with APIMConfigService

use of org.wso2.carbon.apimgt.impl.config.APIMConfigService in project carbon-apimgt by wso2.

the class APIManagerComponent method activate.

@Activate
protected void activate(ComponentContext componentContext) throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("API manager component activated");
    }
    try {
        BundleContext bundleContext = componentContext.getBundleContext();
        addRxtConfigs();
        addApplicationsPermissionsToRegistry();
        int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
        String filePath = CarbonUtils.getCarbonConfigDirPath() + File.separator + "api-manager.xml";
        configuration.load(filePath);
        String gatewayType = configuration.getFirstProperty(APIConstants.API_GATEWAY_TYPE);
        if (APIConstants.API_GATEWAY_TYPE_SYNAPSE.equalsIgnoreCase(gatewayType)) {
            addDefinedSequencesToRegistry();
        }
        CommonConfigDeployer configDeployer = new CommonConfigDeployer();
        bundleContext.registerService(Axis2ConfigurationContextObserver.class.getName(), configDeployer, null);
        TenantLoadMessageSender tenantLoadMessageSender = new TenantLoadMessageSender();
        bundleContext.registerService(Axis2ConfigurationContextObserver.class.getName(), tenantLoadMessageSender, null);
        KeyMgtConfigDeployer keyMgtConfigDeployer = new KeyMgtConfigDeployer();
        bundleContext.registerService(Axis2ConfigurationContextObserver.class.getName(), keyMgtConfigDeployer, null);
        // Registering Notifiers
        bundleContext.registerService(Notifier.class.getName(), new SubscriptionsNotifier(), null);
        bundleContext.registerService(Notifier.class.getName(), new ApisNotifier(), null);
        bundleContext.registerService(Notifier.class.getName(), new ApplicationNotifier(), null);
        bundleContext.registerService(Notifier.class.getName(), new ApplicationRegistrationNotifier(), null);
        bundleContext.registerService(Notifier.class.getName(), new PolicyNotifier(), null);
        bundleContext.registerService(Notifier.class.getName(), new DeployAPIInGatewayNotifier(), null);
        bundleContext.registerService(Notifier.class.getName(), new ScopesNotifier(), null);
        bundleContext.registerService(Notifier.class.getName(), new CertificateNotifier(), null);
        bundleContext.registerService(Notifier.class.getName(), new GoogleAnalyticsNotifier(), null);
        bundleContext.registerService(Notifier.class.getName(), new ExternalGatewayNotifier(), null);
        bundleContext.registerService(Notifier.class.getName(), new ExternallyDeployedApiNotifier(), null);
        APIManagerConfigurationServiceImpl configurationService = new APIManagerConfigurationServiceImpl(configuration);
        ServiceReferenceHolder.getInstance().setAPIManagerConfigurationService(configurationService);
        APIMgtDBUtil.initialize();
        APIMConfigService apimConfigService = new APIMConfigServiceImpl();
        bundleContext.registerService(APIMConfigService.class.getName(), apimConfigService, null);
        APIUtil.loadAndSyncTenantConf(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        APIUtil.loadTenantExternalStoreConfig(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        APIUtil.loadTenantGAConfig(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        APIUtil.loadTenantWorkFlowExtensions(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        // load self sigup configuration to the registry
        APIUtil.loadTenantSelfSignUpConfigurations(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        APIUtil.loadCommonOperationPolicies(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        APIManagerAnalyticsConfiguration analyticsConfiguration = APIManagerAnalyticsConfiguration.getInstance();
        analyticsConfiguration.setAPIManagerConfiguration(configuration);
        registration = componentContext.getBundleContext().registerService(APIManagerConfigurationService.class.getName(), configurationService, null);
        KeyManagerConfigurationServiceImpl keyManagerConfigurationService = new KeyManagerConfigurationServiceImpl();
        registration = componentContext.getBundleContext().registerService(KeyManagerConfigurationService.class, keyManagerConfigurationService, null);
        JWTValidationService jwtValidationService = new JWTValidationServiceImpl();
        registration = componentContext.getBundleContext().registerService(JWTValidationService.class, jwtValidationService, null);
        ServiceReferenceHolder.getInstance().setKeyManagerConfigurationService(keyManagerConfigurationService);
        APIStatusObserverList.getInstance().init(configuration);
        log.debug("Reading Analytics Configuration from file...");
        // This method is called in two places. Mostly by the time activate hits,
        // ServiceDataPublisherAdmin is not activated. Therefore, this same method is run,
        // when ServiceDataPublisherAdmin is set.
        AuthorizationUtils.addAuthorizeRoleListener(APIConstants.AM_CREATOR_APIMGT_EXECUTION_ID, RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + APIConstants.API_APPLICATION_DATA_LOCATION), APIConstants.Permissions.API_CREATE, UserMgtConstants.EXECUTE_ACTION, null);
        AuthorizationUtils.addAuthorizeRoleListener(APIConstants.AM_CREATOR_GOVERNANCE_EXECUTION_ID, RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + "/trunk"), APIConstants.Permissions.API_CREATE, UserMgtConstants.EXECUTE_ACTION, null);
        AuthorizationUtils.addAuthorizeRoleListener(APIConstants.AM_PUBLISHER_APIMGT_EXECUTION_ID, RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + APIConstants.API_APPLICATION_DATA_LOCATION), APIConstants.Permissions.API_PUBLISH, UserMgtConstants.EXECUTE_ACTION, null);
        // Enabling API Publishers/Creators to make changes on life-cycle history.
        AuthorizationUtils.addAuthorizeRoleListener(APIConstants.AM_CREATOR_LIFECYCLE_EXECUTION_ID, RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + APIConstants.API_LIFE_CYCLE_HISTORY), APIConstants.Permissions.API_CREATE, UserMgtConstants.EXECUTE_ACTION, null);
        AuthorizationUtils.addAuthorizeRoleListener(APIConstants.AM_PUBLISHER_LIFECYCLE_EXECUTION_ID, RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + APIConstants.API_LIFE_CYCLE_HISTORY), APIConstants.Permissions.API_PUBLISH, UserMgtConstants.EXECUTE_ACTION, null);
        setupImagePermissions();
        GatewayArtifactsMgtDBUtil.initialize();
        configureEventPublisherProperties();
        configureNotificationEventPublisher();
        // Load initially available api contexts at the server startup. This Cache is only use by the products other than the api-manager
        /* TODO: Load Config values from apimgt.core*/
        boolean apiManagementEnabled = APIUtil.isAPIManagementEnabled();
        boolean loadAPIContextsAtStartup = APIUtil.isLoadAPIContextsAtStartup();
        if (apiManagementEnabled && loadAPIContextsAtStartup) {
            List<String> contextList = ApiMgtDAO.getInstance().getAllAvailableContexts();
            Cache contextCache = APIUtil.getAPIContextCache();
            for (String context : contextList) {
                contextCache.put(context, Boolean.TRUE);
            }
        }
        try {
            APIUtil.createDefaultRoles(MultitenantConstants.SUPER_TENANT_ID);
        } catch (APIManagementException e) {
            log.error("Failed create default roles for tenant " + MultitenantConstants.SUPER_TENANT_ID, e);
        } catch (Exception e) {
            // The generic Exception is handled explicitly so execution does not stop during config deployment
            log.error("Exception when creating default roles for tenant " + MultitenantConstants.SUPER_TENANT_ID, e);
        }
        // Adding default throttle policies
        addDefaultAdvancedThrottlePolicies();
        // Update all NULL THROTTLING_TIER values to Unlimited
        boolean isNullThrottlingTierConversionEnabled = APIUtil.updateNullThrottlingTierAtStartup();
        try {
            if (isNullThrottlingTierConversionEnabled) {
                ApiMgtDAO.getInstance().convertNullThrottlingTiers();
            }
        } catch (APIManagementException e) {
            log.error("Failed to convert NULL THROTTLING_TIERS to Unlimited");
        }
        // // Initialise KeyManager.
        // KeyManagerHolder.initializeKeyManager(configuration);
        // Initialise sql constants
        SQLConstantManagerFactory.initializeSQLConstantManager();
        // Initialize PasswordResolver
        PasswordResolverFactory.initializePasswordResolver();
        APIUtil.init();
        // Activating UserPostSelfRegistration handler componeAPITemplateBuilderImplnt
        try {
            registration = componentContext.getBundleContext().registerService(AbstractEventHandler.class.getName(), new UserPostSelfRegistrationHandler(), null);
        } catch (Exception e) {
            log.error("Error while activating UserPostSelfRegistration handler component.", e);
        }
        // Read the trust store
        ServerConfiguration config = CarbonUtils.getServerConfiguration();
        // Initialize product REST API token caches
        CacheProvider.createRESTAPITokenCache();
        CacheProvider.createRESTAPIInvalidTokenCache();
        CacheProvider.createGatewayJWTTokenCache();
        CacheProvider.createTenantConfigCache();
        CacheProvider.createRecommendationsCache();
        CacheProvider.createParsedSignJWTCache();
        CacheProvider.createGatewayBasicAuthResourceCache();
        CacheProvider.createGatewayUsernameCache();
        CacheProvider.createIntrospectionCache();
        // Initialize Recommendation wso2event output publisher
        configureRecommendationEventPublisherProperties();
        setupAccessTokenGenerator();
        retrieveAndSetParentTrustStore();
        if (configuration.getGatewayArtifactSynchronizerProperties().isRetrieveFromStorageEnabled()) {
            if (APIConstants.GatewayArtifactSynchronizer.DB_RETRIEVER_NAME.equals(configuration.getGatewayArtifactSynchronizerProperties().getRetrieverName())) {
                bundleContext.registerService(ArtifactRetriever.class.getName(), new DBRetriever(), null);
            }
        }
        bundleContext.registerService(ScopeValidator.class, new SystemScopesIssuer(), null);
    } catch (APIManagementException e) {
        log.error("Error while initializing the API manager component", e);
    } catch (APIManagerDatabaseException e) {
        log.fatal("Error while Creating the database", e);
    }
}
Also used : CertificateNotifier(org.wso2.carbon.apimgt.impl.notifier.CertificateNotifier) ExternalGatewayNotifier(org.wso2.carbon.apimgt.impl.notifier.ExternalGatewayNotifier) JWTValidationService(org.wso2.carbon.apimgt.impl.jwt.JWTValidationService) OAuthServerConfiguration(org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration) ServerConfiguration(org.wso2.carbon.base.ServerConfiguration) ApplicationNotifier(org.wso2.carbon.apimgt.impl.notifier.ApplicationNotifier) APIManagerDatabaseException(org.wso2.carbon.apimgt.api.APIManagerDatabaseException) KeyManagerConfigurationServiceImpl(org.wso2.carbon.apimgt.impl.keymgt.KeyManagerConfigurationServiceImpl) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) KeyManagerConfigurationService(org.wso2.carbon.apimgt.impl.keymgt.KeyManagerConfigurationService) SubscriptionsNotifier(org.wso2.carbon.apimgt.impl.notifier.SubscriptionsNotifier) DBRetriever(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.DBRetriever) KeyMgtConfigDeployer(org.wso2.carbon.apimgt.impl.observers.KeyMgtConfigDeployer) ApplicationRegistrationNotifier(org.wso2.carbon.apimgt.impl.notifier.ApplicationRegistrationNotifier) ExternallyDeployedApiNotifier(org.wso2.carbon.apimgt.impl.notifier.ExternallyDeployedApiNotifier) GoogleAnalyticsNotifier(org.wso2.carbon.apimgt.impl.notifier.GoogleAnalyticsNotifier) SubscriptionsNotifier(org.wso2.carbon.apimgt.impl.notifier.SubscriptionsNotifier) PolicyNotifier(org.wso2.carbon.apimgt.impl.notifier.PolicyNotifier) ApplicationNotifier(org.wso2.carbon.apimgt.impl.notifier.ApplicationNotifier) Notifier(org.wso2.carbon.apimgt.impl.notifier.Notifier) ScopesNotifier(org.wso2.carbon.apimgt.impl.notifier.ScopesNotifier) DeployAPIInGatewayNotifier(org.wso2.carbon.apimgt.impl.notifier.DeployAPIInGatewayNotifier) CertificateNotifier(org.wso2.carbon.apimgt.impl.notifier.CertificateNotifier) ExternalGatewayNotifier(org.wso2.carbon.apimgt.impl.notifier.ExternalGatewayNotifier) ApisNotifier(org.wso2.carbon.apimgt.impl.notifier.ApisNotifier) ExternallyDeployedApiNotifier(org.wso2.carbon.apimgt.impl.notifier.ExternallyDeployedApiNotifier) ApplicationRegistrationNotifier(org.wso2.carbon.apimgt.impl.notifier.ApplicationRegistrationNotifier) ApisNotifier(org.wso2.carbon.apimgt.impl.notifier.ApisNotifier) JWTValidationServiceImpl(org.wso2.carbon.apimgt.impl.jwt.JWTValidationServiceImpl) SystemScopesIssuer(org.wso2.carbon.apimgt.impl.issuers.SystemScopesIssuer) GoogleAnalyticsNotifier(org.wso2.carbon.apimgt.impl.notifier.GoogleAnalyticsNotifier) APIMConfigServiceImpl(org.wso2.carbon.apimgt.impl.config.APIMConfigServiceImpl) PolicyNotifier(org.wso2.carbon.apimgt.impl.notifier.PolicyNotifier) KeyStoreException(java.security.KeyStoreException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) OutputEventAdapterException(org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException) APIMgtInternalException(org.wso2.carbon.apimgt.api.APIMgtInternalException) IOException(java.io.IOException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) EventPublisherException(org.wso2.carbon.apimgt.eventing.EventPublisherException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) APIManagerDatabaseException(org.wso2.carbon.apimgt.api.APIManagerDatabaseException) CertificateException(java.security.cert.CertificateException) ArtifactRetriever(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.ArtifactRetriever) CommonConfigDeployer(org.wso2.carbon.apimgt.impl.observers.CommonConfigDeployer) DeployAPIInGatewayNotifier(org.wso2.carbon.apimgt.impl.notifier.DeployAPIInGatewayNotifier) APIManagerAnalyticsConfiguration(org.wso2.carbon.apimgt.impl.APIManagerAnalyticsConfiguration) APIManagerConfigurationServiceImpl(org.wso2.carbon.apimgt.impl.APIManagerConfigurationServiceImpl) Axis2ConfigurationContextObserver(org.wso2.carbon.utils.Axis2ConfigurationContextObserver) UserPostSelfRegistrationHandler(org.wso2.carbon.apimgt.impl.handlers.UserPostSelfRegistrationHandler) ScopesNotifier(org.wso2.carbon.apimgt.impl.notifier.ScopesNotifier) APIMConfigService(org.wso2.carbon.apimgt.impl.config.APIMConfigService) BundleContext(org.osgi.framework.BundleContext) TenantLoadMessageSender(org.wso2.carbon.apimgt.impl.observers.TenantLoadMessageSender) Cache(javax.cache.Cache) Activate(org.osgi.service.component.annotations.Activate)

Example 8 with APIMConfigService

use of org.wso2.carbon.apimgt.impl.config.APIMConfigService in project carbon-apimgt by wso2.

the class APIUtilRolesTest method testCreateDefaultRoles.

@Test
public void testCreateDefaultRoles() throws Exception {
    System.setProperty("carbon.home", APIUtilRolesTest.class.getResource("/").getFile());
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        final int tenantId = MultitenantConstants.SUPER_TENANT_ID;
        final String tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
        File siteConfFile = new File(Thread.currentThread().getContextClassLoader().getResource("tenant-conf.json").getFile());
        String tenantConfValue = FileUtils.readFileToString(siteConfFile);
        InputStream signUpConfStream = new FileInputStream(Thread.currentThread().getContextClassLoader().getResource("default-sign-up-config.xml").getFile());
        ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
        RealmService realmService = Mockito.mock(RealmService.class);
        RegistryService registryService = Mockito.mock(RegistryService.class);
        TenantManager tenantManager = Mockito.mock(TenantManager.class);
        TenantIndexingLoader indexingLoader = Mockito.mock(TenantIndexingLoader.class);
        UserRealm userRealm = Mockito.mock(UserRealm.class);
        UserStoreManager userStoreManager = Mockito.mock(UserStoreManager.class);
        RealmConfiguration realmConfiguration = Mockito.mock(RealmConfiguration.class);
        APIMConfigService apimConfigService = Mockito.mock(APIMConfigService.class);
        PowerMockito.mockStatic(PrivilegedCarbonContext.class);
        PowerMockito.mockStatic(ServiceReferenceHolder.class);
        PowerMockito.mockStatic(APIManagerComponent.class);
        Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
        Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
        Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
        Mockito.when(serviceReferenceHolder.getIndexLoaderService()).thenReturn(indexingLoader);
        Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
        Mockito.when(realmService.getBootstrapRealm()).thenReturn(userRealm);
        Mockito.when(realmService.getTenantUserRealm(tenantId)).thenReturn(userRealm);
        Mockito.when(userRealm.getUserStoreManager()).thenReturn(userStoreManager);
        Mockito.when(userRealm.getRealmConfiguration()).thenReturn(realmConfiguration);
        Mockito.when(realmConfiguration.getAdminUserName()).thenReturn("admin");
        Mockito.when(tenantManager.getTenantId(tenantDomain)).thenReturn(tenantId);
        Mockito.when(tenantManager.getDomain(tenantId)).thenReturn(tenantDomain);
        Mockito.when(serviceReferenceHolder.getApimConfigService()).thenReturn(apimConfigService);
        Mockito.when(apimConfigService.getTenantConfig(tenantDomain)).thenReturn(tenantConfValue);
        Mockito.when(apimConfigService.getSelfSighupConfig(tenantDomain)).thenReturn(IOUtils.toString(signUpConfStream));
        APIUtil.createDefaultRoles(tenantId);
        String[] adminName = { "admin" };
        Mockito.verify(userStoreManager, Mockito.atLeastOnce()).addRole(eq("Internal/publisher"), eq(adminName), new Permission[] { Mockito.any(Permission.class) });
        Mockito.verify(userStoreManager, Mockito.atLeastOnce()).addRole(eq("Internal/subscriber"), eq(adminName), new Permission[] { Mockito.any(Permission.class) });
        Mockito.verify(userStoreManager, Mockito.atLeastOnce()).addRole(eq("Internal/creator"), eq(adminName), new Permission[] { Mockito.any(Permission.class) });
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) UserStoreManager(org.wso2.carbon.user.core.UserStoreManager) FileInputStream(java.io.FileInputStream) RealmConfiguration(org.wso2.carbon.user.core.config.RealmConfiguration) TenantIndexingLoader(org.wso2.carbon.registry.indexing.service.TenantIndexingLoader) UserRealm(org.wso2.carbon.user.core.UserRealm) RealmService(org.wso2.carbon.user.core.service.RealmService) Permission(org.wso2.carbon.user.api.Permission) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) File(java.io.File) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager) APIMConfigService(org.wso2.carbon.apimgt.impl.config.APIMConfigService) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 9 with APIMConfigService

use of org.wso2.carbon.apimgt.impl.config.APIMConfigService in project carbon-apimgt by wso2.

the class APIUtilTest method testGetAPIWithGovernanceArtifactAdvancedThrottlingDisabled.

@Test
public void testGetAPIWithGovernanceArtifactAdvancedThrottlingDisabled() throws Exception {
    System.setProperty("carbon.home", APIUtilTest.class.getResource("/").getFile());
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        API expectedAPI = getUniqueAPI();
        final String provider = expectedAPI.getId().getProviderName();
        final String tenantDomain = org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
        final int tenantId = -1234;
        System.setProperty("carbon.home", "");
        File siteConfFile = new File(Thread.currentThread().getContextClassLoader().getResource("tenant-conf.json").getFile());
        String tenantConfValue = FileUtils.readFileToString(siteConfFile);
        GovernanceArtifact artifact = Mockito.mock(GovernanceArtifact.class);
        Registry registry = Mockito.mock(Registry.class);
        ApiMgtDAO apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
        Resource resource = Mockito.mock(Resource.class);
        ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
        RealmService realmService = Mockito.mock(RealmService.class);
        TenantManager tenantManager = Mockito.mock(TenantManager.class);
        APIManagerConfigurationService apiManagerConfigurationService = Mockito.mock(APIManagerConfigurationService.class);
        APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
        ThrottleProperties throttleProperties = Mockito.mock(ThrottleProperties.class);
        SubscriptionPolicy policy = Mockito.mock(SubscriptionPolicy.class);
        SubscriptionPolicy[] policies = new SubscriptionPolicy[] { policy };
        QuotaPolicy quotaPolicy = Mockito.mock(QuotaPolicy.class);
        RequestCountLimit limit = Mockito.mock(RequestCountLimit.class);
        RegistryService registryService = Mockito.mock(RegistryService.class);
        UserRegistry userRegistry = Mockito.mock(UserRegistry.class);
        APIMConfigService apimConfigService = Mockito.mock(APIMConfigService.class);
        Mockito.when(serviceReferenceHolder.getApimConfigService()).thenReturn(apimConfigService);
        Mockito.when(apimConfigService.getTenantConfig(tenantDomain)).thenReturn(tenantConfValue);
        PowerMockito.mockStatic(ApiMgtDAO.class);
        PowerMockito.mockStatic(GovernanceUtils.class);
        PowerMockito.mockStatic(MultitenantUtils.class);
        PowerMockito.mockStatic(ServiceReferenceHolder.class);
        Mockito.when(ApiMgtDAO.getInstance()).thenReturn(apiMgtDAO);
        Mockito.when(apiMgtDAO.getAPIID(Mockito.any(String.class))).thenReturn(123);
        Mockito.when(apiMgtDAO.getPolicyNames(PolicyConstants.POLICY_LEVEL_SUB, provider)).thenReturn(new String[] { "Unlimited" });
        Mockito.when(artifact.getId()).thenReturn("");
        Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER)).thenReturn(provider);
        Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT)).thenReturn("15");
        Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_TIER)).thenReturn("Unlimited");
        Mockito.when(MultitenantUtils.getTenantDomain(provider)).thenReturn(tenantDomain);
        Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
        Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
        Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
        Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
        Mockito.when(tenantManager.getTenantId(tenantDomain)).thenReturn(tenantId);
        Mockito.when(registryService.getConfigSystemRegistry(tenantId)).thenReturn(userRegistry);
        String artifactPath = "";
        Mockito.when(GovernanceUtils.getArtifactPath(registry, "")).thenReturn(artifactPath);
        Mockito.when(registry.get(artifactPath)).thenReturn(resource);
        Mockito.when(resource.getLastModified()).thenReturn(expectedAPI.getLastUpdated());
        Mockito.when(resource.getCreatedTime()).thenReturn(expectedAPI.getLastUpdated());
        Mockito.when(resource.getContent()).thenReturn(tenantConfValue.getBytes());
        Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigurationService);
        Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
        Mockito.when(apiManagerConfiguration.getThrottleProperties()).thenReturn(throttleProperties);
        Mockito.when(apiMgtDAO.getSubscriptionPolicies(tenantId)).thenReturn(policies);
        Mockito.when(policy.getDefaultQuotaPolicy()).thenReturn(quotaPolicy);
        Mockito.when(quotaPolicy.getLimit()).thenReturn(limit);
        Mockito.when(registry.getTags(artifactPath)).thenReturn(getTagsFromSet(expectedAPI.getTags()));
        ArrayList<URITemplate> urlList = getURLTemplateList(expectedAPI.getUriTemplates());
        Mockito.when(apiMgtDAO.getAllURITemplates(Mockito.anyString(), Mockito.anyString())).thenReturn(urlList);
        CORSConfiguration corsConfiguration = expectedAPI.getCorsConfiguration();
        Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_HEADERS)).thenReturn(corsConfiguration.getAccessControlAllowHeaders().toString());
        Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_METHODS)).thenReturn(corsConfiguration.getAccessControlAllowMethods().toString());
        Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_ORIGIN)).thenReturn(corsConfiguration.getAccessControlAllowOrigins().toString());
        API api = APIUtil.getAPI(artifact);
        Assert.assertNotNull(api);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) 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) 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) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) RealmService(org.wso2.carbon.user.core.service.RealmService) API(org.wso2.carbon.apimgt.api.model.API) QuotaPolicy(org.wso2.carbon.apimgt.api.model.policy.QuotaPolicy) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) File(java.io.File) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager) 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 10 with APIMConfigService

use of org.wso2.carbon.apimgt.impl.config.APIMConfigService in project carbon-apimgt by wso2.

the class APIUtilTierTest method testGetTiersFromApiPolicies.

@Test
public void testGetTiersFromApiPolicies() throws Exception {
    System.setProperty("carbon.home", APIUtilRolesTest.class.getResource("/").getFile());
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain("abc.com");
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(1);
        String policyLevel = PolicyConstants.POLICY_LEVEL_API;
        int tenantId = 1;
        ApiMgtDAOMockCreator daoMockHolder = new ApiMgtDAOMockCreator(tenantId);
        ApiMgtDAO apiMgtDAO = daoMockHolder.getMock();
        PowerMockito.mockStatic(ServiceReferenceHolder.class);
        ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
        RealmService realmService = Mockito.mock(RealmService.class);
        TenantManager tenantManager = Mockito.mock(TenantManager.class);
        Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
        Mockito.when(tenantManager.getDomain(1)).thenReturn("abc.com");
        Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
        Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
        APIMConfigService apimConfigService = Mockito.mock(APIMConfigService.class);
        Mockito.when(serviceReferenceHolder.getApimConfigService()).thenReturn(apimConfigService);
        Mockito.when(apimConfigService.getTenantConfig("abc.com")).thenReturn(IOUtils.toString(tenantConf));
        APIManagerConfigurationService apiManagerConfigurationService = Mockito.mock(APIManagerConfigurationService.class);
        APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
        Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
        Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigurationService);
        ThrottleProperties throttleProperties = new ThrottleProperties();
        throttleProperties.setEnableUnlimitedTier(true);
        Mockito.when(apiManagerConfiguration.getThrottleProperties()).thenReturn(throttleProperties);
        APIPolicy[] policies = generateApiPolicies(tiersReturned);
        Mockito.when(apiMgtDAO.getAPIPolicies(tenantId)).thenReturn(policies);
        Map<String, Tier> tiersFromPolicies = APIUtil.getTiersFromPolicies(policyLevel, tenantId);
        Mockito.verify(apiMgtDAO, Mockito.only()).getAPIPolicies(tenantId);
        for (APIPolicy policy : policies) {
            Tier tier = tiersFromPolicies.get(policy.getPolicyName());
            Assert.assertNotNull(tier);
            Assert.assertEquals(policy.getPolicyName(), tier.getName());
            Assert.assertEquals(policy.getDescription(), tier.getDescription());
        }
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) APIManagerConfigurationService(org.wso2.carbon.apimgt.impl.APIManagerConfigurationService) Tier(org.wso2.carbon.apimgt.api.model.Tier) ApiMgtDAO(org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO) Matchers.anyString(org.mockito.Matchers.anyString) RealmService(org.wso2.carbon.user.core.service.RealmService) ApiMgtDAOMockCreator(org.wso2.carbon.apimgt.impl.ApiMgtDAOMockCreator) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager) 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)

Aggregations

Test (org.junit.Test)16 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)16 APIMConfigService (org.wso2.carbon.apimgt.impl.config.APIMConfigService)13 ServiceReferenceHolder (org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder)13 ApiMgtDAO (org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO)8 File (java.io.File)7 RealmService (org.wso2.carbon.user.core.service.RealmService)7 TenantManager (org.wso2.carbon.user.core.tenant.TenantManager)7 ThrottleProperties (org.wso2.carbon.apimgt.impl.dto.ThrottleProperties)6 BeforeTest (org.testng.annotations.BeforeTest)5 APIAdmin (org.wso2.carbon.apimgt.api.APIAdmin)5 Schema (org.everit.json.schema.Schema)4 Matchers.anyString (org.mockito.Matchers.anyString)4 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)4 Tier (org.wso2.carbon.apimgt.api.model.Tier)4 APIManagerConfiguration (org.wso2.carbon.apimgt.impl.APIManagerConfiguration)4 APIManagerConfigurationService (org.wso2.carbon.apimgt.impl.APIManagerConfigurationService)4 ApiMgtDAOMockCreator (org.wso2.carbon.apimgt.impl.ApiMgtDAOMockCreator)4 APIUtil (org.wso2.carbon.apimgt.impl.utils.APIUtil)4 RegistryService (org.wso2.carbon.registry.core.service.RegistryService)4