Search in sources :

Example 1 with Tier

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

the class ApplicationUpdateWorkflow method completeWorkflow.

public WorkflowResponse completeWorkflow(WorkflowExecutor workflowExecutor) throws APIManagementException {
    String appId = getWorkflowReference();
    String name = getAttribute(WorkflowConstants.ATTRIBUTE_APPLICATION_NAME);
    String updatedUser = getAttribute(WorkflowConstants.ATTRIBUTE_APPLICATION_UPDATEDBY);
    String applicationId = getWorkflowReference();
    String tier = getAttribute(WorkflowConstants.ATTRIBUTE_APPLICATION_TIER);
    String policyId = getAttribute(WorkflowConstants.ATTRIBUTE_APPLICATION_POLICY_ID);
    String description = getAttribute(WorkflowConstants.ATTRIBUTE_APPLICATION_DESCRIPTION);
    String permission = getAttribute(WorkflowConstants.ATTRIBUTE_APPLICATION_PERMISSION);
    Application application = new Application(name, updatedUser);
    application.setPolicy(new ApplicationPolicy(policyId, tier));
    application.setDescription(description);
    application.setId(applicationId);
    application.setUpdatedUser(updatedUser);
    application.setPermissionString(permission);
    application.setUpdatedTime(LocalDateTime.now());
    if (existingApplication == null && updatedApplication == null) {
        // this is when complete method is executed through workflow rest api
        existingApplication = applicationDAO.getApplication(appId);
        updatedApplication = application;
    }
    WorkflowResponse response = workflowExecutor.complete(this);
    setStatus(response.getWorkflowStatus());
    if (WorkflowStatus.APPROVED == response.getWorkflowStatus()) {
        if (log.isDebugEnabled()) {
            log.debug("Application update workflow complete: Approved");
        }
        application.setStatus(APIMgtConstants.ApplicationStatus.APPLICATION_APPROVED);
        applicationDAO.updateApplication(appId, application);
        try {
            getApiGateway().updateApplication(application);
        } catch (GatewayException ex) {
            // This log is not harm to therefore not rethrow
            log.warn("Failed to send the Application Update Event ", ex);
        }
    } else if (WorkflowStatus.REJECTED == response.getWorkflowStatus()) {
        if (log.isDebugEnabled()) {
            log.debug("Application update workflow complete: Rejected");
        }
        String existingAppStatus = getAttribute(WorkflowConstants.ATTRIBUTE_APPLICATION_EXISTIN_APP_STATUS);
        applicationDAO.updateApplicationState(appId, existingAppStatus);
    }
    updateWorkflowEntries(this);
    return response;
}
Also used : ApplicationPolicy(org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy) GatewayException(org.wso2.carbon.apimgt.core.exception.GatewayException) WorkflowResponse(org.wso2.carbon.apimgt.core.api.WorkflowResponse) Application(org.wso2.carbon.apimgt.core.models.Application)

Example 2 with Tier

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

the class PoliciesApiServiceImpl method policiesTierLevelTierNameGet.

