Search in sources :

Example 96 with Subscriber

use of org.wso2.carbon.apimgt.api.model.Subscriber in project carbon-apimgt by wso2.

the class AbstractAPIManager method addDefaultApplicationForSubscriber.

/**
 * Add default application on the first time a subscriber is added to the database
 *
 * @param subscriber Subscriber
 * @throws APIManagementException if an error occurs while adding default application
 */
private void addDefaultApplicationForSubscriber(Subscriber subscriber) throws APIManagementException {
    Application defaultApp = new Application(APIConstants.DEFAULT_APPLICATION_NAME, subscriber);
    if (APIUtil.isEnabledUnlimitedTier()) {
        defaultApp.setTier(APIConstants.UNLIMITED_TIER);
    } else {
        Map<String, Tier> throttlingTiers = APIUtil.getTiers(APIConstants.TIER_APPLICATION_TYPE, getTenantDomain(subscriber.getName()));
        Set<Tier> tierValueList = new HashSet<Tier>(throttlingTiers.values());
        List<Tier> sortedTierList = APIUtil.sortTiers(tierValueList);
        defaultApp.setTier(sortedTierList.get(0).getName());
    }
    // application will not be shared within the group
    defaultApp.setGroupId("");
    defaultApp.setTokenType(APIConstants.TOKEN_TYPE_JWT);
    defaultApp.setUUID(UUID.randomUUID().toString());
    defaultApp.setDescription(APIConstants.DEFAULT_APPLICATION_DESCRIPTION);
    int applicationId = apiMgtDAO.addApplication(defaultApp, subscriber.getName(), tenantDomain);
    ApplicationEvent applicationEvent = new ApplicationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.APPLICATION_CREATE.name(), tenantId, tenantDomain, applicationId, defaultApp.getUUID(), defaultApp.getName(), defaultApp.getTokenType(), defaultApp.getTier(), defaultApp.getGroupId(), defaultApp.getApplicationAttributes(), subscriber.getName());
    APIUtil.sendNotification(applicationEvent, APIConstants.NotifierType.APPLICATION.name());
}
Also used : Tier(org.wso2.carbon.apimgt.api.model.Tier) ApplicationEvent(org.wso2.carbon.apimgt.impl.notifier.events.ApplicationEvent) Application(org.wso2.carbon.apimgt.api.model.Application) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 97 with Subscriber

use of org.wso2.carbon.apimgt.api.model.Subscriber in project carbon-apimgt by wso2.

the class APIProviderImplTest method testGetAPIUsageByAPIId.

@Test
public void testGetAPIUsageByAPIId() throws APIManagementException, RegistryException, UserStoreException {
    String uuid = UUID.randomUUID().toString();
    SubscribedAPI subscribedAPI1 = new SubscribedAPI(new Subscriber("user1"), new APIIdentifier("admin", "API1", "1.0.0"));
    SubscribedAPI subscribedAPI2 = new SubscribedAPI(new Subscriber("user1"), new APIIdentifier("admin", "API2", "1.0.0"));
    UserApplicationAPIUsage apiResult1 = new UserApplicationAPIUsage();
    apiResult1.addApiSubscriptions(subscribedAPI1);
    apiResult1.addApiSubscriptions(subscribedAPI2);
    SubscribedAPI subscribedAPI3 = new SubscribedAPI(new Subscriber("user2"), new APIIdentifier("admin", "API1", "1.0.0"));
    SubscribedAPI subscribedAPI4 = new SubscribedAPI(new Subscriber("user2"), new APIIdentifier("admin", "API2", "1.0.0"));
    UserApplicationAPIUsage apiResult2 = new UserApplicationAPIUsage();
    apiResult2.addApiSubscriptions(subscribedAPI3);
    apiResult2.addApiSubscriptions(subscribedAPI4);
    UserApplicationAPIUsage[] apiResults = { apiResult1, apiResult2 };
    Mockito.when(apimgtDAO.getAllAPIUsageByProviderAndApiId(uuid, "org1")).thenReturn(apiResults);
    Mockito.when(apimgtDAO.getAPIIdentifierFromUUID(uuid)).thenReturn(new APIIdentifier("admin", "API1", "1.0.0"));
    APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apimgtDAO, scopesDAO);
    List<SubscribedAPI> subscribedAPIs = apiProvider.getAPIUsageByAPIId(uuid, "org1");
    Assert.assertEquals(2, subscribedAPIs.size());
    Assert.assertEquals("user1", subscribedAPIs.get(0).getSubscriber().getName());
    Assert.assertEquals("user2", subscribedAPIs.get(1).getSubscriber().getName());
}
Also used : UserApplicationAPIUsage(org.wso2.carbon.apimgt.api.dto.UserApplicationAPIUsage) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 98 with Subscriber

