Search in sources :

Example 16 with ApplicationEvent

use of org.wso2.carbon.apimgt.impl.notifier.events.ApplicationEvent in project carbon-apimgt by wso2.

the class APIConsumerImpl method removeApplication.

/**
 * Function to remove an Application from the API Store
 *
 * @param application - The Application Object that represents the Application
 * @param username
 * @throws APIManagementException
 */
@Override
public void removeApplication(Application application, String username) throws APIManagementException {
    String uuid = application.getUUID();
    Map<String, Pair<String, String>> consumerKeysOfApplication = null;
    if (application.getId() == 0 && !StringUtils.isEmpty(uuid)) {
        application = apiMgtDAO.getApplicationByUUID(uuid);
    }
    consumerKeysOfApplication = apiMgtDAO.getConsumerKeysForApplication(application.getId());
    boolean isTenantFlowStarted = false;
    int applicationId = application.getId();
    boolean isCaseInsensitiveComparisons = Boolean.parseBoolean(getAPIManagerConfiguration().getFirstProperty(APIConstants.API_STORE_FORCE_CI_COMPARISIONS));
    boolean isUserAppOwner;
    if (isCaseInsensitiveComparisons) {
        isUserAppOwner = application.getSubscriber().getName().equalsIgnoreCase(username);
    } else {
        isUserAppOwner = application.getSubscriber().getName().equals(username);
    }
    if (!isUserAppOwner) {
        throw new APIManagementException("user: " + username + ", " + "attempted to remove application owned by: " + application.getSubscriber().getName());
    }
    try {
        String workflowExtRef;
        ApplicationWorkflowDTO workflowDTO;
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            PrivilegedCarbonContext.startTenantFlow();
            isTenantFlowStarted = true;
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        }
        WorkflowExecutor createApplicationWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION);
        WorkflowExecutor createSubscriptionWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION);
        WorkflowExecutor createProductionRegistrationWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION);
        WorkflowExecutor createSandboxRegistrationWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX);
        WorkflowExecutor removeApplicationWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_DELETION);
        workflowExtRef = apiMgtDAO.getExternalWorkflowReferenceByApplicationID(application.getId());
        // in a normal flow workflowExtRef is null when workflows are not enabled
        if (workflowExtRef == null) {
            workflowDTO = new ApplicationWorkflowDTO();
        } else {
            workflowDTO = (ApplicationWorkflowDTO) apiMgtDAO.retrieveWorkflow(workflowExtRef);
        }
        workflowDTO.setApplication(application);
        workflowDTO.setCallbackUrl(removeApplicationWFExecutor.getCallbackURL());
        workflowDTO.setUserName(this.username);
        workflowDTO.setTenantDomain(tenantDomain);
        workflowDTO.setTenantId(tenantId);
        // clean up pending subscription tasks
        Set<Integer> pendingSubscriptions = apiMgtDAO.getPendingSubscriptionsByApplicationId(applicationId);
        for (int subscription : pendingSubscriptions) {
            try {
                workflowExtRef = apiMgtDAO.getExternalWorkflowReferenceForSubscription(subscription);
                createSubscriptionWFExecutor.cleanUpPendingTask(workflowExtRef);
            } catch (APIManagementException ex) {
                // failed cleanup processes are ignored to prevent failing the application removal process
                log.warn("Failed to get external workflow reference for subscription " + subscription);
            } catch (WorkflowException ex) {
                // failed cleanup processes are ignored to prevent failing the application removal process
                log.warn("Failed to clean pending subscription approval task: " + subscription);
            }
        }
        // cleanup pending application registration tasks
        Map<String, String> keyManagerWiseProductionKeyStatus = apiMgtDAO.getRegistrationApprovalState(applicationId, APIConstants.API_KEY_TYPE_PRODUCTION);
        Map<String, String> keyManagerWiseSandboxKeyStatus = apiMgtDAO.getRegistrationApprovalState(applicationId, APIConstants.API_KEY_TYPE_SANDBOX);
        keyManagerWiseProductionKeyStatus.forEach((keyManagerName, state) -> {
            if (WorkflowStatus.CREATED.toString().equals(state)) {
                try {
                    String applicationRegistrationExternalRef = apiMgtDAO.getRegistrationWFReference(applicationId, APIConstants.API_KEY_TYPE_PRODUCTION, keyManagerName);
                    createProductionRegistrationWFExecutor.cleanUpPendingTask(applicationRegistrationExternalRef);
                } catch (APIManagementException ex) {
                    // failed cleanup processes are ignored to prevent failing the application removal process
                    log.warn("Failed to get external workflow reference for production key of application " + applicationId);
                } catch (WorkflowException ex) {
                    // failed cleanup processes are ignored to prevent failing the application removal process
                    log.warn("Failed to clean pending production key approval task of " + applicationId);
                }
            }
        });
        keyManagerWiseSandboxKeyStatus.forEach((keyManagerName, state) -> {
            if (WorkflowStatus.CREATED.toString().equals(state)) {
                try {
                    String applicationRegistrationExternalRef = apiMgtDAO.getRegistrationWFReference(applicationId, APIConstants.API_KEY_TYPE_SANDBOX, keyManagerName);
                    createSandboxRegistrationWFExecutor.cleanUpPendingTask(applicationRegistrationExternalRef);
                } catch (APIManagementException ex) {
                    // failed cleanup processes are ignored to prevent failing the application removal process
                    log.warn("Failed to get external workflow reference for sandbox key of application " + applicationId);
                } catch (WorkflowException ex) {
                    // failed cleanup processes are ignored to prevent failing the application removal process
                    log.warn("Failed to clean pending sandbox key approval task of " + applicationId);
                }
            }
        });
        if (workflowExtRef != null) {
            try {
                createApplicationWFExecutor.cleanUpPendingTask(workflowExtRef);
            } catch (WorkflowException ex) {
                // failed cleanup processes are ignored to prevent failing the application removal process
                log.warn("Failed to clean pending application approval task of " + applicationId);
            }
        }
        // update attributes of the new remove workflow to be created
        workflowDTO.setStatus(WorkflowStatus.CREATED);
        workflowDTO.setCreatedTime(System.currentTimeMillis());
        workflowDTO.setWorkflowType(WorkflowConstants.WF_TYPE_AM_APPLICATION_DELETION);
        workflowDTO.setExternalWorkflowReference(removeApplicationWFExecutor.generateUUID());
        removeApplicationWFExecutor.execute(workflowDTO);
        JSONObject appLogObject = new JSONObject();
        appLogObject.put(APIConstants.AuditLogConstants.NAME, application.getName());
        appLogObject.put(APIConstants.AuditLogConstants.TIER, application.getTier());
        appLogObject.put(APIConstants.AuditLogConstants.CALLBACK, application.getCallbackUrl());
        appLogObject.put(APIConstants.AuditLogConstants.GROUPS, application.getGroupId());
        appLogObject.put(APIConstants.AuditLogConstants.OWNER, application.getSubscriber().getName());
        APIUtil.logAuditMessage(APIConstants.AuditLogConstants.APPLICATION, appLogObject.toString(), APIConstants.AuditLogConstants.DELETED, this.username);
    } catch (WorkflowException e) {
        String errorMsg = "Could not execute Workflow, " + WorkflowConstants.WF_TYPE_AM_APPLICATION_DELETION + " " + "for applicationID " + application.getId();
        handleException(errorMsg, e);
    } finally {
        if (isTenantFlowStarted) {
            endTenantFlow();
        }
    }
    if (log.isDebugEnabled()) {
        String logMessage = "Application Name: " + application.getName() + " successfully removed";
        log.debug(logMessage);
    }
    // Extracting API details for the recommendation system
    if (recommendationEnvironment != null) {
        RecommenderEventPublisher extractor = new RecommenderDetailsExtractor(applicationId, username, requestedTenant);
        Thread recommendationThread = new Thread(extractor);
        recommendationThread.start();
    }
    // get the workflow state once the executor is executed.
    WorkflowDTO wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(Integer.toString(applicationId), WorkflowConstants.WF_TYPE_AM_APPLICATION_DELETION);
    // 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()) || wfDTO.getStatus() == null) {
            ApplicationEvent applicationEvent = new ApplicationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.APPLICATION_DELETE.name(), tenantId, application.getOrganization(), applicationId, application.getUUID(), application.getName(), application.getTokenType(), application.getTier(), application.getGroupId(), Collections.EMPTY_MAP, username);
            APIUtil.sendNotification(applicationEvent, APIConstants.NotifierType.APPLICATION.name());
        }
    } else {
        ApplicationEvent applicationEvent = new ApplicationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.APPLICATION_DELETE.name(), tenantId, application.getOrganization(), applicationId, application.getUUID(), application.getName(), application.getTokenType(), application.getTier(), application.getGroupId(), Collections.EMPTY_MAP, username);
        APIUtil.sendNotification(applicationEvent, APIConstants.NotifierType.APPLICATION.name());
    }
    if (consumerKeysOfApplication != null && consumerKeysOfApplication.size() > 0) {
        for (Map.Entry<String, Pair<String, String>> entry : consumerKeysOfApplication.entrySet()) {
            String consumerKey = entry.getKey();
            String keyManagerName = entry.getValue().getKey();
            String keyManagerTenantDomain = entry.getValue().getValue();
            ApplicationRegistrationEvent removeEntryTrigger = new ApplicationRegistrationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.REMOVE_APPLICATION_KEYMAPPING.name(), APIUtil.getTenantIdFromTenantDomain(keyManagerTenantDomain), keyManagerTenantDomain, application.getId(), application.getUUID(), consumerKey, application.getKeyType(), keyManagerName);
            APIUtil.sendNotification(removeEntryTrigger, APIConstants.NotifierType.APPLICATION_REGISTRATION.name());
        }
    }
}
Also used : 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) RecommenderDetailsExtractor(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommenderDetailsExtractor) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) ApplicationEvent(org.wso2.carbon.apimgt.impl.notifier.events.ApplicationEvent) ApplicationRegistrationEvent(org.wso2.carbon.apimgt.impl.notifier.events.ApplicationRegistrationEvent) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONObject(org.json.simple.JSONObject) ApplicationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationWorkflowDTO) RecommenderEventPublisher(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommenderEventPublisher) WorkflowExecutor(org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutor) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) Pair(org.apache.commons.lang3.tuple.Pair)

