Search in sources :

Example 96 with APIDefinition

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

the class APIProviderImpl method validateResourceThrottlingTiers.

@Override
public void validateResourceThrottlingTiers(String swaggerContent, String tenantDomain) throws APIManagementException {
    if (log.isDebugEnabled()) {
        log.debug("Validating x-throttling tiers defined in swagger api definition resource");
    }
    APIDefinition apiDefinition = OASParserUtil.getOASParser(swaggerContent);
    Set<URITemplate> uriTemplates = apiDefinition.getURITemplates(swaggerContent);
    checkResourceThrottlingTiersInURITemplates(uriTemplates, tenantDomain);
}
Also used : APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate)

Example 97 with APIDefinition

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

the class APIMappingUtil method fromAPItoDTO.

public static APIDTO fromAPItoDTO(API model, String organization) throws APIManagementException {
    APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
    APIDTO dto = new APIDTO();
    dto.setName(model.getId().getApiName());
    dto.setVersion(model.getId().getVersion());
    String providerName = model.getId().getProviderName();
    dto.setProvider(APIUtil.replaceEmailDomainBack(providerName));
    dto.setId(model.getUUID());
    dto.setContext(model.getContext());
    dto.setDescription(model.getDescription());
    dto.setIsDefaultVersion(model.isPublishedDefaultVersion());
    dto.setLifeCycleStatus(model.getStatus());
    dto.setType(model.getType());
    dto.setAvgRating(String.valueOf(model.getRating()));
    Set<Scope> scopes = model.getScopes();
    Map<String, ScopeInfoDTO> uniqueScope = new HashMap<>();
    for (Scope scope : scopes) {
        if (!uniqueScope.containsKey(scope.getKey())) {
            ScopeInfoDTO scopeInfoDTO = new ScopeInfoDTO().key(scope.getKey()).name(scope.getName()).description(scope.getDescription());
            if (StringUtils.isNotBlank(scope.getRoles())) {
                scopeInfoDTO.roles(Arrays.asList(scope.getRoles().trim().split(",")));
            }
            uniqueScope.put(scope.getKey(), scopeInfoDTO);
        }
    }
    dto.setScopes(new ArrayList<>(uniqueScope.values()));
    if (null != model.getLastUpdated()) {
        Date lastUpdateDate = model.getLastUpdated();
        Timestamp timeStamp = new Timestamp(lastUpdateDate.getTime());
        dto.setLastUpdatedTime(String.valueOf(timeStamp));
    }
    String createdTimeStamp = model.getCreatedTime();
    if (null != createdTimeStamp) {
        Date date = new Date(Long.valueOf(createdTimeStamp));
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String dateFormatted = formatter.format(date);
        dto.setCreatedTime(dateFormatted);
    }
    String apiDefinition = null;
    if (model.isAsync()) {
        // for asyncAPI retrieve asyncapi.yml specification
        apiDefinition = apiConsumer.getAsyncAPIDefinition(model.getUuid(), organization);
    } else {
        // retrieve open API definition
        if (model.getSwaggerDefinition() != null) {
            apiDefinition = model.getSwaggerDefinition();
        } else {
            apiDefinition = apiConsumer.getOpenAPIDefinition(model.getUuid(), organization);
        }
    }
    dto.setApiDefinition(apiDefinition);
    if (APIConstants.APITransportType.GRAPHQL.toString().equals(model.getType())) {
        List<APIOperationsDTO> operationList = new ArrayList<>();
        for (URITemplate template : model.getUriTemplates()) {
            APIOperationsDTO operation = new APIOperationsDTO();
            operation.setTarget(template.getUriTemplate());
            operation.setVerb(template.getHTTPVerb());
            operationList.add(operation);
        }
        dto.setOperations(operationList);
    }
    Set<String> apiTags = model.getTags();
    List<String> tagsToReturn = new ArrayList<>();
    tagsToReturn.addAll(apiTags);
    dto.setTags(tagsToReturn);
    // set the monetization status of this API (enabled or disabled)
    APIMonetizationInfoDTO monetizationInfoDTO = new APIMonetizationInfoDTO();
    monetizationInfoDTO.enabled(model.getMonetizationStatus());
    dto.setMonetization(monetizationInfoDTO);
    Set<org.wso2.carbon.apimgt.api.model.Tier> apiTiers = model.getAvailableTiers();
    List<APITiersDTO> tiersToReturn = new ArrayList<>();
    int tenantId = 0;
    if (!StringUtils.isBlank(organization)) {
        tenantId = APIUtil.getInternalOrganizationId(organization);
    }
    Set<String> deniedTiers = apiConsumer.getDeniedTiers(tenantId);
    for (org.wso2.carbon.apimgt.api.model.Tier currentTier : apiTiers) {
        if (!deniedTiers.contains(currentTier.getName())) {
            APITiersDTO apiTiersDTO = new APITiersDTO();
            apiTiersDTO.setTierName(currentTier.getName());
            apiTiersDTO.setTierPlan(currentTier.getTierPlan());
            // monetization attributes are applicable only for commercial tiers
            if (APIConstants.COMMERCIAL_TIER_PLAN.equalsIgnoreCase(currentTier.getTierPlan())) {
                APIMonetizationAttributesDTO monetizationAttributesDTO = new APIMonetizationAttributesDTO();
                if (MapUtils.isNotEmpty(currentTier.getMonetizationAttributes())) {
                    Map<String, String> monetizationAttributes = currentTier.getMonetizationAttributes();
                    // check for the billing plan (fixed or price per request)
                    if (!StringUtils.isBlank(monetizationAttributes.get(APIConstants.Monetization.FIXED_PRICE))) {
                        monetizationAttributesDTO.setFixedPrice(monetizationAttributes.get(APIConstants.Monetization.FIXED_PRICE));
                    } else if (!StringUtils.isBlank(monetizationAttributes.get(APIConstants.Monetization.PRICE_PER_REQUEST))) {
                        monetizationAttributesDTO.setPricePerRequest(monetizationAttributes.get(APIConstants.Monetization.PRICE_PER_REQUEST));
                    }
                    monetizationAttributesDTO.setCurrencyType(monetizationAttributes.get(APIConstants.Monetization.CURRENCY) != null ? monetizationAttributes.get(APIConstants.Monetization.CURRENCY) : StringUtils.EMPTY);
                    monetizationAttributesDTO.setBillingCycle(monetizationAttributes.get(APIConstants.Monetization.BILLING_CYCLE) != null ? monetizationAttributes.get(APIConstants.Monetization.BILLING_CYCLE) : StringUtils.EMPTY);
                }
                apiTiersDTO.setMonetizationAttributes(monetizationAttributesDTO);
            }
            tiersToReturn.add(apiTiersDTO);
        }
    }
    dto.setTiers(tiersToReturn);
    dto.setTransport(Arrays.asList(model.getTransports().split(",")));
    APIBusinessInformationDTO apiBusinessInformationDTO = new APIBusinessInformationDTO();
    apiBusinessInformationDTO.setBusinessOwner(model.getBusinessOwner());
    apiBusinessInformationDTO.setBusinessOwnerEmail(model.getBusinessOwnerEmail());
    apiBusinessInformationDTO.setTechnicalOwner(model.getTechnicalOwner());
    apiBusinessInformationDTO.setTechnicalOwnerEmail(model.getTechnicalOwnerEmail());
    dto.setBusinessInformation(apiBusinessInformationDTO);
    if (!StringUtils.isBlank(model.getThumbnailUrl())) {
        dto.setHasThumbnail(true);
    }
    if (model.getAdditionalProperties() != null) {
        JSONObject additionalProperties = model.getAdditionalProperties();
        List<APIAdditionalPropertiesDTO> additionalPropertiesList = new ArrayList<>();
        for (Object propertyKey : additionalProperties.keySet()) {
            APIAdditionalPropertiesDTO additionalPropertiesDTO = new APIAdditionalPropertiesDTO();
            String key = (String) propertyKey;
            int index = key.lastIndexOf(APIConstants.API_RELATED_CUSTOM_PROPERTIES_SURFIX);
            additionalPropertiesDTO.setValue((String) additionalProperties.get(key));
            if (index > 0) {
                additionalPropertiesDTO.setName(key.substring(0, index));
                additionalPropertiesDTO.setDisplay(true);
                additionalPropertiesList.add(additionalPropertiesDTO);
            }
        }
        dto.setAdditionalProperties(additionalPropertiesList);
    }
    dto.setWsdlUri(model.getWsdlUrl());
    if (model.getEnvironmentList() != null) {
        List<String> environmentListToReturn = new ArrayList<>();
        environmentListToReturn.addAll(model.getEnvironmentList());
        dto.setEnvironmentList(environmentListToReturn);
    }
    dto.setAuthorizationHeader(model.getAuthorizationHeader());
    if (model.getApiSecurity() != null) {
        dto.setSecurityScheme(Arrays.asList(model.getApiSecurity().split(",")));
    }
    dto.setAdvertiseInfo(extractAdvertiseInfo(model));
    String apiTenant = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(model.getId().getProviderName()));
    String subscriptionAvailability = model.getSubscriptionAvailability();
    String subscriptionAllowedTenants = model.getSubscriptionAvailableTenants();
    dto.setIsSubscriptionAvailable(isSubscriptionAvailable(apiTenant, subscriptionAvailability, subscriptionAllowedTenants));
    List<APICategory> apiCategories = model.getApiCategories();
    List<String> categoryNamesList = new ArrayList<>();
    if (apiCategories != null && !apiCategories.isEmpty()) {
        for (APICategory category : apiCategories) {
            categoryNamesList.add(category.getName());
        }
    }
    dto.setCategories(categoryNamesList);
    dto.setKeyManagers(model.getKeyManagers());
    if (model.getGatewayVendor() != null) {
        dto.setGatewayVendor(model.getGatewayVendor());
    } else {
        dto.setGatewayVendor("wso2");
    }
    if (model.getAsyncTransportProtocols() != null) {
        dto.setAsyncTransportProtocols(Arrays.asList(model.getAsyncTransportProtocols().split(",")));
    }
    return dto;
}
Also used : HashMap(java.util.HashMap) APITiersDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APITiersDTO) ArrayList(java.util.ArrayList) APIAdditionalPropertiesDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIAdditionalPropertiesDTO) Timestamp(java.sql.Timestamp) APIBusinessInformationDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIBusinessInformationDTO) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) APIMonetizationInfoDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIMonetizationInfoDTO) Tier(org.wso2.carbon.apimgt.api.model.Tier) Tier(org.wso2.carbon.apimgt.api.model.Tier) ScopeInfoDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ScopeInfoDTO) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) Date(java.util.Date) APIDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIDTO) Scope(org.wso2.carbon.apimgt.api.model.Scope) JSONObject(org.json.simple.JSONObject) DateFormat(java.text.DateFormat) SimpleDateFormat(java.text.SimpleDateFormat) APIOperationsDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIOperationsDTO) JsonObject(com.google.gson.JsonObject) JSONObject(org.json.simple.JSONObject) SimpleDateFormat(java.text.SimpleDateFormat) APICategory(org.wso2.carbon.apimgt.api.model.APICategory) APIMonetizationAttributesDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIMonetizationAttributesDTO)

