Search in sources :

Example 71 with Policy

use of org.wso2.carbon.apimgt.api.model.policy.Policy 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)

Example 72 with Policy

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

the class APIStoreImpl method addApplication.

@Override
public ApplicationCreationResponse addApplication(Application application) throws APIManagementException {
    ApplicationCreationResponse applicationResponse = null;
    try {
        if (getApplicationDAO().isApplicationNameExists(application.getName())) {
            String message = "An application already exists with a duplicate name - " + application.getName();
            log.error(message);
            throw new APIMgtResourceAlreadyExistsException(message, ExceptionCodes.APPLICATION_ALREADY_EXISTS);
        }
        // Tier validation
        Policy tier = application.getPolicy();
        if (tier == null) {
            String message = "Tier name cannot be null - " + application.getName();
            log.error(message);
            throw new APIManagementException(message, ExceptionCodes.TIER_CANNOT_BE_NULL);
        } else {
            Policy policy = getPolicyDAO().getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.application, tier.getPolicyName());
            if (policy == null) {
                String message = "Specified tier " + tier.getPolicyName() + " is invalid";
                log.error(message);
                throw new APIManagementException(message, ExceptionCodes.TIER_CANNOT_BE_NULL);
            }
            application.setPolicy(policy);
        }
        // Generate UUID for application
        String generatedUuid = UUID.randomUUID().toString();
        application.setId(generatedUuid);
        String permissionString = application.getPermissionString();
        if (permissionString != null && !("").equals(permissionString)) {
            HashMap roleNamePermissionList;
            roleNamePermissionList = getAPIPermissionArray(permissionString);
            application.setPermissionMap(roleNamePermissionList);
        }
        application.setCreatedTime(LocalDateTime.now());
        getApplicationDAO().addApplication(application);
        WorkflowExecutor appCreationWFExecutor = WorkflowExecutorFactory.getInstance().getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION);
        ApplicationCreationWorkflow workflow = new ApplicationCreationWorkflow(getApplicationDAO(), getWorkflowDAO(), getApiGateway());
        workflow.setApplication(application);
        workflow.setCreatedBy(getUsername());
        workflow.setWorkflowReference(application.getId());
        workflow.setExternalWorkflowReference(UUID.randomUUID().toString());
        workflow.setCreatedTime(LocalDateTime.now());
        String workflowDescription = "Application [ " + application.getName() + " ] creation request from application creator - " + getUsername() + " with throttling tier - " + tier.getPolicyName() + "";
        workflow.setWorkflowDescription(workflowDescription);
        WorkflowResponse response = appCreationWFExecutor.execute(workflow);
        workflow.setStatus(response.getWorkflowStatus());
        if (WorkflowStatus.CREATED != response.getWorkflowStatus()) {
            completeWorkflow(appCreationWFExecutor, workflow);
        } else {
            getApplicationDAO().updateApplicationState(generatedUuid, APIMgtConstants.ApplicationStatus.APPLICATION_ONHOLD);
            addWorkflowEntries(workflow);
        }
        APIUtils.logDebug("successfully added application with appId " + application.getId(), log);
        applicationResponse = new ApplicationCreationResponse(application.getId(), response);
    } catch (APIMgtDAOException e) {
        String errorMsg = "Error occurred while creating the application - " + application.getName();
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    } catch (ParseException e) {
        String errorMsg = "Error occurred while parsing the permission json from swagger in application - " + application.getName();
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, ExceptionCodes.SWAGGER_PARSE_EXCEPTION);
    } catch (WorkflowException e) {
        String errorMsg = "Error occurred in workflow";
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, ExceptionCodes.WORKFLOW_EXCEPTION);
    }
    return applicationResponse;
}
Also used : Policy(org.wso2.carbon.apimgt.core.models.policy.Policy) APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) ApplicationCreationResponse(org.wso2.carbon.apimgt.core.workflow.ApplicationCreationResponse) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) HashMap(java.util.HashMap) WorkflowException(org.wso2.carbon.apimgt.core.exception.WorkflowException) APIMgtResourceAlreadyExistsException(org.wso2.carbon.apimgt.core.exception.APIMgtResourceAlreadyExistsException) ApplicationCreationWorkflow(org.wso2.carbon.apimgt.core.workflow.ApplicationCreationWorkflow) WorkflowResponse(org.wso2.carbon.apimgt.core.api.WorkflowResponse) WorkflowExecutor(org.wso2.carbon.apimgt.core.api.WorkflowExecutor) ParseException(org.json.simple.parser.ParseException)