Example 17 with ApplicationEvent

use of org.wso2.carbon.apimgt.impl.notifier.events.ApplicationEvent in project carbon-apimgt by wso2.

the class APIConsumerImpl method addApplication.

/**
 * Add a new Application from the store.
 * @param application - {@link org.wso2.carbon.apimgt.api.model.Application}
 * @param userId - {@link String}
 * @param organization
 * @return {@link String}
 */
@Override
public int addApplication(Application application, String userId, String organization) throws APIManagementException {
    if (APIUtil.isOnPremResolver()) {
        organization = tenantDomain;
    }
    if (application.getName() != null && (application.getName().length() != application.getName().trim().length())) {
        handleApplicationNameContainSpacesException("Application name " + "cannot contain leading or trailing white spaces");
    }
    validateApplicationPolicy(application, organization);
    JSONArray applicationAttributesFromConfig = getAppAttributesFromConfig(userId);
    Map<String, String> applicationAttributes = application.getApplicationAttributes();
    if (applicationAttributes == null) {
        /*
             * This empty Hashmap is set to avoid throwing a null pointer exception, in case no application attributes
             * are set when creating an application
             */
        applicationAttributes = new HashMap<String, String>();
    }
    Set<String> configAttributes = new HashSet<>();
    if (applicationAttributesFromConfig != null) {
        for (Object object : applicationAttributesFromConfig) {
            JSONObject attribute = (JSONObject) object;
            Boolean hidden = (Boolean) attribute.get(APIConstants.ApplicationAttributes.HIDDEN);
            Boolean required = (Boolean) attribute.get(APIConstants.ApplicationAttributes.REQUIRED);
            String attributeName = (String) attribute.get(APIConstants.ApplicationAttributes.ATTRIBUTE);
            String defaultValue = (String) attribute.get(APIConstants.ApplicationAttributes.DEFAULT);
            if (BooleanUtils.isTrue(hidden) && BooleanUtils.isTrue(required) && StringUtils.isEmpty(defaultValue)) {
                /*
                     * In case a default value is not provided for a required hidden attribute, an exception is thrown,
                     * we don't do this validation in server startup to support multi tenancy scenarios
                     */
                handleException("Default value not provided for hidden required attribute. Please check the " + "configuration");
            }
            configAttributes.add(attributeName);
            if (BooleanUtils.isTrue(required)) {
                if (BooleanUtils.isTrue(hidden)) {
                    /*
                         * If a required hidden attribute is attempted to be populated, we replace it with
                         * the default value.
                         */
                    String oldValue = applicationAttributes.put(attributeName, defaultValue);
                    if (StringUtils.isNotEmpty(oldValue)) {
                        log.info("Replaced provided value: " + oldValue + " with default the value" + " for the hidden application attribute: " + attributeName);
                    }
                } else if (!applicationAttributes.keySet().contains(attributeName)) {
                    if (StringUtils.isNotEmpty(defaultValue)) {
                        /*
                             * If a required attribute is not provided and a default value is given, we replace it with
                             * the default value.
                             */
                        applicationAttributes.put(attributeName, defaultValue);
                        log.info("Added default value: " + defaultValue + " as required attribute: " + attributeName + "is not provided");
                    } else {
                        /*
                             * If a required attribute is not provided but a default value not given, we throw a bad
                             * request exception.
                             */
                        handleException("Bad Request. Required application attribute not provided");
                    }
                }
            } else if (BooleanUtils.isTrue(hidden)) {
                /*
                     * If an optional hidden attribute is provided, we remove it and leave it blank, and leave it for
                     * an extension to populate it.
                     */
                applicationAttributes.remove(attributeName);
            }
        }
        application.setApplicationAttributes(validateApplicationAttributes(applicationAttributes, configAttributes));
    } else {
        application.setApplicationAttributes(null);
    }
    application.setUUID(UUID.randomUUID().toString());
    if (APIUtil.isApplicationExist(userId, application.getName(), application.getGroupId(), organization)) {
        handleResourceAlreadyExistsException("A duplicate application already exists by the name - " + application.getName());
    }
    // check whether callback url is empty and set null
    if (StringUtils.isBlank(application.getCallbackUrl())) {
        application.setCallbackUrl(null);
    }
    int applicationId = apiMgtDAO.addApplication(application, userId, organization);
    JSONObject appLogObject = new JSONObject();
    appLogObject.put(APIConstants.AuditLogConstants.NAME, application.getName());
    appLogObject.put(APIConstants.AuditLogConstants.TIER, application.getTier());
    appLogObject.put(APIConstants.AuditLogConstants.CALLBACK, application.getCallbackUrl());
    appLogObject.put(APIConstants.AuditLogConstants.GROUPS, application.getGroupId());
    appLogObject.put(APIConstants.AuditLogConstants.OWNER, application.getSubscriber().getName());
    APIUtil.logAuditMessage(APIConstants.AuditLogConstants.APPLICATION, appLogObject.toString(), APIConstants.AuditLogConstants.CREATED, this.username);
    boolean isTenantFlowStarted = false;
    if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
        isTenantFlowStarted = startTenantFlowForTenantDomain(tenantDomain);
    }
    try {
        WorkflowExecutor appCreationWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION);
        ApplicationWorkflowDTO appWFDto = new ApplicationWorkflowDTO();
        appWFDto.setApplication(application);
        appWFDto.setExternalWorkflowReference(appCreationWFExecutor.generateUUID());
        appWFDto.setWorkflowReference(String.valueOf(applicationId));
        appWFDto.setWorkflowType(WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION);
        appWFDto.setCallbackUrl(appCreationWFExecutor.getCallbackURL());
        appWFDto.setStatus(WorkflowStatus.CREATED);
        appWFDto.setTenantDomain(organization);
        appWFDto.setTenantId(tenantId);
        appWFDto.setUserName(userId);
        appWFDto.setCreatedTime(System.currentTimeMillis());
        appCreationWFExecutor.execute(appWFDto);
    } catch (WorkflowException e) {
        // If the workflow execution fails, roll back transaction by removing the application entry.
        application.setId(applicationId);
        apiMgtDAO.deleteApplication(application);
        log.error("Unable to execute Application Creation Workflow", e);
        handleException("Unable to execute Application Creation Workflow", e);
    } finally {
        if (isTenantFlowStarted) {
            endTenantFlow();
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Application Name: " + application.getName() + " added successfully.");
    }
    // Extracting API details for the recommendation system
    if (recommendationEnvironment != null) {
        RecommenderEventPublisher extractor = new RecommenderDetailsExtractor(application, userId, applicationId, requestedTenant);
        Thread recommendationThread = new Thread(extractor);
        recommendationThread.start();
    }
    // get the workflow state once the executor is executed.
    WorkflowDTO wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(Integer.toString(applicationId), WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION);
    // 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())) {
            ApplicationEvent applicationEvent = new ApplicationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.APPLICATION_CREATE.name(), tenantId, organization, applicationId, application.getUUID(), application.getName(), application.getTokenType(), application.getTier(), application.getGroupId(), application.getApplicationAttributes(), userId);
            APIUtil.sendNotification(applicationEvent, APIConstants.NotifierType.APPLICATION.name());
        }
    } else {
        ApplicationEvent applicationEvent = new ApplicationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.APPLICATION_CREATE.name(), tenantId, organization, applicationId, application.getUUID(), application.getName(), application.getTokenType(), application.getTier(), application.getGroupId(), application.getApplicationAttributes(), userId);
        APIUtil.sendNotification(applicationEvent, APIConstants.NotifierType.APPLICATION.name());
    }
    return applicationId;
}
Also used : 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) RecommenderDetailsExtractor(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommenderDetailsExtractor) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) JSONArray(org.json.simple.JSONArray) ApplicationEvent(org.wso2.carbon.apimgt.impl.notifier.events.ApplicationEvent) JSONObject(org.json.simple.JSONObject) ApplicationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationWorkflowDTO) RecommenderEventPublisher(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommenderEventPublisher) JSONObject(org.json.simple.JSONObject) WorkflowExecutor(org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutor) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 18 with ApplicationEvent

