Search in sources :

Example 36 with APIProduct

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

the class APIConsumerImpl method addTiersToAPI.

private APIProduct addTiersToAPI(APIProduct apiProduct, String organization) throws APIManagementException {
    int tenantId = APIUtil.getInternalIdFromTenantDomainOrOrganization(organization);
    Set<Tier> tierNames = apiProduct.getAvailableTiers();
    Map<String, Tier> definedTiers = APIUtil.getTiers(tenantId);
    Set<Tier> availableTiers = new HashSet<>();
    Set<String> deniedTiers = getDeniedTiers(tenantId);
    for (Tier tierName : tierNames) {
        Tier definedTier = definedTiers.get(tierName.getName());
        if (definedTier != null) {
            availableTiers.add(definedTier);
        }
    }
    availableTiers.removeIf(tier -> deniedTiers.contains(tier.getName()));
    apiProduct.removeAllTiers();
    apiProduct.setAvailableTiers(availableTiers);
    return apiProduct;
}
Also used : Tier(org.wso2.carbon.apimgt.api.model.Tier) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 37 with APIProduct

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

the class APIConsumerImpl method filterMultipleVersionedAPIs.

private Map<String, Object> filterMultipleVersionedAPIs(Map<String, Object> searchResults) {
    Object apiObj = searchResults.get("apis");
    ArrayList<Object> apiSet;
    ArrayList<APIProduct> apiProductSet = new ArrayList<>();
    if (apiObj instanceof Set) {
        apiSet = new ArrayList<>(((Set) apiObj));
    } else {
        apiSet = (ArrayList<Object>) apiObj;
    }
    // Store the length of the APIs list with the versioned APIs
    int apiSetLengthWithVersionedApis = apiSet.size();
    int totalLength = Integer.parseInt(searchResults.get("length").toString());
    // filter store results if displayMultipleVersions is set to false
    Boolean displayMultipleVersions = APIUtil.isAllowDisplayMultipleVersions();
    if (!displayMultipleVersions) {
        SortedSet<API> resultApis = new TreeSet<API>(new APINameComparator());
        for (Object result : apiSet) {
            if (result instanceof API) {
                resultApis.add((API) result);
            } else if (result instanceof Map.Entry) {
                Map.Entry<Documentation, API> entry = (Map.Entry<Documentation, API>) result;
                resultApis.add(entry.getValue());
            } else if (result instanceof APIProduct) {
                apiProductSet.add((APIProduct) result);
            }
        }
        Map<String, API> latestPublishedAPIs = new HashMap<String, API>();
        Comparator<API> versionComparator = new APIVersionComparator();
        String key;
        // Run the result api list through API version comparator and filter out multiple versions
        for (API api : resultApis) {
            key = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
            API existingAPI = latestPublishedAPIs.get(key);
            if (existingAPI != null) {
                // this one has a higher version number
                if (versionComparator.compare(api, existingAPI) > 0) {
                    latestPublishedAPIs.put(key, api);
                }
            } else {
                // We haven't seen this API before
                latestPublishedAPIs.put(key, api);
            }
        }
        // filter apiSet
        ArrayList<Object> tempApiSet = new ArrayList<Object>();
        for (Object result : apiSet) {
            API api = null;
            String mapKey;
            API latestAPI;
            if (result instanceof API) {
                api = (API) result;
                mapKey = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
                if (latestPublishedAPIs.containsKey(mapKey)) {
                    latestAPI = latestPublishedAPIs.get(mapKey);
                    if (latestAPI.getId().equals(api.getId())) {
                        tempApiSet.add(api);
                    }
                }
            } else if (result instanceof Map.Entry) {
                Map.Entry<Documentation, API> docEntry = (Map.Entry<Documentation, API>) result;
                api = docEntry.getValue();
                mapKey = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
                if (latestPublishedAPIs.containsKey(mapKey)) {
                    latestAPI = latestPublishedAPIs.get(mapKey);
                    if (latestAPI.getId().equals(api.getId())) {
                        tempApiSet.add(docEntry);
                    }
                }
            }
        }
        // Store the length of the APIs list without the versioned APIs
        int apiSetLengthWithoutVersionedApis = tempApiSet.size();
        apiSet = tempApiSet;
        ArrayList<Object> resultAPIandProductSet = new ArrayList<>();
        resultAPIandProductSet.addAll(apiSet);
        resultAPIandProductSet.addAll(apiProductSet);
        resultAPIandProductSet.sort(new ContentSearchResultNameComparator());
        if (apiObj instanceof Set) {
            searchResults.put("apis", new LinkedHashSet<>(resultAPIandProductSet));
        } else {
            searchResults.put("apis", resultAPIandProductSet);
        }
        searchResults.put("length", totalLength - (apiSetLengthWithVersionedApis - (apiSetLengthWithoutVersionedApis + apiProductSet.size())));
    }
    return searchResults;
}
Also used : Set(java.util.Set) TreeSet(java.util.TreeSet) LinkedHashSet(java.util.LinkedHashSet) SortedSet(java.util.SortedSet) HashSet(java.util.HashSet) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) ArrayList(java.util.ArrayList) APINameComparator(org.wso2.carbon.apimgt.impl.utils.APINameComparator) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIVersionComparator(org.wso2.carbon.apimgt.impl.utils.APIVersionComparator) TreeSet(java.util.TreeSet) JSONObject(org.json.simple.JSONObject) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API) ContentSearchResultNameComparator(org.wso2.carbon.apimgt.impl.utils.ContentSearchResultNameComparator) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap)

