Search in sources :

Example 81 with APIProductIdentifier

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

the class ApiMgtDAO method getAllAPIProductUsageByProvider.

/**
 * @param providerName Name of the provider
 * @return UserApplicationAPIUsage of given provider
 * @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to get
 *                                                           UserApplicationAPIUsage for given provider
 */
public UserApplicationAPIUsage[] getAllAPIProductUsageByProvider(String providerName) throws APIManagementException {
    try (Connection connection = APIMgtDBUtil.getConnection();
        PreparedStatement ps = connection.prepareStatement(SQLConstants.GET_APP_API_USAGE_BY_PROVIDER_SQL)) {
        ps.setString(1, APIUtil.replaceEmailDomainBack(providerName));
        try (ResultSet result = ps.executeQuery()) {
            Map<String, UserApplicationAPIUsage> userApplicationUsages = new TreeMap<String, UserApplicationAPIUsage>();
            while (result.next()) {
                int subId = result.getInt("SUBSCRIPTION_ID");
                String userId = result.getString("USER_ID");
                String application = result.getString("APPNAME");
                int appId = result.getInt("APPLICATION_ID");
                String subStatus = result.getString("SUB_STATUS");
                String subsCreateState = result.getString("SUBS_CREATE_STATE");
                String key = userId + "::" + application;
                UserApplicationAPIUsage usage = userApplicationUsages.get(key);
                if (usage == null) {
                    usage = new UserApplicationAPIUsage();
                    usage.setUserId(userId);
                    usage.setApplicationName(application);
                    usage.setAppId(appId);
                    userApplicationUsages.put(key, usage);
                }
                APIProductIdentifier apiProductId = new APIProductIdentifier(result.getString("API_PROVIDER"), result.getString("API_NAME"), result.getString("API_VERSION"));
                SubscribedAPI apiSubscription = new SubscribedAPI(new Subscriber(userId), apiProductId);
                apiSubscription.setSubStatus(subStatus);
                apiSubscription.setSubCreatedStatus(subsCreateState);
                apiSubscription.setUUID(result.getString("SUB_UUID"));
                apiSubscription.setTier(new Tier(result.getString("SUB_TIER_ID")));
                Application applicationObj = new Application(result.getString("APP_UUID"));
                apiSubscription.setApplication(applicationObj);
                usage.addApiSubscriptions(apiSubscription);
            }
            return userApplicationUsages.values().toArray(new UserApplicationAPIUsage[userApplicationUsages.size()]);
        }
    } catch (SQLException e) {
        handleException("Failed to find API Product Usage for :" + providerName, e);
    }
    return new UserApplicationAPIUsage[] {};
}
Also used : UserApplicationAPIUsage(org.wso2.carbon.apimgt.api.dto.UserApplicationAPIUsage) Tier(org.wso2.carbon.apimgt.api.model.Tier) SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) TreeMap(java.util.TreeMap) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) ResultSet(java.sql.ResultSet) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) Application(org.wso2.carbon.apimgt.api.model.Application)

Example 82 with APIProductIdentifier

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

the class ApiMgtDAO method getAPIProductResourceMappings.

/**
 * get resource mapping of the api product
 * TODO://Get resource scopes from AM_API_RESOURCE_SCOPE table and retrieve scope meta data and bindings from KM.
 *
 * @param productIdentifier api product identifier
 * @throws APIManagementException
 */