Example 73 with Policy

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

the class APIStoreImpl method updateApplication.

@Override
public WorkflowResponse updateApplication(String uuid, Application application) throws APIManagementException {
    try {
        // get old app
        Application existingApplication = getApplicationDAO().getApplication(uuid);
        if (existingApplication != null) {
            WorkflowExecutor executor = WorkflowExecutorFactory.getInstance().getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_UPDATE);
            ApplicationUpdateWorkflow workflow = new ApplicationUpdateWorkflow(getApplicationDAO(), getWorkflowDAO(), getApiGateway());
            application.setId(uuid);
            application.setUpdatedUser(getUsername());
            application.setUpdatedTime(LocalDateTime.now());
            Policy appTier = application.getPolicy();
            if (appTier != null && !appTier.getPolicyName().equals(existingApplication.getPolicy().getPolicyName())) {
                Policy policy = getPolicyDAO().getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.application, appTier.getPolicyName());
                if (policy == null) {
                    String message = "Specified tier " + appTier + " is invalid";
                    log.error(message);
                    throw new APIManagementException(message, ExceptionCodes.TIER_NAME_INVALID);
                }
                application.setPolicy(policy);
            }
            workflow.setExistingApplication(existingApplication);
            workflow.setUpdatedApplication(application);
            workflow.setCreatedBy(getUsername());
            workflow.setWorkflowReference(application.getId());
            workflow.setExternalWorkflowReference(UUID.randomUUID().toString());
            workflow.setCreatedTime(LocalDateTime.now());
            String workflowDescription = "Update application " + existingApplication.getName() + " with tier " + existingApplication.getPolicy().getPolicyName() + " and description \'" + existingApplication.getDescription() + "\' To " + application.getName() + " with tier " + application.getPolicy().getPolicyName() + " and description \'" + application.getDescription() + "\' by " + getUsername();
            workflow.setWorkflowDescription(workflowDescription);
            // setting attributes for internal use. These are set to use from outside the executor's method
            // these will be saved in the AM_WORKFLOW table so these can be retrieved later for external wf approval
            // scenarios. this won't get stored for simple wfs
            workflow.setAttribute(WorkflowConstants.ATTRIBUTE_APPLICATION_NAME, application.getName());
            workflow.setAttribute(WorkflowConstants.ATTRIBUTE_APPLICATION_UPDATEDBY, application.getUpdatedUser());
            workflow.setAttribute(WorkflowConstants.ATTRIBUTE_APPLICATION_TIER, application.getPolicy().getPolicyName());
            workflow.setAttribute(WorkflowConstants.ATTRIBUTE_APPLICATION_POLICY_ID, application.getPolicy().getUuid());
            workflow.setAttribute(WorkflowConstants.ATTRIBUTE_APPLICATION_DESCRIPTION, application.getDescription());
            workflow.setAttribute(WorkflowConstants.ATTRIBUTE_APPLICATION_PERMISSION, application.getPermissionString());
            workflow.setAttribute(WorkflowConstants.ATTRIBUTE_APPLICATION_EXISTIN_APP_STATUS, existingApplication.getStatus());
            WorkflowResponse response = executor.execute(workflow);
            workflow.setStatus(response.getWorkflowStatus());
            if (WorkflowStatus.CREATED != response.getWorkflowStatus()) {
                completeWorkflow(executor, workflow);
            } else {
                getApplicationDAO().updateApplicationState(uuid, ApplicationStatus.APPLICATION_ONHOLD);
                addWorkflowEntries(workflow);
            }
            return response;
        } else {
            String errorMsg = "Applicaiton does not exist - " + uuid;
            log.error(errorMsg);
            throw new APIManagementException(errorMsg, ExceptionCodes.APPLICATION_NOT_FOUND);
        }
    } catch (APIMgtDAOException e) {
        String errorMsg = "Error occurred while updating the application - " + uuid;
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    }
}
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) ApplicationUpdateWorkflow(org.wso2.carbon.apimgt.core.workflow.ApplicationUpdateWorkflow) WorkflowResponse(org.wso2.carbon.apimgt.core.api.WorkflowResponse) WorkflowExecutor(org.wso2.carbon.apimgt.core.api.WorkflowExecutor) Application(org.wso2.carbon.apimgt.core.models.Application)

Example 74 with Policy

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

the class PolicyDAOImplIT method testGetSubscriptionPolicies.