use of org.wso2.carbon.apimgt.api.model.Subscriber in project carbon-apimgt by wso2.

the class APIProviderImplTest method testUpdateAPI_InPublishedState.

@Test
public void testUpdateAPI_InPublishedState() throws Exception {
    APIIdentifier identifier = new APIIdentifier("admin-AT-carbon.super", "API1", "1.0.0");
    Set<String> environments = new HashSet<String>();
    environments.add("PRODUCTION");
    Set<String> newEnvironments = new HashSet<String>();
    newEnvironments.add("SANDBOX");
    Set<URITemplate> uriTemplates = new HashSet<URITemplate>();
    Set<URITemplate> newUriTemplates = new HashSet<URITemplate>();
    URITemplate uriTemplate1 = new URITemplate();
    uriTemplate1.setHTTPVerb("POST");
    uriTemplate1.setAuthType("Application");
    uriTemplate1.setUriTemplate("/add");
    uriTemplate1.setThrottlingTier("Gold");
    uriTemplates.add(uriTemplate1);
    URITemplate uriTemplate2 = new URITemplate();
    uriTemplate2.setHTTPVerb("PUT");
    uriTemplate2.setAuthType("Application");
    uriTemplate2.setUriTemplate("/update");
    uriTemplate2.setThrottlingTier("Gold");
    newUriTemplates.add(uriTemplate1);
    newUriTemplates.add(uriTemplate2);
    final API api = new API(identifier);
    api.setStatus(APIConstants.PUBLISHED);
    api.setVisibility("private");
    api.setVisibleRoles("admin");
    api.setAccessControl("all");
    api.setTransports("http,https");
    api.setContext("/test");
    api.setEnvironments(newEnvironments);
    api.setUriTemplates(newUriTemplates);
    api.setOrganization("carbon.super");
    API oldApi = new API(identifier);
    oldApi.setStatus(APIConstants.PUBLISHED);
    oldApi.setVisibility("public");
    oldApi.setAccessControl("all");
    oldApi.setContext("/test");
    oldApi.setEnvironments(environments);
    oldApi.setOrganization("carbon.super");
    api.setUriTemplates(uriTemplates);
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("test", "new_test");
    api.setAdditionalProperties(jsonObject);
    api.addProperty("secured", "false");
    Tier tier = new Tier("Gold");
    Map<String, Tier> tiers = new TreeMap<>();
    tiers.put("Gold", tier);
    Mockito.when(APIUtil.getTiers(APIConstants.TIER_RESOURCE_TYPE, "carbon.super")).thenReturn(tiers);
    List<Documentation> documentationList = getDocumentationList();
    Documentation documentation = documentationList.get(1);
    Mockito.when(APIUtil.getAPIDocPath(api.getId())).thenReturn(documentation.getFilePath());
    APIProviderImplWrapper apiProviderImplWrapper = new APIProviderImplWrapper(apimgtDAO, scopesDAO);
    Resource docResource = Mockito.mock(Resource.class);
    Mockito.when(docResource.getUUID()).thenReturn(documentation.getId());
    Mockito.when(apiProviderImplWrapper.registry.get(documentation.getFilePath())).thenReturn(docResource);
    GenericArtifact docArtifact = Mockito.mock(GenericArtifact.class);
    Mockito.when(artifactManager.getGenericArtifact(documentation.getId())).thenReturn(docArtifact);
    Mockito.when(APIUtil.getDocumentation(docArtifact)).thenReturn(documentation);
    Mockito.when(docArtifact.getPath()).thenReturn(artifactPath);
    PowerMockito.doNothing().when(APIUtil.class, "clearResourcePermissions", Mockito.any(), Mockito.any(), Mockito.anyInt());
    String[] roles = { "admin", "subscriber" };
    APIUtil.setResourcePermissions("admin", "Public", roles, artifactPath);
    Mockito.when(docArtifact.getAttribute(APIConstants.DOC_FILE_PATH)).thenReturn("docFilePath");
    final APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apiPersistenceInstance, apimgtDAO, scopesDAO, documentationList, null);
    Mockito.when(artifactManager.newGovernanceArtifact(any(QName.class))).thenReturn(artifact);
    Mockito.when(APIUtil.createAPIArtifactContent(artifact, oldApi)).thenReturn(artifact);
    RegistryService registryService = Mockito.mock(RegistryService.class);
    UserRegistry userRegistry = Mockito.mock(UserRegistry.class);
    ServiceReferenceHolder serviceReferenceHolder = TestUtils.getServiceReferenceHolder();
    RealmService realmService = Mockito.mock(RealmService.class);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
    Mockito.when(registryService.getConfigSystemRegistry(Mockito.anyInt())).thenReturn(userRegistry);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    PublisherAPI publisherAPI = Mockito.mock(PublisherAPI.class);
    PowerMockito.when(apiPersistenceInstance.addAPI(any(Organization.class), any(PublisherAPI.class))).thenReturn(publisherAPI);
    apiProvider.addAPI(oldApi);
    RegistryAuthorizationManager registryAuthorizationManager = Mockito.mock(RegistryAuthorizationManager.class);
    PowerMockito.whenNew(RegistryAuthorizationManager.class).withAnyArguments().thenReturn(registryAuthorizationManager);
    // mock has permission
    Resource apiSourceArtifact = Mockito.mock(Resource.class);
    Mockito.when(apiSourceArtifact.getUUID()).thenReturn("12640983654");
    String apiSourcePath = "path";
    PowerMockito.when(APIUtil.getAPIPath(api.getId())).thenReturn(apiSourcePath);
    PowerMockito.when(APIUtil.getAPIPath(oldApi.getId())).thenReturn(apiSourcePath);
    PowerMockito.when(apiProvider.registry.get(apiSourcePath)).thenReturn(apiSourceArtifact);
    // API Status is CREATED and user has permission
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS)).thenReturn("PUBLISHED");
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_USERNAME)).thenReturn("user1");
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD)).thenReturn("password");
    Mockito.when(artifactManager.getGenericArtifact(apiSourceArtifact.getUUID())).thenReturn(artifact);
    PowerMockito.when(APIUtil.hasPermission(null, APIConstants.Permissions.API_PUBLISH)).thenReturn(true);
    PowerMockito.when(APIUtil.hasPermission(null, APIConstants.Permissions.API_CREATE)).thenReturn(true);
    Mockito.when(apimgtDAO.getDefaultVersion(identifier)).thenReturn("1.0.0");
    Mockito.when(apimgtDAO.getPublishedDefaultVersion(identifier)).thenReturn("1.0.0");
    // updateDefaultAPIInRegistry
    String defaultAPIPath = APIConstants.API_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR + identifier.getApiName() + RegistryConstants.PATH_SEPARATOR + identifier.getVersion() + APIConstants.API_RESOURCE_NAME;
    Resource defaultAPISourceArtifact = Mockito.mock(Resource.class);
    String defaultAPIUUID = "12640983600";
    Mockito.when(defaultAPISourceArtifact.getUUID()).thenReturn(defaultAPIUUID);
    Mockito.when(apiProvider.registry.get(defaultAPIPath)).thenReturn(defaultAPISourceArtifact);
    GenericArtifact defaultAPIArtifact = Mockito.mock(GenericArtifact.class);
    Mockito.when(artifactManager.getGenericArtifact(defaultAPIUUID)).thenReturn(defaultAPIArtifact);
    Mockito.doNothing().when(artifactManager).updateGenericArtifact(defaultAPIArtifact);
    TestUtils.mockAPIMConfiguration(APIConstants.API_GATEWAY_TYPE, APIConstants.API_GATEWAY_TYPE_SYNAPSE, -1234);
    // updateApiArtifact
    PowerMockito.when(APIUtil.createAPIArtifactContent(artifact, api)).thenReturn(artifact);
    Mockito.when(artifact.getId()).thenReturn("12640983654");
    PowerMockito.when(GovernanceUtils.getArtifactPath(apiProvider.registry, "12640983654")).thenReturn(apiSourcePath);
    // Mock Updating API
    Mockito.doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            apiProvider.createAPI(api);
            return null;
        }
    }).when(artifactManager).updateGenericArtifact(artifact);
    // Mocking API already not published and published
    PowerMockito.mockStatic(OASParserUtil.class);
    Mockito.when(OASParserUtil.getAPIDefinition(api.getId(), apiProvider.registry)).thenReturn("{\"info\": {\"swagger\":\"data\"}}");
    APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
    GatewayArtifactSynchronizerProperties synchronizerProperties = new GatewayArtifactSynchronizerProperties();
    Mockito.when(config.getGatewayArtifactSynchronizerProperties()).thenReturn(synchronizerProperties);
    PowerMockito.when(apiPersistenceInstance.getPublisherAPI(any(Organization.class), any(String.class))).thenReturn(publisherAPI);
    apiProvider.updateAPI(api, oldApi);
    Assert.assertEquals(1, api.getEnvironments().size());
    Assert.assertEquals(true, api.getEnvironments().contains("SANDBOX"));
    // Previous updateAPI() call enabled API security. Therefore need to set it as false for the second test
    api.setEndpointSecured(false);
    apiProvider.updateAPI(api, oldApi);
    Assert.assertEquals(1, api.getEnvironments().size());
    Assert.assertEquals(true, api.getEnvironments().contains("SANDBOX"));
    // Test WSDL endpoint API
    api.setEndpointConfig(EP_CONFIG_WSDL);
    PowerMockito.when(APIUtil.isValidWSDLURL(WSDL_URL, true)).thenReturn(true);
    PowerMockito.when(APIUtil.createWSDL(apiProvider.registry, api)).thenReturn("wsdl_path");
    apiProvider.updateAPI(api, oldApi);
    Assert.assertEquals(1, api.getEnvironments().size());
    Assert.assertEquals(true, api.getEnvironments().contains("SANDBOX"));
    Assert.assertEquals("Additional properties that are set are not retrieved new_test", "new_test", api.getAdditionalProperties().get("test"));
    Assert.assertEquals("Additional properties that are set are not retrieved new_test", "false", api.getAdditionalProperties().get("secured"));
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) GatewayArtifactSynchronizerProperties(org.wso2.carbon.apimgt.impl.dto.GatewayArtifactSynchronizerProperties) RegistryAuthorizationManager(org.wso2.carbon.registry.core.jdbc.realm.RegistryAuthorizationManager) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager) HashSet(java.util.HashSet) GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) Tier(org.wso2.carbon.apimgt.api.model.Tier) QName(javax.xml.namespace.QName) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) TreeMap(java.util.TreeMap) JSONObject(org.json.simple.JSONObject) RealmService(org.wso2.carbon.user.core.service.RealmService) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 99 with Subscriber

