Search in sources :

Example 31 with APIProduct

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

the class APIProviderImpl method undeployAPIProductRevisionDeployment.

@Override
public void undeployAPIProductRevisionDeployment(String apiProductId, String apiRevisionId, List<APIRevisionDeployment> apiRevisionDeployments) throws APIManagementException {
    APIProductIdentifier apiProductIdentifier = APIUtil.getAPIProductIdentifierFromUUID(apiProductId);
    if (apiProductIdentifier == null) {
        throw new APIMgtResourceNotFoundException("Couldn't retrieve existing API Product with ID: " + apiProductId, ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, apiProductId));
    }
    APIRevision apiRevision = apiMgtDAO.getRevisionByRevisionUUID(apiRevisionId);
    if (apiRevision == null) {
        throw new APIMgtResourceNotFoundException("Couldn't retrieve existing API Revision with Revision UUID: " + apiRevisionId, ExceptionCodes.from(ExceptionCodes.API_REVISION_NOT_FOUND, apiRevisionId));
    }
    APIProduct product = getAPIProductbyUUID(apiRevisionId, tenantDomain);
    product.setUuid(apiProductId);
    Set<String> environmentsToRemove = new HashSet<>();
    for (APIRevisionDeployment apiRevisionDeployment : apiRevisionDeployments) {
        environmentsToRemove.add(apiRevisionDeployment.getDeployment());
    }
    product.setEnvironments(environmentsToRemove);
    removeFromGateway(product, tenantDomain, new HashSet<>(apiRevisionDeployments), Collections.emptySet());
    apiMgtDAO.removeAPIRevisionDeployment(apiRevisionId, apiRevisionDeployments);
    GatewayArtifactsMgtDAO.getInstance().removePublishedGatewayLabels(apiProductId, apiRevisionId);
}
Also used : APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) PublisherAPIProduct(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProduct) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) DeployedAPIRevision(org.wso2.carbon.apimgt.api.model.DeployedAPIRevision) APIRevision(org.wso2.carbon.apimgt.api.model.APIRevision) APIRevisionDeployment(org.wso2.carbon.apimgt.api.model.APIRevisionDeployment) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 32 with APIProduct

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

the class APIProviderImpl method updateApiProductArtifact.

/**
 * Update API Product Artifact in Registry
 *
 * @param apiProduct
 * @param updateMetadata
 * @param updatePermissions
 * @throws APIManagementException
 */
private void updateApiProductArtifact(APIProduct apiProduct, boolean updateMetadata, boolean updatePermissions) throws APIManagementException {
    // Validate Transports and Security
    validateAndSetTransports(apiProduct);
    validateAndSetAPISecurity(apiProduct);
    PublisherAPIProduct publisherAPIProduct = APIProductMapper.INSTANCE.toPublisherApiProduct(apiProduct);
    PublisherAPIProduct addedAPIProduct;
    try {
        publisherAPIProduct.setApiProductName(apiProduct.getId().getName());
        publisherAPIProduct.setProviderName(apiProduct.getId().getProviderName());
        publisherAPIProduct.setVersion(apiProduct.getId().getVersion());
        addedAPIProduct = apiPersistenceInstance.updateAPIProduct(new Organization(CarbonContext.getThreadLocalCarbonContext().getTenantDomain()), publisherAPIProduct);
    } catch (APIPersistenceException e) {
        throw new APIManagementException("Error while creating API product ");
    }
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) PublisherAPIProduct(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProduct)

Example 33 with APIProduct

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

the class APIUtil method setResourceProperties.

/**
 * To set the resource properties to the API Product.
 *
 * @param apiProduct   API Product that need to set the resource properties.
 * @param registry     Registry to get the resource from.
 * @param artifactPath Path of the API Product artifact.
 * @return Updated API.
 * @throws RegistryException Registry Exception.
 */
private static APIProduct setResourceProperties(APIProduct apiProduct, Registry registry, String artifactPath) throws RegistryException {
    Resource productResource = registry.get(artifactPath);
    Properties properties = productResource.getProperties();
    if (properties != null) {
        Enumeration propertyNames = properties.propertyNames();
        while (propertyNames.hasMoreElements()) {
            String propertyName = (String) propertyNames.nextElement();
            if (log.isDebugEnabled()) {
                log.debug("API Product '" + apiProduct.getId().toString() + "' " + "has the property " + propertyName);
            }
            if (propertyName.startsWith(APIConstants.API_RELATED_CUSTOM_PROPERTIES_PREFIX)) {
                apiProduct.addProperty(propertyName.substring(APIConstants.API_RELATED_CUSTOM_PROPERTIES_PREFIX.length()), productResource.getProperty(propertyName));
            }
        }
    }
    apiProduct.setAccessControl(productResource.getProperty(APIConstants.ACCESS_CONTROL));
    String accessControlRoles = null;
    String displayPublisherRoles = productResource.getProperty(APIConstants.DISPLAY_PUBLISHER_ROLES);
    if (displayPublisherRoles == null) {
        String publisherRoles = productResource.getProperty(APIConstants.PUBLISHER_ROLES);
        if (publisherRoles != null) {
            accessControlRoles = APIConstants.NULL_USER_ROLE_LIST.equals(productResource.getProperty(APIConstants.PUBLISHER_ROLES)) ? null : productResource.getProperty(APIConstants.PUBLISHER_ROLES);
        }
    } else {
        accessControlRoles = APIConstants.NULL_USER_ROLE_LIST.equals(displayPublisherRoles) ? null : displayPublisherRoles;
    }
    apiProduct.setAccessControlRoles(accessControlRoles);
    return apiProduct;
}
Also used : Enumeration(java.util.Enumeration) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) Properties(java.util.Properties) ThrottleProperties(org.wso2.carbon.apimgt.impl.dto.ThrottleProperties)