Example 38 with APIProduct

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

the class APIConsumerImpl method addSubscription.

@Override
public SubscriptionResponse addSubscription(ApiTypeWrapper apiTypeWrapper, String userId, Application application) throws APIManagementException {
    API api = null;
    APIProduct product = null;
    Identifier identifier = null;
    int apiId;
    String apiUUID;
    final boolean isApiProduct = apiTypeWrapper.isAPIProduct();
    String state;
    String apiContext;
    if (isApiProduct) {
        product = apiTypeWrapper.getApiProduct();
        state = product.getState();
        identifier = product.getId();
        apiId = product.getProductId();
        apiUUID = product.getUuid();
        apiContext = product.getContext();
    } else {
        api = apiTypeWrapper.getApi();
        state = api.getStatus();
        identifier = api.getId();
        apiId = api.getId().getId();
        apiUUID = api.getUuid();
        apiContext = api.getContext();
    }
    WorkflowResponse workflowResponse = null;
    String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(userId);
    checkSubscriptionAllowed(apiTypeWrapper);
    int subscriptionId;
    if (APIConstants.PUBLISHED.equals(state) || APIConstants.PROTOTYPED.equals(state)) {
        subscriptionId = apiMgtDAO.addSubscription(apiTypeWrapper, application, APIConstants.SubscriptionStatus.ON_HOLD, tenantAwareUsername);
        boolean isTenantFlowStarted = false;
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            isTenantFlowStarted = startTenantFlowForTenantDomain(tenantDomain);
        }
        String applicationName = application.getName();
        try {
            WorkflowExecutor addSubscriptionWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION);
            SubscriptionWorkflowDTO workflowDTO = new SubscriptionWorkflowDTO();
            workflowDTO.setStatus(WorkflowStatus.CREATED);
            workflowDTO.setCreatedTime(System.currentTimeMillis());
            workflowDTO.setTenantDomain(tenantDomain);
            workflowDTO.setTenantId(tenantId);
            workflowDTO.setExternalWorkflowReference(addSubscriptionWFExecutor.generateUUID());
            workflowDTO.setWorkflowReference(String.valueOf(subscriptionId));
            workflowDTO.setWorkflowType(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION);
            workflowDTO.setCallbackUrl(addSubscriptionWFExecutor.getCallbackURL());
            workflowDTO.setApiName(identifier.getName());
            workflowDTO.setApiContext(apiContext);
            workflowDTO.setApiVersion(identifier.getVersion());
            workflowDTO.setApiProvider(identifier.getProviderName());
            workflowDTO.setTierName(identifier.getTier());
            workflowDTO.setRequestedTierName(identifier.getTier());
            workflowDTO.setApplicationName(applicationName);
            workflowDTO.setApplicationId(application.getId());
            workflowDTO.setSubscriber(userId);
            Tier tier = null;
            Set<Tier> policies = Collections.emptySet();
            if (!isApiProduct) {
                policies = api.getAvailableTiers();
            } else {
                policies = product.getAvailableTiers();
            }
            for (Tier policy : policies) {
                if (policy.getName() != null && (policy.getName()).equals(workflowDTO.getTierName())) {
                    tier = policy;
                }
            }
            boolean isMonetizationEnabled = false;
            if (api != null) {
                isMonetizationEnabled = api.getMonetizationStatus();
                // check whether monetization is enabled for API and tier plan is commercial
                if (isMonetizationEnabled && APIConstants.COMMERCIAL_TIER_PLAN.equals(tier.getTierPlan())) {
                    workflowResponse = addSubscriptionWFExecutor.monetizeSubscription(workflowDTO, api);
                } else {
                    workflowResponse = addSubscriptionWFExecutor.execute(workflowDTO);
                }
            } else {
                isMonetizationEnabled = product.getMonetizationStatus();
                // check whether monetization is enabled for API and tier plan is commercial
                if (isMonetizationEnabled && APIConstants.COMMERCIAL_TIER_PLAN.equals(tier.getTierPlan())) {
                    workflowResponse = addSubscriptionWFExecutor.monetizeSubscription(workflowDTO, product);
                } else {
                    workflowResponse = addSubscriptionWFExecutor.execute(workflowDTO);
                }
            }
        } catch (WorkflowException e) {
            // If the workflow execution fails, roll back transaction by removing the subscription entry.
            apiMgtDAO.removeSubscriptionById(subscriptionId);
            log.error("Could not execute Workflow", e);
            throw new APIManagementException("Could not execute Workflow", e);
        } finally {
            if (isTenantFlowStarted) {
                endTenantFlow();
            }
        }
        // to handle on-the-fly subscription rejection (and removal of subscription entry from the database)
        // the response should have {"Status":"REJECTED"} in the json payload for this to work.
        boolean subscriptionRejected = false;
        String subscriptionStatus = null;
        String subscriptionUUID = "";
        SubscribedAPI addedSubscription = getSubscriptionById(subscriptionId);
        if (workflowResponse != null && workflowResponse.getJSONPayload() != null && !workflowResponse.getJSONPayload().isEmpty()) {
            try {
                JSONObject wfResponseJson = (JSONObject) new JSONParser().parse(workflowResponse.getJSONPayload());
                if (APIConstants.SubscriptionStatus.REJECTED.equals(wfResponseJson.get("Status"))) {
                    subscriptionRejected = true;
                    subscriptionStatus = APIConstants.SubscriptionStatus.REJECTED;
                }
            } catch (ParseException e) {
                log.error('\'' + workflowResponse.getJSONPayload() + "' is not a valid JSON.", e);
            }
        }
        if (!subscriptionRejected) {
            subscriptionStatus = addedSubscription.getSubStatus();
            subscriptionUUID = addedSubscription.getUUID();
            JSONObject subsLogObject = new JSONObject();
            subsLogObject.put(APIConstants.AuditLogConstants.API_NAME, identifier.getName());
            subsLogObject.put(APIConstants.AuditLogConstants.PROVIDER, identifier.getProviderName());
            subsLogObject.put(APIConstants.AuditLogConstants.APPLICATION_ID, application.getId());
            subsLogObject.put(APIConstants.AuditLogConstants.APPLICATION_NAME, applicationName);
            subsLogObject.put(APIConstants.AuditLogConstants.TIER, identifier.getTier());
            APIUtil.logAuditMessage(APIConstants.AuditLogConstants.SUBSCRIPTION, subsLogObject.toString(), APIConstants.AuditLogConstants.CREATED, this.username);
            if (workflowResponse == null) {
                workflowResponse = new GeneralWorkflowResponse();
            }
        }
        // get the workflow state once the executor is executed.
        WorkflowDTO wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(Integer.toString(subscriptionId), WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION);
        // only send the notification if approved
        // wfDTO is null when simple wf executor is used because wf state is not stored in the db and is always approved.
        int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
        if (wfDTO != null) {
            if (WorkflowStatus.APPROVED.equals(wfDTO.getStatus())) {
                SubscriptionEvent subscriptionEvent = new SubscriptionEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.SUBSCRIPTIONS_CREATE.name(), tenantId, tenantDomain, subscriptionId, addedSubscription.getUUID(), apiId, apiUUID, application.getId(), application.getUUID(), identifier.getTier(), subscriptionStatus);
                APIUtil.sendNotification(subscriptionEvent, APIConstants.NotifierType.SUBSCRIPTIONS.name());
            }
        } else {
            SubscriptionEvent subscriptionEvent = new SubscriptionEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.SUBSCRIPTIONS_CREATE.name(), tenantId, tenantDomain, subscriptionId, addedSubscription.getUUID(), apiId, apiUUID, application.getId(), application.getUUID(), identifier.getTier(), subscriptionStatus);
            APIUtil.sendNotification(subscriptionEvent, APIConstants.NotifierType.SUBSCRIPTIONS.name());
        }
        if (log.isDebugEnabled()) {
            String logMessage = "API Name: " + identifier.getName() + ", API Version " + identifier.getVersion() + ", Subscription Status: " + subscriptionStatus + " subscribe by " + userId + " for app " + applicationName;
            log.debug(logMessage);
        }
        return new SubscriptionResponse(subscriptionStatus, subscriptionUUID, workflowResponse);
    } else {
        throw new APIMgtResourceNotFoundException("Subscriptions not allowed on APIs/API Products in the state: " + state);
    }
}
Also used : SubscriptionEvent(org.wso2.carbon.apimgt.impl.notifier.events.SubscriptionEvent) ApplicationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationWorkflowDTO) WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) ApplicationRegistrationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO) SubscriptionWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.SubscriptionWorkflowDTO) Tier(org.wso2.carbon.apimgt.api.model.Tier) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) GeneralWorkflowResponse(org.wso2.carbon.apimgt.impl.workflow.GeneralWorkflowResponse) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) Identifier(org.wso2.carbon.apimgt.api.model.Identifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONObject(org.json.simple.JSONObject) SubscriptionWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.SubscriptionWorkflowDTO) GeneralWorkflowResponse(org.wso2.carbon.apimgt.impl.workflow.GeneralWorkflowResponse) WorkflowResponse(org.wso2.carbon.apimgt.api.WorkflowResponse) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API) WorkflowExecutor(org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutor) JSONParser(org.json.simple.parser.JSONParser) SubscriptionResponse(org.wso2.carbon.apimgt.api.model.SubscriptionResponse) ParseException(org.json.simple.parser.ParseException)