@Test(description = "Get Subscription Policies")
public void testGetSubscriptionPolicies() throws Exception {
    SubscriptionPolicy policy = SampleTestObjectCreator.createDefaultSubscriptionPolicy();
    SubscriptionPolicy policy2 = SampleTestObjectCreator.createSubscriptionPolicyWithBandwithLimit();
    // policy 1 has following 2 true. checking for fault scenario from policy2
    policy2.setStopOnQuotaReach(false);
    policy2.setDeployed(false);
    PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
    // add policy
    policyDAO.addSubscriptionPolicy(policy);
    policyDAO.addSubscriptionPolicy(policy2);
    List<SubscriptionPolicy> policyList = policyDAO.getSubscriptionPolicies();
    Assert.assertNotNull(policyList);
    SubscriptionPolicy retrievedPolicy = null;
    SubscriptionPolicy retrievedPolicy2 = null;
    // there are defaut policies already there
    for (Iterator iterator = policyList.iterator(); iterator.hasNext(); ) {
        SubscriptionPolicy subscriptionPolicy = (SubscriptionPolicy) iterator.next();
        if (subscriptionPolicy.getPolicyName().equals(policy.getPolicyName())) {
            retrievedPolicy = policy;
        }
        if (subscriptionPolicy.getPolicyName().equals(policy2.getPolicyName())) {
            retrievedPolicy2 = policy2;
        }
    }
    Assert.assertNotNull(retrievedPolicy, "Policy " + policy.getPolicyName() + " not in DB");
    Assert.assertNotNull(retrievedPolicy2, "Policy " + policy2.getPolicyName() + " not in DB");
    Assert.assertEquals(retrievedPolicy.getPolicyName(), policy.getPolicyName(), "Subscription policy name mismatch");
    Assert.assertEquals(retrievedPolicy.getDisplayName(), policy.getDisplayName(), "Subscription policy display name mismatch");
    Assert.assertEquals(retrievedPolicy.getDescription(), policy.getDescription(), "Subscription policy description mismatch");
    Assert.assertEquals(retrievedPolicy.isDeployed(), policy.isDeployed(), "Subscription policy isDeployed mismatch");
    Assert.assertEquals(retrievedPolicy.getRateLimitCount(), policy.getRateLimitCount(), "Subscription policy rate limit mismatch");
    Assert.assertEquals(retrievedPolicy.getRateLimitTimeUnit(), policy.getRateLimitTimeUnit(), "Subscription policy rate limit mismatch");
    Assert.assertEquals(retrievedPolicy.isStopOnQuotaReach(), policy.isStopOnQuotaReach(), "Subscription policy stop on quota reach mismatch");
    Assert.assertEquals(retrievedPolicy.getCustomAttributes(), policy.getCustomAttributes(), "Subscription policy custom attribute mismatch");
    Assert.assertEquals(retrievedPolicy.getDefaultQuotaPolicy().getType(), policy.getDefaultQuotaPolicy().getType(), "Subscription policy default quota type mismatch");
    RequestCountLimit limitRetrieved = (RequestCountLimit) retrievedPolicy.getDefaultQuotaPolicy().getLimit();
    RequestCountLimit policyLimit = (RequestCountLimit) policy.getDefaultQuotaPolicy().getLimit();
    Assert.assertEquals(limitRetrieved.getRequestCount(), policyLimit.getRequestCount(), "Subscription policy default quota count mismatch");
    Assert.assertEquals(limitRetrieved.getTimeUnit(), policyLimit.getTimeUnit(), "Subscription policy default quota time unit mismatch");
    Assert.assertEquals(limitRetrieved.getUnitTime(), policyLimit.getUnitTime(), "Subscription policy default quota unit time mismatch");
    // check policy related properties for policy 2
    Assert.assertEquals(retrievedPolicy2.getPolicyName(), policy2.getPolicyName(), "Subscription policy name mismatch");
    Assert.assertEquals(retrievedPolicy2.getDisplayName(), policy2.getDisplayName(), "Subscription policy display name mismatch");
    Assert.assertEquals(retrievedPolicy2.getDescription(), policy2.getDescription(), "Subscription policy description mismatch");
    Assert.assertEquals(retrievedPolicy2.isDeployed(), policy2.isDeployed(), "Subscription policy isDeployed mismatch");
    Assert.assertEquals(retrievedPolicy2.getRateLimitCount(), policy2.getRateLimitCount(), "Subscription policy rate limit mismatch");
    Assert.assertEquals(retrievedPolicy2.getRateLimitTimeUnit(), policy2.getRateLimitTimeUnit(), "Subscription policy rate limit mismatch");
    Assert.assertEquals(retrievedPolicy2.isStopOnQuotaReach(), policy2.isStopOnQuotaReach(), "Subscription policy stop on quota reach mismatch");
    Assert.assertEquals(retrievedPolicy2.getCustomAttributes(), policy2.getCustomAttributes(), "Subscription policy custom attribute mismatch");
    Assert.assertEquals(retrievedPolicy2.getDefaultQuotaPolicy().getType(), policy2.getDefaultQuotaPolicy().getType(), "Subscription policy default quota type mismatch");
    BandwidthLimit limitRetrieved2 = (BandwidthLimit) retrievedPolicy2.getDefaultQuotaPolicy().getLimit();
    BandwidthLimit policyLimit2 = (BandwidthLimit) policy2.getDefaultQuotaPolicy().getLimit();
    Assert.assertEquals(limitRetrieved2.getDataAmount(), policyLimit2.getDataAmount(), "Subscription policy default quota data amount mismatch");
    Assert.assertEquals(limitRetrieved2.getDataUnit(), policyLimit2.getDataUnit(), "Subscription policy default quota data amount mismatch");
    Assert.assertEquals(limitRetrieved2.getTimeUnit(), policyLimit2.getTimeUnit(), "Subscription policy default quota time unit mismatch");
    Assert.assertEquals(limitRetrieved2.getUnitTime(), policyLimit2.getUnitTime(), "Subscription policy default quota unit time mismatch");
}
Also used : RequestCountLimit(org.wso2.carbon.apimgt.core.models.policy.RequestCountLimit) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) Iterator(java.util.Iterator) PolicyDAO(org.wso2.carbon.apimgt.core.dao.PolicyDAO) BandwidthLimit(org.wso2.carbon.apimgt.core.models.policy.BandwidthLimit) Test(org.testng.annotations.Test)

