Search in sources :

Example 16 with Tier

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

the class APIStoreImplTestCase method testAddApplicationWorkflowReject.

@Test(description = "Test Application workflow rejection")
public void testAddApplicationWorkflowReject() throws APIManagementException {
    ApplicationDAO applicationDAO = Mockito.mock(ApplicationDAO.class);
    PolicyDAO policyDAO = Mockito.mock(PolicyDAO.class);
    WorkflowDAO workflowDAO = Mockito.mock(WorkflowDAO.class);
    Policy policy = Mockito.mock(Policy.class);
    APIGateway apiGateway = Mockito.mock(APIGateway.class);
    APIStore apiStore = getApiStoreImpl(applicationDAO, policyDAO, workflowDAO, apiGateway);
    Application application = new Application(APP_NAME, USER_NAME);
    application.setPolicy(new ApplicationPolicy(TIER));
    application.setPermissionString("[{\"groupId\": \"testGroup\",\"permission\":[\"READ\",\"UPDATE\",\"DELETE\",\"SUBSCRIPTION\"]}]");
    Mockito.when(applicationDAO.isApplicationNameExists(APP_NAME)).thenReturn(false);
    Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.application, TIER)).thenReturn(policy);
    apiStore.addApplication(application);
    DefaultWorkflowExecutor executor = Mockito.mock(DefaultWorkflowExecutor.class);
    Workflow workflow = new ApplicationCreationWorkflow(applicationDAO, workflowDAO, apiGateway);
    workflow.setWorkflowReference(application.getId());
    WorkflowResponse response = new GeneralWorkflowResponse();
    response.setWorkflowStatus(WorkflowStatus.REJECTED);
    Mockito.when(executor.complete(workflow)).thenReturn(response);
    apiStore.completeWorkflow(executor, workflow);
    Mockito.verify(applicationDAO, Mockito.times(1)).updateApplicationState(application.getId(), "REJECTED");
}
Also used : ApplicationPolicy(org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) Policy(org.wso2.carbon.apimgt.core.models.policy.Policy) GeneralWorkflowResponse(org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse) Workflow(org.wso2.carbon.apimgt.core.workflow.Workflow) ApplicationCreationWorkflow(org.wso2.carbon.apimgt.core.workflow.ApplicationCreationWorkflow) ApplicationUpdateWorkflow(org.wso2.carbon.apimgt.core.workflow.ApplicationUpdateWorkflow) SubscriptionCreationWorkflow(org.wso2.carbon.apimgt.core.workflow.SubscriptionCreationWorkflow) ApplicationDAO(org.wso2.carbon.apimgt.core.dao.ApplicationDAO) DefaultWorkflowExecutor(org.wso2.carbon.apimgt.core.workflow.DefaultWorkflowExecutor) WorkflowDAO(org.wso2.carbon.apimgt.core.dao.WorkflowDAO) ApplicationPolicy(org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy) ApplicationCreationWorkflow(org.wso2.carbon.apimgt.core.workflow.ApplicationCreationWorkflow) WorkflowResponse(org.wso2.carbon.apimgt.core.api.WorkflowResponse) GeneralWorkflowResponse(org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse) APIGateway(org.wso2.carbon.apimgt.core.api.APIGateway) Application(org.wso2.carbon.apimgt.core.models.Application) PolicyDAO(org.wso2.carbon.apimgt.core.dao.PolicyDAO) APIStore(org.wso2.carbon.apimgt.core.api.APIStore) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest)

Example 17 with Tier

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

the class APIStoreImplTestCase method testAddApplicationPermissionStringNull.

