Search in sources :

Example 6 with ApplicationRegistrationEvent

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

the class SolaceKeyGenNotifier method syncSolaceApplicationClientId.

/**
 * Syncing consumer key of the dev portal applications with applications on the Solace broker
 *
 * @param event ApplicationEvent to sync Solace applications with dev portal applications
 * @throws NotifierException if error occurs when patching applications on the Solace broker
 */
private void syncSolaceApplicationClientId(ApplicationRegistrationEvent event) throws NotifierException {
    // get list of subscribed APIs in the application
    try {
        Application application = apiMgtDAO.getApplicationByUUID(event.getApplicationUUID());
        Map<String, Environment> gatewayEnvironments = APIUtil.getReadOnlyGatewayEnvironments();
        Set<SubscribedAPI> subscriptions = apiMgtDAO.getSubscribedAPIs(application.getSubscriber(), application.getName(), application.getGroupId());
        boolean isContainsSolaceApis = false;
        String organizationNameOfSolaceDeployment = null;
        labelOne: // Check whether the application needs to be updated has a Solace API subscription
        for (SubscribedAPI api : subscriptions) {
            List<APIRevisionDeployment> deployments = apiMgtDAO.getAPIRevisionDeploymentByApiUUID(api.getIdentifier().getUUID());
            for (APIRevisionDeployment deployment : deployments) {
                if (gatewayEnvironments.containsKey(deployment.getDeployment())) {
                    if (SolaceConstants.SOLACE_ENVIRONMENT.equalsIgnoreCase(gatewayEnvironments.get(deployment.getDeployment()).getProvider())) {
                        isContainsSolaceApis = true;
                        organizationNameOfSolaceDeployment = gatewayEnvironments.get(deployment.getDeployment()).getAdditionalProperties().get(SolaceConstants.SOLACE_ENVIRONMENT_ORGANIZATION);
                        break labelOne;
                    }
                }
            }
        }
        // Patching consumerKey to Solace application using Admin Apis
        if (isContainsSolaceApis) {
            if (application.getKeys() != null) {
                String consumerSecret = null;
                APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(CarbonContext.getThreadLocalCarbonContext().getUsername());
                Set<APIKey> consumerKeys = apiConsumer.getApplicationKeysOfApplication(application.getId());
                for (APIKey key : consumerKeys) {
                    if (key.getConsumerKey().equals(event.getConsumerKey())) {
                        consumerSecret = key.getConsumerSecret();
                    }
                }
                SolaceNotifierUtils.patchSolaceApplicationClientId(organizationNameOfSolaceDeployment, application, event.getConsumerKey(), consumerSecret);
            } else {
                throw new NotifierException("Application keys are not found in the application : " + application.getName());
            }
        }
    } catch (APIManagementException e) {
        throw new NotifierException(e.getMessage());
    }
}
Also used : APIRevisionDeployment(org.wso2.carbon.apimgt.api.model.APIRevisionDeployment) NotifierException(org.wso2.carbon.apimgt.impl.notifier.exceptions.NotifierException) APIKey(org.wso2.carbon.apimgt.api.model.APIKey) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Environment(org.wso2.carbon.apimgt.api.model.Environment) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) List(java.util.List) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) Application(org.wso2.carbon.apimgt.api.model.Application)

Example 7 with ApplicationRegistrationEvent

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

the class KeyManagerDataServiceImpl method getApplicationKeyMappingFromApplicationRegistrationEvent.

private ApplicationKeyMapping getApplicationKeyMappingFromApplicationRegistrationEvent(ApplicationRegistrationEvent event) {
    ApplicationKeyMapping mapping = new ApplicationKeyMapping();
    mapping.setApplicationId(event.getApplicationId());
    mapping.setApplicationUUID(event.getApplicationUUID());
    mapping.setConsumerKey(event.getConsumerKey());
    mapping.setKeyType(event.getKeyType());
    mapping.setKeyManager(event.getKeyManager());
    if (log.isDebugEnabled()) {
        log.debug("Event: " + event.toString());
        log.debug("Converted : " + mapping.toString());
    }
    return mapping;
}
Also used : ApplicationKeyMapping(org.wso2.carbon.apimgt.keymgt.model.entity.ApplicationKeyMapping)

Example 8 with ApplicationRegistrationEvent

use of org.wso2.carbon.apimgt.impl.notifier.events.ApplicationRegistrationEvent 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 9 with ApplicationRegistrationEvent

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

the class APIConsumerImpl method requestApprovalForApplicationRegistration.

/**
 * This method specifically implemented for REST API by removing application and data access logic
 * from host object layer. So as per new implementation we need to pass requested scopes to this method
 * as tokenScope. So we will do scope related other logic here in this method.
 * So host object should only pass required 9 parameters.
 */
