Search in sources :

Example 6 with RecommendationEnvironment

use of org.wso2.carbon.apimgt.impl.recommendationmgt.RecommendationEnvironment in project carbon-apimgt by wso2.

the class APIManagerComponent method setupAccessTokenGenerator.

private void setupAccessTokenGenerator() {
    RecommendationEnvironment recommendationEnvironment = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration().getApiRecommendationEnvironment();
    if (recommendationEnvironment != null && recommendationEnvironment.getOauthURL() != null) {
        AccessTokenGenerator accessTokenGenerator = new AccessTokenGenerator(recommendationEnvironment.getOauthURL(), recommendationEnvironment.getConsumerKey(), recommendationEnvironment.getConsumerSecret());
        ServiceReferenceHolder.getInstance().setAccessTokenGenerator(accessTokenGenerator);
    }
}
Also used : AccessTokenGenerator(org.wso2.carbon.apimgt.impl.recommendationmgt.AccessTokenGenerator) RecommendationEnvironment(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommendationEnvironment)

Example 7 with RecommendationEnvironment

use of org.wso2.carbon.apimgt.impl.recommendationmgt.RecommendationEnvironment in project carbon-apimgt by wso2.

the class APIProviderImpl method deleteAPI.

public void deleteAPI(String apiUuid, String organization) throws APIManagementException {
    boolean isError = false;
    int apiId = -1;
    API api = null;
    // get api object by uuid
    try {
        api = getAPIbyUUID(apiUuid, organization);
    } catch (APIManagementException e) {
        log.error("Error while getting API by uuid for deleting API " + apiUuid + " on organization " + organization);
        log.debug("Following steps will be skipped while deleting API " + apiUuid + "on organization " + organization + " due to api being null. " + "deleting Resource Registration from key managers, deleting on external API stores, " + "event publishing to gateways, logging audit message, extracting API details for " + "the recommendation system. ");
        isError = true;
    }
    // get api id from db
    try {
        apiId = apiMgtDAO.getAPIID(apiUuid);
    } catch (APIManagementException e) {
        log.error("Error while getting API ID from DB for deleting API " + apiUuid + " on organization " + organization, e);
        log.debug("Following steps will be skipped while deleting the API " + apiUuid + " on organization " + organization + "due to api id being null. cleanup workflow tasks of the API, " + "delete event publishing to gateways");
        isError = true;
    }
    // DB delete operations
    if (!isError && api != null) {
        try {
            deleteAPIRevisions(apiUuid, organization);
            deleteAPIFromDB(api);
            if (log.isDebugEnabled()) {
                String logMessage = "API Name: " + api.getId().getApiName() + ", API Version " + api.getId().getVersion() + " successfully removed from the database.";
                log.debug(logMessage);
            }
        } catch (APIManagementException e) {
            log.error("Error while executing API delete operations on DB for API " + apiUuid + " on organization " + organization, e);
            isError = true;
        }
    }
    // Deleting Resource Registration from key managers
    if (api != null && api.getId() != null && api.getId().toString() != null) {
        Map<String, KeyManagerDto> tenantKeyManagers = KeyManagerHolder.getTenantKeyManagers(tenantDomain);
        for (Map.Entry<String, KeyManagerDto> keyManagerDtoEntry : tenantKeyManagers.entrySet()) {
            KeyManager keyManager = keyManagerDtoEntry.getValue().getKeyManager();
            if (keyManager != null) {
                try {
                    keyManager.deleteRegisteredResourceByAPIId(api.getId().toString());
                    log.debug("API " + apiUuid + " on organization " + organization + " has successfully removed from the Key Manager " + keyManagerDtoEntry.getKey());
                } catch (APIManagementException e) {
                    log.error("Error while deleting Resource Registration for API " + apiUuid + " on organization " + organization + " in Key Manager " + keyManagerDtoEntry.getKey(), e);
                }
            }
        }
    }
    try {
        GatewayArtifactsMgtDAO.getInstance().deleteGatewayArtifacts(apiUuid);
        log.debug("API " + apiUuid + " on organization " + organization + " has successfully removed from the gateway artifacts.");
    } catch (APIManagementException e) {
        log.error("Error while executing API delete operation on gateway artifacts for API " + apiUuid, e);
        isError = true;
    }
    try {
        apiPersistenceInstance.deleteAPI(new Organization(organization), apiUuid);
        log.debug("API " + apiUuid + " on organization " + organization + " has successfully removed from the persistence instance.");
    } catch (APIPersistenceException e) {
        log.error("Error while executing API delete operation on persistence instance for API " + apiUuid + " on organization " + organization, e);
        isError = true;
    }
    // Deleting on external API stores
    if (api != null) {
        // gatewayType check is required when API Management is deployed on
        // other servers to avoid synapse
        // Check if there are already published external APIStores.If yes,removing APIs from them.
        Set<APIStore> apiStoreSet;
        try {
            apiStoreSet = getPublishedExternalAPIStores(apiUuid);
            WSO2APIPublisher wso2APIPublisher = new WSO2APIPublisher();
            if (apiStoreSet != null && !apiStoreSet.isEmpty()) {
                for (APIStore store : apiStoreSet) {
                    wso2APIPublisher.deleteFromStore(api.getId(), APIUtil.getExternalAPIStore(store.getName(), tenantId));
                }
            }
        } catch (APIManagementException e) {
            log.error("Error while executing API delete operation on external API stores for API " + apiUuid + " on organization " + organization, e);
            isError = true;
        }
    }
    if (apiId != -1) {
        try {
            cleanUpPendingAPIStateChangeTask(apiId, false);
        } catch (WorkflowException | APIManagementException e) {
            log.error("Error while executing API delete operation on cleanup workflow tasks for API " + apiUuid + " on organization " + organization, e);
            isError = true;
        }
    }
    // Delete event publishing to gateways
    if (api != null && apiId != -1) {
        APIEvent apiEvent = new APIEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.API_DELETE.name(), tenantId, tenantDomain, api.getId().getApiName(), apiId, api.getUuid(), api.getId().getVersion(), api.getType(), api.getContext(), APIUtil.replaceEmailDomainBack(api.getId().getProviderName()), api.getStatus());
        APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name());
    } else {
        log.debug("Event has not published to gateways due to API id has failed to retrieve from DB for API " + apiUuid + " on organization " + organization);
    }
    // Logging audit message for API delete
    if (api != null) {
        JSONObject apiLogObject = new JSONObject();
        apiLogObject.put(APIConstants.AuditLogConstants.NAME, api.getId().getApiName());
        apiLogObject.put(APIConstants.AuditLogConstants.VERSION, api.getId().getVersion());
        apiLogObject.put(APIConstants.AuditLogConstants.PROVIDER, api.getId().getProviderName());
        APIUtil.logAuditMessage(APIConstants.AuditLogConstants.API, apiLogObject.toString(), APIConstants.AuditLogConstants.DELETED, this.username);
    }
    // Extracting API details for the recommendation system
    if (api != null && recommendationEnvironment != null) {
        RecommenderEventPublisher extractor = new RecommenderDetailsExtractor(api, tenantDomain, APIConstants.DELETE_API);
        Thread recommendationThread = new Thread(extractor);
        recommendationThread.start();
    }
    // if one of the above has failed throw an error
    if (isError) {
        throw new APIManagementException("Error while deleting the API " + apiUuid + " on organization " + organization);
    }
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) RecommenderDetailsExtractor(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommenderDetailsExtractor) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) KeyManagerDto(org.wso2.carbon.apimgt.impl.dto.KeyManagerDto) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIEvent(org.wso2.carbon.apimgt.impl.notifier.events.APIEvent) JSONObject(org.json.simple.JSONObject) RecommenderEventPublisher(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommenderEventPublisher) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) WSO2APIPublisher(org.wso2.carbon.apimgt.impl.publishers.WSO2APIPublisher) Map(java.util.Map) TreeMap(java.util.TreeMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager) APIStore(org.wso2.carbon.apimgt.api.model.APIStore)