use of org.wso2.carbon.apimgt.impl.notifier.events.ApplicationEvent in project carbon-apimgt by wso2.

the class APIConsumerImpl method updateApplication.

/**
 * Updates an Application identified by its id
 *
 * @param application Application object to be updated
 * @throws APIManagementException
 */
@Override
public void updateApplication(Application application) throws APIManagementException {
    Application existingApp;
    String uuid = application.getUUID();
    if (!StringUtils.isEmpty(uuid)) {
        existingApp = apiMgtDAO.getApplicationByUUID(uuid);
        application.setId(existingApp.getId());
    } else {
        existingApp = apiMgtDAO.getApplicationById(application.getId());
    }
    if (existingApp != null && APIConstants.ApplicationStatus.APPLICATION_CREATED.equals(existingApp.getStatus())) {
        throw new APIManagementException("Cannot update the application while it is INACTIVE");
    }
    boolean isCaseInsensitiveComparisons = Boolean.parseBoolean(getAPIManagerConfiguration().getFirstProperty(APIConstants.API_STORE_FORCE_CI_COMPARISIONS));
    boolean isUserAppOwner;
    if (isCaseInsensitiveComparisons) {
        isUserAppOwner = application.getSubscriber().getName().equalsIgnoreCase(existingApp.getSubscriber().getName());
    } else {
        isUserAppOwner = application.getSubscriber().getName().equals(existingApp.getSubscriber().getName());
    }
    if (!isUserAppOwner) {
        throw new APIManagementException("user: " + application.getSubscriber().getName() + ", " + "attempted to update application owned by: " + existingApp.getSubscriber().getName());
    }
    if (application.getName() != null && (application.getName().length() != application.getName().trim().length())) {
        handleApplicationNameContainSpacesException("Application name " + "cannot contain leading or trailing white spaces");
    }
    String processedIds;
    if (!existingApp.getName().equals(application.getName())) {
        processedIds = application.getGroupId();
    } else {
        processedIds = getUpdatedGroupIds(existingApp.getGroupId(), application.getGroupId());
    }
    if (application.getGroupId() != null && APIUtil.isApplicationGroupCombinationExist(application.getSubscriber().getName(), application.getName(), processedIds)) {
        handleResourceAlreadyExistsException("A duplicate application already exists by the name - " + application.getName());
    }
    // Retain the 'DEFAULT' token type of migrated applications unless the token type is changed to 'JWT'.
    if (APIConstants.DEFAULT_TOKEN_TYPE.equals(existingApp.getTokenType()) && APIConstants.TOKEN_TYPE_OAUTH.equals(application.getTokenType())) {
        application.setTokenType(APIConstants.DEFAULT_TOKEN_TYPE);
    }
    // Prevent the change of token type of applications having 'JWT' token type.
    if (APIConstants.TOKEN_TYPE_JWT.equals(existingApp.getTokenType()) && !APIConstants.TOKEN_TYPE_JWT.equals(application.getTokenType())) {
        throw new APIManagementException("Cannot change application token type from " + APIConstants.TOKEN_TYPE_JWT + " to " + application.getTokenType());
    }
    Subscriber subscriber = application.getSubscriber();
    JSONArray applicationAttributesFromConfig = getAppAttributesFromConfig(subscriber.getName());
    Map<String, String> applicationAttributes = application.getApplicationAttributes();
    Map<String, String> existingApplicationAttributes = existingApp.getApplicationAttributes();
    if (applicationAttributes == null) {
        /*
             * This empty Hashmap is set to avoid throwing a null pointer exception, in case no application attributes
             * are set when updating an application
             */
        applicationAttributes = new HashMap<String, String>();
    }
    Set<String> configAttributes = new HashSet<>();
    if (applicationAttributesFromConfig != null) {
        for (Object object : applicationAttributesFromConfig) {
            boolean isExistingValue = false;
            JSONObject attribute = (JSONObject) object;
            Boolean hidden = (Boolean) attribute.get(APIConstants.ApplicationAttributes.HIDDEN);
            Boolean required = (Boolean) attribute.get(APIConstants.ApplicationAttributes.REQUIRED);
            String attributeName = (String) attribute.get(APIConstants.ApplicationAttributes.ATTRIBUTE);
            String defaultValue = (String) attribute.get(APIConstants.ApplicationAttributes.DEFAULT);
            if (BooleanUtils.isTrue(hidden) && BooleanUtils.isTrue(required) && StringUtils.isEmpty(defaultValue)) {
                /*
                     * In case a default value is not provided for a required hidden attribute, an exception is thrown,
                     * we don't do this validation in server startup to support multi tenancy scenarios
                     */
                handleException("Default value not provided for hidden required attribute. Please check the " + "configuration");
            }
            configAttributes.add(attributeName);
            if (existingApplicationAttributes.containsKey(attributeName)) {
                /*
                     * If a there is an existing attribute value, that is used as the default value.
                     */
                isExistingValue = true;
                defaultValue = existingApplicationAttributes.get(attributeName);
            }
            if (BooleanUtils.isTrue(required)) {
                if (BooleanUtils.isTrue(hidden)) {
                    String oldValue = applicationAttributes.put(attributeName, defaultValue);
                    if (StringUtils.isNotEmpty(oldValue)) {
                        log.info("Replaced provided value: " + oldValue + " with the default/existing value for" + " the hidden application attribute: " + attributeName);
                    }
                } else if (!applicationAttributes.keySet().contains(attributeName)) {
                    if (StringUtils.isNotEmpty(defaultValue)) {
                        applicationAttributes.put(attributeName, defaultValue);
                    } else {
                        handleException("Bad Request. Required application attribute not provided");
                    }
                }
            } else if (BooleanUtils.isTrue(hidden)) {
                if (isExistingValue) {
                    applicationAttributes.put(attributeName, defaultValue);
                } else {
                    applicationAttributes.remove(attributeName);
                }
            }
        }
        application.setApplicationAttributes(validateApplicationAttributes(applicationAttributes, configAttributes));
    } else {
        application.setApplicationAttributes(null);
    }
    validateApplicationPolicy(application, existingApp.getOrganization());
    apiMgtDAO.updateApplication(application);
    if (log.isDebugEnabled()) {
        log.debug("Successfully updated the Application: " + application.getId() + " in the database.");
    }
    JSONObject appLogObject = new JSONObject();
    appLogObject.put(APIConstants.AuditLogConstants.NAME, application.getName());
    appLogObject.put(APIConstants.AuditLogConstants.TIER, application.getTier());
    appLogObject.put(APIConstants.AuditLogConstants.STATUS, existingApp != null ? existingApp.getStatus() : "");
    appLogObject.put(APIConstants.AuditLogConstants.CALLBACK, application.getCallbackUrl());
    appLogObject.put(APIConstants.AuditLogConstants.GROUPS, application.getGroupId());
    appLogObject.put(APIConstants.AuditLogConstants.OWNER, application.getSubscriber().getName());
    APIUtil.logAuditMessage(APIConstants.AuditLogConstants.APPLICATION, appLogObject.toString(), APIConstants.AuditLogConstants.UPDATED, this.username);
    // Extracting API details for the recommendation system
    if (recommendationEnvironment != null) {
        RecommenderEventPublisher extractor = new RecommenderDetailsExtractor(application, username, requestedTenant);
        Thread recommendationThread = new Thread(extractor);
        recommendationThread.start();
    }
    ApplicationEvent applicationEvent = new ApplicationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.APPLICATION_UPDATE.name(), tenantId, existingApp.getOrganization(), application.getId(), application.getUUID(), application.getName(), application.getTokenType(), application.getTier(), application.getGroupId(), application.getApplicationAttributes(), existingApp.getSubscriber().getName());
    APIUtil.sendNotification(applicationEvent, APIConstants.NotifierType.APPLICATION.name());
}
Also used : RecommenderDetailsExtractor(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommenderDetailsExtractor) JSONArray(org.json.simple.JSONArray) ApplicationEvent(org.wso2.carbon.apimgt.impl.notifier.events.ApplicationEvent) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONObject(org.json.simple.JSONObject) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) RecommenderEventPublisher(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommenderEventPublisher) JSONObject(org.json.simple.JSONObject) Application(org.wso2.carbon.apimgt.api.model.Application) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Aggregations

