Search in sources :

Example 11 with RecommendationEnvironment

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

Example 12 with RecommendationEnvironment

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

the class APIManagerConfiguration method setRecommendationConfigurations.

/**
 * To populate recommendation related configurations
 *
 * @param element
 */
private void setRecommendationConfigurations(OMElement element) {
    OMElement recommendationSeverEndpointElement = element.getFirstChildWithName(new QName(APIConstants.RECOMMENDATION_ENDPOINT));
    if (recommendationSeverEndpointElement != null) {
        recommendationEnvironment = new RecommendationEnvironment();
        String recommendationSeverEndpoint = recommendationSeverEndpointElement.getText();
        recommendationEnvironment.setRecommendationServerURL(recommendationSeverEndpoint);
        OMElement consumerKeyElement = element.getFirstChildWithName(new QName(APIConstants.RECOMMENDATION_API_CONSUMER_KEY));
        if (consumerKeyElement != null) {
            if (secretResolver.isInitialized() && secretResolver.isTokenProtected("APIManager.Recommendations.ConsumerKey")) {
                recommendationEnvironment.setConsumerKey(secretResolver.resolve("APIManager.Recommendations.ConsumerKey"));
            } else {
                recommendationEnvironment.setConsumerKey(consumerKeyElement.getText());
            }
            OMElement consumerSecretElement = element.getFirstChildWithName(new QName(APIConstants.RECOMMENDATION_API_CONSUMER_SECRET));
            if (consumerSecretElement != null) {
                if (secretResolver.isInitialized() && secretResolver.isTokenProtected("APIManager.Recommendations.ConsumerSecret")) {
                    recommendationEnvironment.setConsumerSecret(secretResolver.resolve("APIManager.Recommendations.ConsumerSecret"));
                } else {
                    recommendationEnvironment.setConsumerSecret(consumerSecretElement.getText());
                }
                OMElement oauthEndpointElement = element.getFirstChildWithName(new QName(APIConstants.AUTHENTICATION_ENDPOINT));
                String oauthEndpoint = null;
                if (oauthEndpointElement != null) {
                    oauthEndpoint = oauthEndpointElement.getText();
                } else {
                    try {
                        URL endpointURL = new URL(recommendationSeverEndpoint);
                        oauthEndpoint = endpointURL.getProtocol() + "://" + endpointURL.getHost() + ":" + endpointURL.getPort();
                    } catch (MalformedURLException e) {
                        log.error("Error when reading the recommendationServer Endpoint", e);
                    }
                }
                // Oauth URL is set only if both consumer key
                recommendationEnvironment.setOauthURL(oauthEndpoint);
            // and consumer secrets are correctly defined
            }
        }
        OMElement applyForAllTenantsElement = element.getFirstChildWithName(new QName(APIConstants.APPLY_RECOMMENDATIONS_FOR_ALL_APIS));
        if (applyForAllTenantsElement != null) {
            recommendationEnvironment.setApplyForAllTenants(JavaUtils.isTrueExplicitly(applyForAllTenantsElement.getText()));
        } else {
            log.debug("Apply For All Tenants Element is not set. Set to default true");
        }
        OMElement maxRecommendationsElement = element.getFirstChildWithName(new QName(APIConstants.MAX_RECOMMENDATIONS));
        if (maxRecommendationsElement != null) {
            recommendationEnvironment.setMaxRecommendations(Integer.parseInt(maxRecommendationsElement.getText()));
        } else {
            log.debug("Max recommendations is not set. Set to default 5");
        }
        OMElement userNameElement = element.getFirstChildWithName(new QName(APIConstants.RECOMMENDATION_USERNAME));
        if (userNameElement != null) {
            recommendationEnvironment.setUserName(userNameElement.getText());
            log.debug("Basic OAuth used for recommendation server");
        }
        OMElement passwordElement = element.getFirstChildWithName(new QName(APIConstants.RECOMMENDATION_PASSWORD));
        if (passwordElement != null) {
            if (secretResolver.isInitialized() && secretResolver.isTokenProtected("APIManager.Recommendations.password")) {
                recommendationEnvironment.setPassword(secretResolver.resolve("APIManager.Recommendations.password"));
            } else {
                recommendationEnvironment.setPassword(passwordElement.getText());
            }
        }
        OMElement waitDurationElement = element.getFirstChildWithName(new QName(APIConstants.WAIT_DURATION));
        if (waitDurationElement != null) {
            recommendationEnvironment.setWaitDuration(Long.parseLong(waitDurationElement.getText()));
        } else {
            log.debug("Max recommendations is not set. Set to default 5");
        }
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) QName(javax.xml.namespace.QName) OMElement(org.apache.axiom.om.OMElement) RecommendationEnvironment(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommendationEnvironment) URL(java.net.URL)

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