Example 39 with APIProduct

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

the class APIConfigContext method setApiProductVelocityContext.

private void setApiProductVelocityContext(APIProduct apiProduct, VelocityContext context) {
    APIProductIdentifier id = apiProduct.getId();
    // set the api name version and context
    context.put("apiName", PRODUCT_PREFIX + "--" + id.getName());
    context.put("apiVersion", "1.0.0");
    // We set the context pattern now to support plugable version strategy
    // context.put("apiContext", api.getContext());
    context.put("apiContext", apiProduct.getContext());
    // the api object will be passed on to the template so it properties can be used to
    // customise how the synapse config is generated.
    context.put("apiObj", apiProduct);
    context.put("apiIsBlocked", Boolean.FALSE);
    String apiSecurity = apiProduct.getApiSecurity();
    // if API is secured with ouath2
    if (apiSecurity == null || apiSecurity.contains(APIConstants.DEFAULT_API_SECURITY_OAUTH2)) {
        context.put("apiIsOauthProtected", Boolean.TRUE);
    } else {
        context.put("apiIsOauthProtected", Boolean.FALSE);
    }
    // if API is secured with api_Key
    if (apiSecurity.contains(APIConstants.API_SECURITY_API_KEY)) {
        context.put("apiIsApiKeyProtected", Boolean.TRUE);
    } else {
        context.put("apiIsApiKeyProtected", Boolean.FALSE);
    }
    // if API is secured with basic_auth
    if (apiSecurity.contains(APIConstants.API_SECURITY_BASIC_AUTH)) {
        context.put("apiIsBasicAuthProtected", Boolean.TRUE);
    } else {
        context.put("apiIsBasicAuthProtected", Boolean.FALSE);
    }
    if (apiProduct.isEnabledSchemaValidation()) {
        context.put("enableSchemaValidation", Boolean.TRUE);
    } else {
        context.put("enableSchemaValidation", Boolean.FALSE);
    }
    if (apiProduct.isEnableStore()) {
        context.put("enableStore", Boolean.TRUE);
    } else {
        context.put("enableStore", Boolean.FALSE);
    }
    // API test key
    context.put("testKey", apiProduct.getTestKey());
    context.put("apiType", apiProduct.getType());
}
Also used : APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier)