@Test(description = "Add an application with null permission String")
public void testAddApplicationPermissionStringNull() throws APIManagementException {
    ApplicationDAO applicationDAO = Mockito.mock(ApplicationDAO.class);
    PolicyDAO policyDAO = Mockito.mock(PolicyDAO.class);
    Policy policy = Mockito.mock(Policy.class);
    WorkflowDAO workflowDAO = Mockito.mock(WorkflowDAO.class);
    APIGateway apiGateway = Mockito.mock(APIGateway.class);
    APIStore apiStore = getApiStoreImpl(applicationDAO, policyDAO, workflowDAO, apiGateway);
    Application application = new Application(APP_NAME, USER_NAME);
    application.setPolicy(new ApplicationPolicy(TIER));
    application.setPermissionString(null);
    Mockito.when(applicationDAO.isApplicationNameExists(APP_NAME)).thenReturn(false);
    Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.application, TIER)).thenReturn(policy);
    ApplicationCreationResponse applicationResponse = apiStore.addApplication(application);
    String applicationUuid = applicationResponse.getApplicationUUID();
    Assert.assertNotNull(applicationUuid);
    Mockito.verify(applicationDAO, Mockito.times(1)).addApplication(application);
}
Also used : ApplicationPolicy(org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) Policy(org.wso2.carbon.apimgt.core.models.policy.Policy) WorkflowDAO(org.wso2.carbon.apimgt.core.dao.WorkflowDAO) ApplicationCreationResponse(org.wso2.carbon.apimgt.core.workflow.ApplicationCreationResponse) ApplicationPolicy(org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy) APIGateway(org.wso2.carbon.apimgt.core.api.APIGateway) ApplicationDAO(org.wso2.carbon.apimgt.core.dao.ApplicationDAO) Application(org.wso2.carbon.apimgt.core.models.Application) PolicyDAO(org.wso2.carbon.apimgt.core.dao.PolicyDAO) APIStore(org.wso2.carbon.apimgt.core.api.APIStore) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest)

Example 18 with Tier

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

the class AbstractAPIManager method getTiers.

/**
 * Returns a list of pre-defined # {@link org.wso2.carbon.apimgt.api.model.Tier} in the system.
 *
 * @return Set<Tier>
 */
public Set<Tier> getTiers() throws APIManagementException {
    Set<Tier> tiers = new TreeSet<Tier>(new TierNameComparator());
    Map<String, Tier> tierMap = APIUtil.getTiersFromPolicies(PolicyConstants.POLICY_LEVEL_SUB, tenantId);
    tiers.addAll(tierMap.values());
    return tiers;
}
Also used : Tier(org.wso2.carbon.apimgt.api.model.Tier) TreeSet(java.util.TreeSet) TierNameComparator(org.wso2.carbon.apimgt.impl.utils.TierNameComparator)

Example 19 with Tier

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

the class AbstractAPIManager method populateDevPortalAPIInformation.