Example 98 with APIDefinition

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

the class APIUtil method createSwaggerJSONContent.

/**
 * Create API Definition in JSON
 *
 * @param api API
 * @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to generate the content and save
 * @deprecated
 */
@Deprecated
public static String createSwaggerJSONContent(API api) throws APIManagementException {
    APIIdentifier identifier = api.getId();
    String organization = api.getOrganization();
    Environment environment = (Environment) getEnvironments(organization).values().toArray()[0];
    String endpoints = environment.getApiGatewayEndpoint();
    String[] endpointsSet = endpoints.split(",");
    String apiContext = api.getContext();
    String version = identifier.getVersion();
    Set<URITemplate> uriTemplates = api.getUriTemplates();
    String description = api.getDescription();
    // With the new context version strategy, the URL prefix is the apiContext. the verison will be embedded in
    // the apiContext.
    String urlPrefix = apiContext;
    if (endpointsSet.length < 1) {
        throw new APIManagementException("Error in creating JSON representation of the API" + identifier.getApiName());
    }
    if (description == null || "".equals(description)) {
        description = "";
    } else {
        description = description.trim();
    }
    Map<String, List<Operation>> uriTemplateDefinitions = new HashMap<String, List<Operation>>();
    List<APIResource> apis = new ArrayList<APIResource>();
    for (URITemplate template : uriTemplates) {
        List<Operation> ops;
        List<Parameter> parameters;
        String path = urlPrefix + APIUtil.removeAnySymbolFromUriTempate(template.getUriTemplate());
        /* path exists in uriTemplateDefinitions */
        if (uriTemplateDefinitions.get(path) != null) {
            ops = uriTemplateDefinitions.get(path);
            parameters = new ArrayList<Parameter>();
            String httpVerb = template.getHTTPVerb();
            /* For GET and DELETE Parameter name - Query Parameters */
            if (Constants.Configuration.HTTP_METHOD_GET.equals(httpVerb) || Constants.Configuration.HTTP_METHOD_DELETE.equals(httpVerb)) {
                Parameter queryParam = new Parameter(APIConstants.OperationParameter.QUERY_PARAM_NAME, APIConstants.OperationParameter.QUERY_PARAM_DESCRIPTION, APIConstants.OperationParameter.PAYLOAD_PARAM_TYPE, false, false, "String");
                parameters.add(queryParam);
            } else {
                /* For POST, PUT and PATCH Parameter name - Payload */
                Parameter payLoadParam = new Parameter(APIConstants.OperationParameter.PAYLOAD_PARAM_NAME, APIConstants.OperationParameter.PAYLOAD_PARAM_DESCRIPTION, APIConstants.OperationParameter.PAYLOAD_PARAM_TYPE, false, false, "String");
                parameters.add(payLoadParam);
            }
            Parameter authParam = new Parameter(APIConstants.OperationParameter.AUTH_PARAM_NAME, APIConstants.OperationParameter.AUTH_PARAM_DESCRIPTION, APIConstants.OperationParameter.AUTH_PARAM_TYPE, false, false, "String");
            parameters.add(authParam);
            if (!"OPTIONS".equals(httpVerb)) {
                Operation op = new Operation(httpVerb, description, description, parameters);
                ops.add(op);
            }
        } else {
            /* path not exists in uriTemplateDefinitions */
            ops = new ArrayList<Operation>();
            parameters = new ArrayList<Parameter>();
            String httpVerb = template.getHTTPVerb();
            /* For GET and DELETE Parameter name - Query Parameters */
            if (Constants.Configuration.HTTP_METHOD_GET.equals(httpVerb) || Constants.Configuration.HTTP_METHOD_DELETE.equals(httpVerb)) {
                Parameter queryParam = new Parameter(APIConstants.OperationParameter.QUERY_PARAM_NAME, APIConstants.OperationParameter.QUERY_PARAM_DESCRIPTION, APIConstants.OperationParameter.PAYLOAD_PARAM_TYPE, false, false, "String");
                parameters.add(queryParam);
            } else {
                /* For POST,PUT and PATCH Parameter name - Payload */
                Parameter payLoadParam = new Parameter(APIConstants.OperationParameter.PAYLOAD_PARAM_NAME, APIConstants.OperationParameter.PAYLOAD_PARAM_DESCRIPTION, APIConstants.OperationParameter.PAYLOAD_PARAM_TYPE, false, false, "String");
                parameters.add(payLoadParam);
            }
            Parameter authParam = new Parameter(APIConstants.OperationParameter.AUTH_PARAM_NAME, APIConstants.OperationParameter.AUTH_PARAM_DESCRIPTION, APIConstants.OperationParameter.AUTH_PARAM_TYPE, false, false, "String");
            parameters.add(authParam);
            if (!"OPTIONS".equals(httpVerb)) {
                Operation op = new Operation(httpVerb, description, description, parameters);
                ops.add(op);
            }
            uriTemplateDefinitions.put(path, ops);
        }
    }
    final Set<Entry<String, List<Operation>>> entries = uriTemplateDefinitions.entrySet();
    for (Entry entry : entries) {
        APIResource apiResource = new APIResource((String) entry.getKey(), description, (List<Operation>) entry.getValue());
        apis.add(apiResource);
    }
    APIDefinition apidefinition = new APIDefinition(version, APIConstants.SWAGGER_VERSION, endpointsSet[0], apiContext, apis);
    Gson gson = new Gson();
    return gson.toJson(apidefinition);
}
Also used : LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) Operation(org.wso2.carbon.apimgt.api.doc.model.Operation) Entry(java.util.Map.Entry) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIDefinition(org.wso2.carbon.apimgt.api.doc.model.APIDefinition) RecommendationEnvironment(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommendationEnvironment) Environment(org.wso2.carbon.apimgt.api.model.Environment) ExternalEnvironment(org.wso2.carbon.apimgt.impl.ExternalEnvironment) Parameter(org.wso2.carbon.apimgt.api.doc.model.Parameter) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) SolrDocumentList(org.apache.solr.common.SolrDocumentList) ArrayList(java.util.ArrayList) List(java.util.List)