use of org.wso2.carbon.apimgt.api.model.Subscriber in project carbon-apimgt by wso2.

the class APIProviderImplTest method testGetSubscribersOfAPI.

@Test
public void testGetSubscribersOfAPI() throws APIManagementException {
    APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apimgtDAO, scopesDAO);
    Set<Subscriber> subscriberSet = new HashSet<Subscriber>();
    APIIdentifier apiId = new APIIdentifier("admin", "API1", "1.0.1");
    Mockito.when(apimgtDAO.getSubscribersOfAPI(apiId)).thenReturn(subscriberSet);
    Assert.assertNotNull(apiProvider.getSubscribersOfAPI(apiId));
    Mockito.when(apimgtDAO.getSubscribersOfAPI(apiId)).thenThrow(APIManagementException.class);
    try {
        apiProvider.getSubscribersOfAPI(apiId);
        assertTrue(false);
    } catch (APIManagementException e) {
        Assert.assertEquals("Failed to get subscribers for API : API1", e.getMessage());
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) HashSet(java.util.HashSet) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 100 with Subscriber

use of org.wso2.carbon.apimgt.api.model.Subscriber in project carbon-apimgt by wso2.

the class ThrottleConditionEvaluatorTest method testApplicabilityOfNonMatchingJWTClaimsCondition.