Example 34 with APIProduct

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

the class APIAPIProductNameComparator method compare.

@Override
public int compare(Object o1, Object o2) {
    Identifier identifier1;
    Identifier identifier2;
    if (o1 instanceof API) {
        identifier1 = ((API) o1).getId();
    } else {
        identifier1 = ((APIProduct) o1).getId();
    }
    if (o2 instanceof API) {
        identifier2 = ((API) o2).getId();
    } else {
        identifier2 = ((APIProduct) o2).getId();
    }
    Provider provider = new Provider(identifier1.getProviderName(), identifier2.getProviderName());
    Name name = new Name(identifier1.getName(), identifier2.getName());
    Version version = new Version(identifier1.getVersion(), identifier2.getVersion());
    return compareFields(provider, name, version);
}
Also used : Identifier(org.wso2.carbon.apimgt.api.model.Identifier) API(org.wso2.carbon.apimgt.api.model.API)

Example 35 with APIProduct

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

the class APIConsumerImpl method updateSubscription.

@Override
public SubscriptionResponse updateSubscription(ApiTypeWrapper apiTypeWrapper, String userId, Application application, String inputSubscriptionId, String currentThrottlingPolicy, String requestedThrottlingPolicy) 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();
        apiId = product.getProductId();
        apiUUId = product.getUuid();
        identifier = product.getId();
        apiContext = product.getContext();
    } else {
        api = apiTypeWrapper.getApi();
        state = api.getStatus();
        identifier = api.getId();
        apiId = identifier.getId();
        apiUUId = api.getUuid();
        apiContext = api.getContext();
    }
    checkSubscriptionAllowed(apiTypeWrapper);
    WorkflowResponse workflowResponse = null;
    int subscriptionId;
    if (APIConstants.PUBLISHED.equals(state)) {
        subscriptionId = apiMgtDAO.updateSubscription(apiTypeWrapper, inputSubscriptionId, APIConstants.SubscriptionStatus.TIER_UPDATE_PENDING, requestedThrottlingPolicy);
        boolean isTenantFlowStarted = false;
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            isTenantFlowStarted = startTenantFlowForTenantDomain(tenantDomain);
        }
        try {
            WorkflowExecutor updateSubscriptionWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_UPDATE);
            SubscriptionWorkflowDTO workflowDTO = new SubscriptionWorkflowDTO();
            workflowDTO.setStatus(WorkflowStatus.CREATED);
            workflowDTO.setCreatedTime(System.currentTimeMillis());
            workflowDTO.setTenantDomain(tenantDomain);
            workflowDTO.setTenantId(tenantId);
            workflowDTO.setExternalWorkflowReference(updateSubscriptionWFExecutor.generateUUID());
            workflowDTO.setWorkflowReference(String.valueOf(subscriptionId));
            workflowDTO.setWorkflowType(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_UPDATE);
            workflowDTO.setCallbackUrl(updateSubscriptionWFExecutor.getCallbackURL());
            workflowDTO.setApiName(identifier.getName());
            workflowDTO.setApiContext(apiContext);
            workflowDTO.setApiVersion(identifier.getVersion());
            workflowDTO.setApiProvider(identifier.getProviderName());
            workflowDTO.setTierName(identifier.getTier());
            workflowDTO.setRequestedTierName(requestedThrottlingPolicy);
            workflowDTO.setApplicationName(application.getName());
            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 = updateSubscriptionWFExecutor.monetizeSubscription(workflowDTO, api);
                } else {
                    workflowResponse = updateSubscriptionWFExecutor.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 = updateSubscriptionWFExecutor.monetizeSubscription(workflowDTO, product);
                } else {
                    workflowResponse = updateSubscriptionWFExecutor.execute(workflowDTO);
                }
            }
        } catch (WorkflowException 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 updatedSubscription = 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 = updatedSubscription.getSubStatus();
            subscriptionUUID = updatedSubscription.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, application.getName());
            subsLogObject.put(APIConstants.AuditLogConstants.TIER, identifier.getTier());
            subsLogObject.put(APIConstants.AuditLogConstants.REQUESTED_TIER, requestedThrottlingPolicy);
            APIUtil.logAuditMessage(APIConstants.AuditLogConstants.SUBSCRIPTION, subsLogObject.toString(), APIConstants.AuditLogConstants.UPDATED, 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_UPDATE);
        // wfDTO is null when simple wf executor is used because wf state is not stored in the db and is always approved.
        if (wfDTO != null) {
            if (WorkflowStatus.APPROVED.equals(wfDTO.getStatus())) {
                SubscriptionEvent subscriptionEvent = new SubscriptionEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.SUBSCRIPTIONS_UPDATE.name(), tenantId, tenantDomain, subscriptionId, updatedSubscription.getUUID(), apiId, apiUUId, application.getId(), application.getUUID(), requestedThrottlingPolicy, subscriptionStatus);
                APIUtil.sendNotification(subscriptionEvent, APIConstants.NotifierType.SUBSCRIPTIONS.name());
            }
        } else {
            SubscriptionEvent subscriptionEvent = new SubscriptionEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.SUBSCRIPTIONS_UPDATE.name(), tenantId, tenantDomain, subscriptionId, updatedSubscription.getUUID(), apiId, apiUUId, application.getId(), application.getUUID(), requestedThrottlingPolicy, 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 " + application.getName();
            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)

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