/**
 * Retrieves a tier by tier name and level
 *
 * @param tierName        Name of the tier
 * @param tierLevel       Level of the tier
 * @param ifNoneMatch     If-Non-Match header value
 * @param ifModifiedSince If-Modified-Since header value
 * @param request         msf4j request object
 * @return The requested tier as the response
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response policiesTierLevelTierNameGet(String tierName, String tierLevel, String ifNoneMatch, String ifModifiedSince, Request request) throws NotFoundException {
    TierDTO tierDTO = null;
    String username = RestApiUtil.getLoggedInUsername(request);
    try {
        APIStore apiStore = RestApiUtil.getConsumer(username);
        String existingFingerprint = policiesTierLevelTierNameGetFingerprint(tierName, tierLevel, ifNoneMatch, ifModifiedSince, request);
        if (!StringUtils.isEmpty(ifNoneMatch) && !StringUtils.isEmpty(existingFingerprint) && ifNoneMatch.contains(existingFingerprint)) {
            return Response.notModified().build();
        }
        Policy tier = apiStore.getPolicy(RestApiUtil.mapRestApiPolicyLevelToPolicyLevelEnum(tierLevel), tierName);
        tierDTO = TierMappingUtil.fromTierToDTO(tier, tierLevel);
        return Response.ok().entity(tierDTO).header(HttpHeaders.ETAG, "\"" + existingFingerprint + "\"").build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving tier";
        HashMap<String, String> paramList = new HashMap<String, String>();
        paramList.put(APIMgtConstants.ExceptionsConstants.TIER_LEVEL, tierLevel);
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
        log.error(errorMessage, e);
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    }
}
Also used : Policy(org.wso2.carbon.apimgt.core.models.policy.Policy) TierDTO(org.wso2.carbon.apimgt.rest.api.store.dto.TierDTO) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) HashMap(java.util.HashMap) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) APIStore(org.wso2.carbon.apimgt.core.api.APIStore)

Example 3 with Tier

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

the class SubscriptionsApiServiceImpl method subscriptionsPost.

/**
 * Adds a new subscription
 *
 * @param body        Subscription details to be added
 * @param request     msf4j request object
 * @return Newly added subscription as the response
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response subscriptionsPost(SubscriptionDTO body, Request request) throws NotFoundException {
    String username = RestApiUtil.getLoggedInUsername(request);
    SubscriptionDTO subscriptionDTO = null;
    URI location = null;
    try {
        APIStore apiStore = RestApiUtil.getConsumer(username);
        String applicationId = body.getApplicationId();
        String apiId = body.getApiIdentifier();
        String tier = body.getPolicy();
        Application application = apiStore.getApplicationByUuid(applicationId);
        if (application != null && !ApplicationStatus.APPLICATION_APPROVED.equals(application.getStatus())) {
            String errorMessage = "Application " + applicationId + " is not active";
            ExceptionCodes exceptionCode = ExceptionCodes.APPLICATION_INACTIVE;
            APIManagementException e = new APIManagementException(errorMessage, exceptionCode);
            Map<String, String> paramList = new HashMap<>();
            ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
            log.error(errorMessage, e);
            return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
        }
        if (application != null) {
            SubscriptionResponse addSubResponse = apiStore.addApiSubscription(apiId, applicationId, tier);
            String subscriptionId = addSubResponse.getSubscriptionUUID();
            Subscription subscription = apiStore.getSubscriptionByUUID(subscriptionId);
            location = new URI(RestApiConstants.RESOURCE_PATH_SUBSCRIPTION + "/" + subscriptionId);
            subscriptionDTO = SubscriptionMappingUtil.fromSubscriptionToDTO(subscription);
            // be in either pending or approved state) send back the workflow response
            if (SubscriptionStatus.ON_HOLD == subscription.getStatus()) {
                WorkflowResponseDTO workflowResponse = MiscMappingUtil.fromWorkflowResponseToDTO(addSubResponse.getWorkflowResponse());
                return Response.status(Response.Status.ACCEPTED).header(RestApiConstants.LOCATION_HEADER, location).entity(workflowResponse).build();
            }
        } else {
            String errorMessage = null;
            ExceptionCodes exceptionCode = null;
            exceptionCode = ExceptionCodes.APPLICATION_NOT_FOUND;
            errorMessage = "Application not found";
            APIMgtResourceNotFoundException e = new APIMgtResourceNotFoundException(errorMessage, exceptionCode);
            Map<String, String> paramList = new HashMap<>();
            ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
            log.error(errorMessage, e);
            return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
        }
    } catch (GatewayException e) {
        String errorMessage = "Failed to add subscription of API : " + body.getApiIdentifier() + " to gateway";
        log.error(errorMessage, e);
        return Response.status(Response.Status.ACCEPTED).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while adding subscriptions";
        Map<String, String> paramList = new HashMap<>();
        paramList.put(APIMgtConstants.ExceptionsConstants.API_ID, body.getApiIdentifier());
        paramList.put(APIMgtConstants.ExceptionsConstants.APPLICATION_ID, body.getApplicationId());
        paramList.put(APIMgtConstants.ExceptionsConstants.TIER, body.getPolicy());
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
        log.error(errorMessage, e);
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    } catch (URISyntaxException e) {
        String errorMessage = "Error while adding location header in response for subscription : " + body.getSubscriptionId();
        Map<String, String> paramList = new HashMap<>();
        paramList.put(APIMgtConstants.ExceptionsConstants.SUBSCRIPTION_ID, body.getSubscriptionId());
        ErrorHandler errorHandler = ExceptionCodes.LOCATION_HEADER_INCORRECT;
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(errorHandler, paramList);
        log.error(errorMessage, e);
        return Response.status(errorHandler.getHttpStatusCode()).entity(errorDTO).build();
    }
    return Response.status(Response.Status.CREATED).header(RestApiConstants.LOCATION_HEADER, location).entity(subscriptionDTO).build();
}
Also used : ErrorHandler(org.wso2.carbon.apimgt.core.exception.ErrorHandler) HashMap(java.util.HashMap) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) URISyntaxException(java.net.URISyntaxException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.core.exception.APIMgtResourceNotFoundException) URI(java.net.URI) WorkflowResponseDTO(org.wso2.carbon.apimgt.rest.api.store.dto.WorkflowResponseDTO) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) GatewayException(org.wso2.carbon.apimgt.core.exception.GatewayException) SubscriptionResponse(org.wso2.carbon.apimgt.core.models.SubscriptionResponse) ExceptionCodes(org.wso2.carbon.apimgt.core.exception.ExceptionCodes) Subscription(org.wso2.carbon.apimgt.core.models.Subscription) SubscriptionDTO(org.wso2.carbon.apimgt.rest.api.store.dto.SubscriptionDTO) Application(org.wso2.carbon.apimgt.core.models.Application) HashMap(java.util.HashMap) Map(java.util.Map) APIStore(org.wso2.carbon.apimgt.core.api.APIStore)

Example 4 with Tier

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

the class TierMappingUtil method fromTierListToDTO.

/**
 * Converts a List object of Tiers into a DTO
 *
 * @param tiers  a list of Tier objects
 * @param limit  max number of objects returned
 * @param offset starting index
 * @return TierListDTO object containing TierDTOs
 */
