Search in sources :

Example 51 with APIConsumer

use of org.wso2.carbon.apimgt.api.APIConsumer in project carbon-apimgt by wso2.

the class ImportUtils method importSubscriptions.

/**
 * Import and add subscriptions of a particular application for the available APIs and API products
 *
 * @param subscribedAPIs Subscribed APIs
 * @param userId         Username of the subscriber
 * @param application    Application
 * @param update         Whether to update the application or not
 * @param apiConsumer    API Consumer
 * @param organization   Organization
 * @return a list of APIIdentifiers of the skipped subscriptions
 * @throws APIManagementException if an error occurs while importing and adding subscriptions
 * @throws UserStoreException     if an error occurs while checking whether the tenant domain exists
 */
public static List<APIIdentifier> importSubscriptions(Set<ExportedSubscribedAPI> subscribedAPIs, String userId, Application application, Boolean update, APIConsumer apiConsumer, String organization) throws APIManagementException, UserStoreException {
    List<APIIdentifier> skippedAPIList = new ArrayList<>();
    for (ExportedSubscribedAPI subscribedAPI : subscribedAPIs) {
        APIIdentifier apiIdentifier = subscribedAPI.getApiId();
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(apiIdentifier.getProviderName()));
        if (!StringUtils.isEmpty(tenantDomain) && APIUtil.isTenantAvailable(tenantDomain)) {
            String name = apiIdentifier.getApiName();
            String version = apiIdentifier.getVersion();
            // Creating a solr compatible search query, here we will execute a search query without wildcard *s
            StringBuilder searchQuery = new StringBuilder();
            String[] searchCriteria = { name, "version:" + version };
            for (int i = 0; i < searchCriteria.length; i++) {
                if (i == 0) {
                    searchQuery = new StringBuilder(APIUtil.getSingleSearchCriteria(searchCriteria[i]).replace("*", ""));
                } else {
                    searchQuery.append(APIConstants.SEARCH_AND_TAG).append(APIUtil.getSingleSearchCriteria(searchCriteria[i]).replace("*", ""));
                }
            }
            Map matchedAPIs;
            matchedAPIs = apiConsumer.searchPaginatedAPIs(searchQuery.toString(), tenantDomain, 0, Integer.MAX_VALUE, false);
            Set<Object> apiSet = (Set<Object>) matchedAPIs.get("apis");
            if (apiSet != null && !apiSet.isEmpty()) {
                Object type = apiSet.iterator().next();
                ApiTypeWrapper apiTypeWrapper = null;
                String apiOrApiProductUuid;
                // Check whether the object is ApiProduct
                if (isApiProduct(type)) {
                    APIProduct apiProduct = (APIProduct) apiSet.iterator().next();
                    apiOrApiProductUuid = APIUtil.getUUIDFromIdentifier(apiProduct.getId(), organization);
                } else {
                    API api = (API) apiSet.iterator().next();
                    apiOrApiProductUuid = APIUtil.getUUIDFromIdentifier(api.getId(), organization);
                }
                apiTypeWrapper = apiConsumer.getAPIorAPIProductByUUID(apiOrApiProductUuid, organization);
                // Tier of the imported subscription
                String targetTier = subscribedAPI.getThrottlingPolicy();
                // Checking whether the target tier is available
                if (isTierAvailable(targetTier, apiTypeWrapper) && apiTypeWrapper.getStatus() != null && APIConstants.PUBLISHED.equals(apiTypeWrapper.getStatus())) {
                    apiTypeWrapper.setTier(targetTier);
                    // It will throw an error if subscriber already exists
                    if (update == null || !update) {
                        apiConsumer.addSubscription(apiTypeWrapper, userId, application);
                    } else if (!apiConsumer.isSubscribedToApp(subscribedAPI.getApiId(), userId, application.getId())) {
                        // on update skip subscriptions that already exists
                        apiConsumer.addSubscription(apiTypeWrapper, userId, application);
                    }
                } else {
                    log.error("Failed to import Subscription as API/API Product " + name + "-" + version + " as one or more tiers may be unavailable or the API/API Product may not have been published ");
                    skippedAPIList.add(subscribedAPI.getApiId());
                }
            } else {
                log.error("Failed to import Subscription as API " + name + "-" + version + " is not available");
                skippedAPIList.add(subscribedAPI.getApiId());
            }
        } else {
            log.error("Failed to import Subscription as Tenant domain: " + tenantDomain + " is not available");
            skippedAPIList.add(subscribedAPI.getApiId());
        }
    }
    return skippedAPIList;
}
Also used : ExportedSubscribedAPI(org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedSubscribedAPI) Set(java.util.Set) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) ArrayList(java.util.ArrayList) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) JSONObject(org.json.simple.JSONObject) API(org.wso2.carbon.apimgt.api.model.API) ExportedSubscribedAPI(org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedSubscribedAPI) Map(java.util.Map)

Example 52 with APIConsumer

use of org.wso2.carbon.apimgt.api.APIConsumer 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 53 with APIConsumer

use of org.wso2.carbon.apimgt.api.APIConsumer in project carbon-apimgt by wso2.

the class RestAPIStoreUtils method isUserAccessAllowedForAPI.

/**
 * Check whether the specified API exists and the current logged in user has access to it.
 * <p>
 * When it tries to retrieve the resource from the registry, it will fail with AuthorizationFailedException if user
 * does not have enough privileges. If the API does not exist, this will throw a APIMgtResourceNotFoundException
 *
 * @param apiId API identifier
 * @throws APIManagementException
 */
