Search in sources :

Example 21 with APIMgtResourceNotFoundException

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

the class RegistryPersistenceImpl method getPublisherAPIProduct.

@Override
public PublisherAPIProduct getPublisherAPIProduct(Organization org, String apiProductId) throws APIPersistenceException {
    boolean tenantFlowStarted = false;
    try {
        RegistryHolder holder = getRegistry(org.getName());
        tenantFlowStarted = holder.isTenantFlowStarted();
        Registry registry = holder.getRegistry();
        GenericArtifact apiArtifact = getAPIArtifact(apiProductId, registry);
        if (apiArtifact != null) {
            APIProduct apiProduct = RegistryPersistenceUtil.getAPIProduct(apiArtifact, registry);
            String definitionPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + RegistryPersistenceUtil.replaceEmailDomain(apiProduct.getId().getProviderName()) + RegistryConstants.PATH_SEPARATOR + apiProduct.getId().getName() + RegistryConstants.PATH_SEPARATOR + apiProduct.getId().getVersion() + RegistryConstants.PATH_SEPARATOR + APIConstants.API_OAS_DEFINITION_RESOURCE_NAME;
            if (registry.resourceExists(definitionPath)) {
                Resource apiDocResource = registry.get(definitionPath);
                String apiDocContent = new String((byte[]) apiDocResource.getContent(), Charset.defaultCharset());
                apiProduct.setDefinition(apiDocContent);
            }
            PublisherAPIProduct pubApi = APIProductMapper.INSTANCE.toPublisherApiProduct(apiProduct);
            pubApi.setApiProductName(apiProduct.getId().getName());
            pubApi.setProviderName(apiProduct.getId().getProviderName());
            pubApi.setVersion(apiProduct.getId().getVersion());
            if (log.isDebugEnabled()) {
                log.debug("API Product for id " + apiProductId + " : " + pubApi.toString());
            }
            return pubApi;
        } else {
            String msg = "Failed to get API. API artifact corresponding to artifactId " + apiProductId + " does not exist";
            throw new APIMgtResourceNotFoundException(msg);
        }
    } catch (RegistryException e) {
        String msg = "Failed to get API";
        throw new APIPersistenceException(msg, e);
    } catch (APIManagementException e) {
        String msg = "Failed to get API";
        throw new APIPersistenceException(msg, e);
    } finally {
        if (tenantFlowStarted) {
            RegistryPersistenceUtil.endTenantFlow();
        }
    }
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) PublisherAPIProduct(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProduct) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Resource(org.wso2.carbon.registry.core.Resource) PublisherAPIProduct(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProduct) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 22 with APIMgtResourceNotFoundException

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

the class APIAdminImpl method getworkflowReferenceByExternalWorkflowReferenceID.

/**
 * The method converts the date into timestamp
 *
 * @param externelWorkflowRef External Workflow Reference of workflow pending request
 * @param status              Workflow status of workflow pending request
 * @param tenantDomain        tenant domain of user
 * @return Workflow pending request
 * @throws APIManagementException
 */
public Workflow getworkflowReferenceByExternalWorkflowReferenceID(String externelWorkflowRef, String status, String tenantDomain) throws APIManagementException {
    Workflow workflow = null;
    WorkflowProperties workflowConfig = org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration().getWorkflowProperties();
    if (workflowConfig.isListTasks()) {
        workflow = apiMgtDAO.getworkflowReferenceByExternalWorkflowReferenceID(externelWorkflowRef, status, tenantDomain);
    }
    if (workflow == null) {
        String msg = "External workflow Reference: " + externelWorkflowRef + " was not found.";
        throw new APIMgtResourceNotFoundException(msg);
    }
    return workflow;
}
Also used : Workflow(org.wso2.carbon.apimgt.api.model.Workflow) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) WorkflowProperties(org.wso2.carbon.apimgt.impl.dto.WorkflowProperties)

Example 23 with APIMgtResourceNotFoundException

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

the class APIAdminImpl method updateEnvironment.

@Override
public Environment updateEnvironment(String tenantDomain, Environment environment) throws APIManagementException {
    // check if the VHost exists in the tenant domain with given UUID, throw error if not found
    Environment existingEnv = getEnvironment(tenantDomain, environment.getUuid());
    if (existingEnv.isReadOnly()) {
        String errorMessage = String.format("Failed to update Environment with UUID '%s'. Environment is read only", environment.getUuid());
        throw new APIMgtResourceNotFoundException(errorMessage, ExceptionCodes.from(ExceptionCodes.READONLY_GATEWAY_ENVIRONMENT, String.format("UUID '%s'", environment.getUuid())));
    }
    if (!existingEnv.getName().equals(environment.getName())) {
        String errorMessage = String.format("Failed to update Environment with UUID '%s'. Environment name " + "can not be changed", environment.getUuid());
        throw new APIMgtResourceNotFoundException(errorMessage, ExceptionCodes.from(ExceptionCodes.READONLY_GATEWAY_ENVIRONMENT_NAME));
    }
    validateForUniqueVhostNames(environment);
    environment.setId(existingEnv.getId());
    return apiMgtDAO.updateEnvironment(environment);
}
Also used : Environment(org.wso2.carbon.apimgt.api.model.Environment) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)

Example 24 with APIMgtResourceNotFoundException

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

the class APIAdminImpl method deleteEnvironment.

@Override
public void deleteEnvironment(String tenantDomain, String uuid) throws APIManagementException {
    // check if the VHost exists in the tenant domain with given UUID, throw error if not found
    Environment existingEnv = getEnvironment(tenantDomain, uuid);
    if (existingEnv.isReadOnly()) {
        String errorMessage = String.format("Failed to delete Environment with UUID '%s'. Environment is read only", uuid);
        throw new APIMgtResourceNotFoundException(errorMessage, ExceptionCodes.from(ExceptionCodes.READONLY_GATEWAY_ENVIRONMENT, String.format("UUID '%s'", uuid)));
    }
    apiMgtDAO.deleteEnvironment(uuid);
}
Also used : Environment(org.wso2.carbon.apimgt.api.model.Environment) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)

Example 25 with APIMgtResourceNotFoundException

use of org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException 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

APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)67 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)48 API (org.wso2.carbon.apimgt.api.model.API)22 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)22 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.core.exception.APIMgtResourceNotFoundException)22 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)21 Organization (org.wso2.carbon.apimgt.persistence.dto.Organization)21 HashMap (java.util.HashMap)19 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)19 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)17 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)16 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)14 ErrorDTO (org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)14 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)12 APIRevision (org.wso2.carbon.apimgt.api.model.APIRevision)11 DeployedAPIRevision (org.wso2.carbon.apimgt.api.model.DeployedAPIRevision)11 APIProduct (org.wso2.carbon.apimgt.api.model.APIProduct)10 ParseException (org.json.simple.parser.ParseException)9 APIRevisionDeployment (org.wso2.carbon.apimgt.api.model.APIRevisionDeployment)9 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)8