@Override
public Map<String, Object> requestApprovalForApplicationRegistration(String userId, Application application, String tokenType, String callbackUrl, String[] allowedDomains, String validityTime, String tokenScope, String jsonString, String keyManagerName, String tenantDomain, boolean isImportMode) throws APIManagementException {
    boolean isTenantFlowStarted = false;
    if (StringUtils.isEmpty(tenantDomain)) {
        tenantDomain = MultitenantUtils.getTenantDomain(userId);
    } else {
        int tenantId = APIUtil.getInternalOrganizationId(tenantDomain);
        // To handle choreo scenario.
        if (tenantId == MultitenantConstants.SUPER_TENANT_ID) {
            tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
        }
    }
    String keyManagerId = null;
    if (keyManagerName != null) {
        KeyManagerConfigurationDTO keyManagerConfiguration = apiMgtDAO.getKeyManagerConfigurationByName(tenantDomain, keyManagerName);
        if (keyManagerConfiguration == null) {
            keyManagerConfiguration = apiMgtDAO.getKeyManagerConfigurationByUUID(keyManagerName);
            if (keyManagerConfiguration != null) {
                keyManagerId = keyManagerName;
                keyManagerName = keyManagerConfiguration.getName();
            }
        } else {
            keyManagerId = keyManagerConfiguration.getUuid();
        }
        if (keyManagerConfiguration == null || !keyManagerConfiguration.isEnabled()) {
            throw new APIManagementException("Key Manager " + keyManagerName + " doesn't exist in Tenant " + tenantDomain, ExceptionCodes.KEY_MANAGER_NOT_REGISTERED);
        }
        if (KeyManagerConfiguration.TokenType.EXCHANGED.toString().equals(keyManagerConfiguration.getTokenType())) {
            throw new APIManagementException("Key Manager " + keyManagerName + " doesn't support to generate" + " Client Application", ExceptionCodes.KEY_MANAGER_NOT_SUPPORT_OAUTH_APP_CREATION);
        }
        Object enableOauthAppCreation = keyManagerConfiguration.getProperty(APIConstants.KeyManager.ENABLE_OAUTH_APP_CREATION);
        if (enableOauthAppCreation != null && !(Boolean) enableOauthAppCreation) {
            if (isImportMode) {
                log.debug("Importing application when KM OAuth App creation is disabled. Trying to map keys");
                // in the `jsonString` and ApplicationUtils#createOauthAppRequest logic handles it.
                return mapExistingOAuthClient(jsonString, userId, null, application.getName(), tokenType, APIConstants.DEFAULT_TOKEN_TYPE, keyManagerName, tenantDomain);
            } else {
                throw new APIManagementException("Key Manager " + keyManagerName + " doesn't support to generate" + " Client Application", ExceptionCodes.KEY_MANAGER_NOT_SUPPORT_OAUTH_APP_CREATION);
            }
        }
    }
    try {
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            isTenantFlowStarted = startTenantFlowForTenantDomain(tenantDomain);
        }
        // check if there are any existing key mappings set for the application and the key manager.
        if (apiMgtDAO.isKeyMappingExistsForApplication(application.getId(), keyManagerName, keyManagerId, tokenType)) {
            throw new APIManagementException("Key Mappings already exists for application " + application.getName(), ExceptionCodes.KEY_MAPPING_ALREADY_EXIST);
        }
        // initiate WorkflowExecutor
        WorkflowExecutor appRegistrationWorkflow = null;
        // initiate ApplicationRegistrationWorkflowDTO
        ApplicationRegistrationWorkflowDTO appRegWFDto = null;
        ApplicationKeysDTO appKeysDto = new ApplicationKeysDTO();
        boolean isCaseInsensitiveComparisons = Boolean.parseBoolean(getAPIManagerConfiguration().getFirstProperty(APIConstants.API_STORE_FORCE_CI_COMPARISIONS));
        boolean isUserAppOwner;
        if (isCaseInsensitiveComparisons) {
            isUserAppOwner = application.getSubscriber().getName().equalsIgnoreCase(userId);
        } else {
            isUserAppOwner = application.getSubscriber().getName().equals(userId);
        }
        if (!isUserAppOwner) {
            throw new APIManagementException("user: " + application.getSubscriber().getName() + ", " + "attempted to generate tokens for application owned by: " + userId);
        }
        // if its a PRODUCTION application.
        if (APIConstants.API_KEY_TYPE_PRODUCTION.equals(tokenType)) {
            // initiate workflow type. By default simple work flow will be
            // executed.
            appRegistrationWorkflow = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION);
            appRegWFDto = (ApplicationRegistrationWorkflowDTO) WorkflowExecutorFactory.getInstance().createWorkflowDTO(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION);
        } else // if it is a sandBox application.
        if (APIConstants.API_KEY_TYPE_SANDBOX.equals(tokenType)) {
            // if its a SANDBOX application.
            appRegistrationWorkflow = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX);
            appRegWFDto = (ApplicationRegistrationWorkflowDTO) WorkflowExecutorFactory.getInstance().createWorkflowDTO(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX);
        } else {
            throw new APIManagementException("Invalid Token Type '" + tokenType + "' requested.");
        }
        // check whether callback url is empty and set null
        if (StringUtils.isBlank(callbackUrl)) {
            callbackUrl = null;
        }
        String applicationTokenType = application.getTokenType();
        if (StringUtils.isEmpty(application.getTokenType())) {
            applicationTokenType = APIConstants.DEFAULT_TOKEN_TYPE;
        }
        // Build key manager instance and create oAuthAppRequest by jsonString.
        OAuthAppRequest request = ApplicationUtils.createOauthAppRequest(application.getName(), null, callbackUrl, tokenScope, jsonString, applicationTokenType, tenantDomain, keyManagerName);
        request.getOAuthApplicationInfo().addParameter(ApplicationConstants.VALIDITY_PERIOD, validityTime);
        request.getOAuthApplicationInfo().addParameter(ApplicationConstants.APP_KEY_TYPE, tokenType);
        request.getOAuthApplicationInfo().addParameter(ApplicationConstants.APP_CALLBACK_URL, callbackUrl);
        request.getOAuthApplicationInfo().setApplicationUUID(application.getUUID());
        // Setting request values in WorkflowDTO - In future we should keep
        // Application/OAuthApplication related
        // information in the respective entities not in the workflowDTO.
        appRegWFDto.setStatus(WorkflowStatus.CREATED);
        appRegWFDto.setCreatedTime(System.currentTimeMillis());
        appRegWFDto.setTenantDomain(tenantDomain);
        appRegWFDto.setTenantId(tenantId);
        appRegWFDto.setExternalWorkflowReference(appRegistrationWorkflow.generateUUID());
        appRegWFDto.setWorkflowReference(appRegWFDto.getExternalWorkflowReference());
        appRegWFDto.setApplication(application);
        appRegWFDto.setKeyManager(keyManagerId);
        request.setMappingId(appRegWFDto.getWorkflowReference());
        if (!application.getSubscriber().getName().equals(userId)) {
            appRegWFDto.setUserName(application.getSubscriber().getName());
        } else {
            appRegWFDto.setUserName(userId);
        }
        appRegWFDto.setCallbackUrl(appRegistrationWorkflow.getCallbackURL());
        appRegWFDto.setAppInfoDTO(request);
        appRegWFDto.setDomainList(allowedDomains);
        appRegWFDto.setKeyDetails(appKeysDto);
        appRegistrationWorkflow.execute(appRegWFDto);
        Map<String, Object> keyDetails = new HashMap<String, Object>();
        keyDetails.put(APIConstants.FrontEndParameterNames.KEY_STATE, appRegWFDto.getStatus().toString());
        OAuthApplicationInfo applicationInfo = appRegWFDto.getApplicationInfo();
        String keyMappingId = apiMgtDAO.getKeyMappingIdFromApplicationIdKeyTypeAndKeyManager(application.getId(), tokenType, keyManagerId);
        keyDetails.put(APIConstants.FrontEndParameterNames.KEY_MAPPING_ID, keyMappingId);
        if (applicationInfo != null) {
            keyDetails.put(APIConstants.FrontEndParameterNames.CONSUMER_KEY, applicationInfo.getClientId());
            keyDetails.put(APIConstants.FrontEndParameterNames.CONSUMER_SECRET, applicationInfo.getClientSecret());
            keyDetails.put(ApplicationConstants.OAUTH_APP_DETAILS, applicationInfo.getJsonString());
            keyDetails.put(APIConstants.FrontEndParameterNames.MODE, APIConstants.OAuthAppMode.CREATED.name());
        }
        // There can be instances where generating the Application Token is
        // not required. In those cases,
        // token info will have nothing.
        AccessTokenInfo tokenInfo = appRegWFDto.getAccessTokenInfo();
        if (tokenInfo != null) {
            keyDetails.put("accessToken", tokenInfo.getAccessToken());
            keyDetails.put("validityTime", tokenInfo.getValidityPeriod());
            keyDetails.put("tokenDetails", tokenInfo.getJSONString());
            keyDetails.put("tokenScope", tokenInfo.getScopes());
        }
        JSONObject appLogObject = new JSONObject();
        appLogObject.put("Generated keys for application", application.getName());
        APIUtil.logAuditMessage(APIConstants.AuditLogConstants.APPLICATION, appLogObject.toString(), APIConstants.AuditLogConstants.UPDATED, this.username);
        // if its a PRODUCTION application.
        if (APIConstants.API_KEY_TYPE_PRODUCTION.equals(tokenType)) {
            // get the workflow state once the executor is executed.
            WorkflowDTO wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(appRegWFDto.getExternalWorkflowReference(), WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION);
            // 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())) {
                    ApplicationRegistrationEvent applicationRegistrationEvent = new ApplicationRegistrationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.APPLICATION_REGISTRATION_CREATE.name(), tenantId, tenantDomain, application.getId(), application.getUUID(), applicationInfo.getClientId(), tokenType, keyManagerName);
                    APIUtil.sendNotification(applicationRegistrationEvent, APIConstants.NotifierType.APPLICATION_REGISTRATION.name());
                }
            } else {
                ApplicationRegistrationEvent applicationRegistrationEvent = new ApplicationRegistrationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.APPLICATION_REGISTRATION_CREATE.name(), tenantId, tenantDomain, application.getId(), application.getUUID(), applicationInfo.getClientId(), tokenType, keyManagerName);
                APIUtil.sendNotification(applicationRegistrationEvent, APIConstants.NotifierType.APPLICATION_REGISTRATION.name());
            }
        } else if (APIConstants.API_KEY_TYPE_SANDBOX.equals(tokenType)) {
            // get the workflow state once the executor is executed.
            WorkflowDTO wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(appRegWFDto.getExternalWorkflowReference(), WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX);
            // 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())) {
                    ApplicationRegistrationEvent applicationRegistrationEvent = new ApplicationRegistrationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.APPLICATION_REGISTRATION_CREATE.name(), tenantId, tenantDomain, application.getId(), application.getUUID(), applicationInfo.getClientId(), tokenType, keyManagerName);
                    APIUtil.sendNotification(applicationRegistrationEvent, APIConstants.NotifierType.APPLICATION_REGISTRATION.name());
                }
            } else {
                ApplicationRegistrationEvent applicationRegistrationEvent = new ApplicationRegistrationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.APPLICATION_REGISTRATION_CREATE.name(), tenantId, tenantDomain, application.getId(), application.getUUID(), applicationInfo.getClientId(), tokenType, keyManagerName);
                APIUtil.sendNotification(applicationRegistrationEvent, APIConstants.NotifierType.APPLICATION_REGISTRATION.name());
            }
        }
        return keyDetails;
    } catch (WorkflowException e) {
        log.error("Could not execute Workflow", e);
        throw new APIManagementException(e);
    } finally {
        if (isTenantFlowStarted) {
            endTenantFlow();
        }
    }
}
Also used : KeyManagerConfigurationDTO(org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO) ApplicationRegistrationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO) 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) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) ApplicationRegistrationEvent(org.wso2.carbon.apimgt.impl.notifier.events.ApplicationRegistrationEvent) AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo) ApplicationKeysDTO(org.wso2.carbon.apimgt.api.model.ApplicationKeysDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONObject(org.json.simple.JSONObject) OAuthAppRequest(org.wso2.carbon.apimgt.api.model.OAuthAppRequest) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) JSONObject(org.json.simple.JSONObject) WorkflowExecutor(org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutor)

Aggregations

ApplicationRegistrationEvent (org.wso2.carbon.apimgt.impl.notifier.events.ApplicationRegistrationEvent)5 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)4 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 ApplicationEvent (org.wso2.carbon.apimgt.impl.notifier.events.ApplicationEvent)3 HashMap (java.util.HashMap)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 JSONObject (org.json.simple.JSONObject)2 Application (org.wso2.carbon.apimgt.api.model.Application)2 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)2 WorkflowDTO (org.wso2.carbon.apimgt.impl.dto.WorkflowDTO)2 APIEvent (org.wso2.carbon.apimgt.impl.notifier.events.APIEvent)2 SubscriptionEvent (org.wso2.carbon.apimgt.impl.notifier.events.SubscriptionEvent)2 WorkflowException (org.wso2.carbon.apimgt.impl.workflow.WorkflowException)2 WorkflowExecutor (org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutor)2 SubscriptionDataStore (org.wso2.carbon.apimgt.keymgt.model.SubscriptionDataStore)2 Gson (com.google.gson.Gson)1 HashSet (java.util.HashSet)1 List (java.util.List)1