protected void populateDevPortalAPIInformation(String uuid, String organization, API api) throws APIManagementException, OASPersistenceException, ParseException {
    Organization org = new Organization(organization);
    // UUID
    if (api.getUuid() == null) {
        api.setUuid(uuid);
    }
    api.setOrganization(organization);
    // environment
    String environmentString = null;
    if (api.getEnvironments() != null) {
        environmentString = String.join(",", api.getEnvironments());
    }
    api.setEnvironments(APIUtil.extractEnvironmentsForAPI(environmentString, organization));
    // workflow status
    APIIdentifier apiId = api.getId();
    String currentApiUuid = uuid;
    if (api.isRevision() && api.getRevisionedApiId() != null) {
        currentApiUuid = api.getRevisionedApiId();
    }
    // TODO try to use a single query to get info from db
    // Ratings
    int internalId = apiMgtDAO.getAPIID(currentApiUuid);
    api.setRating(APIUtil.getAverageRating(internalId));
    apiId.setId(internalId);
    // api level tier
    String apiLevelTier = apiMgtDAO.getAPILevelTier(internalId);
    api.setApiLevelPolicy(apiLevelTier);
    // available tier
    String tiers = null;
    Set<Tier> tiersSet = api.getAvailableTiers();
    Set<String> tierNameSet = new HashSet<String>();
    for (Tier t : tiersSet) {
        tierNameSet.add(t.getName());
    }
    if (api.getAvailableTiers() != null) {
        tiers = String.join("||", tierNameSet);
    }
    Map<String, Tier> definedTiers = APIUtil.getTiers(APIUtil.getInternalOrganizationId(organization));
    Set<Tier> availableTier = APIUtil.getAvailableTiers(definedTiers, tiers, api.getId().getApiName());
    api.setAvailableTiers(availableTier);
    // Scopes
    Map<String, Scope> scopeToKeyMapping = APIUtil.getAPIScopes(currentApiUuid, organization);
    api.setScopes(new LinkedHashSet<>(scopeToKeyMapping.values()));
    // templates
    String resourceConfigsString = null;
    if (api.getSwaggerDefinition() != null) {
        resourceConfigsString = api.getSwaggerDefinition();
    } else {
        resourceConfigsString = apiPersistenceInstance.getOASDefinition(org, uuid);
    }
    api.setSwaggerDefinition(resourceConfigsString);
    if (api.getType() != null && APIConstants.APITransportType.GRAPHQL.toString().equals(api.getType())) {
        api.setGraphQLSchema(getGraphqlSchemaDefinition(uuid, organization));
    }
    JSONParser jsonParser = new JSONParser();
    JSONObject paths = null;
    if (resourceConfigsString != null) {
        JSONObject resourceConfigsJSON = (JSONObject) jsonParser.parse(resourceConfigsString);
        paths = (JSONObject) resourceConfigsJSON.get(APIConstants.SWAGGER_PATHS);
    }
    Set<URITemplate> uriTemplates = apiMgtDAO.getURITemplatesOfAPI(api.getUuid());
    for (URITemplate uriTemplate : uriTemplates) {
        String uTemplate = uriTemplate.getUriTemplate();
        String method = uriTemplate.getHTTPVerb();
        List<Scope> oldTemplateScopes = uriTemplate.retrieveAllScopes();
        List<Scope> newTemplateScopes = new ArrayList<>();
        if (!oldTemplateScopes.isEmpty()) {
            for (Scope templateScope : oldTemplateScopes) {
                Scope scope = scopeToKeyMapping.get(templateScope.getKey());
                newTemplateScopes.add(scope);
            }
        }
        uriTemplate.addAllScopes(newTemplateScopes);
        uriTemplate.setResourceURI(api.getUrl());
        uriTemplate.setResourceSandboxURI(api.getSandboxUrl());
        // AWS Lambda: set arn & timeout to URI template
        if (paths != null) {
            JSONObject path = (JSONObject) paths.get(uTemplate);
            if (path != null) {
                JSONObject operation = (JSONObject) path.get(method.toLowerCase());
                if (operation != null) {
                    if (operation.containsKey(APIConstants.SWAGGER_X_AMZN_RESOURCE_NAME)) {
                        uriTemplate.setAmznResourceName((String) operation.get(APIConstants.SWAGGER_X_AMZN_RESOURCE_NAME));
                    }
                    if (operation.containsKey(APIConstants.SWAGGER_X_AMZN_RESOURCE_TIMEOUT)) {
                        uriTemplate.setAmznResourceTimeout(((Long) operation.get(APIConstants.SWAGGER_X_AMZN_RESOURCE_TIMEOUT)).intValue());
                    }
                }
            }
        }
    }
    if (APIConstants.IMPLEMENTATION_TYPE_INLINE.equalsIgnoreCase(api.getImplementation())) {
        for (URITemplate template : uriTemplates) {
            template.setMediationScript(template.getAggregatedMediationScript());
        }
    }
    api.setUriTemplates(uriTemplates);
    // CORS . if null is returned, set default config from the configuration
    if (api.getCorsConfiguration() == null) {
        api.setCorsConfiguration(APIUtil.getDefaultCorsConfiguration());
    }
    // set category
    List<APICategory> categories = api.getApiCategories();
    if (categories != null) {
        List<String> categoriesOfAPI = new ArrayList<String>();
        for (APICategory apiCategory : categories) {
            categoriesOfAPI.add(apiCategory.getName());
        }
        List<APICategory> categoryList = new ArrayList<>();
        if (!categoriesOfAPI.isEmpty()) {
            // category array retrieved from artifact has only the category name, therefore we need to fetch
            // categories
            // and fill out missing attributes before attaching the list to the api
            List<APICategory> allCategories = APIUtil.getAllAPICategoriesOfOrganization(organization);
            for (String categoryName : categoriesOfAPI) {
                for (APICategory category : allCategories) {
                    if (categoryName.equals(category.getName())) {
                        categoryList.add(category);
                        break;
                    }
                }
            }
        }
        api.setApiCategories(categoryList);
    }
}
Also used : Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) Tier(org.wso2.carbon.apimgt.api.model.Tier) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) ArrayList(java.util.ArrayList) Scope(org.wso2.carbon.apimgt.api.model.Scope) JSONObject(org.json.simple.JSONObject) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) JSONParser(org.json.simple.parser.JSONParser) APICategory(org.wso2.carbon.apimgt.api.model.APICategory) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 20 with Tier

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