public List<APIProductResource> getAPIProductResourceMappings(APIProductIdentifier productIdentifier) throws APIManagementException {
    int productId = getAPIProductId(productIdentifier);
    List<APIProductResource> productResourceList = new ArrayList<>();
    try (Connection connection = APIMgtDBUtil.getConnection()) {
        if (checkAPIUUIDIsARevisionUUID(productIdentifier.getUUID()) == null) {
            String sql = SQLConstants.GET_RESOURCES_OF_PRODUCT;
            try (PreparedStatement ps = connection.prepareStatement(sql)) {
                ps.setInt(1, productId);
                ps.setString(2, String.valueOf(productId));
                try (ResultSet rs = ps.executeQuery()) {
                    while (rs.next()) {
                        APIProductResource resource = new APIProductResource();
                        APIIdentifier apiId = new APIIdentifier(rs.getString("API_PROVIDER"), rs.getString("API_NAME"), rs.getString("API_VERSION"));
                        apiId.setUuid(rs.getString("API_UUID"));
                        resource.setProductIdentifier(productIdentifier);
                        resource.setApiIdentifier(apiId);
                        resource.setApiName(rs.getString("API_NAME"));
                        URITemplate uriTemplate = new URITemplate();
                        uriTemplate.setUriTemplate(rs.getString("URL_PATTERN"));
                        uriTemplate.setResourceURI(rs.getString("URL_PATTERN"));
                        uriTemplate.setHTTPVerb(rs.getString("HTTP_METHOD"));
                        int uriTemplateId = rs.getInt("URL_MAPPING_ID");
                        uriTemplate.setId(uriTemplateId);
                        uriTemplate.setAuthType(rs.getString("AUTH_SCHEME"));
                        uriTemplate.setThrottlingTier(rs.getString("THROTTLING_TIER"));
                        try (PreparedStatement scopesStatement = connection.prepareStatement(SQLConstants.GET_SCOPE_KEYS_BY_URL_MAPPING_ID)) {
                            scopesStatement.setInt(1, uriTemplateId);
                            try (ResultSet scopesResult = scopesStatement.executeQuery()) {
                                while (scopesResult.next()) {
                                    Scope scope = new Scope();
                                    scope.setKey(scopesResult.getString("SCOPE_NAME"));
                                    uriTemplate.setScopes(scope);
                                }
                            }
                        }
                        try (PreparedStatement policiesStatement = connection.prepareStatement(SQLConstants.OperationPolicyConstants.GET_OPERATION_POLICIES_BY_URI_TEMPLATE_ID)) {
                            policiesStatement.setInt(1, uriTemplateId);
                            try (ResultSet policiesResult = policiesStatement.executeQuery()) {
                                List<OperationPolicy> operationPolicies = new ArrayList<>();
                                while (policiesResult.next()) {
                                    OperationPolicy policy = populateOperationPolicyWithRS(policiesResult);
                                    operationPolicies.add(policy);
                                }
                                uriTemplate.setOperationPolicies(operationPolicies);
                            }
                        }
                        resource.setUriTemplate(uriTemplate);
                        productResourceList.add(resource);
                    }
                }
            }
        } else {
            String sql = SQLConstants.GET_RESOURCES_OF_PRODUCT_REVISION;
            try (PreparedStatement ps = connection.prepareStatement(sql)) {
                ps.setInt(1, productId);
                ps.setString(2, productIdentifier.getUUID());
                ps.setString(3, productIdentifier.getUUID());
                try (ResultSet rs = ps.executeQuery()) {
                    while (rs.next()) {
                        APIProductResource resource = new APIProductResource();
                        APIIdentifier apiId = new APIIdentifier(rs.getString("API_PROVIDER"), rs.getString("API_NAME"), rs.getString("API_VERSION"));
                        apiId.setUuid(rs.getString("API_UUID"));
                        resource.setProductIdentifier(productIdentifier);
                        resource.setApiIdentifier(apiId);
                        resource.setApiName(rs.getString("API_NAME"));
                        URITemplate uriTemplate = new URITemplate();
                        uriTemplate.setUriTemplate(rs.getString("URL_PATTERN"));
                        uriTemplate.setResourceURI(rs.getString("URL_PATTERN"));
                        uriTemplate.setHTTPVerb(rs.getString("HTTP_METHOD"));
                        int uriTemplateId = rs.getInt("URL_MAPPING_ID");
                        uriTemplate.setId(uriTemplateId);
                        uriTemplate.setAuthType(rs.getString("AUTH_SCHEME"));
                        uriTemplate.setThrottlingTier(rs.getString("THROTTLING_TIER"));
                        try (PreparedStatement scopesStatement = connection.prepareStatement(SQLConstants.GET_SCOPE_KEYS_BY_URL_MAPPING_ID)) {
                            scopesStatement.setInt(1, uriTemplateId);
                            try (ResultSet scopesResult = scopesStatement.executeQuery()) {
                                while (scopesResult.next()) {
                                    Scope scope = new Scope();
                                    scope.setKey(scopesResult.getString("SCOPE_NAME"));
                                    uriTemplate.setScopes(scope);
                                }
                            }
                        }
                        try (PreparedStatement policiesStatement = connection.prepareStatement(SQLConstants.OperationPolicyConstants.GET_OPERATION_POLICIES_BY_URI_TEMPLATE_ID)) {
                            policiesStatement.setInt(1, uriTemplateId);
                            try (ResultSet policiesResult = policiesStatement.executeQuery()) {
                                List<OperationPolicy> operationPolicies = new ArrayList<>();
                                while (policiesResult.next()) {
                                    OperationPolicy policy = populateOperationPolicyWithRS(policiesResult);
                                    operationPolicies.add(policy);
                                }
                                uriTemplate.setOperationPolicies(operationPolicies);
                            }
                        }
                        resource.setUriTemplate(uriTemplate);
                        productResourceList.add(resource);
                    }
                }
            }
        }
    } catch (SQLException e) {
        handleException("Failed to get product resources of api product : " + productIdentifier, e);
    }
    return productResourceList;
}
Also used : SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) Connection(java.sql.Connection) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) PreparedStatement(java.sql.PreparedStatement) Scope(org.wso2.carbon.apimgt.api.model.Scope) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) OperationPolicy(org.wso2.carbon.apimgt.api.model.OperationPolicy) ResultSet(java.sql.ResultSet) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