Example 8 with RecommendationEnvironment

use of org.wso2.carbon.apimgt.impl.recommendationmgt.RecommendationEnvironment in project carbon-apimgt by wso2.

the class RecommendationsApiServiceImpl method recommendationsGet.

public Response recommendationsGet(MessageContext messageContext) throws APIManagementException {
    String organization = RestApiUtil.getValidatedOrganization(messageContext);
    RecommendationEnvironment recommendationEnvironment = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration().getApiRecommendationEnvironment();
    List<JSONObject> recommendedApis = new ArrayList<>();
    JSONObject responseObj = new JSONObject();
    String apiId = null;
    try {
        String userName = RestApiCommonUtil.getLoggedInUsername();
        APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
        String requestedTenantDomain = apiConsumer.getRequestedTenant();
        if (apiConsumer.isRecommendationEnabled(requestedTenantDomain) && !APIConstants.WSO2_ANONYMOUS_USER.equals(userName)) {
            int maxRecommendations = recommendationEnvironment.getMaxRecommendations();
            String recommendations = apiConsumer.getApiRecommendations(userName, requestedTenantDomain);
            if (recommendations != null) {
                JSONObject jsonResponse = new JSONObject(recommendations);
                JSONArray apiList = jsonResponse.getJSONArray("userRecommendations");
                for (int i = 0; i < apiList.length(); i++) {
                    try {
                        JSONObject apiObj = apiList.getJSONObject(i);
                        apiId = apiObj.getString("id");
                        ApiTypeWrapper apiWrapper = apiConsumer.getAPIorAPIProductByUUID(apiId, organization);
                        API api = apiWrapper.getApi();
                        APIIdentifier apiIdentifier = api.getId();
                        boolean isApiSubscribed = apiConsumer.isSubscribed(apiIdentifier, userName);
                        if (!isApiSubscribed && recommendedApis.size() < maxRecommendations) {
                            JSONObject apiDetails = new JSONObject();
                            apiDetails.put("id", apiId);
                            apiDetails.put("name", apiWrapper.getName());
                            apiDetails.put("avgRating", api.getRating());
                            recommendedApis.add(apiDetails);
                        }
                    } catch (APIManagementException e) {
                        log.debug("Requested API " + apiId + " is not accessible by the consumer");
                    }
                }
            }
        }
    } catch (Exception e) {
        log.error("Error occurred when retrieving recommendations through the rest api: ", e);
    }
    int count = recommendedApis.size();
    responseObj.put("count", count);
    responseObj.put("list", recommendedApis);
    String responseStringObj = String.valueOf(responseObj);
    return Response.ok().entity(responseStringObj).build();
}
Also used : ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) ArrayList(java.util.ArrayList) JSONArray(org.json.JSONArray) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONObject(org.json.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) API(org.wso2.carbon.apimgt.api.model.API) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) RecommendationEnvironment(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommendationEnvironment)