Example 40 with APIProduct

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

the class APIMappingUtil method setAPICategoriesToModel.

/**
 * Set API categories to API or APIProduct based on the instance type of the DTO object passes.
 *
 * @param dto   APIDTO or APIProductDTO
 * @param model API or APIProduct
 */
private static void setAPICategoriesToModel(Object dto, Object model, String provider) {
    List<String> apiCategoryNames = new ArrayList<>();
    if (dto instanceof APIDTO) {
        APIDTO apiDTO = (APIDTO) dto;
        apiCategoryNames = apiDTO.getCategories();
    } else {
        APIProductDTO apiProductDTO = (APIProductDTO) dto;
        apiCategoryNames = apiProductDTO.getCategories();
    }
    List<APICategory> apiCategories = new ArrayList<>();
    for (String categoryName : apiCategoryNames) {
        APICategory category = new APICategory();
        category.setName(categoryName);
        apiCategories.add(category);
    }
    if (model instanceof API) {
        ((API) model).setApiCategories(apiCategories);
    } else {
        ((APIProduct) model).setApiCategories(apiCategories);
    }
}
Also used : APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) ProductAPIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ProductAPIDTO) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIProductDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIProductDTO) ArrayList(java.util.ArrayList) API(org.wso2.carbon.apimgt.api.model.API) APICategory(org.wso2.carbon.apimgt.api.model.APICategory)

Aggregations

APIProduct (org.wso2.carbon.apimgt.api.model.APIProduct)71 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)52 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)51 API (org.wso2.carbon.apimgt.api.model.API)37 ArrayList (java.util.ArrayList)31 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)22 PublisherAPIProduct (org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProduct)22 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)21 Tier (org.wso2.carbon.apimgt.api.model.Tier)21 HashMap (java.util.HashMap)19 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)19 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)18 JSONObject (org.json.simple.JSONObject)17 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)17 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)16 HashSet (java.util.HashSet)15 GenericArtifactManager (org.wso2.carbon.governance.api.generic.GenericArtifactManager)15 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)14 Organization (org.wso2.carbon.apimgt.persistence.dto.Organization)14 ParseException (org.json.simple.parser.ParseException)12