public static boolean isUserAccessAllowedForAPI(APIIdentifier apiId) throws APIManagementException {
    String username = RestApiCommonUtil.getLoggedInUsername();
    // this is just to check whether the user has access to the api or the api exists.
    try {
        APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
        String organization = ApiMgtDAO.getInstance().getOrganizationByAPIUUID(apiId.getUUID());
        apiConsumer.getLightweightAPIByUUID(apiId.getUUID(), organization);
    } catch (APIManagementException e) {
        if (RestApiUtil.isDueToAuthorizationFailure(e)) {
            String message = "user " + username + " failed to access the API " + apiId + " due to an authorization failure";
            log.info(message);
            return false;
        } else {
            // This is an unexpected failure
            String message = "Failed to retrieve the API " + apiId + " to check user " + username + " has access to the API";
            throw new APIManagementException(message, e);
        }
    }
    return true;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer)

Example 54 with APIConsumer

use of org.wso2.carbon.apimgt.api.APIConsumer in project carbon-apimgt by wso2.

the class RestAPIStoreUtils method isUserAccessAllowedForAPIByUUID.

/**
 * Check whether the specified API exists and the current logged in user has access to it.
 * <p>
 * When it tries to retrieve the resource from the registry, it will fail with AuthorizationFailedException if user
 * does not have enough privileges. If the API does not exist, this will throw a APIMgtResourceNotFoundException
 *
 * @param apiId API UUID
 * @param organization Identifier of the organization
 * @throws APIManagementException
 */
public static boolean isUserAccessAllowedForAPIByUUID(String apiId, String organization) throws APIManagementException {
    String username = RestApiCommonUtil.getLoggedInUsername();
    APIConsumer consumer = RestApiCommonUtil.getLoggedInUserConsumer();
    // this is just to check whether the user has access to the api or the api exists.
    try {
        consumer.getLightweightAPIByUUID(apiId, organization);
    } catch (APIManagementException e) {
        if (RestApiUtil.isDueToAuthorizationFailure(e)) {
            String message = "user " + username + " failed to access the API " + apiId + " due to an authorization failure";
            log.info(message);
            return false;
        } else {
            // This is an unexpected failure
            String message = "Failed to retrieve the API " + apiId + " to check user " + username + " has access to the API";
            throw new APIManagementException(message, e);
        }
    }
    return true;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer)

Example 55 with APIConsumer

use of org.wso2.carbon.apimgt.api.APIConsumer in project carbon-apimgt by wso2.

the class APIMappingUtil method fromAPIRevisionListToEndpointsList.

public static List<APIEndpointURLsDTO> fromAPIRevisionListToEndpointsList(APIDTO apidto, String organization) throws APIManagementException {
    Map<String, Environment> environments = APIUtil.getEnvironments(organization);
    APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
    List<APIRevisionDeployment> revisionDeployments = apiConsumer.getAPIRevisionDeploymentListOfAPI(apidto.getId());
    // custom gateway URL of tenant
    Map<String, String> domains = new HashMap<>();
    if (organization != null) {
        domains = apiConsumer.getTenantDomainMappings(organization, APIConstants.API_DOMAIN_MAPPINGS_GATEWAY);
    }
    String customGatewayUrl = domains.get(APIConstants.CUSTOM_URL);
    List<APIEndpointURLsDTO> endpointUrls = new ArrayList<>();
    for (APIRevisionDeployment revisionDeployment : revisionDeployments) {
        if (revisionDeployment.isDisplayOnDevportal()) {
            // Deployed environment
            Environment environment = environments.get(revisionDeployment.getDeployment());
            if (environment != null) {
                APIEndpointURLsDTO apiEndpointURLsDTO = fromAPIRevisionToEndpoints(apidto, environment, revisionDeployment.getVhost(), customGatewayUrl, organization);
                endpointUrls.add(apiEndpointURLsDTO);
            }
        }
    }
    return endpointUrls;
}
Also used : HashMap(java.util.HashMap) APIEndpointURLsDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIEndpointURLsDTO) ArrayList(java.util.ArrayList) Environment(org.wso2.carbon.apimgt.api.model.Environment) APIRevisionDeployment(org.wso2.carbon.apimgt.api.model.APIRevisionDeployment) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer)

Aggregations

APIConsumer (org.wso2.carbon.apimgt.api.APIConsumer)91 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)79 Application (org.wso2.carbon.apimgt.api.model.Application)50 Test (org.junit.Test)46 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)46 HashMap (java.util.HashMap)32 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)29 ArrayList (java.util.ArrayList)28 API (org.wso2.carbon.apimgt.api.model.API)28 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)28 JSONObject (org.json.simple.JSONObject)23 ExportedApplication (org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedApplication)23 Subscriber (org.wso2.carbon.apimgt.api.model.Subscriber)20 Map (java.util.Map)19 Matchers.anyString (org.mockito.Matchers.anyString)19 ApiTypeWrapper (org.wso2.carbon.apimgt.api.model.ApiTypeWrapper)18 Tier (org.wso2.carbon.apimgt.api.model.Tier)18 DevPortalAPI (org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI)15 URI (java.net.URI)13 URISyntaxException (java.net.URISyntaxException)13