Example 9 with RecommendationEnvironment

use of org.wso2.carbon.apimgt.impl.recommendationmgt.RecommendationEnvironment 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 10 with RecommendationEnvironment

use of org.wso2.carbon.apimgt.impl.recommendationmgt.RecommendationEnvironment 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)

Aggregations

RecommenderDetailsExtractor (org.wso2.carbon.apimgt.impl.recommendationmgt.RecommenderDetailsExtractor)8 RecommenderEventPublisher (org.wso2.carbon.apimgt.impl.recommendationmgt.RecommenderEventPublisher)8 JSONObject (org.json.simple.JSONObject)6 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)6 RecommendationEnvironment (org.wso2.carbon.apimgt.impl.recommendationmgt.RecommendationEnvironment)4 HashMap (java.util.HashMap)3 Map (java.util.Map)3 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)3 API (org.wso2.carbon.apimgt.api.model.API)3 ApplicationEvent (org.wso2.carbon.apimgt.impl.notifier.events.ApplicationEvent)3 WorkflowException (org.wso2.carbon.apimgt.impl.workflow.WorkflowException)3 HashSet (java.util.HashSet)2 LinkedHashSet (java.util.LinkedHashSet)2 TreeMap (java.util.TreeMap)2 JSONArray (org.json.simple.JSONArray)2 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)2 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)2 ApplicationRegistrationWorkflowDTO (org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO)2 ApplicationWorkflowDTO (org.wso2.carbon.apimgt.impl.dto.ApplicationWorkflowDTO)2 SubscriptionWorkflowDTO (org.wso2.carbon.apimgt.impl.dto.SubscriptionWorkflowDTO)2