public static TierListDTO fromTierListToDTO(List<Policy> tiers, String tierLevel, int limit, int offset) {
    TierListDTO tierListDTO = new TierListDTO();
    List<TierDTO> tierDTOs = tierListDTO.getList();
    if (tierDTOs == null) {
        tierDTOs = new ArrayList<>();
        tierListDTO.setList(tierDTOs);
    }
    // identifying the proper start and end indexes
    int size = tiers.size();
    int start = offset < size && offset >= 0 ? offset : Integer.MAX_VALUE;
    int end = offset + limit - 1 <= size - 1 ? offset + limit - 1 : size - 1;
    for (int i = start; i <= end; i++) {
        Policy tier = tiers.get(i);
        tierDTOs.add(fromTierToDTO(tier, tierLevel));
    }
    tierListDTO.setCount(tierDTOs.size());
    return tierListDTO;
}
Also used : Policy(org.wso2.carbon.apimgt.core.models.policy.Policy) TierDTO(org.wso2.carbon.apimgt.rest.api.store.dto.TierDTO) TierListDTO(org.wso2.carbon.apimgt.rest.api.store.dto.TierListDTO)

Example 5 with Tier

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

the class APIStoreImpl method addApiSubscription.

@Override
public SubscriptionResponse addApiSubscription(String apiId, String applicationId, String tier) throws APIManagementException {
    SubscriptionResponse subScriptionResponse;
    // Generate UUID for application
    String subscriptionId = UUID.randomUUID().toString();
    try {
        API api = getAPIbyUUID(apiId);
        Application application = getApplicationByUuid(applicationId);
        if (application == null) {
            String errorMsg = "Cannot find an application for given applicationId - " + applicationId;
            log.error(errorMsg);
            throw new APIManagementException(errorMsg, ExceptionCodes.APPLICATION_NOT_FOUND);
        }
        Policy policy = getPolicyDAO().getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.subscription, tier);
        if (policy == null) {
            String errorMsg = "Cannot find an subscription policy for given policy name - " + tier;
            log.error(errorMsg);
            throw new APIManagementException(errorMsg, ExceptionCodes.POLICY_NOT_FOUND);
        }
        getApiSubscriptionDAO().addAPISubscription(subscriptionId, apiId, applicationId, policy.getUuid(), APIMgtConstants.SubscriptionStatus.ON_HOLD);
        WorkflowExecutor addSubscriptionWFExecutor = WorkflowExecutorFactory.getInstance().getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION);
        // Instead of quering the db, we create same subscription object
        Subscription subscription = new Subscription(subscriptionId, application, api, policy);
        subscription.setStatus(APIMgtConstants.SubscriptionStatus.ON_HOLD);
        SubscriptionCreationWorkflow workflow = new SubscriptionCreationWorkflow(getApiSubscriptionDAO(), getWorkflowDAO(), getApiGateway());
        workflow.setCreatedTime(LocalDateTime.now());
        workflow.setExternalWorkflowReference(UUID.randomUUID().toString());
        workflow.setWorkflowReference(subscriptionId);
        workflow.setWorkflowType(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION);
        workflow.setSubscription(subscription);
        workflow.setSubscriber(getUsername());
        String workflowDescription = "API [ " + subscription.getApi().getName() + " - " + subscription.getApi().getVersion() + " ] subscription creation request from subscriber - " + getUsername() + "  for the application - " + subscription.getApplication().getName() + "";
        workflow.setWorkflowDescription(workflowDescription);
        WorkflowResponse response = addSubscriptionWFExecutor.execute(workflow);
        workflow.setStatus(response.getWorkflowStatus());
        if (WorkflowStatus.CREATED != response.getWorkflowStatus()) {
            completeWorkflow(addSubscriptionWFExecutor, workflow);
        } else {
            // only add entry to workflow table if it is a pending task
            addWorkflowEntries(workflow);
        }
        subScriptionResponse = new SubscriptionResponse(subscriptionId, response);
    } catch (APIMgtDAOException e) {
        String errorMsg = "Error occurred while adding api subscription for api - " + apiId;
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    }
    return subScriptionResponse;
}
Also used : Policy(org.wso2.carbon.apimgt.core.models.policy.Policy) APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) SubscriptionCreationWorkflow(org.wso2.carbon.apimgt.core.workflow.SubscriptionCreationWorkflow) WorkflowResponse(org.wso2.carbon.apimgt.core.api.WorkflowResponse) SubscriptionResponse(org.wso2.carbon.apimgt.core.models.SubscriptionResponse) CompositeAPI(org.wso2.carbon.apimgt.core.models.CompositeAPI) API(org.wso2.carbon.apimgt.core.models.API) WorkflowExecutor(org.wso2.carbon.apimgt.core.api.WorkflowExecutor) Subscription(org.wso2.carbon.apimgt.core.models.Subscription) Application(org.wso2.carbon.apimgt.core.models.Application)

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