Example 75 with Policy

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

the class PolicyDAOImplIT method testAddGetAndDeleteApiPolicy.

@Test(description = "Add, Get and Delete an API policy")
public void testAddGetAndDeleteApiPolicy() throws Exception {
    APIPolicy policy = SampleTestObjectCreator.createDefaultAPIPolicy();
    PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
    // add policy
    policyDAO.addApiPolicy(policy);
    // get added policy
    Policy addedPolicy = policyDAO.getApiPolicy(policy.getPolicyName());
    Assert.assertNotNull(addedPolicy);
    Assert.assertEquals(addedPolicy.getPolicyName(), policy.getPolicyName());
    // delete policy
    policyDAO.deletePolicy(APIMgtAdminService.PolicyLevel.api, policy.getPolicyName());
    // get policy after deletion
    try {
        policyDAO.getApiPolicy(policy.getPolicyName());
        Assert.fail("Exception expected, but not thrown.");
    } catch (APIMgtDAOException ex) {
        Assert.assertEquals(ex.getMessage(), "API Policy not found for name: " + addedPolicy.getPolicyName());
    }
    try {
        policyDAO.getApiPolicyByUuid(policy.getUuid());
        Assert.fail("Exception expected, but not thrown.");
    } catch (APIMgtDAOException ex) {
        Assert.assertEquals(ex.getMessage(), "API Policy not found for id: " + addedPolicy.getUuid());
    }
}
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) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy) CustomPolicy(org.wso2.carbon.apimgt.core.models.policy.CustomPolicy) APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy) PolicyDAO(org.wso2.carbon.apimgt.core.dao.PolicyDAO) Test(org.testng.annotations.Test)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)114 Test (org.testng.annotations.Test)106 ArrayList (java.util.ArrayList)96 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)79 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)73 SubscriptionPolicy (org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy)73 Test (org.junit.Test)72 PreparedStatement (java.sql.PreparedStatement)68 APIPolicy (org.wso2.carbon.apimgt.core.models.policy.APIPolicy)64 Policy (org.wso2.carbon.apimgt.core.models.policy.Policy)63 SQLException (java.sql.SQLException)62 PolicyDAO (org.wso2.carbon.apimgt.core.dao.PolicyDAO)62 Connection (java.sql.Connection)58 ApplicationPolicy (org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy)58 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)54 ResultSet (java.sql.ResultSet)49 SubscriptionPolicy (org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy)43 HashMap (java.util.HashMap)40 APIPolicy (org.wso2.carbon.apimgt.api.model.policy.APIPolicy)40 CustomPolicy (org.wso2.carbon.apimgt.core.models.policy.CustomPolicy)40