Example 83 with APIProductIdentifier

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

the class ApiMgtDAO method getPaginatedSubscribedAPIsByApplication.

public Set<SubscribedAPI> getPaginatedSubscribedAPIsByApplication(Application application, Integer offset, Integer limit, String organization) throws APIManagementException {
    Set<SubscribedAPI> subscribedAPIs = new LinkedHashSet<>();
    try (Connection connection = APIMgtDBUtil.getConnection();
        PreparedStatement ps = connection.prepareStatement(SQLConstants.GET_PAGINATED_SUBSCRIBED_APIS_BY_APP_ID_SQL)) {
        ps.setInt(1, application.getId());
        ps.setString(2, organization);
        try (ResultSet result = ps.executeQuery()) {
            int index = 0;
            while (result.next()) {
                if (index >= offset && index < limit) {
                    String apiType = result.getString("TYPE");
                    if (APIConstants.API_PRODUCT.toString().equals(apiType)) {
                        APIProductIdentifier identifier = new APIProductIdentifier(APIUtil.replaceEmailDomain(result.getString("API_PROVIDER")), result.getString("API_NAME"), result.getString("API_VERSION"));
                        identifier.setUUID(result.getString("API_UUID"));
                        SubscribedAPI subscribedAPI = new SubscribedAPI(application.getSubscriber(), identifier);
                        subscribedAPI.setApplication(application);
                        initSubscribedAPI(subscribedAPI, result);
                        subscribedAPIs.add(subscribedAPI);
                    } else {
                        APIIdentifier identifier = new APIIdentifier(APIUtil.replaceEmailDomain(result.getString("API_PROVIDER")), result.getString("API_NAME"), result.getString("API_VERSION"));
                        identifier.setUuid(result.getString("API_UUID"));
                        SubscribedAPI subscribedAPI = new SubscribedAPI(application.getSubscriber(), identifier);
                        subscribedAPI.setApplication(application);
                        initSubscribedAPI(subscribedAPI, result);
                        subscribedAPIs.add(subscribedAPI);
                    }
                    if (index == limit - 1) {
                        break;
                    }
                }
                index++;
            }
        }
    } catch (SQLException e) {
        handleException("Failed to get SubscribedAPI of application :" + application.getName(), e);
    }
    return subscribedAPIs;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PreparedStatement(java.sql.PreparedStatement) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

Example 84 with APIProductIdentifier

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

the class APIMappingUtil method getOperationFromURITemplate.

/**
 * Converts a URI template object to a REST API DTO.
 *
 * @param uriTemplate URI Template object
 * @return REST API DTO representing URI template object
 */
private static APIOperationsDTO getOperationFromURITemplate(URITemplate uriTemplate) {
    APIOperationsDTO operationsDTO = new APIOperationsDTO();
    // todo: Set ID properly
    operationsDTO.setId("");
    if (APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN.equals(uriTemplate.getAuthType())) {
        operationsDTO.setAuthType(APIConstants.OASResourceAuthTypes.APPLICATION_OR_APPLICATION_USER);
    } else if (APIConstants.AUTH_APPLICATION_USER_LEVEL_TOKEN.equals(uriTemplate.getAuthType())) {
        operationsDTO.setAuthType(APIConstants.OASResourceAuthTypes.APPLICATION_USER);
    } else if (APIConstants.AUTH_NO_AUTHENTICATION.equals(uriTemplate.getAuthType())) {
        operationsDTO.setAuthType(APIConstants.OASResourceAuthTypes.NONE);
    } else if (APIConstants.AUTH_APPLICATION_LEVEL_TOKEN.equals(uriTemplate.getAuthType())) {
        operationsDTO.setAuthType(APIConstants.OASResourceAuthTypes.APPLICATION);
    } else {
        operationsDTO.setAuthType(APIConstants.OASResourceAuthTypes.APPLICATION_OR_APPLICATION_USER);
    }
    operationsDTO.setVerb(uriTemplate.getHTTPVerb());
    operationsDTO.setTarget(uriTemplate.getUriTemplate());
    operationsDTO.setScopes(uriTemplate.retrieveAllScopes().stream().map(Scope::getKey).collect(Collectors.toList()));
    operationsDTO.setOperationPolicies(OperationPolicyMappingUtil.fromOperationPolicyListToDTO(uriTemplate.getOperationPolicies()));
    operationsDTO.setThrottlingPolicy(uriTemplate.getThrottlingTier());
    Set<APIProductIdentifier> usedByProducts = uriTemplate.retrieveUsedByProducts();
    List<String> usedProductIds = new ArrayList<>();
    for (APIProductIdentifier usedByProduct : usedByProducts) {
        usedProductIds.add(usedByProduct.getUUID());
    }
    if (!usedProductIds.isEmpty()) {
        operationsDTO.setUsedProductIds(usedProductIds);
    }
    return operationsDTO;
}
Also used : APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) Scope(org.wso2.carbon.apimgt.api.model.Scope) APIOperationsDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO) ArrayList(java.util.ArrayList)