the class AbstractAPIManager method populateAPIProductInformation.

protected void populateAPIProductInformation(String uuid, String organization, APIProduct apiProduct) throws APIManagementException, OASPersistenceException, ParseException {
    Organization org = new Organization(organization);
    apiProduct.setOrganization(organization);
    ApiMgtDAO.getInstance().setAPIProductFromDB(apiProduct);
    apiProduct.setRating(Float.toString(APIUtil.getAverageRating(apiProduct.getProductId())));
    List<APIProductResource> resources = ApiMgtDAO.getInstance().getAPIProductResourceMappings(apiProduct.getId());
    Map<String, Scope> uniqueAPIProductScopeKeyMappings = new LinkedHashMap<>();
    for (APIProductResource resource : resources) {
        List<Scope> resourceScopes = resource.getUriTemplate().retrieveAllScopes();
        ListIterator it = resourceScopes.listIterator();
        while (it.hasNext()) {
            Scope resourceScope = (Scope) it.next();
            String scopeKey = resourceScope.getKey();
            if (!uniqueAPIProductScopeKeyMappings.containsKey(scopeKey)) {
                resourceScope = APIUtil.getScopeByName(scopeKey, organization);
                uniqueAPIProductScopeKeyMappings.put(scopeKey, resourceScope);
            } else {
                resourceScope = uniqueAPIProductScopeKeyMappings.get(scopeKey);
            }
            it.set(resourceScope);
        }
    }
    for (APIProductResource resource : resources) {
        String resourceAPIUUID = resource.getApiIdentifier().getUUID();
        resource.setApiId(resourceAPIUUID);
        try {
            PublisherAPI publisherAPI = apiPersistenceInstance.getPublisherAPI(org, resourceAPIUUID);
            API api = APIMapper.INSTANCE.toApi(publisherAPI);
            if (api.isAdvertiseOnly()) {
                resource.setEndpointConfig(APIUtil.generateEndpointConfigForAdvertiseOnlyApi(api));
            } else {
                resource.setEndpointConfig(api.getEndpointConfig());
            }
            resource.setEndpointSecurityMap(APIUtil.setEndpointSecurityForAPIProduct(api));
        } catch (APIPersistenceException e) {
            throw new APIManagementException("Error while retrieving the api for api product " + e);
        }
    }
    apiProduct.setProductResources(resources);
    // UUID
    if (apiProduct.getUuid() == null) {
        apiProduct.setUuid(uuid);
    }
    // environment
    String environmentString = null;
    if (apiProduct.getEnvironments() != null) {
        environmentString = String.join(",", apiProduct.getEnvironments());
    }
    apiProduct.setEnvironments(APIUtil.extractEnvironmentsForAPI(environmentString, organization));
    // workflow status
    APIProductIdentifier productIdentifier = apiProduct.getId();
    WorkflowDTO workflow;
    String currentApiProductUuid = uuid;
    if (apiProduct.isRevision() && apiProduct.getRevisionedApiProductId() != null) {
        currentApiProductUuid = apiProduct.getRevisionedApiProductId();
    }
    workflow = APIUtil.getAPIWorkflowStatus(currentApiProductUuid, WF_TYPE_AM_API_PRODUCT_STATE);
    if (workflow != null) {
        WorkflowStatus status = workflow.getStatus();
        apiProduct.setWorkflowStatus(status.toString());
    }
    // available tier
    String tiers = null;
    Set<Tier> tiersSet = apiProduct.getAvailableTiers();
    Set<String> tierNameSet = new HashSet<String>();
    for (Tier t : tiersSet) {
        tierNameSet.add(t.getName());
    }
    if (apiProduct.getAvailableTiers() != null) {
        tiers = String.join("||", tierNameSet);
    }
    Map<String, Tier> definedTiers = APIUtil.getTiers(tenantId);
    Set<Tier> availableTier = APIUtil.getAvailableTiers(definedTiers, tiers, apiProduct.getId().getName());
    apiProduct.setAvailableTiers(availableTier);
    // Scopes
    /*
        Map<String, Scope> scopeToKeyMapping = APIUtil.getAPIScopes(api.getId(), requestedTenantDomain);
        apiProduct.setScopes(new LinkedHashSet<>(scopeToKeyMapping.values()));
        */
    // templates
    String resourceConfigsString = null;
    if (apiProduct.getDefinition() != null) {
        resourceConfigsString = apiProduct.getDefinition();
    } else {
        resourceConfigsString = apiPersistenceInstance.getOASDefinition(org, uuid);
        apiProduct.setDefinition(resourceConfigsString);
    }
    // CORS . if null is returned, set default config from the configuration
    if (apiProduct.getCorsConfiguration() == null) {
        apiProduct.setCorsConfiguration(APIUtil.getDefaultCorsConfiguration());
    }
    // set category
    List<APICategory> categories = apiProduct.getApiCategories();
    if (categories != null) {
        List<String> categoriesOfAPI = new ArrayList<String>();
        for (APICategory apiCategory : categories) {
            categoriesOfAPI.add(apiCategory.getName());
        }
        List<APICategory> categoryList = new ArrayList<>();
        if (!categoriesOfAPI.isEmpty()) {
            // category array retrieved from artifact has only the category name, therefore we need to fetch
            // categories
            // and fill out missing attributes before attaching the list to the api
            List<APICategory> allCategories = APIUtil.getAllAPICategoriesOfOrganization(organization);
            // todo-category: optimize this loop with breaks
            for (String categoryName : categoriesOfAPI) {
                for (APICategory category : allCategories) {
                    if (categoryName.equals(category.getName())) {
                        categoryList.add(category);
                        break;
                    }
                }
            }
        }
        apiProduct.setApiCategories(categoryList);
    }
}
Also used : WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Tier(org.wso2.carbon.apimgt.api.model.Tier) ListIterator(java.util.ListIterator) WorkflowStatus(org.wso2.carbon.apimgt.impl.workflow.WorkflowStatus) Scope(org.wso2.carbon.apimgt.api.model.Scope) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) APICategory(org.wso2.carbon.apimgt.api.model.APICategory)

Aggregations

Tier (org.wso2.carbon.apimgt.api.model.Tier)108 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)53 ArrayList (java.util.ArrayList)42 Test (org.junit.Test)40 HashSet (java.util.HashSet)39 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)37 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)37 API (org.wso2.carbon.apimgt.api.model.API)33 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)32 HashMap (java.util.HashMap)28 Application (org.wso2.carbon.apimgt.api.model.Application)26 Test (org.testng.annotations.Test)22 APIStore (org.wso2.carbon.apimgt.core.api.APIStore)22 Application (org.wso2.carbon.apimgt.core.models.Application)22 LinkedHashSet (java.util.LinkedHashSet)21 JSONObject (org.json.simple.JSONObject)20 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)20 ApplicationDAO (org.wso2.carbon.apimgt.core.dao.ApplicationDAO)20 Policy (org.wso2.carbon.apimgt.core.models.policy.Policy)20 BeforeTest (org.testng.annotations.BeforeTest)19