Example 99 with APIDefinition

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

the class SettingsMappingUtil method getScopeList.

private List<String> getScopeList() throws APIManagementException {
    String definition = null;
    try {
        definition = IOUtils.toString(RestApiUtil.class.getResourceAsStream("/admin-api.yaml"), "UTF-8");
    } catch (IOException e) {
        log.error("Error while reading the swagger definition", e);
    }
    APIDefinition oasParser = OASParserUtil.getOASParser(definition);
    Set<Scope> scopeSet = oasParser.getScopes(definition);
    List<String> scopeList = new ArrayList<>();
    for (Scope entry : scopeSet) {
        scopeList.add(entry.getKey());
    }
    return scopeList;
}
Also used : Scope(org.wso2.carbon.apimgt.api.model.Scope) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) ArrayList(java.util.ArrayList) IOException(java.io.IOException)

Example 100 with APIDefinition

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

the class RestApiCommonUtil method retrieveSwaggerDefinition.

/**
 * This method retrieves the Swagger Definition for an API to be displayed
 *
 * @param api         API
 * @param apiProvider API Provider
 * @return String with the swagger definition
 */
public static String retrieveSwaggerDefinition(API api, APIProvider apiProvider) throws APIManagementException {
    String apiSwagger = null;
    if (api.getUuid() != null) {
        apiSwagger = apiProvider.getOpenAPIDefinition(api.getUuid(), api.getOrganization());
    } else {
        apiSwagger = apiProvider.getOpenAPIDefinition(api.getId(), api.getOrganization());
    }
    APIDefinition parser = OASParserUtil.getOASParser(apiSwagger);
    return parser.getOASDefinitionForPublisher(api, apiSwagger);
}
Also used : APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)32 HashMap (java.util.HashMap)30 APIDefinition (org.wso2.carbon.apimgt.api.APIDefinition)30 API (org.wso2.carbon.apimgt.core.models.API)30 CompositeAPI (org.wso2.carbon.apimgt.core.models.CompositeAPI)25 ArrayList (java.util.ArrayList)23 API (org.wso2.carbon.apimgt.api.model.API)20 Map (java.util.Map)19 IOException (java.io.IOException)18 Test (org.testng.annotations.Test)18 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)18 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)16 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)15 Scope (org.wso2.carbon.apimgt.api.model.Scope)15 HashSet (java.util.HashSet)13 APIPolicy (org.wso2.carbon.apimgt.core.models.policy.APIPolicy)13 APIDefinitionValidationResponse (org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)12 SwaggerData (org.wso2.carbon.apimgt.api.model.SwaggerData)12 BusinessInformation (org.wso2.carbon.apimgt.core.models.BusinessInformation)12 CorsConfiguration (org.wso2.carbon.apimgt.core.models.CorsConfiguration)12