Example 85 with APIProductIdentifier

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

the class APIProviderImpl method updateAPIProduct.

@Override
public Map<API, List<APIProductResource>> updateAPIProduct(APIProduct product) throws APIManagementException, FaultGatewaysException {
    Map<API, List<APIProductResource>> apiToProductResourceMapping = new HashMap<>();
    // validate resources and set api identifiers and resource ids to product
    List<APIProductResource> resources = product.getProductResources();
    for (APIProductResource apiProductResource : resources) {
        API api;
        APIProductIdentifier productIdentifier = apiProductResource.getProductIdentifier();
        String apiUUID;
        if (productIdentifier != null) {
            APIIdentifier productAPIIdentifier = apiProductResource.getApiIdentifier();
            String emailReplacedAPIProviderName = APIUtil.replaceEmailDomain(productAPIIdentifier.getProviderName());
            APIIdentifier emailReplacedAPIIdentifier = new APIIdentifier(emailReplacedAPIProviderName, productAPIIdentifier.getApiName(), productAPIIdentifier.getVersion());
            apiUUID = apiMgtDAO.getUUIDFromIdentifier(emailReplacedAPIIdentifier, product.getOrganization());
            api = getAPIbyUUID(apiUUID, tenantDomain);
        } else {
            apiUUID = apiProductResource.getApiId();
            api = getAPIbyUUID(apiUUID, tenantDomain);
        }
        if (api.getSwaggerDefinition() != null) {
            api.setSwaggerDefinition(getOpenAPIDefinition(apiUUID, tenantDomain));
        }
        if (!apiToProductResourceMapping.containsKey(api)) {
            apiToProductResourceMapping.put(api, new ArrayList<>());
        }
        List<APIProductResource> apiProductResources = apiToProductResourceMapping.get(api);
        apiProductResources.add(apiProductResource);
        // if API does not exist, getLightweightAPIByUUID() method throws exception. so no need to handle NULL
        apiProductResource.setApiIdentifier(api.getId());
        apiProductResource.setProductIdentifier(product.getId());
        if (api.isAdvertiseOnly()) {
            apiProductResource.setEndpointConfig(APIUtil.generateEndpointConfigForAdvertiseOnlyApi(api));
        } else {
            apiProductResource.setEndpointConfig(api.getEndpointConfig());
        }
        apiProductResource.setEndpointSecurityMap(APIUtil.setEndpointSecurityForAPIProduct(api));
        URITemplate uriTemplate = apiProductResource.getUriTemplate();
        Map<String, URITemplate> templateMap = apiMgtDAO.getURITemplatesForAPI(api);
        if (uriTemplate == null) {
        // TODO handle if no resource is defined. either throw an error or add all the resources of that API
        // to the product
        } else {
            String key = uriTemplate.getHTTPVerb() + ":" + uriTemplate.getUriTemplate();
            if (templateMap.containsKey(key)) {
                // Since the template ID is not set from the request, we manually set it.
                uriTemplate.setId(templateMap.get(key).getId());
            } else {
                throw new APIManagementException("API with id " + apiProductResource.getApiId() + " does not have a resource " + uriTemplate.getUriTemplate() + " with http method " + uriTemplate.getHTTPVerb());
            }
        }
    }
    APIProduct oldApi = getAPIProductbyUUID(product.getUuid(), CarbonContext.getThreadLocalCarbonContext().getTenantDomain());
    Gson gson = new Gson();
    Map<String, String> oldMonetizationProperties = gson.fromJson(oldApi.getMonetizationProperties().toString(), HashMap.class);
    if (oldMonetizationProperties != null && !oldMonetizationProperties.isEmpty()) {
        Map<String, String> newMonetizationProperties = gson.fromJson(product.getMonetizationProperties().toString(), HashMap.class);
        if (newMonetizationProperties != null) {
            for (Map.Entry<String, String> entry : oldMonetizationProperties.entrySet()) {
                String newValue = newMonetizationProperties.get(entry.getKey());
                if (StringUtils.isAllBlank(newValue)) {
                    newMonetizationProperties.put(entry.getKey(), entry.getValue());
                }
            }
            JSONParser parser = new JSONParser();
            try {
                JSONObject jsonObj = (JSONObject) parser.parse(gson.toJson(newMonetizationProperties));
                product.setMonetizationProperties(jsonObj);
            } catch (ParseException e) {
                throw new APIManagementException("Error when parsing monetization properties ", e);
            }
        }
    }
    invalidateResourceCache(product.getContext(), product.getId().getVersion(), Collections.EMPTY_SET);
    // todo : check whether permissions need to be updated and pass it along
    updateApiProductArtifact(product, true, true);
    apiMgtDAO.updateAPIProduct(product, userNameWithoutChange);
    int productId = apiMgtDAO.getAPIProductId(product.getId());
    APIEvent apiEvent = new APIEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.API_UPDATE.name(), tenantId, tenantDomain, product.getId().getName(), productId, product.getId().getUUID(), product.getId().getVersion(), product.getType(), product.getContext(), product.getId().getProviderName(), APIConstants.LC_PUBLISH_LC_STATE);
    APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name());
    return apiToProductResourceMapping;
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) Gson(com.google.gson.Gson) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) PublisherAPIProduct(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProduct) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONObject(org.json.simple.JSONObject) APIEvent(org.wso2.carbon.apimgt.impl.notifier.events.APIEvent) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) 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) ArrayList(java.util.ArrayList) List(java.util.List) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException) Map(java.util.Map) TreeMap(java.util.TreeMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap)

Aggregations

APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)91 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)48 APIProduct (org.wso2.carbon.apimgt.api.model.APIProduct)33 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)22 PreparedStatement (java.sql.PreparedStatement)19 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)19 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)19 Connection (java.sql.Connection)18 ArrayList (java.util.ArrayList)18 ResultSet (java.sql.ResultSet)17 SQLException (java.sql.SQLException)17 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)17 API (org.wso2.carbon.apimgt.api.model.API)14 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)14 HashSet (java.util.HashSet)13 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)13 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)13 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)13 Tier (org.wso2.carbon.apimgt.api.model.Tier)12 PublisherAPIProduct (org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProduct)12