@Test
public void testApplicabilityOfNonMatchingJWTClaimsCondition() {
    ConditionGroupDTO conditionGroupDTO = new ConditionGroupDTO();
    conditionGroupDTO.setConditionGroupId("JWTClaimsConditionGroup");
    ConditionDTO nonMatchingCondition = new ConditionDTO();
    nonMatchingCondition.setConditionType("JWTClaims");
    nonMatchingCondition.setConditionName("http://wso2.org/claims/subscriber");
    nonMatchingCondition.setConditionValue("testUser");
    ConditionDTO[] conditionDTOS = { nonMatchingCondition };
    conditionGroupDTO.setConditions(conditionDTOS);
    ConditionGroupDTO[] conditionGroupDTOS = { conditionGroupDTO };
    AuthenticationContext authenticationContext = new AuthenticationContext();
    authenticationContext.setCallerToken(JWTToken);
    MessageContext messageContext = TestUtils.getMessageContext(apiContext, apiVersion);
    List<ConditionGroupDTO> matchingConditionGroups = throttleConditionEvaluator.getApplicableConditions(messageContext, authenticationContext, conditionGroupDTOS);
    Assert.assertNull(matchingConditionGroups.get(0));
}
Also used : AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) ConditionDTO(org.wso2.carbon.apimgt.api.dto.ConditionDTO) ConditionGroupDTO(org.wso2.carbon.apimgt.api.dto.ConditionGroupDTO) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) Test(org.junit.Test)

Aggregations

Subscriber (org.wso2.carbon.apimgt.api.model.Subscriber)98 Test (org.junit.Test)64 Application (org.wso2.carbon.apimgt.api.model.Application)63 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)60 PreparedStatement (java.sql.PreparedStatement)39 SQLException (java.sql.SQLException)39 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)39 ResultSet (java.sql.ResultSet)37 Connection (java.sql.Connection)31 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)28 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)25 Tier (org.wso2.carbon.apimgt.api.model.Tier)20 ArrayList (java.util.ArrayList)19 HashSet (java.util.HashSet)19 Date (java.util.Date)14 HashMap (java.util.HashMap)11 LinkedHashSet (java.util.LinkedHashSet)10 JSONObject (org.json.simple.JSONObject)10 OAuthApplicationInfo (org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo)10 TreeMap (java.util.TreeMap)9