ApplicationEvent (org.wso2.carbon.apimgt.impl.notifier.events.ApplicationEvent)7 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)6 Application (org.wso2.carbon.apimgt.api.model.Application)5 HashSet (java.util.HashSet)4 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)4 ArrayList (java.util.ArrayList)3 LinkedHashSet (java.util.LinkedHashSet)3 List (java.util.List)3 JSONObject (org.json.simple.JSONObject)3 APIRevisionDeployment (org.wso2.carbon.apimgt.api.model.APIRevisionDeployment)3 Environment (org.wso2.carbon.apimgt.api.model.Environment)3 Subscriber (org.wso2.carbon.apimgt.api.model.Subscriber)3 ApplicationEvent (org.wso2.carbon.apimgt.core.models.events.ApplicationEvent)3 ApplicationRegistrationWorkflowDTO (org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO)3 ApplicationWorkflowDTO (org.wso2.carbon.apimgt.impl.dto.ApplicationWorkflowDTO)3 SubscriptionWorkflowDTO (org.wso2.carbon.apimgt.impl.dto.SubscriptionWorkflowDTO)3 ApplicationRegistrationEvent (org.wso2.carbon.apimgt.impl.notifier.events.ApplicationRegistrationEvent)3 NotifierException (org.wso2.carbon.apimgt.impl.notifier.exceptions.NotifierException)3 RecommenderDetailsExtractor (org.wso2.carbon.apimgt.impl.recommendationmgt.RecommenderDetailsExtractor)3 RecommenderEventPublisher (org.wso2.carbon.apimgt.impl.recommendationmgt.RecommenderEventPublisher)3